blob: b0535919b121a58e543ed632a9777e6f8a3dafb9 [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
Fam Zheng67a1de02016-06-01 17:44:21 +080028#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010029#include "qapi/error.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010030#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010031#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010032#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010033#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010034#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020035#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000036#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010037#include "qemu/option.h"
38#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030039#include "qemu/log.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020040#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000041#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010042#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020043#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010044#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020045#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080046#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010047#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030048#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000049
Thomas Huth7e563bf2018-02-15 12:06:47 +010050#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020051 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040052
Anthony Liguoric227f092009-10-01 16:12:16 -050053typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010054 const char *name;
55 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050056} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010057
Federico Simoncelli8599ea42013-01-28 06:59:47 -050058enum {
59 OPTION_OUTPUT = 256,
60 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000061 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000062 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020063 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020064 OPTION_FLUSH_INTERVAL = 261,
65 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010066 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010067 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020068 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030069 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050070};
71
72typedef enum OutputFormat {
73 OFORMAT_JSON,
74 OFORMAT_HUMAN,
75} OutputFormat;
76
Kevin Wolfe6996142016-03-15 13:03:11 +010077/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040078#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000079
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010080static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000081{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010082 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000083}
84
Fam Zhengac1307a2014-04-22 13:36:11 +080085static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
86{
87 va_list ap;
88
Fam Zhengac1307a2014-04-22 13:36:11 +080089 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +020090 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +080091 va_end(ap);
92
Markus Armbrustere9e1d922019-04-17 21:06:27 +020093 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +080094 exit(EXIT_FAILURE);
95}
96
Stefan Hajnoczic9192972017-03-17 18:45:41 +080097static void QEMU_NORETURN missing_argument(const char *option)
98{
99 error_exit("missing argument for option '%s'", option);
100}
101
102static void QEMU_NORETURN unrecognized_option(const char *option)
103{
104 error_exit("unrecognized option '%s'", option);
105}
106
blueswir1d2c639d2009-01-24 18:19:25 +0000107/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800108static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000109{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100110 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400111 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300112 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300113 "QEMU disk image utility\n"
114 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300115 " '-h', '--help' display this help and exit\n"
116 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300117 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300119 "\n"
malc3f020d72010-02-08 12:04:56 +0300120 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100121#define DEF(option, callback, arg_string) \
122 " " arg_string "\n"
123#include "qemu-img-cmds.h"
124#undef DEF
malc3f020d72010-02-08 12:04:56 +0300125 "\n"
126 "Command parameters:\n"
127 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000128 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
129 " manual page for a description of the object properties. The most common\n"
130 " object type is a 'secret', which is used to supply passwords and/or\n"
131 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300132 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400133 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800134 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
135 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100136 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
137 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300138 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200139 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
140 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
141 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300142 " 'output_filename' is the destination disk image filename\n"
143 " 'output_fmt' is the destination format\n"
144 " 'options' is a comma separated list of format specific options in a\n"
145 " name=value format. Use -o ? for an overview of the options supported by the\n"
146 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800147 " 'snapshot_param' is param used for internal snapshot, format\n"
148 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
149 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300150 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400151 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
152 " new backing file match exactly. The image doesn't need a working\n"
153 " backing file before rebasing in this case (useful for renaming the\n"
154 " backing file). For image creation, allow creating without attempting\n"
155 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300156 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200157 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100158 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200159 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
160 " contain only zeros for qemu-img to create a sparse image during\n"
161 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
162 " unallocated or zero sectors, and the destination image will always be\n"
163 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200164 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100165 " '-n' skips the target volume creation (useful if the volume is created\n"
166 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300167 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200168 "Parameters to check subcommand:\n"
169 " '-r' tries to repair any inconsistencies that are found during the check.\n"
170 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
171 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200172 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200173 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100174 "Parameters to convert subcommand:\n"
175 " '-m' specifies how many coroutines work in parallel during the convert\n"
176 " process (defaults to 8)\n"
177 " '-W' allow to write to the target out of order rather than sequential\n"
178 "\n"
malc3f020d72010-02-08 12:04:56 +0300179 "Parameters to snapshot subcommand:\n"
180 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
181 " '-a' applies a snapshot (revert disk to saved state)\n"
182 " '-c' creates a snapshot\n"
183 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100184 " '-l' lists all snapshots in the given image\n"
185 "\n"
186 "Parameters to compare subcommand:\n"
187 " '-f' first image format\n"
188 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200189 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
190 "\n"
191 "Parameters to dd subcommand:\n"
192 " 'bs=BYTES' read and write up to BYTES bytes at a time "
193 "(default: 512)\n"
194 " 'count=N' copy only N input blocks\n"
195 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200196 " 'of=FILE' write to FILE\n"
197 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100198
199 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300200 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500201 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800202 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000203}
204
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000205static QemuOptsList qemu_object_opts = {
206 .name = "object",
207 .implied_opt_name = "qom-type",
208 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
209 .desc = {
210 { }
211 },
212};
213
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000214static QemuOptsList qemu_source_opts = {
215 .name = "source",
216 .implied_opt_name = "file",
217 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
218 .desc = {
219 { }
220 },
221};
222
Stefan Weil7c30f652013-06-16 17:01:05 +0200223static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100224{
225 int ret = 0;
226 if (!quiet) {
227 va_list args;
228 va_start(args, fmt);
229 ret = vprintf(fmt, args);
230 va_end(args);
231 }
232 return ret;
233}
234
bellardea2384d2004-08-01 21:59:26 +0000235
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100236static int print_block_option_help(const char *filename, const char *fmt)
237{
238 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800239 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500240 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100241
242 /* Find driver and parse its options */
243 drv = bdrv_find_format(fmt);
244 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100245 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100246 return 1;
247 }
248
Max Reitzd402b6a2018-05-09 23:00:21 +0200249 if (!drv->create_opts) {
250 error_report("Format driver '%s' does not support image creation", fmt);
251 return 1;
252 }
253
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800254 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100255 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500256 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100257 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100258 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800259 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100260 return 1;
261 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200262 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100263 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200264 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100265 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200266 return 1;
267 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800268 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100269 }
270
Max Reitzf4619af2019-04-13 17:20:37 +0200271 if (filename) {
272 printf("Supported options:\n");
273 } else {
274 printf("Supported %s options:\n", fmt);
275 }
Max Reitz63898712018-10-19 18:49:25 +0200276 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800277 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200278
279 if (!filename) {
280 printf("\n"
281 "The protocol level may support further options.\n"
282 "Specify the target filename to include those options.\n");
283 }
284
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100285 return 0;
286}
287
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000288
Max Reitzefaa7c42016-03-16 19:54:38 +0100289static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100290 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800291 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000292{
293 QDict *options;
294 Error *local_err = NULL;
295 BlockBackend *blk;
296 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800297 if (force_share) {
298 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200299 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800300 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200301 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800302 return NULL;
303 }
Max Reitz4615f872018-05-02 22:20:50 +0200304 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800305 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100306 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000307 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100308 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000309 return NULL;
310 }
Kevin Wolfce099542016-03-15 13:01:04 +0100311 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000312
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000313 return blk;
314}
315
Max Reitzefaa7c42016-03-16 19:54:38 +0100316static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100317 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000318 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800319 bool writethrough, bool quiet,
320 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000321{
322 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200323 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100324
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100325 if (!options) {
326 options = qdict_new();
327 }
bellard75c23802004-08-27 21:28:58 +0000328 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500329 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000330 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100331
Fam Zheng335e9932017-05-03 00:35:39 +0800332 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500333 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800334 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100335 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500336 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100337 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000338 return NULL;
bellard75c23802004-08-27 21:28:58 +0000339 }
Kevin Wolfce099542016-03-15 13:01:04 +0100340 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100341
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200342 return blk;
bellard75c23802004-08-27 21:28:58 +0000343}
344
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000345
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100346static int img_add_key_secrets(void *opaque,
347 const char *name, const char *value,
348 Error **errp)
349{
350 QDict *options = opaque;
351
352 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600353 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100354 }
355
356 return 0;
357}
358
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100359
Max Reitzefaa7c42016-03-16 19:54:38 +0100360static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000361 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100362 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800363 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000364{
365 BlockBackend *blk;
366 if (image_opts) {
367 QemuOpts *opts;
368 if (fmt) {
369 error_report("--image-opts and --format are mutually exclusive");
370 return NULL;
371 }
372 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
373 filename, true);
374 if (!opts) {
375 return NULL;
376 }
Fam Zheng335e9932017-05-03 00:35:39 +0800377 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
378 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000379 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100380 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800381 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000382 }
383 return blk;
384}
385
386
Chunyan Liu83d05212014-06-05 17:20:51 +0800387static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100388 const char *base_filename,
389 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200390{
Markus Armbruster6750e792015-02-12 17:43:08 +0100391 Error *err = NULL;
392
Kevin Wolfefa84d42009-05-18 16:42:12 +0200393 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100394 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100395 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100396 error_report("Backing file not supported for file format '%s'",
397 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100398 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900399 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200400 }
401 }
402 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100403 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100404 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100405 error_report("Backing file format not supported for file "
406 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100407 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900408 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200409 }
410 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900411 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200412}
413
Markus Armbruster606caa02017-02-21 21:14:04 +0100414static int64_t cvtnum(const char *s)
415{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100416 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100417 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100418
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100419 err = qemu_strtosz(s, NULL, &value);
420 if (err < 0) {
421 return err;
422 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100423 if (value > INT64_MAX) {
424 return -ERANGE;
425 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100426 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100427}
428
bellardea2384d2004-08-01 21:59:26 +0000429static int img_create(int argc, char **argv)
430{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200431 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100432 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000433 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000434 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000435 const char *filename;
436 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200437 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200438 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100439 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400440 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000441
bellardea2384d2004-08-01 21:59:26 +0000442 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000443 static const struct option long_options[] = {
444 {"help", no_argument, 0, 'h'},
445 {"object", required_argument, 0, OPTION_OBJECT},
446 {0, 0, 0, 0}
447 };
John Snow6e6e55f2017-07-17 20:34:22 -0400448 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000449 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100450 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000451 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100452 }
bellardea2384d2004-08-01 21:59:26 +0000453 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800454 case ':':
455 missing_argument(argv[optind - 1]);
456 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100457 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800458 unrecognized_option(argv[optind - 1]);
459 break;
bellardea2384d2004-08-01 21:59:26 +0000460 case 'h':
461 help();
462 break;
aliguori9230eaf2009-03-28 17:55:19 +0000463 case 'F':
464 base_fmt = optarg;
465 break;
bellardea2384d2004-08-01 21:59:26 +0000466 case 'b':
467 base_filename = optarg;
468 break;
469 case 'f':
470 fmt = optarg;
471 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200472 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100473 if (!is_valid_option_list(optarg)) {
474 error_report("Invalid option list: %s", optarg);
475 goto fail;
476 }
477 if (!options) {
478 options = g_strdup(optarg);
479 } else {
480 char *old_options = options;
481 options = g_strdup_printf("%s,%s", options, optarg);
482 g_free(old_options);
483 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200484 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100485 case 'q':
486 quiet = true;
487 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400488 case 'u':
489 flags |= BDRV_O_NO_BACKING;
490 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000491 case OPTION_OBJECT: {
492 QemuOpts *opts;
493 opts = qemu_opts_parse_noisily(&qemu_object_opts,
494 optarg, true);
495 if (!opts) {
496 goto fail;
497 }
498 } break;
bellardea2384d2004-08-01 21:59:26 +0000499 }
500 }
aliguori9230eaf2009-03-28 17:55:19 +0000501
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900502 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100503 filename = (optind < argc) ? argv[optind] : NULL;
504 if (options && has_help_option(options)) {
505 g_free(options);
506 return print_block_option_help(filename, fmt);
507 }
508
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100509 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800510 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100511 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100512 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900513
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000514 if (qemu_opts_foreach(&qemu_object_opts,
515 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000516 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000517 goto fail;
518 }
519
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100520 /* Get image size, if specified */
521 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100522 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100523
524 sval = cvtnum(argv[optind++]);
525 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800526 if (sval == -ERANGE) {
527 error_report("Image size must be less than 8 EiB!");
528 } else {
529 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200530 "G, T, P or E suffixes for ");
531 error_report("kilobytes, megabytes, gigabytes, terabytes, "
532 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800533 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100534 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100535 }
536 img_size = (uint64_t)sval;
537 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200538 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800539 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200540 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100541
Luiz Capitulino9b375252012-11-30 10:52:05 -0200542 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400543 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100544 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100545 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100546 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900547 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200548
Kevin Wolf77386bf2014-02-21 16:24:04 +0100549 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000550 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100551
552fail:
553 g_free(options);
554 return 1;
bellardea2384d2004-08-01 21:59:26 +0000555}
556
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100557static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500558{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500559 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100561 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600562
563 visit_type_ImageCheck(v, NULL, &check, &error_abort);
564 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500565 str = qobject_to_json_pretty(obj);
566 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100567 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200568 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600569 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200570 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500571}
572
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100573static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500574{
575 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100576 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500577 } else {
578 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100579 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
580 "Data may be corrupted, or further writes to the image "
581 "may corrupt it.\n",
582 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500583 }
584
585 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100586 qprintf(quiet,
587 "\n%" PRId64 " leaked clusters were found on the image.\n"
588 "This means waste of disk space, but no harm to data.\n",
589 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500590 }
591
592 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100593 qprintf(quiet,
594 "\n%" PRId64
595 " internal errors have occurred during the check.\n",
596 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500597 }
598 }
599
600 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100601 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
602 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
603 check->allocated_clusters, check->total_clusters,
604 check->allocated_clusters * 100.0 / check->total_clusters,
605 check->fragmented_clusters * 100.0 / check->allocated_clusters,
606 check->compressed_clusters * 100.0 /
607 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608 }
609
610 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100611 qprintf(quiet,
612 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500613 }
614}
615
616static int collect_image_check(BlockDriverState *bs,
617 ImageCheck *check,
618 const char *filename,
619 const char *fmt,
620 int fix)
621{
622 int ret;
623 BdrvCheckResult result;
624
625 ret = bdrv_check(bs, &result, fix);
626 if (ret < 0) {
627 return ret;
628 }
629
630 check->filename = g_strdup(filename);
631 check->format = g_strdup(bdrv_get_format_name(bs));
632 check->check_errors = result.check_errors;
633 check->corruptions = result.corruptions;
634 check->has_corruptions = result.corruptions != 0;
635 check->leaks = result.leaks;
636 check->has_leaks = result.leaks != 0;
637 check->corruptions_fixed = result.corruptions_fixed;
638 check->has_corruptions_fixed = result.corruptions != 0;
639 check->leaks_fixed = result.leaks_fixed;
640 check->has_leaks_fixed = result.leaks != 0;
641 check->image_end_offset = result.image_end_offset;
642 check->has_image_end_offset = result.image_end_offset != 0;
643 check->total_clusters = result.bfi.total_clusters;
644 check->has_total_clusters = result.bfi.total_clusters != 0;
645 check->allocated_clusters = result.bfi.allocated_clusters;
646 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
647 check->fragmented_clusters = result.bfi.fragmented_clusters;
648 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100649 check->compressed_clusters = result.bfi.compressed_clusters;
650 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500651
652 return 0;
653}
654
Kevin Wolfe076f332010-06-29 11:43:13 +0200655/*
656 * Checks an image for consistency. Exit codes:
657 *
Max Reitzd6635c42014-06-02 22:15:21 +0200658 * 0 - Check completed, image is good
659 * 1 - Check not completed because of internal errors
660 * 2 - Check completed, image is corrupted
661 * 3 - Check completed, image has leaked clusters, but is good otherwise
662 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200663 */
aliguori15859692009-04-21 23:11:53 +0000664static int img_check(int argc, char **argv)
665{
666 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500667 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200668 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200669 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000670 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200671 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100672 int flags = BDRV_O_CHECK;
673 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200674 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100675 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000676 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800677 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000678
679 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500680 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200681 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100682
aliguori15859692009-04-21 23:11:53 +0000683 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 int option_index = 0;
685 static const struct option long_options[] = {
686 {"help", no_argument, 0, 'h'},
687 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530688 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500689 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000690 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000691 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800692 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500693 {0, 0, 0, 0}
694 };
Fam Zheng335e9932017-05-03 00:35:39 +0800695 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500696 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100697 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000698 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100699 }
aliguori15859692009-04-21 23:11:53 +0000700 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800701 case ':':
702 missing_argument(argv[optind - 1]);
703 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100704 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800705 unrecognized_option(argv[optind - 1]);
706 break;
aliguori15859692009-04-21 23:11:53 +0000707 case 'h':
708 help();
709 break;
710 case 'f':
711 fmt = optarg;
712 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200713 case 'r':
714 flags |= BDRV_O_RDWR;
715
716 if (!strcmp(optarg, "leaks")) {
717 fix = BDRV_FIX_LEAKS;
718 } else if (!strcmp(optarg, "all")) {
719 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
720 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800721 error_exit("Unknown option value for -r "
722 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200723 }
724 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500725 case OPTION_OUTPUT:
726 output = optarg;
727 break;
Max Reitz40055952014-07-22 22:58:42 +0200728 case 'T':
729 cache = optarg;
730 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100731 case 'q':
732 quiet = true;
733 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800734 case 'U':
735 force_share = true;
736 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000737 case OPTION_OBJECT: {
738 QemuOpts *opts;
739 opts = qemu_opts_parse_noisily(&qemu_object_opts,
740 optarg, true);
741 if (!opts) {
742 return 1;
743 }
744 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000745 case OPTION_IMAGE_OPTS:
746 image_opts = true;
747 break;
aliguori15859692009-04-21 23:11:53 +0000748 }
749 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200750 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800751 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100752 }
aliguori15859692009-04-21 23:11:53 +0000753 filename = argv[optind++];
754
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500755 if (output && !strcmp(output, "json")) {
756 output_format = OFORMAT_JSON;
757 } else if (output && !strcmp(output, "human")) {
758 output_format = OFORMAT_HUMAN;
759 } else if (output) {
760 error_report("--output must be used with human or json as argument.");
761 return 1;
762 }
763
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000764 if (qemu_opts_foreach(&qemu_object_opts,
765 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000766 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000767 return 1;
768 }
769
Kevin Wolfce099542016-03-15 13:01:04 +0100770 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200771 if (ret < 0) {
772 error_report("Invalid source cache option: %s", cache);
773 return 1;
774 }
775
Fam Zheng335e9932017-05-03 00:35:39 +0800776 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
777 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200778 if (!blk) {
779 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900780 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200781 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500782
783 check = g_new0(ImageCheck, 1);
784 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200785
786 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200787 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200788 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500789 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200790 }
791
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500792 if (check->corruptions_fixed || check->leaks_fixed) {
793 int corruptions_fixed, leaks_fixed;
794
795 leaks_fixed = check->leaks_fixed;
796 corruptions_fixed = check->corruptions_fixed;
797
798 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100799 qprintf(quiet,
800 "The following inconsistencies were found and repaired:\n\n"
801 " %" PRId64 " leaked clusters\n"
802 " %" PRId64 " corruptions\n\n"
803 "Double checking the fixed image now...\n",
804 check->leaks_fixed,
805 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500806 }
807
808 ret = collect_image_check(bs, check, filename, fmt, 0);
809
810 check->leaks_fixed = leaks_fixed;
811 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200812 }
813
Max Reitz832390a2014-10-23 15:29:12 +0200814 if (!ret) {
815 switch (output_format) {
816 case OFORMAT_HUMAN:
817 dump_human_image_check(check, quiet);
818 break;
819 case OFORMAT_JSON:
820 dump_json_image_check(check, quiet);
821 break;
822 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500823 }
824
825 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200826 if (ret) {
827 error_report("Check failed: %s", strerror(-ret));
828 } else {
829 error_report("Check failed");
830 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500831 ret = 1;
832 goto fail;
833 }
834
835 if (check->corruptions) {
836 ret = 2;
837 } else if (check->leaks) {
838 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200839 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500840 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000841 }
842
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500843fail:
844 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200845 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500846 return ret;
aliguori15859692009-04-21 23:11:53 +0000847}
848
Max Reitzd4a32382014-10-24 15:57:37 +0200849typedef struct CommonBlockJobCBInfo {
850 BlockDriverState *bs;
851 Error **errp;
852} CommonBlockJobCBInfo;
853
854static void common_block_job_cb(void *opaque, int ret)
855{
856 CommonBlockJobCBInfo *cbi = opaque;
857
858 if (ret < 0) {
859 error_setg_errno(cbi->errp, -ret, "Block job failed");
860 }
Max Reitzd4a32382014-10-24 15:57:37 +0200861}
862
863static void run_block_job(BlockJob *job, Error **errp)
864{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200865 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800866 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200867
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200868 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200869 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200870 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200871 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200872 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200873 if (job->job.progress_total) {
874 progress = (float)job->job.progress_current /
875 job->job.progress_total * 100.f;
876 }
877 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200878 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200879
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200880 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200881 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800882 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200883 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800884 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200885 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200886 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200887
sochin.jiang4172a002017-06-15 14:47:33 +0800888 /* publish completion progress only when success */
889 if (!ret) {
890 qemu_progress_print(100.f, 0);
891 }
Max Reitzd4a32382014-10-24 15:57:37 +0200892}
893
bellardea2384d2004-08-01 21:59:26 +0000894static int img_commit(int argc, char **argv)
895{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400896 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200897 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200898 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200899 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100900 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200901 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100902 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200903 Error *local_err = NULL;
904 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000905 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200906 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000907
908 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400909 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200910 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000911 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000912 static const struct option long_options[] = {
913 {"help", no_argument, 0, 'h'},
914 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000915 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000916 {0, 0, 0, 0}
917 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800918 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000919 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100920 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000921 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100922 }
bellardea2384d2004-08-01 21:59:26 +0000923 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800924 case ':':
925 missing_argument(argv[optind - 1]);
926 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100927 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800928 unrecognized_option(argv[optind - 1]);
929 break;
bellardea2384d2004-08-01 21:59:26 +0000930 case 'h':
931 help();
932 break;
933 case 'f':
934 fmt = optarg;
935 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400936 case 't':
937 cache = optarg;
938 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200939 case 'b':
940 base = optarg;
941 /* -b implies -d */
942 drop = true;
943 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200944 case 'd':
945 drop = true;
946 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200947 case 'p':
948 progress = true;
949 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100950 case 'q':
951 quiet = true;
952 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000953 case OPTION_OBJECT: {
954 QemuOpts *opts;
955 opts = qemu_opts_parse_noisily(&qemu_object_opts,
956 optarg, true);
957 if (!opts) {
958 return 1;
959 }
960 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000961 case OPTION_IMAGE_OPTS:
962 image_opts = true;
963 break;
bellardea2384d2004-08-01 21:59:26 +0000964 }
965 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200966
967 /* Progress is not shown in Quiet mode */
968 if (quiet) {
969 progress = false;
970 }
971
Kevin Wolffc11eb22013-08-05 10:53:04 +0200972 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800973 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100974 }
bellardea2384d2004-08-01 21:59:26 +0000975 filename = argv[optind++];
976
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000977 if (qemu_opts_foreach(&qemu_object_opts,
978 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000979 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000980 return 1;
981 }
982
Max Reitz9a86fe42014-10-24 15:57:38 +0200983 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100984 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400985 if (ret < 0) {
986 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100987 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400988 }
989
Fam Zheng335e9932017-05-03 00:35:39 +0800990 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
991 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200992 if (!blk) {
993 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900994 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200995 bs = blk_bs(blk);
996
Max Reitz687fa1d2014-10-24 15:57:39 +0200997 qemu_progress_init(progress, 1.f);
998 qemu_progress_print(0.f, 100);
999
Max Reitz1b22bff2014-10-24 15:57:40 +02001000 if (base) {
1001 base_bs = bdrv_find_backing_image(bs, base);
1002 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001003 error_setg(&local_err,
1004 "Did not find '%s' in the backing chain of '%s'",
1005 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001006 goto done;
1007 }
1008 } else {
1009 /* This is different from QMP, which by default uses the deepest file in
1010 * the backing chain (i.e., the very base); however, the traditional
1011 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001012 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001013 if (!base_bs) {
1014 error_setg(&local_err, "Image does not have a backing file");
1015 goto done;
1016 }
bellardea2384d2004-08-01 21:59:26 +00001017 }
1018
Max Reitzd4a32382014-10-24 15:57:37 +02001019 cbi = (CommonBlockJobCBInfo){
1020 .errp = &local_err,
1021 .bs = bs,
1022 };
1023
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001024 aio_context = bdrv_get_aio_context(bs);
1025 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001026 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001027 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001028 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001029 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001030 if (local_err) {
1031 goto done;
1032 }
1033
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001034 /* When the block job completes, the BlockBackend reference will point to
1035 * the old backing file. In order to avoid that the top image is already
1036 * deleted, so we can still empty it afterwards, increment the reference
1037 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001038 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001039 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001040 }
1041
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001042 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001043 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001044 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001045 if (local_err) {
1046 goto unref_backing;
1047 }
1048
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001049 if (!drop && bs->drv->bdrv_make_empty) {
1050 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001051 if (ret) {
1052 error_setg_errno(&local_err, -ret, "Could not empty %s",
1053 filename);
1054 goto unref_backing;
1055 }
1056 }
1057
1058unref_backing:
1059 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001060 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001061 }
Max Reitzd4a32382014-10-24 15:57:37 +02001062
1063done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001064 qemu_progress_end();
1065
Markus Armbruster26f54e92014-10-07 13:59:04 +02001066 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001067
1068 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001069 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001070 return 1;
1071 }
Max Reitzd4a32382014-10-24 15:57:37 +02001072
1073 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001074 return 0;
1075}
1076
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001077/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001078 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1079 * of the first sector boundary within buf where the sector contains a
1080 * non-zero byte. This function is robust to a buffer that is not
1081 * sector-aligned.
1082 */
1083static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1084{
1085 int64_t i;
1086 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1087
1088 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1089 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1090 return i;
1091 }
1092 }
1093 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1094 return i;
1095 }
1096 return -1;
1097}
1098
1099/*
thsf58c7b32008-06-05 21:53:49 +00001100 * Returns true iff the first sector pointed to by 'buf' contains at least
1101 * a non-NUL byte.
1102 *
1103 * 'pnum' is set to the number of sectors (including and immediately following
1104 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001105 * The function will try to align the end offset to alignment boundaries so
1106 * that the request will at least end aligned and consequtive requests will
1107 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001108 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001109static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1110 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001111{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001112 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001113 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001114
1115 if (n <= 0) {
1116 *pnum = 0;
1117 return 0;
1118 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001119 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001120 for(i = 1; i < n; i++) {
1121 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001122 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001123 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001124 }
bellardea2384d2004-08-01 21:59:26 +00001125 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001126
1127 tail = (sector_num + i) & (alignment - 1);
1128 if (tail) {
1129 if (is_zero && i <= tail) {
1130 /* treat unallocated areas which only consist
1131 * of a small tail as allocated. */
1132 is_zero = false;
1133 }
1134 if (!is_zero) {
1135 /* align up end offset of allocated areas. */
1136 i += alignment - tail;
1137 i = MIN(i, n);
1138 } else {
1139 /* align down end offset of zero areas. */
1140 i -= tail;
1141 }
1142 }
bellardea2384d2004-08-01 21:59:26 +00001143 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001144 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001145}
1146
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001147/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001148 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1149 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1150 * breaking up write requests for only small sparse areas.
1151 */
1152static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001153 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001154{
1155 int ret;
1156 int num_checked, num_used;
1157
1158 if (n < min) {
1159 min = n;
1160 }
1161
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001162 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001163 if (!ret) {
1164 return ret;
1165 }
1166
1167 num_used = *pnum;
1168 buf += BDRV_SECTOR_SIZE * *pnum;
1169 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001170 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001171 num_checked = num_used;
1172
1173 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001174 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001175
1176 buf += BDRV_SECTOR_SIZE * *pnum;
1177 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001178 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001179 num_checked += *pnum;
1180 if (ret) {
1181 num_used = num_checked;
1182 } else if (*pnum >= min) {
1183 break;
1184 }
1185 }
1186
1187 *pnum = num_used;
1188 return 1;
1189}
1190
1191/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001192 * Compares two buffers sector by sector. Returns 0 if the first
1193 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001194 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001195 * pnum is set to the sector-aligned size of the buffer prefix that
1196 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001197 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001198static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1199 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001200{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001201 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001202 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001203
Eric Blakedc61cd32017-10-11 22:47:14 -05001204 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001205
Eric Blakedc61cd32017-10-11 22:47:14 -05001206 res = !!memcmp(buf1, buf2, i);
1207 while (i < bytes) {
1208 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001209
Eric Blakedc61cd32017-10-11 22:47:14 -05001210 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001211 break;
1212 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001213 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001214 }
1215
1216 *pnum = i;
1217 return res;
1218}
1219
Stefano Garzarella97ede572019-05-08 12:43:24 +02001220#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001221
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001222/*
1223 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1224 *
Eric Blake0608e402017-10-11 22:47:12 -05001225 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1226 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1227 * failure), and 4 on error (the exit status for read errors), after emitting
1228 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001229 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001230 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001231 * @param offset: Starting offset to check
1232 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001233 * @param filename: Name of disk file we are checking (logging purpose)
1234 * @param buffer: Allocated buffer for storing read data
1235 * @param quiet: Flag for quiet mode
1236 */
Eric Blakec41508e2017-10-11 22:47:13 -05001237static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1238 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001239 uint8_t *buffer, bool quiet)
1240{
Eric Blakedebb38a2017-10-11 22:47:11 -05001241 int ret = 0;
1242 int64_t idx;
1243
Eric Blakec41508e2017-10-11 22:47:13 -05001244 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001245 if (ret < 0) {
1246 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001247 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001248 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001249 }
Eric Blakec41508e2017-10-11 22:47:13 -05001250 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001251 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001252 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001253 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001254 return 1;
1255 }
1256
1257 return 0;
1258}
1259
1260/*
1261 * Compares two images. Exit codes:
1262 *
1263 * 0 - Images are identical
1264 * 1 - Images differ
1265 * >1 - Error occurred
1266 */
1267static int img_compare(int argc, char **argv)
1268{
Max Reitz40055952014-07-22 22:58:42 +02001269 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001270 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001271 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001272 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001273 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001274 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001275 int allocated1, allocated2;
1276 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1277 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001278 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001279 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001280 int64_t total_size;
1281 int64_t offset = 0;
1282 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001283 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001284 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001285 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001286 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287
Max Reitz40055952014-07-22 22:58:42 +02001288 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001289 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001290 static const struct option long_options[] = {
1291 {"help", no_argument, 0, 'h'},
1292 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001293 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001294 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001295 {0, 0, 0, 0}
1296 };
Fam Zheng335e9932017-05-03 00:35:39 +08001297 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001298 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001299 if (c == -1) {
1300 break;
1301 }
1302 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001303 case ':':
1304 missing_argument(argv[optind - 1]);
1305 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001306 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001307 unrecognized_option(argv[optind - 1]);
1308 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001309 case 'h':
1310 help();
1311 break;
1312 case 'f':
1313 fmt1 = optarg;
1314 break;
1315 case 'F':
1316 fmt2 = optarg;
1317 break;
Max Reitz40055952014-07-22 22:58:42 +02001318 case 'T':
1319 cache = optarg;
1320 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001321 case 'p':
1322 progress = true;
1323 break;
1324 case 'q':
1325 quiet = true;
1326 break;
1327 case 's':
1328 strict = true;
1329 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001330 case 'U':
1331 force_share = true;
1332 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001333 case OPTION_OBJECT: {
1334 QemuOpts *opts;
1335 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1336 optarg, true);
1337 if (!opts) {
1338 ret = 2;
1339 goto out4;
1340 }
1341 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001342 case OPTION_IMAGE_OPTS:
1343 image_opts = true;
1344 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001345 }
1346 }
1347
1348 /* Progress is not shown in Quiet mode */
1349 if (quiet) {
1350 progress = false;
1351 }
1352
1353
Kevin Wolffc11eb22013-08-05 10:53:04 +02001354 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001355 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001356 }
1357 filename1 = argv[optind++];
1358 filename2 = argv[optind++];
1359
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001360 if (qemu_opts_foreach(&qemu_object_opts,
1361 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00001362 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001363 ret = 2;
1364 goto out4;
1365 }
1366
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001367 /* Initialize before goto out */
1368 qemu_progress_init(progress, 2.0);
1369
Kevin Wolfce099542016-03-15 13:01:04 +01001370 flags = 0;
1371 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001372 if (ret < 0) {
1373 error_report("Invalid source cache option: %s", cache);
1374 ret = 2;
1375 goto out3;
1376 }
1377
Fam Zheng335e9932017-05-03 00:35:39 +08001378 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1379 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001380 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001381 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001382 goto out3;
1383 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001384
Fam Zheng335e9932017-05-03 00:35:39 +08001385 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1386 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001387 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001388 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001389 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001390 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001391 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001392 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001393
Max Reitzf1d3cd72015-02-05 13:58:18 -05001394 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1395 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001396 total_size1 = blk_getlength(blk1);
1397 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001398 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001399 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001400 ret = 4;
1401 goto out;
1402 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001403 total_size2 = blk_getlength(blk2);
1404 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001405 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001406 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001407 ret = 4;
1408 goto out;
1409 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001410 total_size = MIN(total_size1, total_size2);
1411 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001412
1413 qemu_progress_print(0, 100);
1414
Eric Blake033d9fc2017-10-11 22:47:16 -05001415 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001416 ret = 1;
1417 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1418 goto out;
1419 }
1420
Eric Blake033d9fc2017-10-11 22:47:16 -05001421 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001422 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001423
Eric Blake033d9fc2017-10-11 22:47:16 -05001424 status1 = bdrv_block_status_above(bs1, NULL, offset,
1425 total_size1 - offset, &pnum1, NULL,
1426 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001427 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001428 ret = 3;
1429 error_report("Sector allocation test failed for %s", filename1);
1430 goto out;
1431 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001432 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001433
Eric Blake033d9fc2017-10-11 22:47:16 -05001434 status2 = bdrv_block_status_above(bs2, NULL, offset,
1435 total_size2 - offset, &pnum2, NULL,
1436 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001437 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001438 ret = 3;
1439 error_report("Sector allocation test failed for %s", filename2);
1440 goto out;
1441 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001442 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001443
1444 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001445 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001446
Fam Zheng25ad8e62016-01-13 16:37:41 +08001447 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001448 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001449 ret = 1;
1450 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001451 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001452 goto out;
1453 }
1454 }
1455 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001456 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001457 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001458 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001459 int64_t pnum;
1460
Eric Blake033d9fc2017-10-11 22:47:16 -05001461 chunk = MIN(chunk, IO_BUF_SIZE);
1462 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001463 if (ret < 0) {
1464 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001465 " of %s: %s",
1466 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001467 ret = 4;
1468 goto out;
1469 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001470 ret = blk_pread(blk2, offset, buf2, chunk);
1471 if (ret < 0) {
1472 error_report("Error while reading offset %" PRId64
1473 " of %s: %s",
1474 offset, filename2, strerror(-ret));
1475 ret = 4;
1476 goto out;
1477 }
1478 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1479 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001480 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001481 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001482 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001483 goto out;
1484 }
1485 }
1486 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001487 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001488 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001489 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001490 filename1, buf1, quiet);
1491 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001493 filename2, buf1, quiet);
1494 }
1495 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001496 goto out;
1497 }
1498 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001499 offset += chunk;
1500 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001501 }
1502
Eric Blake033d9fc2017-10-11 22:47:16 -05001503 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001504 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001505 const char *filename_over;
1506
1507 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001508 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001509 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001510 filename_over = filename1;
1511 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001512 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001513 filename_over = filename2;
1514 }
1515
Eric Blake033d9fc2017-10-11 22:47:16 -05001516 while (offset < progress_base) {
1517 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1518 progress_base - offset, &chunk,
1519 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001520 if (ret < 0) {
1521 ret = 3;
1522 error_report("Sector allocation test failed for %s",
1523 filename_over);
1524 goto out;
1525
1526 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001527 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001528 chunk = MIN(chunk, IO_BUF_SIZE);
1529 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001530 filename_over, buf1, quiet);
1531 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 goto out;
1533 }
1534 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001535 offset += chunk;
1536 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001537 }
1538 }
1539
1540 qprintf(quiet, "Images are identical.\n");
1541 ret = 0;
1542
1543out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001544 qemu_vfree(buf1);
1545 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001546 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001547out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001548 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001549out3:
1550 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001551out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001552 return ret;
1553}
1554
Kevin Wolf690c7302015-03-19 13:33:32 +01001555enum ImgConvertBlockStatus {
1556 BLK_DATA,
1557 BLK_ZERO,
1558 BLK_BACKING_FILE,
1559};
1560
Peter Lieven2d9187b2017-02-28 13:40:07 +01001561#define MAX_COROUTINES 16
1562
Kevin Wolf690c7302015-03-19 13:33:32 +01001563typedef struct ImgConvertState {
1564 BlockBackend **src;
1565 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001566 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001567 int64_t total_sectors;
1568 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001569 int64_t allocated_done;
1570 int64_t sector_num;
1571 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001572 enum ImgConvertBlockStatus status;
1573 int64_t sector_next_status;
1574 BlockBackend *target;
1575 bool has_zero_init;
1576 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001577 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001578 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001579 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001580 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001581 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001582 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001583 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001584 size_t cluster_sectors;
1585 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001586 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001587 int running_coroutines;
1588 Coroutine *co[MAX_COROUTINES];
1589 int64_t wait_sector_num[MAX_COROUTINES];
1590 CoMutex lock;
1591 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001592} ImgConvertState;
1593
Peter Lieven2d9187b2017-02-28 13:40:07 +01001594static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1595 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001596{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001597 *src_cur = 0;
1598 *src_cur_offset = 0;
1599 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1600 *src_cur_offset += s->src_sectors[*src_cur];
1601 (*src_cur)++;
1602 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001603 }
1604}
1605
1606static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1607{
Eric Blake31826642017-10-11 22:47:08 -05001608 int64_t src_cur_offset;
1609 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001610 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001611
Peter Lieven2d9187b2017-02-28 13:40:07 +01001612 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001613
1614 assert(s->total_sectors > sector_num);
1615 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1616
Max Reitz351c8ef2018-05-01 18:57:49 +02001617 if (s->target_backing_sectors >= 0) {
1618 if (sector_num >= s->target_backing_sectors) {
1619 post_backing_zero = s->unallocated_blocks_are_zero;
1620 } else if (sector_num + n > s->target_backing_sectors) {
1621 /* Split requests around target_backing_sectors (because
1622 * starting from there, zeros are handled differently) */
1623 n = s->target_backing_sectors - sector_num;
1624 }
1625 }
1626
Kevin Wolf690c7302015-03-19 13:33:32 +01001627 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001628 int64_t count = n * BDRV_SECTOR_SIZE;
1629
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001630 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001631
1632 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1633 (sector_num - src_cur_offset) *
1634 BDRV_SECTOR_SIZE,
1635 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001636 } else {
Eric Blake31826642017-10-11 22:47:08 -05001637 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1638 (sector_num - src_cur_offset) *
1639 BDRV_SECTOR_SIZE,
1640 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001641 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001642 if (ret < 0) {
Eric Blake2058c2a2019-03-23 16:26:38 -05001643 error_report("error while reading block status of sector %" PRId64
1644 ": %s", sector_num, strerror(-ret));
Kevin Wolf690c7302015-03-19 13:33:32 +01001645 return ret;
1646 }
Eric Blake31826642017-10-11 22:47:08 -05001647 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001648
1649 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001650 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001651 } else if (ret & BDRV_BLOCK_DATA) {
1652 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001653 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001654 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001655 }
1656
1657 s->sector_next_status = sector_num + n;
1658 }
1659
1660 n = MIN(n, s->sector_next_status - sector_num);
1661 if (s->status == BLK_DATA) {
1662 n = MIN(n, s->buf_sectors);
1663 }
1664
1665 /* We need to write complete clusters for compressed images, so if an
1666 * unallocated area is shorter than that, we must consider the whole
1667 * cluster allocated. */
1668 if (s->compressed) {
1669 if (n < s->cluster_sectors) {
1670 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1671 s->status = BLK_DATA;
1672 } else {
1673 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1674 }
1675 }
1676
1677 return n;
1678}
1679
Peter Lieven2d9187b2017-02-28 13:40:07 +01001680static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1681 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001682{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001683 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001684
Kevin Wolf690c7302015-03-19 13:33:32 +01001685 assert(nb_sectors <= s->buf_sectors);
1686 while (nb_sectors > 0) {
1687 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001688 int src_cur;
1689 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001690
1691 /* In the case of compression with multiple source files, we can get a
1692 * nb_sectors that spreads into the next part. So we must be able to
1693 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001694 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1695 blk = s->src[src_cur];
1696 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001697
Peter Lieven2d9187b2017-02-28 13:40:07 +01001698 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
Peter Lieven2d9187b2017-02-28 13:40:07 +01001699
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001700 ret = blk_co_pread(
Peter Lieven2d9187b2017-02-28 13:40:07 +01001701 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001702 n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001703 if (ret < 0) {
1704 return ret;
1705 }
1706
1707 sector_num += n;
1708 nb_sectors -= n;
1709 buf += n * BDRV_SECTOR_SIZE;
1710 }
1711
1712 return 0;
1713}
1714
Peter Lieven2d9187b2017-02-28 13:40:07 +01001715
1716static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1717 int nb_sectors, uint8_t *buf,
1718 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001719{
1720 int ret;
1721
1722 while (nb_sectors > 0) {
1723 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001724 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1725
Peter Lieven2d9187b2017-02-28 13:40:07 +01001726 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001727 case BLK_BACKING_FILE:
1728 /* If we have a backing file, leave clusters unallocated that are
1729 * unallocated in the source image, so that the backing file is
1730 * visible at the respective offset. */
1731 assert(s->target_has_backing);
1732 break;
1733
1734 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001735 /* If we're told to keep the target fully allocated (-S 0) or there
1736 * is real non-zero data, we must write it. Otherwise we can treat
1737 * it as zero sectors.
1738 * Compressed clusters need to be written as a whole, so in that
1739 * case we can only save the write if the buffer is completely
1740 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001741 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001742 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001743 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1744 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001745 (s->compressed &&
1746 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001747 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001748 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1749 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001750 if (ret < 0) {
1751 return ret;
1752 }
1753 break;
1754 }
1755 /* fall-through */
1756
1757 case BLK_ZERO:
1758 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001759 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001760 break;
1761 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001762 ret = blk_co_pwrite_zeroes(s->target,
1763 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001764 n << BDRV_SECTOR_BITS,
1765 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001766 if (ret < 0) {
1767 return ret;
1768 }
1769 break;
1770 }
1771
1772 sector_num += n;
1773 nb_sectors -= n;
1774 buf += n * BDRV_SECTOR_SIZE;
1775 }
1776
1777 return 0;
1778}
1779
Fam Zhengee5306d2018-06-01 17:26:48 +08001780static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1781 int nb_sectors)
1782{
1783 int n, ret;
1784
1785 while (nb_sectors > 0) {
1786 BlockBackend *blk;
1787 int src_cur;
1788 int64_t bs_sectors, src_cur_offset;
1789 int64_t offset;
1790
1791 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1792 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1793 blk = s->src[src_cur];
1794 bs_sectors = s->src_sectors[src_cur];
1795
1796 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1797
1798 ret = blk_co_copy_range(blk, offset, s->target,
1799 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001800 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001801 if (ret < 0) {
1802 return ret;
1803 }
1804
1805 sector_num += n;
1806 nb_sectors -= n;
1807 }
1808 return 0;
1809}
1810
Peter Lieven2d9187b2017-02-28 13:40:07 +01001811static void coroutine_fn convert_co_do_copy(void *opaque)
1812{
1813 ImgConvertState *s = opaque;
1814 uint8_t *buf = NULL;
1815 int ret, i;
1816 int index = -1;
1817
1818 for (i = 0; i < s->num_coroutines; i++) {
1819 if (s->co[i] == qemu_coroutine_self()) {
1820 index = i;
1821 break;
1822 }
1823 }
1824 assert(index >= 0);
1825
1826 s->running_coroutines++;
1827 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1828
1829 while (1) {
1830 int n;
1831 int64_t sector_num;
1832 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001833 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001834
1835 qemu_co_mutex_lock(&s->lock);
1836 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1837 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001838 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001839 }
1840 n = convert_iteration_sectors(s, s->sector_num);
1841 if (n < 0) {
1842 qemu_co_mutex_unlock(&s->lock);
1843 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001844 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001845 }
1846 /* save current sector and allocation status to local variables */
1847 sector_num = s->sector_num;
1848 status = s->status;
1849 if (!s->min_sparse && s->status == BLK_ZERO) {
1850 n = MIN(n, s->buf_sectors);
1851 }
1852 /* increment global sector counter so that other coroutines can
1853 * already continue reading beyond this request */
1854 s->sector_num += n;
1855 qemu_co_mutex_unlock(&s->lock);
1856
1857 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1858 s->allocated_done += n;
1859 qemu_progress_print(100.0 * s->allocated_done /
1860 s->allocated_sectors, 0);
1861 }
1862
Fam Zhengee5306d2018-06-01 17:26:48 +08001863retry:
1864 copy_range = s->copy_range && s->status == BLK_DATA;
1865 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001866 ret = convert_co_read(s, sector_num, n, buf);
1867 if (ret < 0) {
1868 error_report("error while reading sector %" PRId64
1869 ": %s", sector_num, strerror(-ret));
1870 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001871 }
1872 } else if (!s->min_sparse && status == BLK_ZERO) {
1873 status = BLK_DATA;
1874 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1875 }
1876
1877 if (s->wr_in_order) {
1878 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001879 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001880 s->wait_sector_num[index] = sector_num;
1881 qemu_coroutine_yield();
1882 }
1883 s->wait_sector_num[index] = -1;
1884 }
1885
Anton Nefedovb91127e2017-04-26 11:33:15 +03001886 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001887 if (copy_range) {
1888 ret = convert_co_copy_range(s, sector_num, n);
1889 if (ret) {
1890 s->copy_range = false;
1891 goto retry;
1892 }
1893 } else {
1894 ret = convert_co_write(s, sector_num, n, buf, status);
1895 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001896 if (ret < 0) {
1897 error_report("error while writing sector %" PRId64
1898 ": %s", sector_num, strerror(-ret));
1899 s->ret = ret;
1900 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001901 }
1902
1903 if (s->wr_in_order) {
1904 /* reenter the coroutine that might have waited
1905 * for this write to complete */
1906 s->wr_offs = sector_num + n;
1907 for (i = 0; i < s->num_coroutines; i++) {
1908 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1909 /*
1910 * A -> B -> A cannot occur because A has
1911 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1912 * B will never enter A during this time window.
1913 */
1914 qemu_coroutine_enter(s->co[i]);
1915 break;
1916 }
1917 }
1918 }
1919 }
1920
Peter Lieven2d9187b2017-02-28 13:40:07 +01001921 qemu_vfree(buf);
1922 s->co[index] = NULL;
1923 s->running_coroutines--;
1924 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1925 /* the convert job finished successfully */
1926 s->ret = 0;
1927 }
1928}
1929
Kevin Wolf690c7302015-03-19 13:33:32 +01001930static int convert_do_copy(ImgConvertState *s)
1931{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001932 int ret, i, n;
1933 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001934
1935 /* Check whether we have zero initialisation or can get it efficiently */
1936 s->has_zero_init = s->min_sparse && !s->target_has_backing
1937 ? bdrv_has_zero_init(blk_bs(s->target))
1938 : false;
1939
1940 if (!s->has_zero_init && !s->target_has_backing &&
1941 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1942 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001943 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001944 if (ret == 0) {
1945 s->has_zero_init = true;
1946 }
1947 }
1948
1949 /* Allocate buffer for copied data. For compressed images, only one cluster
1950 * can be copied at a time. */
1951 if (s->compressed) {
1952 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1953 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001954 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001955 }
1956 s->buf_sectors = s->cluster_sectors;
1957 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001958
Kevin Wolf690c7302015-03-19 13:33:32 +01001959 while (sector_num < s->total_sectors) {
1960 n = convert_iteration_sectors(s, sector_num);
1961 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001962 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001963 }
Max Reitzaad15de2016-03-24 23:33:57 +01001964 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1965 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001966 s->allocated_sectors += n;
1967 }
1968 sector_num += n;
1969 }
1970
1971 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001972 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001973 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001974
Peter Lieven2d9187b2017-02-28 13:40:07 +01001975 qemu_co_mutex_init(&s->lock);
1976 for (i = 0; i < s->num_coroutines; i++) {
1977 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1978 s->wait_sector_num[i] = -1;
1979 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001980 }
1981
Anton Nefedovb91127e2017-04-26 11:33:15 +03001982 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001983 main_loop_wait(false);
1984 }
1985
1986 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001987 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001988 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001989 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001990 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001991 }
1992 }
1993
Peter Lieven2d9187b2017-02-28 13:40:07 +01001994 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001995}
1996
Peter Lieven6360ab22018-07-13 09:15:39 +02001997#define MAX_BUF_SECTORS 32768
1998
bellardea2384d2004-08-01 21:59:26 +00001999static int img_convert(int argc, char **argv)
2000{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002001 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002002 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002003 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2004 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002005 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002006 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002007 BlockDriverState *out_bs;
2008 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002009 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002010 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002011 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002012 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002013 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002014 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002015 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002016 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002017 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002018
Peter Lieven9fd77f92017-04-21 11:11:55 +02002019 ImgConvertState s = (ImgConvertState) {
2020 /* Need at least 4k of zeros for sparse detection */
2021 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002022 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002023 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2024 .wr_in_order = true,
2025 .num_coroutines = 8,
2026 };
2027
bellardea2384d2004-08-01 21:59:26 +00002028 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002029 static const struct option long_options[] = {
2030 {"help", no_argument, 0, 'h'},
2031 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002032 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002033 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002034 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002035 {0, 0, 0, 0}
2036 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002037 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002038 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002039 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002040 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002041 }
bellardea2384d2004-08-01 21:59:26 +00002042 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002043 case ':':
2044 missing_argument(argv[optind - 1]);
2045 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002046 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002047 unrecognized_option(argv[optind - 1]);
2048 break;
bellardea2384d2004-08-01 21:59:26 +00002049 case 'h':
2050 help();
2051 break;
2052 case 'f':
2053 fmt = optarg;
2054 break;
2055 case 'O':
2056 out_fmt = optarg;
2057 break;
thsf58c7b32008-06-05 21:53:49 +00002058 case 'B':
2059 out_baseimg = optarg;
2060 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002061 case 'C':
2062 s.copy_range = true;
2063 break;
bellardea2384d2004-08-01 21:59:26 +00002064 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002065 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002066 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002067 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002068 if (!is_valid_option_list(optarg)) {
2069 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002070 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002071 }
2072 if (!options) {
2073 options = g_strdup(optarg);
2074 } else {
2075 char *old_options = options;
2076 options = g_strdup_printf("%s,%s", options, optarg);
2077 g_free(old_options);
2078 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002079 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002080 case 'l':
2081 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002082 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2083 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002084 if (!sn_opts) {
2085 error_report("Failed in parsing snapshot param '%s'",
2086 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002087 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002088 }
2089 } else {
2090 snapshot_name = optarg;
2091 }
2092 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002093 case 'S':
2094 {
2095 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002096
2097 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002098 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2099 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2100 error_report("Invalid buffer size for sparse output specified. "
2101 "Valid sizes are multiples of %llu up to %llu. Select "
2102 "0 to disable sparse detection (fully allocates output).",
2103 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002104 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002105 }
2106
Peter Lieven9fd77f92017-04-21 11:11:55 +02002107 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002108 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002109 break;
2110 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002111 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002112 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002113 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002114 case 't':
2115 cache = optarg;
2116 break;
Max Reitz40055952014-07-22 22:58:42 +02002117 case 'T':
2118 src_cache = optarg;
2119 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002120 case 'q':
2121 quiet = true;
2122 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002123 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002124 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002125 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002126 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002127 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2128 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002129 error_report("Invalid number of coroutines. Allowed number of"
2130 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002131 goto fail_getopt;
2132 }
2133 break;
2134 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002135 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002136 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002137 case 'U':
2138 force_share = true;
2139 break;
Max Reitz3258b912017-04-26 15:46:47 +02002140 case OPTION_OBJECT: {
2141 QemuOpts *object_opts;
2142 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2143 optarg, true);
2144 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002145 goto fail_getopt;
2146 }
2147 break;
Max Reitz3258b912017-04-26 15:46:47 +02002148 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002149 case OPTION_IMAGE_OPTS:
2150 image_opts = true;
2151 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002152 case OPTION_TARGET_IMAGE_OPTS:
2153 tgt_image_opts = true;
2154 break;
bellardea2384d2004-08-01 21:59:26 +00002155 }
2156 }
ths3b46e622007-09-17 08:09:54 +00002157
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002158 if (!out_fmt && !tgt_image_opts) {
2159 out_fmt = "raw";
2160 }
2161
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002162 if (qemu_opts_foreach(&qemu_object_opts,
2163 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002164 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002165 goto fail_getopt;
2166 }
2167
Fam Zhenge11ce122018-07-27 11:34:01 +08002168 if (s.compressed && s.copy_range) {
2169 error_report("Cannot enable copy offloading when -c is used");
2170 goto fail_getopt;
2171 }
2172
2173 if (explict_min_sparse && s.copy_range) {
2174 error_report("Cannot enable copy offloading when -S is used");
2175 goto fail_getopt;
2176 }
2177
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002178 if (tgt_image_opts && !skip_create) {
2179 error_report("--target-image-opts requires use of -n flag");
2180 goto fail_getopt;
2181 }
2182
Peter Lieven9fd77f92017-04-21 11:11:55 +02002183 s.src_num = argc - optind - 1;
2184 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2185
2186 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002187 if (out_fmt) {
2188 ret = print_block_option_help(out_filename, out_fmt);
2189 goto fail_getopt;
2190 } else {
2191 error_report("Option help requires a format be specified");
2192 goto fail_getopt;
2193 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002194 }
2195
2196 if (s.src_num < 1) {
2197 error_report("Must specify image file name");
2198 goto fail_getopt;
2199 }
2200
2201
Peter Lieven9fd77f92017-04-21 11:11:55 +02002202 /* ret is still -EINVAL until here */
2203 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2204 if (ret < 0) {
2205 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002206 goto fail_getopt;
2207 }
2208
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002209 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002210 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002211 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002212 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002213 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002214 qemu_progress_print(0, 100);
2215
Peter Lieven9fd77f92017-04-21 11:11:55 +02002216 s.src = g_new0(BlockBackend *, s.src_num);
2217 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002218
Peter Lieven9fd77f92017-04-21 11:11:55 +02002219 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2220 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002221 fmt, src_flags, src_writethrough, quiet,
2222 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002223 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002224 ret = -1;
2225 goto out;
2226 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002227 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2228 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002229 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002230 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002231 ret = -1;
2232 goto out;
2233 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002234 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002235 }
bellardea2384d2004-08-01 21:59:26 +00002236
Wenchao Xiaef806542013-12-04 17:10:57 +08002237 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002238 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002239 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2240 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2241 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002242 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002243 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002244 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002245 ret = -1;
2246 goto out;
2247 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002248
Peter Lieven9fd77f92017-04-21 11:11:55 +02002249 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2250 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002251 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002252 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002253 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002254 ret = -1;
2255 goto out;
edison51ef6722010-09-21 19:58:41 -07002256 }
2257
Max Reitz2e024cd2015-02-11 09:58:46 -05002258 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002259 /* Find driver and parse its options */
2260 drv = bdrv_find_format(out_fmt);
2261 if (!drv) {
2262 error_report("Unknown file format '%s'", out_fmt);
2263 ret = -1;
2264 goto out;
2265 }
2266
2267 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2268 if (!proto_drv) {
2269 error_report_err(local_err);
2270 ret = -1;
2271 goto out;
2272 }
2273
Max Reitz2e024cd2015-02-11 09:58:46 -05002274 if (!drv->create_opts) {
2275 error_report("Format driver '%s' does not support image creation",
2276 drv->format_name);
2277 ret = -1;
2278 goto out;
2279 }
Max Reitzf75613c2014-12-02 18:32:46 +01002280
Max Reitz2e024cd2015-02-11 09:58:46 -05002281 if (!proto_drv->create_opts) {
2282 error_report("Protocol driver '%s' does not support image creation",
2283 proto_drv->format_name);
2284 ret = -1;
2285 goto out;
2286 }
Max Reitzf75613c2014-12-02 18:32:46 +01002287
Max Reitz2e024cd2015-02-11 09:58:46 -05002288 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2289 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002290
Max Reitz2e024cd2015-02-11 09:58:46 -05002291 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002292 if (options) {
2293 qemu_opts_do_parse(opts, options, NULL, &local_err);
2294 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002295 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002296 ret = -1;
2297 goto out;
2298 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002299 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002300
Peter Lieven9fd77f92017-04-21 11:11:55 +02002301 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002302 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002303 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2304 if (ret < 0) {
2305 goto out;
2306 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002307 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002308
Kevin Wolfa18953f2010-10-14 15:46:04 +02002309 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002310 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002311 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002312 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002313 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002314 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002315
Max Reitz48758a82017-04-26 15:46:48 +02002316 if (s.src_num > 1 && out_baseimg) {
2317 error_report("Having a backing file for the target makes no sense when "
2318 "concatenating multiple input images");
2319 ret = -1;
2320 goto out;
2321 }
2322
Kevin Wolfefa84d42009-05-18 16:42:12 +02002323 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002324 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002325 bool encryption =
2326 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002327 const char *encryptfmt =
2328 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002329 const char *preallocation =
2330 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002331
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002332 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002333 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002334 ret = -1;
2335 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002336 }
2337
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002338 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002339 error_report("Compression and encryption not supported at "
2340 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002341 ret = -1;
2342 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002343 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002344
Chunyan Liu83d05212014-06-05 17:20:51 +08002345 if (preallocation
2346 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002347 {
2348 error_report("Compression and preallocation not supported at "
2349 "the same time");
2350 ret = -1;
2351 goto out;
2352 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002353 }
2354
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002355 /*
2356 * The later open call will need any decryption secrets, and
2357 * bdrv_create() will purge "opts", so extract them now before
2358 * they are lost.
2359 */
2360 if (!skip_create) {
2361 open_opts = qdict_new();
2362 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2363 }
2364
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002365 if (!skip_create) {
2366 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002367 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002368 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002369 error_reportf_err(local_err, "%s: error while converting %s: ",
2370 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002371 goto out;
bellardea2384d2004-08-01 21:59:26 +00002372 }
2373 }
ths3b46e622007-09-17 08:09:54 +00002374
Peter Lieven9fd77f92017-04-21 11:11:55 +02002375 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002376 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002377 if (ret < 0) {
2378 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002379 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002380 }
2381
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002382 if (skip_create) {
2383 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2384 flags, writethrough, quiet, false);
2385 } else {
2386 /* TODO ultimately we should allow --target-image-opts
2387 * to be used even when -n is not given.
2388 * That has to wait for bdrv_create to be improved
2389 * to allow filenames in option syntax
2390 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002391 s.target = img_open_file(out_filename, open_opts, out_fmt,
2392 flags, writethrough, quiet, false);
2393 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002394 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002395 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002396 ret = -1;
2397 goto out;
2398 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002399 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002400
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002401 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2402 error_report("Compression not supported for this file format");
2403 ret = -1;
2404 goto out;
2405 }
2406
Eric Blake5def6b82016-06-23 16:37:19 -06002407 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002408 * or discard_alignment of the out_bs is greater. Limit to
2409 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2410 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002411 MAX(s.buf_sectors,
2412 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2413 out_bs->bl.pdiscard_alignment >>
2414 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002415
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002416 /* try to align the write requests to the destination to avoid unnecessary
2417 * RMW cycles. */
2418 s.alignment = MAX(pow2floor(s.min_sparse),
2419 DIV_ROUND_UP(out_bs->bl.request_alignment,
2420 BDRV_SECTOR_SIZE));
2421 assert(is_power_of_2(s.alignment));
2422
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002423 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002424 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002425 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002426 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002427 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002428 ret = -1;
2429 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002430 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002431 error_report("output file is smaller than input file");
2432 ret = -1;
2433 goto out;
2434 }
2435 }
2436
Max Reitz351c8ef2018-05-01 18:57:49 +02002437 if (s.target_has_backing) {
2438 /* Errors are treated as "backing length unknown" (which means
2439 * s.target_backing_sectors has to be negative, which it will
2440 * be automatically). The backing file length is used only
2441 * for optimizations, so such a case is not fatal. */
2442 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2443 } else {
2444 s.target_backing_sectors = -1;
2445 }
2446
Peter Lieven24f833c2013-11-27 11:07:07 +01002447 ret = bdrv_get_info(out_bs, &bdi);
2448 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002449 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002450 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002451 goto out;
2452 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002453 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002454 s.compressed = s.compressed || bdi.needs_compressed_writes;
2455 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002456 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002457 }
2458
Peter Lieven9fd77f92017-04-21 11:11:55 +02002459 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002460out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002461 if (!ret) {
2462 qemu_progress_print(100, 0);
2463 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002464 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002465 qemu_opts_del(opts);
2466 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002467 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002468 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002469 blk_unref(s.target);
2470 if (s.src) {
2471 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2472 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002473 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002474 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002475 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002476 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002477fail_getopt:
2478 g_free(options);
2479
Peter Lieven9fd77f92017-04-21 11:11:55 +02002480 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002481}
2482
bellard57d1a2b2004-08-03 21:15:11 +00002483
bellardfaea38e2006-08-05 21:31:00 +00002484static void dump_snapshots(BlockDriverState *bs)
2485{
2486 QEMUSnapshotInfo *sn_tab, *sn;
2487 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002488
2489 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2490 if (nb_sns <= 0)
2491 return;
2492 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002493 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002494 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002495 for(i = 0; i < nb_sns; i++) {
2496 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002497 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002498 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002499 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002500 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002501}
2502
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002503static void dump_json_image_info_list(ImageInfoList *list)
2504{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002505 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002506 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002507 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002508
2509 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2510 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002511 str = qobject_to_json_pretty(obj);
2512 assert(str != NULL);
2513 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002514 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002515 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002516 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002517}
2518
Benoît Canetc054b3f2012-09-05 13:09:02 +02002519static void dump_json_image_info(ImageInfo *info)
2520{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002521 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002522 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002523 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002524
2525 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2526 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002527 str = qobject_to_json_pretty(obj);
2528 assert(str != NULL);
2529 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002530 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002531 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002532 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002533}
2534
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002535static void dump_human_image_info_list(ImageInfoList *list)
2536{
2537 ImageInfoList *elem;
2538 bool delim = false;
2539
2540 for (elem = list; elem; elem = elem->next) {
2541 if (delim) {
2542 printf("\n");
2543 }
2544 delim = true;
2545
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002546 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002547 }
2548}
2549
2550static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2551{
2552 return strcmp(a, b) == 0;
2553}
2554
2555/**
2556 * Open an image file chain and return an ImageInfoList
2557 *
2558 * @filename: topmost image filename
2559 * @fmt: topmost image format (may be NULL to autodetect)
2560 * @chain: true - enumerate entire backing file chain
2561 * false - only topmost image file
2562 *
2563 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2564 * image file. If there was an error a message will have been printed to
2565 * stderr.
2566 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002567static ImageInfoList *collect_image_info_list(bool image_opts,
2568 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002569 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002570 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002571{
2572 ImageInfoList *head = NULL;
2573 ImageInfoList **last = &head;
2574 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002575 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002576
2577 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2578
2579 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002580 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002581 BlockDriverState *bs;
2582 ImageInfo *info;
2583 ImageInfoList *elem;
2584
2585 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2586 error_report("Backing file '%s' creates an infinite loop.",
2587 filename);
2588 goto err;
2589 }
2590 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2591
Max Reitzefaa7c42016-03-16 19:54:38 +01002592 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002593 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2594 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002595 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002596 goto err;
2597 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002598 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002599
Wenchao Xia43526ec2013-06-06 12:27:58 +08002600 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002601 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002602 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002603 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002604 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002605 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002606
2607 elem = g_new0(ImageInfoList, 1);
2608 elem->value = info;
2609 *last = elem;
2610 last = &elem->next;
2611
Markus Armbruster26f54e92014-10-07 13:59:04 +02002612 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002613
2614 filename = fmt = NULL;
2615 if (chain) {
2616 if (info->has_full_backing_filename) {
2617 filename = info->full_backing_filename;
2618 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002619 error_report("Could not determine absolute backing filename,"
2620 " but backing filename '%s' present",
2621 info->backing_filename);
2622 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002623 }
2624 if (info->has_backing_filename_format) {
2625 fmt = info->backing_filename_format;
2626 }
2627 }
2628 }
2629 g_hash_table_destroy(filenames);
2630 return head;
2631
2632err:
2633 qapi_free_ImageInfoList(head);
2634 g_hash_table_destroy(filenames);
2635 return NULL;
2636}
2637
Benoît Canetc054b3f2012-09-05 13:09:02 +02002638static int img_info(int argc, char **argv)
2639{
2640 int c;
2641 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002642 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002643 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002644 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002645 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002646 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002647
bellardea2384d2004-08-01 21:59:26 +00002648 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002649 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002650 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002651 int option_index = 0;
2652 static const struct option long_options[] = {
2653 {"help", no_argument, 0, 'h'},
2654 {"format", required_argument, 0, 'f'},
2655 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002656 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002657 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002658 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002659 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002660 {0, 0, 0, 0}
2661 };
Fam Zheng335e9932017-05-03 00:35:39 +08002662 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002663 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002664 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002665 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002666 }
bellardea2384d2004-08-01 21:59:26 +00002667 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002668 case ':':
2669 missing_argument(argv[optind - 1]);
2670 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002671 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002672 unrecognized_option(argv[optind - 1]);
2673 break;
bellardea2384d2004-08-01 21:59:26 +00002674 case 'h':
2675 help();
2676 break;
2677 case 'f':
2678 fmt = optarg;
2679 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002680 case 'U':
2681 force_share = true;
2682 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002683 case OPTION_OUTPUT:
2684 output = optarg;
2685 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002686 case OPTION_BACKING_CHAIN:
2687 chain = true;
2688 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002689 case OPTION_OBJECT: {
2690 QemuOpts *opts;
2691 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2692 optarg, true);
2693 if (!opts) {
2694 return 1;
2695 }
2696 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002697 case OPTION_IMAGE_OPTS:
2698 image_opts = true;
2699 break;
bellardea2384d2004-08-01 21:59:26 +00002700 }
2701 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002702 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002703 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002704 }
bellardea2384d2004-08-01 21:59:26 +00002705 filename = argv[optind++];
2706
Benoît Canetc054b3f2012-09-05 13:09:02 +02002707 if (output && !strcmp(output, "json")) {
2708 output_format = OFORMAT_JSON;
2709 } else if (output && !strcmp(output, "human")) {
2710 output_format = OFORMAT_HUMAN;
2711 } else if (output) {
2712 error_report("--output must be used with human or json as argument.");
2713 return 1;
2714 }
2715
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002716 if (qemu_opts_foreach(&qemu_object_opts,
2717 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002718 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002719 return 1;
2720 }
2721
Fam Zheng335e9932017-05-03 00:35:39 +08002722 list = collect_image_info_list(image_opts, filename, fmt, chain,
2723 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002724 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002725 return 1;
2726 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002727
Benoît Canetc054b3f2012-09-05 13:09:02 +02002728 switch (output_format) {
2729 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002730 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002731 break;
2732 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002733 if (chain) {
2734 dump_json_image_info_list(list);
2735 } else {
2736 dump_json_image_info(list->value);
2737 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002738 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002739 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002740
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002741 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002742 return 0;
2743}
2744
Eric Blake30065d12019-03-26 13:40:43 -05002745static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2746 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002747{
2748 switch (output_format) {
2749 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002750 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002751 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002752 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002753 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002754 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002755 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002756 e->start, e->length,
2757 e->has_offset ? e->offset : 0,
2758 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002759 }
2760 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2761 * Modify the flags here to allow more coalescing.
2762 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002763 if (next && (!next->data || next->zero)) {
2764 next->data = false;
2765 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002766 }
2767 break;
2768 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002769 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2770 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002771 (e->start == 0 ? "[" : ",\n"),
2772 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002773 e->zero ? "true" : "false",
2774 e->data ? "true" : "false");
2775 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002776 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002777 }
2778 putchar('}');
2779
2780 if (!next) {
2781 printf("]\n");
2782 }
2783 break;
2784 }
Eric Blake30065d12019-03-26 13:40:43 -05002785 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002786}
2787
Eric Blake5e344dd2017-10-11 22:47:02 -05002788static int get_block_status(BlockDriverState *bs, int64_t offset,
2789 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002790{
Eric Blake237d78f2017-10-11 22:47:03 -05002791 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002792 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002793 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002794 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002795 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002796 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002797
2798 /* As an optimization, we could cache the current range of unallocated
2799 * clusters in each file of the chain, and avoid querying the same
2800 * range repeatedly.
2801 */
2802
2803 depth = 0;
2804 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002805 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002806 if (ret < 0) {
2807 return ret;
2808 }
Eric Blake237d78f2017-10-11 22:47:03 -05002809 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002810 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2811 break;
2812 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002813 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002814 if (bs == NULL) {
2815 ret = 0;
2816 break;
2817 }
2818
2819 depth++;
2820 }
2821
John Snow28756452016-02-05 13:12:33 -05002822 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2823
Max Reitzf30c66b2019-02-01 20:29:05 +01002824 if (file && has_offset) {
2825 bdrv_refresh_filename(file);
2826 filename = file->filename;
2827 }
2828
John Snow28756452016-02-05 13:12:33 -05002829 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002830 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002831 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002832 .data = !!(ret & BDRV_BLOCK_DATA),
2833 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002834 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002835 .has_offset = has_offset,
2836 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002837 .has_filename = filename,
2838 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002839 };
2840
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002841 return 0;
2842}
2843
Fam Zheng16b0d552016-01-26 11:59:02 +08002844static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2845{
2846 if (curr->length == 0) {
2847 return false;
2848 }
2849 if (curr->zero != next->zero ||
2850 curr->data != next->data ||
2851 curr->depth != next->depth ||
2852 curr->has_filename != next->has_filename ||
2853 curr->has_offset != next->has_offset) {
2854 return false;
2855 }
2856 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2857 return false;
2858 }
2859 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2860 return false;
2861 }
2862 return true;
2863}
2864
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002865static int img_map(int argc, char **argv)
2866{
2867 int c;
2868 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002869 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002870 BlockDriverState *bs;
2871 const char *filename, *fmt, *output;
2872 int64_t length;
2873 MapEntry curr = { .length = 0 }, next;
2874 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002875 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002876 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002877
2878 fmt = NULL;
2879 output = NULL;
2880 for (;;) {
2881 int option_index = 0;
2882 static const struct option long_options[] = {
2883 {"help", no_argument, 0, 'h'},
2884 {"format", required_argument, 0, 'f'},
2885 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002886 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002887 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002888 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002889 {0, 0, 0, 0}
2890 };
Fam Zheng335e9932017-05-03 00:35:39 +08002891 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002892 long_options, &option_index);
2893 if (c == -1) {
2894 break;
2895 }
2896 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002897 case ':':
2898 missing_argument(argv[optind - 1]);
2899 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002900 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002901 unrecognized_option(argv[optind - 1]);
2902 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002903 case 'h':
2904 help();
2905 break;
2906 case 'f':
2907 fmt = optarg;
2908 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002909 case 'U':
2910 force_share = true;
2911 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002912 case OPTION_OUTPUT:
2913 output = optarg;
2914 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002915 case OPTION_OBJECT: {
2916 QemuOpts *opts;
2917 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2918 optarg, true);
2919 if (!opts) {
2920 return 1;
2921 }
2922 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002923 case OPTION_IMAGE_OPTS:
2924 image_opts = true;
2925 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002926 }
2927 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002928 if (optind != argc - 1) {
2929 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002930 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002931 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002932
2933 if (output && !strcmp(output, "json")) {
2934 output_format = OFORMAT_JSON;
2935 } else if (output && !strcmp(output, "human")) {
2936 output_format = OFORMAT_HUMAN;
2937 } else if (output) {
2938 error_report("--output must be used with human or json as argument.");
2939 return 1;
2940 }
2941
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002942 if (qemu_opts_foreach(&qemu_object_opts,
2943 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002944 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002945 return 1;
2946 }
2947
Fam Zheng335e9932017-05-03 00:35:39 +08002948 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002949 if (!blk) {
2950 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002951 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002952 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002953
2954 if (output_format == OFORMAT_HUMAN) {
2955 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2956 }
2957
Max Reitzf1d3cd72015-02-05 13:58:18 -05002958 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002959 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002960 int64_t offset = curr.start + curr.length;
2961 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002962
2963 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02002964 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002965 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002966
2967 if (ret < 0) {
2968 error_report("Could not read file metadata: %s", strerror(-ret));
2969 goto out;
2970 }
2971
Fam Zheng16b0d552016-01-26 11:59:02 +08002972 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002973 curr.length += next.length;
2974 continue;
2975 }
2976
2977 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05002978 ret = dump_map_entry(output_format, &curr, &next);
2979 if (ret < 0) {
2980 goto out;
2981 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002982 }
2983 curr = next;
2984 }
2985
Eric Blake30065d12019-03-26 13:40:43 -05002986 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002987
2988out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002989 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002990 return ret < 0;
2991}
2992
aliguorif7b4a942009-01-07 17:40:15 +00002993#define SNAPSHOT_LIST 1
2994#define SNAPSHOT_CREATE 2
2995#define SNAPSHOT_APPLY 3
2996#define SNAPSHOT_DELETE 4
2997
Stuart Brady153859b2009-06-07 00:42:17 +01002998static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002999{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003000 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003001 BlockDriverState *bs;
3002 QEMUSnapshotInfo sn;
3003 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003004 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003005 int action = 0;
3006 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003007 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003008 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003009 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003010 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003011
Kevin Wolfce099542016-03-15 13:01:04 +01003012 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003013 /* Parse commandline parameters */
3014 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003015 static const struct option long_options[] = {
3016 {"help", no_argument, 0, 'h'},
3017 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003018 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003019 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003020 {0, 0, 0, 0}
3021 };
Fam Zheng335e9932017-05-03 00:35:39 +08003022 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003023 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003024 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003025 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003026 }
aliguorif7b4a942009-01-07 17:40:15 +00003027 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003028 case ':':
3029 missing_argument(argv[optind - 1]);
3030 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003031 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003032 unrecognized_option(argv[optind - 1]);
3033 break;
aliguorif7b4a942009-01-07 17:40:15 +00003034 case 'h':
3035 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003036 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003037 case 'l':
3038 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003039 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003040 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003041 }
3042 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003043 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003044 break;
3045 case 'a':
3046 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003047 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003048 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003049 }
3050 action = SNAPSHOT_APPLY;
3051 snapshot_name = optarg;
3052 break;
3053 case 'c':
3054 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003055 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003056 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003057 }
3058 action = SNAPSHOT_CREATE;
3059 snapshot_name = optarg;
3060 break;
3061 case 'd':
3062 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003063 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003064 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003065 }
3066 action = SNAPSHOT_DELETE;
3067 snapshot_name = optarg;
3068 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003069 case 'q':
3070 quiet = true;
3071 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003072 case 'U':
3073 force_share = true;
3074 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003075 case OPTION_OBJECT: {
3076 QemuOpts *opts;
3077 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3078 optarg, true);
3079 if (!opts) {
3080 return 1;
3081 }
3082 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003083 case OPTION_IMAGE_OPTS:
3084 image_opts = true;
3085 break;
aliguorif7b4a942009-01-07 17:40:15 +00003086 }
3087 }
3088
Kevin Wolffc11eb22013-08-05 10:53:04 +02003089 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003090 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003091 }
aliguorif7b4a942009-01-07 17:40:15 +00003092 filename = argv[optind++];
3093
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003094 if (qemu_opts_foreach(&qemu_object_opts,
3095 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003096 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003097 return 1;
3098 }
3099
aliguorif7b4a942009-01-07 17:40:15 +00003100 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003101 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3102 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003103 if (!blk) {
3104 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003105 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003106 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003107
3108 /* Perform the requested action */
3109 switch(action) {
3110 case SNAPSHOT_LIST:
3111 dump_snapshots(bs);
3112 break;
3113
3114 case SNAPSHOT_CREATE:
3115 memset(&sn, 0, sizeof(sn));
3116 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3117
3118 qemu_gettimeofday(&tv);
3119 sn.date_sec = tv.tv_sec;
3120 sn.date_nsec = tv.tv_usec * 1000;
3121
3122 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003123 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003124 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003125 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003126 }
aliguorif7b4a942009-01-07 17:40:15 +00003127 break;
3128
3129 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003130 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003131 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003132 error_reportf_err(err, "Could not apply snapshot '%s': ",
3133 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003134 }
aliguorif7b4a942009-01-07 17:40:15 +00003135 break;
3136
3137 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003138 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3139 if (ret < 0) {
3140 error_report("Could not delete snapshot '%s': snapshot not "
3141 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003142 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003143 } else {
3144 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3145 if (ret < 0) {
3146 error_reportf_err(err, "Could not delete snapshot '%s': ",
3147 snapshot_name);
3148 ret = 1;
3149 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003150 }
aliguorif7b4a942009-01-07 17:40:15 +00003151 break;
3152 }
3153
3154 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003155 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003156 if (ret) {
3157 return 1;
3158 }
Stuart Brady153859b2009-06-07 00:42:17 +01003159 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003160}
3161
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003162static int img_rebase(int argc, char **argv)
3163{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003164 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003165 uint8_t *buf_old = NULL;
3166 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003167 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003168 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003169 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3170 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003171 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003172 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003173 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003174 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003175 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003176 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003177 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003178
3179 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003180 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003181 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003182 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003183 out_baseimg = NULL;
3184 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003185 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003186 static const struct option long_options[] = {
3187 {"help", no_argument, 0, 'h'},
3188 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003189 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003190 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003191 {0, 0, 0, 0}
3192 };
Fam Zheng335e9932017-05-03 00:35:39 +08003193 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003194 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003195 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003196 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003197 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003198 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003199 case ':':
3200 missing_argument(argv[optind - 1]);
3201 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003202 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003203 unrecognized_option(argv[optind - 1]);
3204 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003205 case 'h':
3206 help();
3207 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003208 case 'f':
3209 fmt = optarg;
3210 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003211 case 'F':
3212 out_basefmt = optarg;
3213 break;
3214 case 'b':
3215 out_baseimg = optarg;
3216 break;
3217 case 'u':
3218 unsafe = 1;
3219 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003220 case 'p':
3221 progress = 1;
3222 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003223 case 't':
3224 cache = optarg;
3225 break;
Max Reitz40055952014-07-22 22:58:42 +02003226 case 'T':
3227 src_cache = optarg;
3228 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003229 case 'q':
3230 quiet = true;
3231 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003232 case OPTION_OBJECT: {
3233 QemuOpts *opts;
3234 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3235 optarg, true);
3236 if (!opts) {
3237 return 1;
3238 }
3239 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003240 case OPTION_IMAGE_OPTS:
3241 image_opts = true;
3242 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003243 case 'U':
3244 force_share = true;
3245 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003246 }
3247 }
3248
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003249 if (quiet) {
3250 progress = 0;
3251 }
3252
Fam Zhengac1307a2014-04-22 13:36:11 +08003253 if (optind != argc - 1) {
3254 error_exit("Expecting one image file name");
3255 }
3256 if (!unsafe && !out_baseimg) {
3257 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003258 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003259 filename = argv[optind++];
3260
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003261 if (qemu_opts_foreach(&qemu_object_opts,
3262 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003263 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003264 return 1;
3265 }
3266
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003267 qemu_progress_init(progress, 2.0);
3268 qemu_progress_print(0, 100);
3269
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003270 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003271 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003272 if (ret < 0) {
3273 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003274 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003275 }
3276
Kevin Wolfce099542016-03-15 13:01:04 +01003277 src_flags = 0;
3278 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003279 if (ret < 0) {
3280 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003281 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003282 }
3283
Kevin Wolfce099542016-03-15 13:01:04 +01003284 /* The source files are opened read-only, don't care about WCE */
3285 assert((src_flags & BDRV_O_RDWR) == 0);
3286 (void) src_writethrough;
3287
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003288 /*
3289 * Open the images.
3290 *
3291 * Ignore the old backing file for unsafe rebase in case we want to correct
3292 * the reference to a renamed or moved backing file.
3293 */
Fam Zheng335e9932017-05-03 00:35:39 +08003294 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3295 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003296 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003297 ret = -1;
3298 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003299 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003300 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003301
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003302 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003303 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003304 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003305 ret = -1;
3306 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003307 }
3308 }
3309
3310 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003311 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003312 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003313 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003314
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003315 if (base_bs) {
3316 blk_old_backing = blk_new(BLK_PERM_CONSISTENT_READ,
3317 BLK_PERM_ALL);
3318 ret = blk_insert_bs(blk_old_backing, base_bs,
3319 &local_err);
3320 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003321 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003322 "Could not reuse old backing file '%s': ",
3323 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003324 goto out;
3325 }
3326 } else {
3327 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003328 }
Max Reitz644483d2015-02-05 13:58:17 -05003329
Alex Bligha6166732012-10-16 13:46:18 +01003330 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003331 const char *overlay_filename;
3332 char *out_real_path;
3333
Fam Zheng335e9932017-05-03 00:35:39 +08003334 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003335 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003336 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003337 }
3338 if (force_share) {
3339 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003340 }
3341
Max Reitzf30c66b2019-02-01 20:29:05 +01003342 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003343 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3344 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003345 out_real_path =
3346 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3347 out_baseimg,
3348 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003349 if (local_err) {
3350 error_reportf_err(local_err,
3351 "Could not resolve backing filename: ");
3352 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003353 goto out;
3354 }
3355
Sam Eiderman863cc782019-05-23 19:33:36 +03003356 /*
3357 * Find out whether we rebase an image on top of a previous image
3358 * in its chain.
3359 */
3360 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003361 if (prefix_chain_bs) {
3362 g_free(out_real_path);
3363 blk_new_backing = blk_new(BLK_PERM_CONSISTENT_READ,
3364 BLK_PERM_ALL);
3365 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3366 &local_err);
3367 if (ret < 0) {
3368 error_reportf_err(local_err,
3369 "Could not reuse backing file '%s': ",
3370 out_baseimg);
3371 goto out;
3372 }
3373 } else {
3374 blk_new_backing = blk_new_open(out_real_path, NULL,
3375 options, src_flags, &local_err);
3376 g_free(out_real_path);
3377 if (!blk_new_backing) {
3378 error_reportf_err(local_err,
3379 "Could not open new backing file '%s': ",
3380 out_baseimg);
3381 ret = -1;
3382 goto out;
3383 }
Alex Bligha6166732012-10-16 13:46:18 +01003384 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003385 }
3386 }
3387
3388 /*
3389 * Check each unallocated cluster in the COW file. If it is unallocated,
3390 * accesses go to the backing file. We must therefore compare this cluster
3391 * in the old and new backing file, and if they differ we need to copy it
3392 * from the old backing file into the COW file.
3393 *
3394 * If qemu-img crashes during this step, no harm is done. The content of
3395 * the image is the same as the original one at any time.
3396 */
3397 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003398 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003399 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003400 int64_t new_backing_size = 0;
3401 uint64_t offset;
3402 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003403 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003404
Max Reitzf1d3cd72015-02-05 13:58:18 -05003405 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3406 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003407
Eric Blake41536282017-10-11 22:47:15 -05003408 size = blk_getlength(blk);
3409 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003410 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003411 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003412 ret = -1;
3413 goto out;
3414 }
Max Reitz35ddd932019-05-09 19:52:35 +02003415 if (blk_old_backing) {
3416 old_backing_size = blk_getlength(blk_old_backing);
3417 if (old_backing_size < 0) {
3418 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003419
Max Reitz35ddd932019-05-09 19:52:35 +02003420 bdrv_get_backing_filename(bs, backing_name,
3421 sizeof(backing_name));
3422 error_report("Could not get size of '%s': %s",
3423 backing_name, strerror(-old_backing_size));
3424 ret = -1;
3425 goto out;
3426 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003427 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003428 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003429 new_backing_size = blk_getlength(blk_new_backing);
3430 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003431 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003432 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003433 ret = -1;
3434 goto out;
3435 }
Alex Bligha6166732012-10-16 13:46:18 +01003436 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003437
Eric Blake41536282017-10-11 22:47:15 -05003438 if (size != 0) {
3439 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003440 }
3441
Eric Blake41536282017-10-11 22:47:15 -05003442 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003443 bool buf_old_is_zero = false;
3444
Eric Blake41536282017-10-11 22:47:15 -05003445 /* How many bytes can we handle with the next read? */
3446 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003447
3448 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003449 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003450 if (ret < 0) {
3451 error_report("error while reading image metadata: %s",
3452 strerror(-ret));
3453 goto out;
3454 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003455 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003456 continue;
3457 }
3458
Sam Eiderman863cc782019-05-23 19:33:36 +03003459 if (prefix_chain_bs) {
3460 /*
3461 * If cluster wasn't changed since prefix_chain, we don't need
3462 * to take action
3463 */
3464 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3465 offset, n, &n);
3466 if (ret < 0) {
3467 error_report("error while reading image metadata: %s",
3468 strerror(-ret));
3469 goto out;
3470 }
3471 if (!ret) {
3472 continue;
3473 }
3474 }
3475
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003476 /*
3477 * Read old and new backing file and take into consideration that
3478 * backing files may be smaller than the COW image.
3479 */
Eric Blake41536282017-10-11 22:47:15 -05003480 if (offset >= old_backing_size) {
3481 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003482 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003483 } else {
Eric Blake41536282017-10-11 22:47:15 -05003484 if (offset + n > old_backing_size) {
3485 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003486 }
3487
Eric Blake41536282017-10-11 22:47:15 -05003488 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003489 if (ret < 0) {
3490 error_report("error while reading from old backing file");
3491 goto out;
3492 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003493 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003494
Eric Blake41536282017-10-11 22:47:15 -05003495 if (offset >= new_backing_size || !blk_new_backing) {
3496 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003497 } else {
Eric Blake41536282017-10-11 22:47:15 -05003498 if (offset + n > new_backing_size) {
3499 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003500 }
3501
Eric Blake41536282017-10-11 22:47:15 -05003502 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003503 if (ret < 0) {
3504 error_report("error while reading from new backing file");
3505 goto out;
3506 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003507 }
3508
3509 /* If they differ, we need to write to the COW file */
3510 uint64_t written = 0;
3511
Eric Blake41536282017-10-11 22:47:15 -05003512 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003513 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003514
Eric Blake41536282017-10-11 22:47:15 -05003515 if (compare_buffers(buf_old + written, buf_new + written,
3516 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003517 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003518 if (buf_old_is_zero) {
3519 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3520 } else {
3521 ret = blk_pwrite(blk, offset + written,
3522 buf_old + written, pnum, 0);
3523 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003524 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003525 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003526 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003527 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003528 }
3529 }
3530
3531 written += pnum;
3532 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003533 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003534 }
3535 }
3536
3537 /*
3538 * Change the backing file. All clusters that are different from the old
3539 * backing file are overwritten in the COW file now, so the visible content
3540 * doesn't change when we switch the backing file.
3541 */
Alex Bligha6166732012-10-16 13:46:18 +01003542 if (out_baseimg && *out_baseimg) {
3543 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3544 } else {
3545 ret = bdrv_change_backing_file(bs, NULL, NULL);
3546 }
3547
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003548 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003549 error_report("Could not change the backing file to '%s': No "
3550 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003551 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003552 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003553 out_baseimg, strerror(-ret));
3554 }
3555
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003556 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003557 /*
3558 * TODO At this point it is possible to check if any clusters that are
3559 * allocated in the COW file are the same in the backing file. If so, they
3560 * could be dropped from the COW file. Don't do this before switching the
3561 * backing file, in case of a crash this would lead to corruption.
3562 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003563out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003564 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003565 /* Cleanup */
3566 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003567 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003568 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003569 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003570 qemu_vfree(buf_old);
3571 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003572
Markus Armbruster26f54e92014-10-07 13:59:04 +02003573 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003574 if (ret) {
3575 return 1;
3576 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003577 return 0;
3578}
3579
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003580static int img_resize(int argc, char **argv)
3581{
Markus Armbruster6750e792015-02-12 17:43:08 +01003582 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003583 int c, ret, relative;
3584 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003585 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003586 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003587 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003588 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003589 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003590
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003591 static QemuOptsList resize_options = {
3592 .name = "resize_options",
3593 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3594 .desc = {
3595 {
3596 .name = BLOCK_OPT_SIZE,
3597 .type = QEMU_OPT_SIZE,
3598 .help = "Virtual disk size"
3599 }, {
3600 /* end of list */
3601 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003602 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003603 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003604 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003605 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003606
Kevin Wolfe80fec72011-04-29 10:58:12 +02003607 /* Remove size from argv manually so that negative numbers are not treated
3608 * as options by getopt. */
3609 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003610 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003611 return 1;
3612 }
3613
3614 size = argv[--argc];
3615
3616 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003617 fmt = NULL;
3618 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003619 static const struct option long_options[] = {
3620 {"help", no_argument, 0, 'h'},
3621 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003622 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003623 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003624 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003625 {0, 0, 0, 0}
3626 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003627 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003628 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003629 if (c == -1) {
3630 break;
3631 }
3632 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003633 case ':':
3634 missing_argument(argv[optind - 1]);
3635 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003636 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003637 unrecognized_option(argv[optind - 1]);
3638 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003639 case 'h':
3640 help();
3641 break;
3642 case 'f':
3643 fmt = optarg;
3644 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003645 case 'q':
3646 quiet = true;
3647 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003648 case OPTION_OBJECT: {
3649 QemuOpts *opts;
3650 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3651 optarg, true);
3652 if (!opts) {
3653 return 1;
3654 }
3655 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003656 case OPTION_IMAGE_OPTS:
3657 image_opts = true;
3658 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003659 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003660 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003661 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003662 if (prealloc == PREALLOC_MODE__MAX) {
3663 error_report("Invalid preallocation mode '%s'", optarg);
3664 return 1;
3665 }
3666 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003667 case OPTION_SHRINK:
3668 shrink = true;
3669 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003670 }
3671 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003672 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003673 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003674 }
3675 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003676
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003677 if (qemu_opts_foreach(&qemu_object_opts,
3678 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003679 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003680 return 1;
3681 }
3682
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003683 /* Choose grow, shrink, or absolute resize mode */
3684 switch (size[0]) {
3685 case '+':
3686 relative = 1;
3687 size++;
3688 break;
3689 case '-':
3690 relative = -1;
3691 size++;
3692 break;
3693 default:
3694 relative = 0;
3695 break;
3696 }
3697
3698 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003699 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003700 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003701 if (err) {
3702 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003703 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003704 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003705 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003706 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003707 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3708 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003709
Max Reitzefaa7c42016-03-16 19:54:38 +01003710 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003711 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3712 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003713 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003714 ret = -1;
3715 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003716 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003717
Max Reitzdc5f6902017-06-13 22:20:55 +02003718 current_size = blk_getlength(blk);
3719 if (current_size < 0) {
3720 error_report("Failed to inquire current image length: %s",
3721 strerror(-current_size));
3722 ret = -1;
3723 goto out;
3724 }
3725
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003726 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003727 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003728 } else {
3729 total_size = n;
3730 }
3731 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003732 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003733 ret = -1;
3734 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003735 }
3736
Max Reitzdc5f6902017-06-13 22:20:55 +02003737 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3738 error_report("Preallocation can only be used for growing images");
3739 ret = -1;
3740 goto out;
3741 }
3742
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003743 if (total_size < current_size && !shrink) {
3744 warn_report("Shrinking an image will delete all data beyond the "
3745 "shrunken image's end. Before performing such an "
3746 "operation, make sure there is no important data there.");
3747
3748 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3749 error_report(
3750 "Use the --shrink option to perform a shrink operation.");
3751 ret = -1;
3752 goto out;
3753 } else {
3754 warn_report("Using the --shrink option will suppress this message. "
3755 "Note that future versions of qemu-img may refuse to "
3756 "shrink images without this option.");
3757 }
3758 }
3759
Max Reitzdc5f6902017-06-13 22:20:55 +02003760 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003761 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003762 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003763 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003764 }
Max Reitz5279b302018-04-21 18:39:57 +02003765
3766 new_size = blk_getlength(blk);
3767 if (new_size < 0) {
3768 error_report("Failed to verify truncated image length: %s",
3769 strerror(-new_size));
3770 ret = -1;
3771 goto out;
3772 }
3773
3774 /* Some block drivers implement a truncation method, but only so
3775 * the user can cause qemu to refresh the image's size from disk.
3776 * The idea is that the user resizes the image outside of qemu and
3777 * then invokes block_resize to inform qemu about it.
3778 * (This includes iscsi and file-posix for device files.)
3779 * Of course, that is not the behavior someone invoking
3780 * qemu-img resize would find useful, so we catch that behavior
3781 * here and tell the user. */
3782 if (new_size != total_size && new_size == current_size) {
3783 error_report("Image was not resized; resizing may not be supported "
3784 "for this image");
3785 ret = -1;
3786 goto out;
3787 }
3788
3789 if (new_size != total_size) {
3790 warn_report("Image should have been resized to %" PRIi64
3791 " bytes, but was resized to %" PRIi64 " bytes",
3792 total_size, new_size);
3793 }
3794
3795 qprintf(quiet, "Image resized.\n");
3796
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003797out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003798 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003799 if (ret) {
3800 return 1;
3801 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003802 return 0;
3803}
3804
Max Reitz76a3a342014-10-27 11:12:51 +01003805static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003806 int64_t offset, int64_t total_work_size,
3807 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003808{
3809 qemu_progress_print(100.f * offset / total_work_size, 0);
3810}
3811
Max Reitz51641352018-05-09 23:00:20 +02003812static int print_amend_option_help(const char *format)
3813{
3814 BlockDriver *drv;
3815
3816 /* Find driver and parse its options */
3817 drv = bdrv_find_format(format);
3818 if (!drv) {
3819 error_report("Unknown file format '%s'", format);
3820 return 1;
3821 }
3822
3823 if (!drv->bdrv_amend_options) {
3824 error_report("Format driver '%s' does not support option amendment",
3825 format);
3826 return 1;
3827 }
3828
3829 /* Every driver supporting amendment must have create_opts */
3830 assert(drv->create_opts);
3831
3832 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003833 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003834 printf("\nNote that not all of these options may be amendable.\n");
3835 return 0;
3836}
3837
Max Reitz6f176b42013-09-03 10:09:50 +02003838static int img_amend(int argc, char **argv)
3839{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003840 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003841 int c, ret = 0;
3842 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003843 QemuOptsList *create_opts = NULL;
3844 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003845 const char *fmt = NULL, *filename, *cache;
3846 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003847 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003848 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003849 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003850 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003851 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003852
Max Reitzbd39e6e2014-07-22 22:58:43 +02003853 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003854 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003855 static const struct option long_options[] = {
3856 {"help", no_argument, 0, 'h'},
3857 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003858 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003859 {0, 0, 0, 0}
3860 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003861 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003862 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003863 if (c == -1) {
3864 break;
3865 }
3866
3867 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003868 case ':':
3869 missing_argument(argv[optind - 1]);
3870 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003871 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003872 unrecognized_option(argv[optind - 1]);
3873 break;
3874 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003875 help();
3876 break;
3877 case 'o':
3878 if (!is_valid_option_list(optarg)) {
3879 error_report("Invalid option list: %s", optarg);
3880 ret = -1;
3881 goto out_no_progress;
3882 }
3883 if (!options) {
3884 options = g_strdup(optarg);
3885 } else {
3886 char *old_options = options;
3887 options = g_strdup_printf("%s,%s", options, optarg);
3888 g_free(old_options);
3889 }
3890 break;
3891 case 'f':
3892 fmt = optarg;
3893 break;
3894 case 't':
3895 cache = optarg;
3896 break;
3897 case 'p':
3898 progress = true;
3899 break;
3900 case 'q':
3901 quiet = true;
3902 break;
3903 case OPTION_OBJECT:
3904 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3905 optarg, true);
3906 if (!opts) {
3907 ret = -1;
3908 goto out_no_progress;
3909 }
3910 break;
3911 case OPTION_IMAGE_OPTS:
3912 image_opts = true;
3913 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003914 }
3915 }
3916
Max Reitz6f176b42013-09-03 10:09:50 +02003917 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003918 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003919 }
3920
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003921 if (qemu_opts_foreach(&qemu_object_opts,
3922 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003923 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003924 ret = -1;
3925 goto out_no_progress;
3926 }
3927
Max Reitz76a3a342014-10-27 11:12:51 +01003928 if (quiet) {
3929 progress = false;
3930 }
3931 qemu_progress_init(progress, 1.0);
3932
Kevin Wolfa283cb62014-02-21 16:24:07 +01003933 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3934 if (fmt && has_help_option(options)) {
3935 /* If a format is explicitly specified (and possibly no filename is
3936 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003937 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003938 goto out;
3939 }
3940
3941 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003942 error_report("Expecting one image file name");
3943 ret = -1;
3944 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003945 }
Max Reitz6f176b42013-09-03 10:09:50 +02003946
Kevin Wolfce099542016-03-15 13:01:04 +01003947 flags = BDRV_O_RDWR;
3948 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003949 if (ret < 0) {
3950 error_report("Invalid cache option: %s", cache);
3951 goto out;
3952 }
3953
Fam Zheng335e9932017-05-03 00:35:39 +08003954 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3955 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003956 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003957 ret = -1;
3958 goto out;
3959 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003960 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003961
3962 fmt = bs->drv->format_name;
3963
Kevin Wolf626f84f2014-02-21 16:24:06 +01003964 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003965 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003966 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003967 goto out;
3968 }
3969
Max Reitz1f996682018-05-09 23:00:17 +02003970 if (!bs->drv->bdrv_amend_options) {
3971 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003972 fmt);
3973 ret = -1;
3974 goto out;
3975 }
3976
Max Reitz1f996682018-05-09 23:00:17 +02003977 /* Every driver supporting amendment must have create_opts */
3978 assert(bs->drv->create_opts);
3979
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003980 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003981 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003982 qemu_opts_do_parse(opts, options, NULL, &err);
3983 if (err) {
3984 error_report_err(err);
3985 ret = -1;
3986 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003987 }
3988
Max Reitz76a3a342014-10-27 11:12:51 +01003989 /* In case the driver does not call amend_status_cb() */
3990 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003991 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003992 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003993 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003994 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003995 goto out;
3996 }
3997
3998out:
Max Reitz76a3a342014-10-27 11:12:51 +01003999 qemu_progress_end();
4000
Max Reitze814dff2015-08-20 16:00:38 -07004001out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004002 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004003 qemu_opts_del(opts);
4004 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004005 g_free(options);
4006
Max Reitz6f176b42013-09-03 10:09:50 +02004007 if (ret) {
4008 return 1;
4009 }
4010 return 0;
4011}
4012
Kevin Wolfb6133b82014-08-05 14:17:13 +02004013typedef struct BenchData {
4014 BlockBackend *blk;
4015 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004016 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004017 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004018 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004019 int nrreq;
4020 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004021 int flush_interval;
4022 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004023 uint8_t *buf;
4024 QEMUIOVector *qiov;
4025
4026 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004027 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004028 uint64_t offset;
4029} BenchData;
4030
Kevin Wolf55d539c2016-06-03 13:59:41 +02004031static void bench_undrained_flush_cb(void *opaque, int ret)
4032{
4033 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004034 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004035 exit(EXIT_FAILURE);
4036 }
4037}
4038
Kevin Wolfb6133b82014-08-05 14:17:13 +02004039static void bench_cb(void *opaque, int ret)
4040{
4041 BenchData *b = opaque;
4042 BlockAIOCB *acb;
4043
4044 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004045 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004046 exit(EXIT_FAILURE);
4047 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004048
4049 if (b->in_flush) {
4050 /* Just finished a flush with drained queue: Start next requests */
4051 assert(b->in_flight == 0);
4052 b->in_flush = false;
4053 } else if (b->in_flight > 0) {
4054 int remaining = b->n - b->in_flight;
4055
Kevin Wolfb6133b82014-08-05 14:17:13 +02004056 b->n--;
4057 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004058
4059 /* Time for flush? Drain queue if requested, then flush */
4060 if (b->flush_interval && remaining % b->flush_interval == 0) {
4061 if (!b->in_flight || !b->drain_on_flush) {
4062 BlockCompletionFunc *cb;
4063
4064 if (b->drain_on_flush) {
4065 b->in_flush = true;
4066 cb = bench_cb;
4067 } else {
4068 cb = bench_undrained_flush_cb;
4069 }
4070
4071 acb = blk_aio_flush(b->blk, cb, b);
4072 if (!acb) {
4073 error_report("Failed to issue flush request");
4074 exit(EXIT_FAILURE);
4075 }
4076 }
4077 if (b->drain_on_flush) {
4078 return;
4079 }
4080 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004081 }
4082
4083 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004084 int64_t offset = b->offset;
4085 /* blk_aio_* might look for completed I/Os and kick bench_cb
4086 * again, so make sure this operation is counted by in_flight
4087 * and b->offset is ready for the next submission.
4088 */
4089 b->in_flight++;
4090 b->offset += b->step;
4091 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004092 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004093 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004094 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004095 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004096 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004097 if (!acb) {
4098 error_report("Failed to issue request");
4099 exit(EXIT_FAILURE);
4100 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004101 }
4102}
4103
4104static int img_bench(int argc, char **argv)
4105{
4106 int c, ret = 0;
4107 const char *fmt = NULL, *filename;
4108 bool quiet = false;
4109 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004110 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004111 int count = 75000;
4112 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004113 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004114 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004115 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004116 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004117 int flush_interval = 0;
4118 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004119 int64_t image_size;
4120 BlockBackend *blk = NULL;
4121 BenchData data = {};
4122 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004123 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004124 struct timeval t1, t2;
4125 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004126 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004127 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004128
4129 for (;;) {
4130 static const struct option long_options[] = {
4131 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004132 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004133 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004134 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004135 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004136 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004137 {0, 0, 0, 0}
4138 };
Fam Zheng335e9932017-05-03 00:35:39 +08004139 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004140 if (c == -1) {
4141 break;
4142 }
4143
4144 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004145 case ':':
4146 missing_argument(argv[optind - 1]);
4147 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004148 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004149 unrecognized_option(argv[optind - 1]);
4150 break;
4151 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004152 help();
4153 break;
4154 case 'c':
4155 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004156 unsigned long res;
4157
4158 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004159 error_report("Invalid request count specified");
4160 return 1;
4161 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004162 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004163 break;
4164 }
4165 case 'd':
4166 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004167 unsigned long res;
4168
4169 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004170 error_report("Invalid queue depth specified");
4171 return 1;
4172 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004173 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004174 break;
4175 }
4176 case 'f':
4177 fmt = optarg;
4178 break;
4179 case 'n':
4180 flags |= BDRV_O_NATIVE_AIO;
4181 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004182 case 'o':
4183 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004184 offset = cvtnum(optarg);
4185 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004186 error_report("Invalid offset specified");
4187 return 1;
4188 }
4189 break;
4190 }
4191 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004192 case 'q':
4193 quiet = true;
4194 break;
4195 case 's':
4196 {
4197 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004198
Markus Armbruster606caa02017-02-21 21:14:04 +01004199 sval = cvtnum(optarg);
4200 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004201 error_report("Invalid buffer size specified");
4202 return 1;
4203 }
4204
4205 bufsize = sval;
4206 break;
4207 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004208 case 'S':
4209 {
4210 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004211
Markus Armbruster606caa02017-02-21 21:14:04 +01004212 sval = cvtnum(optarg);
4213 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004214 error_report("Invalid step size specified");
4215 return 1;
4216 }
4217
4218 step = sval;
4219 break;
4220 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004221 case 't':
4222 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4223 if (ret < 0) {
4224 error_report("Invalid cache mode");
4225 ret = -1;
4226 goto out;
4227 }
4228 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004229 case 'w':
4230 flags |= BDRV_O_RDWR;
4231 is_write = true;
4232 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004233 case 'U':
4234 force_share = true;
4235 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004236 case OPTION_PATTERN:
4237 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004238 unsigned long res;
4239
4240 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004241 error_report("Invalid pattern byte specified");
4242 return 1;
4243 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004244 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004245 break;
4246 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004247 case OPTION_FLUSH_INTERVAL:
4248 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004249 unsigned long res;
4250
4251 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004252 error_report("Invalid flush interval specified");
4253 return 1;
4254 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004255 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004256 break;
4257 }
4258 case OPTION_NO_DRAIN:
4259 drain_on_flush = false;
4260 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004261 case OPTION_IMAGE_OPTS:
4262 image_opts = true;
4263 break;
4264 }
4265 }
4266
4267 if (optind != argc - 1) {
4268 error_exit("Expecting one image file name");
4269 }
4270 filename = argv[argc - 1];
4271
Kevin Wolf55d539c2016-06-03 13:59:41 +02004272 if (!is_write && flush_interval) {
4273 error_report("--flush-interval is only available in write tests");
4274 ret = -1;
4275 goto out;
4276 }
4277 if (flush_interval && flush_interval < depth) {
4278 error_report("Flush interval can't be smaller than depth");
4279 ret = -1;
4280 goto out;
4281 }
4282
Fam Zheng335e9932017-05-03 00:35:39 +08004283 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4284 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004285 if (!blk) {
4286 ret = -1;
4287 goto out;
4288 }
4289
4290 image_size = blk_getlength(blk);
4291 if (image_size < 0) {
4292 ret = image_size;
4293 goto out;
4294 }
4295
4296 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004297 .blk = blk,
4298 .image_size = image_size,
4299 .bufsize = bufsize,
4300 .step = step ?: bufsize,
4301 .nrreq = depth,
4302 .n = count,
4303 .offset = offset,
4304 .write = is_write,
4305 .flush_interval = flush_interval,
4306 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004307 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004308 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004309 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004310 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004311 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004312 if (flush_interval) {
4313 printf("Sending flush every %d requests\n", flush_interval);
4314 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004315
Fam Zheng79d46582018-01-16 14:08:58 +08004316 buf_size = data.nrreq * data.bufsize;
4317 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004318 memset(data.buf, pattern, data.nrreq * data.bufsize);
4319
Fam Zheng79d46582018-01-16 14:08:58 +08004320 blk_register_buf(blk, data.buf, buf_size);
4321
Kevin Wolfb6133b82014-08-05 14:17:13 +02004322 data.qiov = g_new(QEMUIOVector, data.nrreq);
4323 for (i = 0; i < data.nrreq; i++) {
4324 qemu_iovec_init(&data.qiov[i], 1);
4325 qemu_iovec_add(&data.qiov[i],
4326 data.buf + i * data.bufsize, data.bufsize);
4327 }
4328
4329 gettimeofday(&t1, NULL);
4330 bench_cb(&data, 0);
4331
4332 while (data.n > 0) {
4333 main_loop_wait(false);
4334 }
4335 gettimeofday(&t2, NULL);
4336
4337 printf("Run completed in %3.3f seconds.\n",
4338 (t2.tv_sec - t1.tv_sec)
4339 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4340
4341out:
Fam Zheng79d46582018-01-16 14:08:58 +08004342 if (data.buf) {
4343 blk_unregister_buf(blk, data.buf);
4344 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004345 qemu_vfree(data.buf);
4346 blk_unref(blk);
4347
4348 if (ret) {
4349 return 1;
4350 }
4351 return 0;
4352}
4353
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004354#define C_BS 01
4355#define C_COUNT 02
4356#define C_IF 04
4357#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004358#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004359
4360struct DdInfo {
4361 unsigned int flags;
4362 int64_t count;
4363};
4364
4365struct DdIo {
4366 int bsz; /* Block size */
4367 char *filename;
4368 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004369 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004370};
4371
4372struct DdOpts {
4373 const char *name;
4374 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4375 unsigned int flag;
4376};
4377
4378static int img_dd_bs(const char *arg,
4379 struct DdIo *in, struct DdIo *out,
4380 struct DdInfo *dd)
4381{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004382 int64_t res;
4383
Markus Armbruster606caa02017-02-21 21:14:04 +01004384 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004385
Markus Armbruster606caa02017-02-21 21:14:04 +01004386 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004387 error_report("invalid number: '%s'", arg);
4388 return 1;
4389 }
4390 in->bsz = out->bsz = res;
4391
4392 return 0;
4393}
4394
4395static int img_dd_count(const char *arg,
4396 struct DdIo *in, struct DdIo *out,
4397 struct DdInfo *dd)
4398{
Markus Armbruster606caa02017-02-21 21:14:04 +01004399 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004400
Markus Armbruster606caa02017-02-21 21:14:04 +01004401 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004402 error_report("invalid number: '%s'", arg);
4403 return 1;
4404 }
4405
4406 return 0;
4407}
4408
4409static int img_dd_if(const char *arg,
4410 struct DdIo *in, struct DdIo *out,
4411 struct DdInfo *dd)
4412{
4413 in->filename = g_strdup(arg);
4414
4415 return 0;
4416}
4417
4418static int img_dd_of(const char *arg,
4419 struct DdIo *in, struct DdIo *out,
4420 struct DdInfo *dd)
4421{
4422 out->filename = g_strdup(arg);
4423
4424 return 0;
4425}
4426
Reda Sallahif7c15532016-08-10 16:16:09 +02004427static int img_dd_skip(const char *arg,
4428 struct DdIo *in, struct DdIo *out,
4429 struct DdInfo *dd)
4430{
Markus Armbruster606caa02017-02-21 21:14:04 +01004431 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004432
Markus Armbruster606caa02017-02-21 21:14:04 +01004433 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004434 error_report("invalid number: '%s'", arg);
4435 return 1;
4436 }
4437
4438 return 0;
4439}
4440
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004441static int img_dd(int argc, char **argv)
4442{
4443 int ret = 0;
4444 char *arg = NULL;
4445 char *tmp;
4446 BlockDriver *drv = NULL, *proto_drv = NULL;
4447 BlockBackend *blk1 = NULL, *blk2 = NULL;
4448 QemuOpts *opts = NULL;
4449 QemuOptsList *create_opts = NULL;
4450 Error *local_err = NULL;
4451 bool image_opts = false;
4452 int c, i;
4453 const char *out_fmt = "raw";
4454 const char *fmt = NULL;
4455 int64_t size = 0;
4456 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004457 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004458 struct DdInfo dd = {
4459 .flags = 0,
4460 .count = 0,
4461 };
4462 struct DdIo in = {
4463 .bsz = 512, /* Block size is by default 512 bytes */
4464 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004465 .buf = NULL,
4466 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004467 };
4468 struct DdIo out = {
4469 .bsz = 512,
4470 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004471 .buf = NULL,
4472 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004473 };
4474
4475 const struct DdOpts options[] = {
4476 { "bs", img_dd_bs, C_BS },
4477 { "count", img_dd_count, C_COUNT },
4478 { "if", img_dd_if, C_IF },
4479 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004480 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004481 { NULL, NULL, 0 }
4482 };
4483 const struct option long_options[] = {
4484 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004485 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004486 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004487 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004488 { 0, 0, 0, 0 }
4489 };
4490
Fam Zheng335e9932017-05-03 00:35:39 +08004491 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004492 if (c == EOF) {
4493 break;
4494 }
4495 switch (c) {
4496 case 'O':
4497 out_fmt = optarg;
4498 break;
4499 case 'f':
4500 fmt = optarg;
4501 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004502 case ':':
4503 missing_argument(argv[optind - 1]);
4504 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004505 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004506 unrecognized_option(argv[optind - 1]);
4507 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004508 case 'h':
4509 help();
4510 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004511 case 'U':
4512 force_share = true;
4513 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004514 case OPTION_OBJECT:
4515 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004516 ret = -1;
4517 goto out;
4518 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004519 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004520 case OPTION_IMAGE_OPTS:
4521 image_opts = true;
4522 break;
4523 }
4524 }
4525
4526 for (i = optind; i < argc; i++) {
4527 int j;
4528 arg = g_strdup(argv[i]);
4529
4530 tmp = strchr(arg, '=');
4531 if (tmp == NULL) {
4532 error_report("unrecognized operand %s", arg);
4533 ret = -1;
4534 goto out;
4535 }
4536
4537 *tmp++ = '\0';
4538
4539 for (j = 0; options[j].name != NULL; j++) {
4540 if (!strcmp(arg, options[j].name)) {
4541 break;
4542 }
4543 }
4544 if (options[j].name == NULL) {
4545 error_report("unrecognized operand %s", arg);
4546 ret = -1;
4547 goto out;
4548 }
4549
4550 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4551 ret = -1;
4552 goto out;
4553 }
4554 dd.flags |= options[j].flag;
4555 g_free(arg);
4556 arg = NULL;
4557 }
4558
4559 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4560 error_report("Must specify both input and output files");
4561 ret = -1;
4562 goto out;
4563 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004564
4565 if (qemu_opts_foreach(&qemu_object_opts,
4566 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004567 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004568 ret = -1;
4569 goto out;
4570 }
4571
Fam Zheng335e9932017-05-03 00:35:39 +08004572 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4573 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004574
4575 if (!blk1) {
4576 ret = -1;
4577 goto out;
4578 }
4579
4580 drv = bdrv_find_format(out_fmt);
4581 if (!drv) {
4582 error_report("Unknown file format");
4583 ret = -1;
4584 goto out;
4585 }
4586 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4587
4588 if (!proto_drv) {
4589 error_report_err(local_err);
4590 ret = -1;
4591 goto out;
4592 }
4593 if (!drv->create_opts) {
4594 error_report("Format driver '%s' does not support image creation",
4595 drv->format_name);
4596 ret = -1;
4597 goto out;
4598 }
4599 if (!proto_drv->create_opts) {
4600 error_report("Protocol driver '%s' does not support image creation",
4601 proto_drv->format_name);
4602 ret = -1;
4603 goto out;
4604 }
4605 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4606 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4607
4608 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4609
4610 size = blk_getlength(blk1);
4611 if (size < 0) {
4612 error_report("Failed to get size for '%s'", in.filename);
4613 ret = -1;
4614 goto out;
4615 }
4616
4617 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4618 dd.count * in.bsz < size) {
4619 size = dd.count * in.bsz;
4620 }
4621
Reda Sallahif7c15532016-08-10 16:16:09 +02004622 /* Overflow means the specified offset is beyond input image's size */
4623 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4624 size < in.bsz * in.offset)) {
4625 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4626 } else {
4627 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4628 size - in.bsz * in.offset, &error_abort);
4629 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004630
4631 ret = bdrv_create(drv, out.filename, opts, &local_err);
4632 if (ret < 0) {
4633 error_reportf_err(local_err,
4634 "%s: error while creating output image: ",
4635 out.filename);
4636 ret = -1;
4637 goto out;
4638 }
4639
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004640 /* TODO, we can't honour --image-opts for the target,
4641 * since it needs to be given in a format compatible
4642 * with the bdrv_create() call above which does not
4643 * support image-opts style.
4644 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004645 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004646 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004647
4648 if (!blk2) {
4649 ret = -1;
4650 goto out;
4651 }
4652
Reda Sallahif7c15532016-08-10 16:16:09 +02004653 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4654 size < in.offset * in.bsz)) {
4655 /* We give a warning if the skip option is bigger than the input
4656 * size and create an empty output disk image (i.e. like dd(1)).
4657 */
4658 error_report("%s: cannot skip to specified offset", in.filename);
4659 in_pos = size;
4660 } else {
4661 in_pos = in.offset * in.bsz;
4662 }
4663
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004664 in.buf = g_new(uint8_t, in.bsz);
4665
Reda Sallahif7c15532016-08-10 16:16:09 +02004666 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004667 int in_ret, out_ret;
4668
4669 if (in_pos + in.bsz > size) {
4670 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4671 } else {
4672 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4673 }
4674 if (in_ret < 0) {
4675 error_report("error while reading from input image file: %s",
4676 strerror(-in_ret));
4677 ret = -1;
4678 goto out;
4679 }
4680 in_pos += in_ret;
4681
4682 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4683
4684 if (out_ret < 0) {
4685 error_report("error while writing to output image file: %s",
4686 strerror(-out_ret));
4687 ret = -1;
4688 goto out;
4689 }
4690 out_pos += out_ret;
4691 }
4692
4693out:
4694 g_free(arg);
4695 qemu_opts_del(opts);
4696 qemu_opts_free(create_opts);
4697 blk_unref(blk1);
4698 blk_unref(blk2);
4699 g_free(in.filename);
4700 g_free(out.filename);
4701 g_free(in.buf);
4702 g_free(out.buf);
4703
4704 if (ret) {
4705 return 1;
4706 }
4707 return 0;
4708}
4709
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004710static void dump_json_block_measure_info(BlockMeasureInfo *info)
4711{
4712 QString *str;
4713 QObject *obj;
4714 Visitor *v = qobject_output_visitor_new(&obj);
4715
4716 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4717 visit_complete(v, &obj);
4718 str = qobject_to_json_pretty(obj);
4719 assert(str != NULL);
4720 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004721 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004722 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004723 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004724}
4725
4726static int img_measure(int argc, char **argv)
4727{
4728 static const struct option long_options[] = {
4729 {"help", no_argument, 0, 'h'},
4730 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4731 {"object", required_argument, 0, OPTION_OBJECT},
4732 {"output", required_argument, 0, OPTION_OUTPUT},
4733 {"size", required_argument, 0, OPTION_SIZE},
4734 {"force-share", no_argument, 0, 'U'},
4735 {0, 0, 0, 0}
4736 };
4737 OutputFormat output_format = OFORMAT_HUMAN;
4738 BlockBackend *in_blk = NULL;
4739 BlockDriver *drv;
4740 const char *filename = NULL;
4741 const char *fmt = NULL;
4742 const char *out_fmt = "raw";
4743 char *options = NULL;
4744 char *snapshot_name = NULL;
4745 bool force_share = false;
4746 QemuOpts *opts = NULL;
4747 QemuOpts *object_opts = NULL;
4748 QemuOpts *sn_opts = NULL;
4749 QemuOptsList *create_opts = NULL;
4750 bool image_opts = false;
4751 uint64_t img_size = UINT64_MAX;
4752 BlockMeasureInfo *info = NULL;
4753 Error *local_err = NULL;
4754 int ret = 1;
4755 int c;
4756
4757 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4758 long_options, NULL)) != -1) {
4759 switch (c) {
4760 case '?':
4761 case 'h':
4762 help();
4763 break;
4764 case 'f':
4765 fmt = optarg;
4766 break;
4767 case 'O':
4768 out_fmt = optarg;
4769 break;
4770 case 'o':
4771 if (!is_valid_option_list(optarg)) {
4772 error_report("Invalid option list: %s", optarg);
4773 goto out;
4774 }
4775 if (!options) {
4776 options = g_strdup(optarg);
4777 } else {
4778 char *old_options = options;
4779 options = g_strdup_printf("%s,%s", options, optarg);
4780 g_free(old_options);
4781 }
4782 break;
4783 case 'l':
4784 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4785 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4786 optarg, false);
4787 if (!sn_opts) {
4788 error_report("Failed in parsing snapshot param '%s'",
4789 optarg);
4790 goto out;
4791 }
4792 } else {
4793 snapshot_name = optarg;
4794 }
4795 break;
4796 case 'U':
4797 force_share = true;
4798 break;
4799 case OPTION_OBJECT:
4800 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4801 optarg, true);
4802 if (!object_opts) {
4803 goto out;
4804 }
4805 break;
4806 case OPTION_IMAGE_OPTS:
4807 image_opts = true;
4808 break;
4809 case OPTION_OUTPUT:
4810 if (!strcmp(optarg, "json")) {
4811 output_format = OFORMAT_JSON;
4812 } else if (!strcmp(optarg, "human")) {
4813 output_format = OFORMAT_HUMAN;
4814 } else {
4815 error_report("--output must be used with human or json "
4816 "as argument.");
4817 goto out;
4818 }
4819 break;
4820 case OPTION_SIZE:
4821 {
4822 int64_t sval;
4823
4824 sval = cvtnum(optarg);
4825 if (sval < 0) {
4826 if (sval == -ERANGE) {
4827 error_report("Image size must be less than 8 EiB!");
4828 } else {
4829 error_report("Invalid image size specified! You may use "
4830 "k, M, G, T, P or E suffixes for ");
4831 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4832 "petabytes and exabytes.");
4833 }
4834 goto out;
4835 }
4836 img_size = (uint64_t)sval;
4837 }
4838 break;
4839 }
4840 }
4841
4842 if (qemu_opts_foreach(&qemu_object_opts,
4843 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004844 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004845 goto out;
4846 }
4847
4848 if (argc - optind > 1) {
4849 error_report("At most one filename argument is allowed.");
4850 goto out;
4851 } else if (argc - optind == 1) {
4852 filename = argv[optind];
4853 }
4854
4855 if (!filename &&
4856 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4857 error_report("--object, --image-opts, -f, and -l "
4858 "require a filename argument.");
4859 goto out;
4860 }
4861 if (filename && img_size != UINT64_MAX) {
4862 error_report("--size N cannot be used together with a filename.");
4863 goto out;
4864 }
4865 if (!filename && img_size == UINT64_MAX) {
4866 error_report("Either --size N or one filename must be specified.");
4867 goto out;
4868 }
4869
4870 if (filename) {
4871 in_blk = img_open(image_opts, filename, fmt, 0,
4872 false, false, force_share);
4873 if (!in_blk) {
4874 goto out;
4875 }
4876
4877 if (sn_opts) {
4878 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4879 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4880 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4881 &local_err);
4882 } else if (snapshot_name != NULL) {
4883 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4884 snapshot_name, &local_err);
4885 }
4886 if (local_err) {
4887 error_reportf_err(local_err, "Failed to load snapshot: ");
4888 goto out;
4889 }
4890 }
4891
4892 drv = bdrv_find_format(out_fmt);
4893 if (!drv) {
4894 error_report("Unknown file format '%s'", out_fmt);
4895 goto out;
4896 }
4897 if (!drv->create_opts) {
4898 error_report("Format driver '%s' does not support image creation",
4899 drv->format_name);
4900 goto out;
4901 }
4902
4903 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4904 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4905 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4906 if (options) {
4907 qemu_opts_do_parse(opts, options, NULL, &local_err);
4908 if (local_err) {
4909 error_report_err(local_err);
4910 error_report("Invalid options for file format '%s'", out_fmt);
4911 goto out;
4912 }
4913 }
4914 if (img_size != UINT64_MAX) {
4915 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4916 }
4917
4918 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4919 if (local_err) {
4920 error_report_err(local_err);
4921 goto out;
4922 }
4923
4924 if (output_format == OFORMAT_HUMAN) {
4925 printf("required size: %" PRIu64 "\n", info->required);
4926 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4927 } else {
4928 dump_json_block_measure_info(info);
4929 }
4930
4931 ret = 0;
4932
4933out:
4934 qapi_free_BlockMeasureInfo(info);
4935 qemu_opts_del(object_opts);
4936 qemu_opts_del(opts);
4937 qemu_opts_del(sn_opts);
4938 qemu_opts_free(create_opts);
4939 g_free(options);
4940 blk_unref(in_blk);
4941 return ret;
4942}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004943
Anthony Liguoric227f092009-10-01 16:12:16 -05004944static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004945#define DEF(option, callback, arg_string) \
4946 { option, callback },
4947#include "qemu-img-cmds.h"
4948#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004949 { NULL, NULL, },
4950};
4951
bellardea2384d2004-08-01 21:59:26 +00004952int main(int argc, char **argv)
4953{
Anthony Liguoric227f092009-10-01 16:12:16 -05004954 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004955 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004956 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004957 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004958 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004959 static const struct option long_options[] = {
4960 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004961 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004962 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004963 {0, 0, 0, 0}
4964 };
bellardea2384d2004-08-01 21:59:26 +00004965
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004966#ifdef CONFIG_POSIX
4967 signal(SIGPIPE, SIG_IGN);
4968#endif
4969
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01004970 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004971 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004972 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004973
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004974 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004975 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004976 exit(EXIT_FAILURE);
4977 }
4978
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004979 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004980
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004981 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004982 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004983 if (argc < 2) {
4984 error_exit("Not enough arguments");
4985 }
Stuart Brady153859b2009-06-07 00:42:17 +01004986
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004987 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004988 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004989 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004990
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004991 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004992 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004993 case ':':
4994 missing_argument(argv[optind - 1]);
4995 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004996 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004997 unrecognized_option(argv[optind - 1]);
4998 return 0;
4999 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005000 help();
5001 return 0;
5002 case 'V':
5003 printf(QEMU_IMG_VERSION);
5004 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005005 case 'T':
5006 g_free(trace_file);
5007 trace_file = trace_opt_parse(optarg);
5008 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005009 }
bellardea2384d2004-08-01 21:59:26 +00005010 }
Stuart Brady153859b2009-06-07 00:42:17 +01005011
Denis V. Lunev10985132016-06-17 17:44:13 +03005012 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005013
Denis V. Lunev10985132016-06-17 17:44:13 +03005014 /* reset getopt_long scanning */
5015 argc -= optind;
5016 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005017 return 0;
5018 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005019 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005020 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005021
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005022 if (!trace_init_backends()) {
5023 exit(1);
5024 }
5025 trace_init_file(trace_file);
5026 qemu_set_log(LOG_TRACE);
5027
Denis V. Lunev10985132016-06-17 17:44:13 +03005028 /* find the command */
5029 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5030 if (!strcmp(cmdname, cmd->name)) {
5031 return cmd->handler(argc, argv);
5032 }
5033 }
Jeff Cody7db16892014-04-25 17:02:32 -04005034
Stuart Brady153859b2009-06-07 00:42:17 +01005035 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005036 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005037}