blob: 9bd0bb1e4726285ea7d27d80b0fe1672cab2d049 [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;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003167 BlockDriverState *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
3356 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003357 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003358 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003359 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003360 error_reportf_err(local_err,
3361 "Could not open new backing file '%s': ",
3362 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003363 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003364 goto out;
3365 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003366 }
3367 }
3368
3369 /*
3370 * Check each unallocated cluster in the COW file. If it is unallocated,
3371 * accesses go to the backing file. We must therefore compare this cluster
3372 * in the old and new backing file, and if they differ we need to copy it
3373 * from the old backing file into the COW file.
3374 *
3375 * If qemu-img crashes during this step, no harm is done. The content of
3376 * the image is the same as the original one at any time.
3377 */
3378 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003379 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003380 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003381 int64_t new_backing_size = 0;
3382 uint64_t offset;
3383 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003384 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003385
Max Reitzf1d3cd72015-02-05 13:58:18 -05003386 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3387 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003388
Eric Blake41536282017-10-11 22:47:15 -05003389 size = blk_getlength(blk);
3390 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003391 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003392 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003393 ret = -1;
3394 goto out;
3395 }
Max Reitz35ddd932019-05-09 19:52:35 +02003396 if (blk_old_backing) {
3397 old_backing_size = blk_getlength(blk_old_backing);
3398 if (old_backing_size < 0) {
3399 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003400
Max Reitz35ddd932019-05-09 19:52:35 +02003401 bdrv_get_backing_filename(bs, backing_name,
3402 sizeof(backing_name));
3403 error_report("Could not get size of '%s': %s",
3404 backing_name, strerror(-old_backing_size));
3405 ret = -1;
3406 goto out;
3407 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003408 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003409 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003410 new_backing_size = blk_getlength(blk_new_backing);
3411 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003412 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003413 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003414 ret = -1;
3415 goto out;
3416 }
Alex Bligha6166732012-10-16 13:46:18 +01003417 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003418
Eric Blake41536282017-10-11 22:47:15 -05003419 if (size != 0) {
3420 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003421 }
3422
Eric Blake41536282017-10-11 22:47:15 -05003423 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003424 bool buf_old_is_zero = false;
3425
Eric Blake41536282017-10-11 22:47:15 -05003426 /* How many bytes can we handle with the next read? */
3427 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003428
3429 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003430 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003431 if (ret < 0) {
3432 error_report("error while reading image metadata: %s",
3433 strerror(-ret));
3434 goto out;
3435 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003436 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003437 continue;
3438 }
3439
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003440 /*
3441 * Read old and new backing file and take into consideration that
3442 * backing files may be smaller than the COW image.
3443 */
Eric Blake41536282017-10-11 22:47:15 -05003444 if (offset >= old_backing_size) {
3445 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003446 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003447 } else {
Eric Blake41536282017-10-11 22:47:15 -05003448 if (offset + n > old_backing_size) {
3449 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003450 }
3451
Eric Blake41536282017-10-11 22:47:15 -05003452 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003453 if (ret < 0) {
3454 error_report("error while reading from old backing file");
3455 goto out;
3456 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003457 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003458
Eric Blake41536282017-10-11 22:47:15 -05003459 if (offset >= new_backing_size || !blk_new_backing) {
3460 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003461 } else {
Eric Blake41536282017-10-11 22:47:15 -05003462 if (offset + n > new_backing_size) {
3463 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003464 }
3465
Eric Blake41536282017-10-11 22:47:15 -05003466 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003467 if (ret < 0) {
3468 error_report("error while reading from new backing file");
3469 goto out;
3470 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003471 }
3472
3473 /* If they differ, we need to write to the COW file */
3474 uint64_t written = 0;
3475
Eric Blake41536282017-10-11 22:47:15 -05003476 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003477 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003478
Eric Blake41536282017-10-11 22:47:15 -05003479 if (compare_buffers(buf_old + written, buf_new + written,
3480 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003481 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003482 if (buf_old_is_zero) {
3483 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3484 } else {
3485 ret = blk_pwrite(blk, offset + written,
3486 buf_old + written, pnum, 0);
3487 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003488 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003489 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003490 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003491 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003492 }
3493 }
3494
3495 written += pnum;
3496 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003497 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003498 }
3499 }
3500
3501 /*
3502 * Change the backing file. All clusters that are different from the old
3503 * backing file are overwritten in the COW file now, so the visible content
3504 * doesn't change when we switch the backing file.
3505 */
Alex Bligha6166732012-10-16 13:46:18 +01003506 if (out_baseimg && *out_baseimg) {
3507 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3508 } else {
3509 ret = bdrv_change_backing_file(bs, NULL, NULL);
3510 }
3511
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003512 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003513 error_report("Could not change the backing file to '%s': No "
3514 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003515 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003516 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003517 out_baseimg, strerror(-ret));
3518 }
3519
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003520 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003521 /*
3522 * TODO At this point it is possible to check if any clusters that are
3523 * allocated in the COW file are the same in the backing file. If so, they
3524 * could be dropped from the COW file. Don't do this before switching the
3525 * backing file, in case of a crash this would lead to corruption.
3526 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003527out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003528 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003529 /* Cleanup */
3530 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003531 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003532 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003533 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003534 qemu_vfree(buf_old);
3535 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003536
Markus Armbruster26f54e92014-10-07 13:59:04 +02003537 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003538 if (ret) {
3539 return 1;
3540 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003541 return 0;
3542}
3543
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003544static int img_resize(int argc, char **argv)
3545{
Markus Armbruster6750e792015-02-12 17:43:08 +01003546 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003547 int c, ret, relative;
3548 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003549 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003550 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003551 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003552 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003553 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003554
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003555 static QemuOptsList resize_options = {
3556 .name = "resize_options",
3557 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3558 .desc = {
3559 {
3560 .name = BLOCK_OPT_SIZE,
3561 .type = QEMU_OPT_SIZE,
3562 .help = "Virtual disk size"
3563 }, {
3564 /* end of list */
3565 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003566 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003567 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003568 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003569 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003570
Kevin Wolfe80fec72011-04-29 10:58:12 +02003571 /* Remove size from argv manually so that negative numbers are not treated
3572 * as options by getopt. */
3573 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003574 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003575 return 1;
3576 }
3577
3578 size = argv[--argc];
3579
3580 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003581 fmt = NULL;
3582 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003583 static const struct option long_options[] = {
3584 {"help", no_argument, 0, 'h'},
3585 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003586 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003587 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003588 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003589 {0, 0, 0, 0}
3590 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003591 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003592 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003593 if (c == -1) {
3594 break;
3595 }
3596 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003597 case ':':
3598 missing_argument(argv[optind - 1]);
3599 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003600 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003601 unrecognized_option(argv[optind - 1]);
3602 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003603 case 'h':
3604 help();
3605 break;
3606 case 'f':
3607 fmt = optarg;
3608 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003609 case 'q':
3610 quiet = true;
3611 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003612 case OPTION_OBJECT: {
3613 QemuOpts *opts;
3614 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3615 optarg, true);
3616 if (!opts) {
3617 return 1;
3618 }
3619 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003620 case OPTION_IMAGE_OPTS:
3621 image_opts = true;
3622 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003623 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003624 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003625 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003626 if (prealloc == PREALLOC_MODE__MAX) {
3627 error_report("Invalid preallocation mode '%s'", optarg);
3628 return 1;
3629 }
3630 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003631 case OPTION_SHRINK:
3632 shrink = true;
3633 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003634 }
3635 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003636 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003637 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003638 }
3639 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003640
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003641 if (qemu_opts_foreach(&qemu_object_opts,
3642 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003643 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003644 return 1;
3645 }
3646
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003647 /* Choose grow, shrink, or absolute resize mode */
3648 switch (size[0]) {
3649 case '+':
3650 relative = 1;
3651 size++;
3652 break;
3653 case '-':
3654 relative = -1;
3655 size++;
3656 break;
3657 default:
3658 relative = 0;
3659 break;
3660 }
3661
3662 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003663 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003664 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003665 if (err) {
3666 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003667 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003668 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003669 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003670 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003671 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3672 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003673
Max Reitzefaa7c42016-03-16 19:54:38 +01003674 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003675 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3676 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003677 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003678 ret = -1;
3679 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003680 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003681
Max Reitzdc5f6902017-06-13 22:20:55 +02003682 current_size = blk_getlength(blk);
3683 if (current_size < 0) {
3684 error_report("Failed to inquire current image length: %s",
3685 strerror(-current_size));
3686 ret = -1;
3687 goto out;
3688 }
3689
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003690 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003691 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003692 } else {
3693 total_size = n;
3694 }
3695 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003696 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003697 ret = -1;
3698 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003699 }
3700
Max Reitzdc5f6902017-06-13 22:20:55 +02003701 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3702 error_report("Preallocation can only be used for growing images");
3703 ret = -1;
3704 goto out;
3705 }
3706
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003707 if (total_size < current_size && !shrink) {
3708 warn_report("Shrinking an image will delete all data beyond the "
3709 "shrunken image's end. Before performing such an "
3710 "operation, make sure there is no important data there.");
3711
3712 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3713 error_report(
3714 "Use the --shrink option to perform a shrink operation.");
3715 ret = -1;
3716 goto out;
3717 } else {
3718 warn_report("Using the --shrink option will suppress this message. "
3719 "Note that future versions of qemu-img may refuse to "
3720 "shrink images without this option.");
3721 }
3722 }
3723
Max Reitzdc5f6902017-06-13 22:20:55 +02003724 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003725 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003726 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003727 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003728 }
Max Reitz5279b302018-04-21 18:39:57 +02003729
3730 new_size = blk_getlength(blk);
3731 if (new_size < 0) {
3732 error_report("Failed to verify truncated image length: %s",
3733 strerror(-new_size));
3734 ret = -1;
3735 goto out;
3736 }
3737
3738 /* Some block drivers implement a truncation method, but only so
3739 * the user can cause qemu to refresh the image's size from disk.
3740 * The idea is that the user resizes the image outside of qemu and
3741 * then invokes block_resize to inform qemu about it.
3742 * (This includes iscsi and file-posix for device files.)
3743 * Of course, that is not the behavior someone invoking
3744 * qemu-img resize would find useful, so we catch that behavior
3745 * here and tell the user. */
3746 if (new_size != total_size && new_size == current_size) {
3747 error_report("Image was not resized; resizing may not be supported "
3748 "for this image");
3749 ret = -1;
3750 goto out;
3751 }
3752
3753 if (new_size != total_size) {
3754 warn_report("Image should have been resized to %" PRIi64
3755 " bytes, but was resized to %" PRIi64 " bytes",
3756 total_size, new_size);
3757 }
3758
3759 qprintf(quiet, "Image resized.\n");
3760
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003761out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003762 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003763 if (ret) {
3764 return 1;
3765 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003766 return 0;
3767}
3768
Max Reitz76a3a342014-10-27 11:12:51 +01003769static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003770 int64_t offset, int64_t total_work_size,
3771 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003772{
3773 qemu_progress_print(100.f * offset / total_work_size, 0);
3774}
3775
Max Reitz51641352018-05-09 23:00:20 +02003776static int print_amend_option_help(const char *format)
3777{
3778 BlockDriver *drv;
3779
3780 /* Find driver and parse its options */
3781 drv = bdrv_find_format(format);
3782 if (!drv) {
3783 error_report("Unknown file format '%s'", format);
3784 return 1;
3785 }
3786
3787 if (!drv->bdrv_amend_options) {
3788 error_report("Format driver '%s' does not support option amendment",
3789 format);
3790 return 1;
3791 }
3792
3793 /* Every driver supporting amendment must have create_opts */
3794 assert(drv->create_opts);
3795
3796 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003797 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003798 printf("\nNote that not all of these options may be amendable.\n");
3799 return 0;
3800}
3801
Max Reitz6f176b42013-09-03 10:09:50 +02003802static int img_amend(int argc, char **argv)
3803{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003804 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003805 int c, ret = 0;
3806 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003807 QemuOptsList *create_opts = NULL;
3808 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003809 const char *fmt = NULL, *filename, *cache;
3810 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003811 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003812 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003813 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003814 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003815 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003816
Max Reitzbd39e6e2014-07-22 22:58:43 +02003817 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003818 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003819 static const struct option long_options[] = {
3820 {"help", no_argument, 0, 'h'},
3821 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003822 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003823 {0, 0, 0, 0}
3824 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003825 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003826 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003827 if (c == -1) {
3828 break;
3829 }
3830
3831 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003832 case ':':
3833 missing_argument(argv[optind - 1]);
3834 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003835 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003836 unrecognized_option(argv[optind - 1]);
3837 break;
3838 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003839 help();
3840 break;
3841 case 'o':
3842 if (!is_valid_option_list(optarg)) {
3843 error_report("Invalid option list: %s", optarg);
3844 ret = -1;
3845 goto out_no_progress;
3846 }
3847 if (!options) {
3848 options = g_strdup(optarg);
3849 } else {
3850 char *old_options = options;
3851 options = g_strdup_printf("%s,%s", options, optarg);
3852 g_free(old_options);
3853 }
3854 break;
3855 case 'f':
3856 fmt = optarg;
3857 break;
3858 case 't':
3859 cache = optarg;
3860 break;
3861 case 'p':
3862 progress = true;
3863 break;
3864 case 'q':
3865 quiet = true;
3866 break;
3867 case OPTION_OBJECT:
3868 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3869 optarg, true);
3870 if (!opts) {
3871 ret = -1;
3872 goto out_no_progress;
3873 }
3874 break;
3875 case OPTION_IMAGE_OPTS:
3876 image_opts = true;
3877 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003878 }
3879 }
3880
Max Reitz6f176b42013-09-03 10:09:50 +02003881 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003882 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003883 }
3884
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003885 if (qemu_opts_foreach(&qemu_object_opts,
3886 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003887 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003888 ret = -1;
3889 goto out_no_progress;
3890 }
3891
Max Reitz76a3a342014-10-27 11:12:51 +01003892 if (quiet) {
3893 progress = false;
3894 }
3895 qemu_progress_init(progress, 1.0);
3896
Kevin Wolfa283cb62014-02-21 16:24:07 +01003897 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3898 if (fmt && has_help_option(options)) {
3899 /* If a format is explicitly specified (and possibly no filename is
3900 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003901 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003902 goto out;
3903 }
3904
3905 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003906 error_report("Expecting one image file name");
3907 ret = -1;
3908 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003909 }
Max Reitz6f176b42013-09-03 10:09:50 +02003910
Kevin Wolfce099542016-03-15 13:01:04 +01003911 flags = BDRV_O_RDWR;
3912 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003913 if (ret < 0) {
3914 error_report("Invalid cache option: %s", cache);
3915 goto out;
3916 }
3917
Fam Zheng335e9932017-05-03 00:35:39 +08003918 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3919 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003920 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003921 ret = -1;
3922 goto out;
3923 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003924 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003925
3926 fmt = bs->drv->format_name;
3927
Kevin Wolf626f84f2014-02-21 16:24:06 +01003928 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003929 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003930 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003931 goto out;
3932 }
3933
Max Reitz1f996682018-05-09 23:00:17 +02003934 if (!bs->drv->bdrv_amend_options) {
3935 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003936 fmt);
3937 ret = -1;
3938 goto out;
3939 }
3940
Max Reitz1f996682018-05-09 23:00:17 +02003941 /* Every driver supporting amendment must have create_opts */
3942 assert(bs->drv->create_opts);
3943
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003944 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003945 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003946 qemu_opts_do_parse(opts, options, NULL, &err);
3947 if (err) {
3948 error_report_err(err);
3949 ret = -1;
3950 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003951 }
3952
Max Reitz76a3a342014-10-27 11:12:51 +01003953 /* In case the driver does not call amend_status_cb() */
3954 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003955 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003956 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003957 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003958 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003959 goto out;
3960 }
3961
3962out:
Max Reitz76a3a342014-10-27 11:12:51 +01003963 qemu_progress_end();
3964
Max Reitze814dff2015-08-20 16:00:38 -07003965out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003966 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003967 qemu_opts_del(opts);
3968 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003969 g_free(options);
3970
Max Reitz6f176b42013-09-03 10:09:50 +02003971 if (ret) {
3972 return 1;
3973 }
3974 return 0;
3975}
3976
Kevin Wolfb6133b82014-08-05 14:17:13 +02003977typedef struct BenchData {
3978 BlockBackend *blk;
3979 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003980 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003981 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003982 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003983 int nrreq;
3984 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003985 int flush_interval;
3986 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003987 uint8_t *buf;
3988 QEMUIOVector *qiov;
3989
3990 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003991 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003992 uint64_t offset;
3993} BenchData;
3994
Kevin Wolf55d539c2016-06-03 13:59:41 +02003995static void bench_undrained_flush_cb(void *opaque, int ret)
3996{
3997 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003998 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003999 exit(EXIT_FAILURE);
4000 }
4001}
4002
Kevin Wolfb6133b82014-08-05 14:17:13 +02004003static void bench_cb(void *opaque, int ret)
4004{
4005 BenchData *b = opaque;
4006 BlockAIOCB *acb;
4007
4008 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004009 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004010 exit(EXIT_FAILURE);
4011 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004012
4013 if (b->in_flush) {
4014 /* Just finished a flush with drained queue: Start next requests */
4015 assert(b->in_flight == 0);
4016 b->in_flush = false;
4017 } else if (b->in_flight > 0) {
4018 int remaining = b->n - b->in_flight;
4019
Kevin Wolfb6133b82014-08-05 14:17:13 +02004020 b->n--;
4021 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004022
4023 /* Time for flush? Drain queue if requested, then flush */
4024 if (b->flush_interval && remaining % b->flush_interval == 0) {
4025 if (!b->in_flight || !b->drain_on_flush) {
4026 BlockCompletionFunc *cb;
4027
4028 if (b->drain_on_flush) {
4029 b->in_flush = true;
4030 cb = bench_cb;
4031 } else {
4032 cb = bench_undrained_flush_cb;
4033 }
4034
4035 acb = blk_aio_flush(b->blk, cb, b);
4036 if (!acb) {
4037 error_report("Failed to issue flush request");
4038 exit(EXIT_FAILURE);
4039 }
4040 }
4041 if (b->drain_on_flush) {
4042 return;
4043 }
4044 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004045 }
4046
4047 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004048 int64_t offset = b->offset;
4049 /* blk_aio_* might look for completed I/Os and kick bench_cb
4050 * again, so make sure this operation is counted by in_flight
4051 * and b->offset is ready for the next submission.
4052 */
4053 b->in_flight++;
4054 b->offset += b->step;
4055 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004056 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004057 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004058 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004059 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004060 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004061 if (!acb) {
4062 error_report("Failed to issue request");
4063 exit(EXIT_FAILURE);
4064 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004065 }
4066}
4067
4068static int img_bench(int argc, char **argv)
4069{
4070 int c, ret = 0;
4071 const char *fmt = NULL, *filename;
4072 bool quiet = false;
4073 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004074 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004075 int count = 75000;
4076 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004077 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004078 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004079 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004080 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004081 int flush_interval = 0;
4082 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004083 int64_t image_size;
4084 BlockBackend *blk = NULL;
4085 BenchData data = {};
4086 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004087 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004088 struct timeval t1, t2;
4089 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004090 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004091 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004092
4093 for (;;) {
4094 static const struct option long_options[] = {
4095 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004096 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004097 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004098 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004099 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004100 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004101 {0, 0, 0, 0}
4102 };
Fam Zheng335e9932017-05-03 00:35:39 +08004103 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004104 if (c == -1) {
4105 break;
4106 }
4107
4108 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004109 case ':':
4110 missing_argument(argv[optind - 1]);
4111 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004112 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004113 unrecognized_option(argv[optind - 1]);
4114 break;
4115 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004116 help();
4117 break;
4118 case 'c':
4119 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004120 unsigned long res;
4121
4122 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004123 error_report("Invalid request count specified");
4124 return 1;
4125 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004126 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004127 break;
4128 }
4129 case 'd':
4130 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004131 unsigned long res;
4132
4133 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004134 error_report("Invalid queue depth specified");
4135 return 1;
4136 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004137 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004138 break;
4139 }
4140 case 'f':
4141 fmt = optarg;
4142 break;
4143 case 'n':
4144 flags |= BDRV_O_NATIVE_AIO;
4145 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004146 case 'o':
4147 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004148 offset = cvtnum(optarg);
4149 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004150 error_report("Invalid offset specified");
4151 return 1;
4152 }
4153 break;
4154 }
4155 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004156 case 'q':
4157 quiet = true;
4158 break;
4159 case 's':
4160 {
4161 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004162
Markus Armbruster606caa02017-02-21 21:14:04 +01004163 sval = cvtnum(optarg);
4164 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004165 error_report("Invalid buffer size specified");
4166 return 1;
4167 }
4168
4169 bufsize = sval;
4170 break;
4171 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004172 case 'S':
4173 {
4174 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004175
Markus Armbruster606caa02017-02-21 21:14:04 +01004176 sval = cvtnum(optarg);
4177 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004178 error_report("Invalid step size specified");
4179 return 1;
4180 }
4181
4182 step = sval;
4183 break;
4184 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004185 case 't':
4186 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4187 if (ret < 0) {
4188 error_report("Invalid cache mode");
4189 ret = -1;
4190 goto out;
4191 }
4192 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004193 case 'w':
4194 flags |= BDRV_O_RDWR;
4195 is_write = true;
4196 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004197 case 'U':
4198 force_share = true;
4199 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004200 case OPTION_PATTERN:
4201 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004202 unsigned long res;
4203
4204 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004205 error_report("Invalid pattern byte specified");
4206 return 1;
4207 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004208 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004209 break;
4210 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004211 case OPTION_FLUSH_INTERVAL:
4212 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004213 unsigned long res;
4214
4215 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004216 error_report("Invalid flush interval specified");
4217 return 1;
4218 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004219 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004220 break;
4221 }
4222 case OPTION_NO_DRAIN:
4223 drain_on_flush = false;
4224 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004225 case OPTION_IMAGE_OPTS:
4226 image_opts = true;
4227 break;
4228 }
4229 }
4230
4231 if (optind != argc - 1) {
4232 error_exit("Expecting one image file name");
4233 }
4234 filename = argv[argc - 1];
4235
Kevin Wolf55d539c2016-06-03 13:59:41 +02004236 if (!is_write && flush_interval) {
4237 error_report("--flush-interval is only available in write tests");
4238 ret = -1;
4239 goto out;
4240 }
4241 if (flush_interval && flush_interval < depth) {
4242 error_report("Flush interval can't be smaller than depth");
4243 ret = -1;
4244 goto out;
4245 }
4246
Fam Zheng335e9932017-05-03 00:35:39 +08004247 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4248 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004249 if (!blk) {
4250 ret = -1;
4251 goto out;
4252 }
4253
4254 image_size = blk_getlength(blk);
4255 if (image_size < 0) {
4256 ret = image_size;
4257 goto out;
4258 }
4259
4260 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004261 .blk = blk,
4262 .image_size = image_size,
4263 .bufsize = bufsize,
4264 .step = step ?: bufsize,
4265 .nrreq = depth,
4266 .n = count,
4267 .offset = offset,
4268 .write = is_write,
4269 .flush_interval = flush_interval,
4270 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004271 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004272 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004273 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004274 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004275 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004276 if (flush_interval) {
4277 printf("Sending flush every %d requests\n", flush_interval);
4278 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004279
Fam Zheng79d46582018-01-16 14:08:58 +08004280 buf_size = data.nrreq * data.bufsize;
4281 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004282 memset(data.buf, pattern, data.nrreq * data.bufsize);
4283
Fam Zheng79d46582018-01-16 14:08:58 +08004284 blk_register_buf(blk, data.buf, buf_size);
4285
Kevin Wolfb6133b82014-08-05 14:17:13 +02004286 data.qiov = g_new(QEMUIOVector, data.nrreq);
4287 for (i = 0; i < data.nrreq; i++) {
4288 qemu_iovec_init(&data.qiov[i], 1);
4289 qemu_iovec_add(&data.qiov[i],
4290 data.buf + i * data.bufsize, data.bufsize);
4291 }
4292
4293 gettimeofday(&t1, NULL);
4294 bench_cb(&data, 0);
4295
4296 while (data.n > 0) {
4297 main_loop_wait(false);
4298 }
4299 gettimeofday(&t2, NULL);
4300
4301 printf("Run completed in %3.3f seconds.\n",
4302 (t2.tv_sec - t1.tv_sec)
4303 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4304
4305out:
Fam Zheng79d46582018-01-16 14:08:58 +08004306 if (data.buf) {
4307 blk_unregister_buf(blk, data.buf);
4308 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004309 qemu_vfree(data.buf);
4310 blk_unref(blk);
4311
4312 if (ret) {
4313 return 1;
4314 }
4315 return 0;
4316}
4317
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004318#define C_BS 01
4319#define C_COUNT 02
4320#define C_IF 04
4321#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004322#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004323
4324struct DdInfo {
4325 unsigned int flags;
4326 int64_t count;
4327};
4328
4329struct DdIo {
4330 int bsz; /* Block size */
4331 char *filename;
4332 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004333 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004334};
4335
4336struct DdOpts {
4337 const char *name;
4338 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4339 unsigned int flag;
4340};
4341
4342static int img_dd_bs(const char *arg,
4343 struct DdIo *in, struct DdIo *out,
4344 struct DdInfo *dd)
4345{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004346 int64_t res;
4347
Markus Armbruster606caa02017-02-21 21:14:04 +01004348 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004349
Markus Armbruster606caa02017-02-21 21:14:04 +01004350 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004351 error_report("invalid number: '%s'", arg);
4352 return 1;
4353 }
4354 in->bsz = out->bsz = res;
4355
4356 return 0;
4357}
4358
4359static int img_dd_count(const char *arg,
4360 struct DdIo *in, struct DdIo *out,
4361 struct DdInfo *dd)
4362{
Markus Armbruster606caa02017-02-21 21:14:04 +01004363 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004364
Markus Armbruster606caa02017-02-21 21:14:04 +01004365 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004366 error_report("invalid number: '%s'", arg);
4367 return 1;
4368 }
4369
4370 return 0;
4371}
4372
4373static int img_dd_if(const char *arg,
4374 struct DdIo *in, struct DdIo *out,
4375 struct DdInfo *dd)
4376{
4377 in->filename = g_strdup(arg);
4378
4379 return 0;
4380}
4381
4382static int img_dd_of(const char *arg,
4383 struct DdIo *in, struct DdIo *out,
4384 struct DdInfo *dd)
4385{
4386 out->filename = g_strdup(arg);
4387
4388 return 0;
4389}
4390
Reda Sallahif7c15532016-08-10 16:16:09 +02004391static int img_dd_skip(const char *arg,
4392 struct DdIo *in, struct DdIo *out,
4393 struct DdInfo *dd)
4394{
Markus Armbruster606caa02017-02-21 21:14:04 +01004395 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004396
Markus Armbruster606caa02017-02-21 21:14:04 +01004397 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004398 error_report("invalid number: '%s'", arg);
4399 return 1;
4400 }
4401
4402 return 0;
4403}
4404
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004405static int img_dd(int argc, char **argv)
4406{
4407 int ret = 0;
4408 char *arg = NULL;
4409 char *tmp;
4410 BlockDriver *drv = NULL, *proto_drv = NULL;
4411 BlockBackend *blk1 = NULL, *blk2 = NULL;
4412 QemuOpts *opts = NULL;
4413 QemuOptsList *create_opts = NULL;
4414 Error *local_err = NULL;
4415 bool image_opts = false;
4416 int c, i;
4417 const char *out_fmt = "raw";
4418 const char *fmt = NULL;
4419 int64_t size = 0;
4420 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004421 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004422 struct DdInfo dd = {
4423 .flags = 0,
4424 .count = 0,
4425 };
4426 struct DdIo in = {
4427 .bsz = 512, /* Block size is by default 512 bytes */
4428 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004429 .buf = NULL,
4430 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004431 };
4432 struct DdIo out = {
4433 .bsz = 512,
4434 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004435 .buf = NULL,
4436 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004437 };
4438
4439 const struct DdOpts options[] = {
4440 { "bs", img_dd_bs, C_BS },
4441 { "count", img_dd_count, C_COUNT },
4442 { "if", img_dd_if, C_IF },
4443 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004444 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004445 { NULL, NULL, 0 }
4446 };
4447 const struct option long_options[] = {
4448 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004449 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004450 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004451 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004452 { 0, 0, 0, 0 }
4453 };
4454
Fam Zheng335e9932017-05-03 00:35:39 +08004455 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004456 if (c == EOF) {
4457 break;
4458 }
4459 switch (c) {
4460 case 'O':
4461 out_fmt = optarg;
4462 break;
4463 case 'f':
4464 fmt = optarg;
4465 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004466 case ':':
4467 missing_argument(argv[optind - 1]);
4468 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004469 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004470 unrecognized_option(argv[optind - 1]);
4471 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004472 case 'h':
4473 help();
4474 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004475 case 'U':
4476 force_share = true;
4477 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004478 case OPTION_OBJECT:
4479 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004480 ret = -1;
4481 goto out;
4482 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004483 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004484 case OPTION_IMAGE_OPTS:
4485 image_opts = true;
4486 break;
4487 }
4488 }
4489
4490 for (i = optind; i < argc; i++) {
4491 int j;
4492 arg = g_strdup(argv[i]);
4493
4494 tmp = strchr(arg, '=');
4495 if (tmp == NULL) {
4496 error_report("unrecognized operand %s", arg);
4497 ret = -1;
4498 goto out;
4499 }
4500
4501 *tmp++ = '\0';
4502
4503 for (j = 0; options[j].name != NULL; j++) {
4504 if (!strcmp(arg, options[j].name)) {
4505 break;
4506 }
4507 }
4508 if (options[j].name == NULL) {
4509 error_report("unrecognized operand %s", arg);
4510 ret = -1;
4511 goto out;
4512 }
4513
4514 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4515 ret = -1;
4516 goto out;
4517 }
4518 dd.flags |= options[j].flag;
4519 g_free(arg);
4520 arg = NULL;
4521 }
4522
4523 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4524 error_report("Must specify both input and output files");
4525 ret = -1;
4526 goto out;
4527 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004528
4529 if (qemu_opts_foreach(&qemu_object_opts,
4530 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004531 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004532 ret = -1;
4533 goto out;
4534 }
4535
Fam Zheng335e9932017-05-03 00:35:39 +08004536 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4537 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004538
4539 if (!blk1) {
4540 ret = -1;
4541 goto out;
4542 }
4543
4544 drv = bdrv_find_format(out_fmt);
4545 if (!drv) {
4546 error_report("Unknown file format");
4547 ret = -1;
4548 goto out;
4549 }
4550 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4551
4552 if (!proto_drv) {
4553 error_report_err(local_err);
4554 ret = -1;
4555 goto out;
4556 }
4557 if (!drv->create_opts) {
4558 error_report("Format driver '%s' does not support image creation",
4559 drv->format_name);
4560 ret = -1;
4561 goto out;
4562 }
4563 if (!proto_drv->create_opts) {
4564 error_report("Protocol driver '%s' does not support image creation",
4565 proto_drv->format_name);
4566 ret = -1;
4567 goto out;
4568 }
4569 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4570 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4571
4572 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4573
4574 size = blk_getlength(blk1);
4575 if (size < 0) {
4576 error_report("Failed to get size for '%s'", in.filename);
4577 ret = -1;
4578 goto out;
4579 }
4580
4581 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4582 dd.count * in.bsz < size) {
4583 size = dd.count * in.bsz;
4584 }
4585
Reda Sallahif7c15532016-08-10 16:16:09 +02004586 /* Overflow means the specified offset is beyond input image's size */
4587 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4588 size < in.bsz * in.offset)) {
4589 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4590 } else {
4591 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4592 size - in.bsz * in.offset, &error_abort);
4593 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004594
4595 ret = bdrv_create(drv, out.filename, opts, &local_err);
4596 if (ret < 0) {
4597 error_reportf_err(local_err,
4598 "%s: error while creating output image: ",
4599 out.filename);
4600 ret = -1;
4601 goto out;
4602 }
4603
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004604 /* TODO, we can't honour --image-opts for the target,
4605 * since it needs to be given in a format compatible
4606 * with the bdrv_create() call above which does not
4607 * support image-opts style.
4608 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004609 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004610 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004611
4612 if (!blk2) {
4613 ret = -1;
4614 goto out;
4615 }
4616
Reda Sallahif7c15532016-08-10 16:16:09 +02004617 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4618 size < in.offset * in.bsz)) {
4619 /* We give a warning if the skip option is bigger than the input
4620 * size and create an empty output disk image (i.e. like dd(1)).
4621 */
4622 error_report("%s: cannot skip to specified offset", in.filename);
4623 in_pos = size;
4624 } else {
4625 in_pos = in.offset * in.bsz;
4626 }
4627
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004628 in.buf = g_new(uint8_t, in.bsz);
4629
Reda Sallahif7c15532016-08-10 16:16:09 +02004630 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004631 int in_ret, out_ret;
4632
4633 if (in_pos + in.bsz > size) {
4634 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4635 } else {
4636 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4637 }
4638 if (in_ret < 0) {
4639 error_report("error while reading from input image file: %s",
4640 strerror(-in_ret));
4641 ret = -1;
4642 goto out;
4643 }
4644 in_pos += in_ret;
4645
4646 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4647
4648 if (out_ret < 0) {
4649 error_report("error while writing to output image file: %s",
4650 strerror(-out_ret));
4651 ret = -1;
4652 goto out;
4653 }
4654 out_pos += out_ret;
4655 }
4656
4657out:
4658 g_free(arg);
4659 qemu_opts_del(opts);
4660 qemu_opts_free(create_opts);
4661 blk_unref(blk1);
4662 blk_unref(blk2);
4663 g_free(in.filename);
4664 g_free(out.filename);
4665 g_free(in.buf);
4666 g_free(out.buf);
4667
4668 if (ret) {
4669 return 1;
4670 }
4671 return 0;
4672}
4673
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004674static void dump_json_block_measure_info(BlockMeasureInfo *info)
4675{
4676 QString *str;
4677 QObject *obj;
4678 Visitor *v = qobject_output_visitor_new(&obj);
4679
4680 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4681 visit_complete(v, &obj);
4682 str = qobject_to_json_pretty(obj);
4683 assert(str != NULL);
4684 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004685 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004686 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004687 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004688}
4689
4690static int img_measure(int argc, char **argv)
4691{
4692 static const struct option long_options[] = {
4693 {"help", no_argument, 0, 'h'},
4694 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4695 {"object", required_argument, 0, OPTION_OBJECT},
4696 {"output", required_argument, 0, OPTION_OUTPUT},
4697 {"size", required_argument, 0, OPTION_SIZE},
4698 {"force-share", no_argument, 0, 'U'},
4699 {0, 0, 0, 0}
4700 };
4701 OutputFormat output_format = OFORMAT_HUMAN;
4702 BlockBackend *in_blk = NULL;
4703 BlockDriver *drv;
4704 const char *filename = NULL;
4705 const char *fmt = NULL;
4706 const char *out_fmt = "raw";
4707 char *options = NULL;
4708 char *snapshot_name = NULL;
4709 bool force_share = false;
4710 QemuOpts *opts = NULL;
4711 QemuOpts *object_opts = NULL;
4712 QemuOpts *sn_opts = NULL;
4713 QemuOptsList *create_opts = NULL;
4714 bool image_opts = false;
4715 uint64_t img_size = UINT64_MAX;
4716 BlockMeasureInfo *info = NULL;
4717 Error *local_err = NULL;
4718 int ret = 1;
4719 int c;
4720
4721 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4722 long_options, NULL)) != -1) {
4723 switch (c) {
4724 case '?':
4725 case 'h':
4726 help();
4727 break;
4728 case 'f':
4729 fmt = optarg;
4730 break;
4731 case 'O':
4732 out_fmt = optarg;
4733 break;
4734 case 'o':
4735 if (!is_valid_option_list(optarg)) {
4736 error_report("Invalid option list: %s", optarg);
4737 goto out;
4738 }
4739 if (!options) {
4740 options = g_strdup(optarg);
4741 } else {
4742 char *old_options = options;
4743 options = g_strdup_printf("%s,%s", options, optarg);
4744 g_free(old_options);
4745 }
4746 break;
4747 case 'l':
4748 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4749 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4750 optarg, false);
4751 if (!sn_opts) {
4752 error_report("Failed in parsing snapshot param '%s'",
4753 optarg);
4754 goto out;
4755 }
4756 } else {
4757 snapshot_name = optarg;
4758 }
4759 break;
4760 case 'U':
4761 force_share = true;
4762 break;
4763 case OPTION_OBJECT:
4764 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4765 optarg, true);
4766 if (!object_opts) {
4767 goto out;
4768 }
4769 break;
4770 case OPTION_IMAGE_OPTS:
4771 image_opts = true;
4772 break;
4773 case OPTION_OUTPUT:
4774 if (!strcmp(optarg, "json")) {
4775 output_format = OFORMAT_JSON;
4776 } else if (!strcmp(optarg, "human")) {
4777 output_format = OFORMAT_HUMAN;
4778 } else {
4779 error_report("--output must be used with human or json "
4780 "as argument.");
4781 goto out;
4782 }
4783 break;
4784 case OPTION_SIZE:
4785 {
4786 int64_t sval;
4787
4788 sval = cvtnum(optarg);
4789 if (sval < 0) {
4790 if (sval == -ERANGE) {
4791 error_report("Image size must be less than 8 EiB!");
4792 } else {
4793 error_report("Invalid image size specified! You may use "
4794 "k, M, G, T, P or E suffixes for ");
4795 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4796 "petabytes and exabytes.");
4797 }
4798 goto out;
4799 }
4800 img_size = (uint64_t)sval;
4801 }
4802 break;
4803 }
4804 }
4805
4806 if (qemu_opts_foreach(&qemu_object_opts,
4807 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004808 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004809 goto out;
4810 }
4811
4812 if (argc - optind > 1) {
4813 error_report("At most one filename argument is allowed.");
4814 goto out;
4815 } else if (argc - optind == 1) {
4816 filename = argv[optind];
4817 }
4818
4819 if (!filename &&
4820 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4821 error_report("--object, --image-opts, -f, and -l "
4822 "require a filename argument.");
4823 goto out;
4824 }
4825 if (filename && img_size != UINT64_MAX) {
4826 error_report("--size N cannot be used together with a filename.");
4827 goto out;
4828 }
4829 if (!filename && img_size == UINT64_MAX) {
4830 error_report("Either --size N or one filename must be specified.");
4831 goto out;
4832 }
4833
4834 if (filename) {
4835 in_blk = img_open(image_opts, filename, fmt, 0,
4836 false, false, force_share);
4837 if (!in_blk) {
4838 goto out;
4839 }
4840
4841 if (sn_opts) {
4842 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4843 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4844 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4845 &local_err);
4846 } else if (snapshot_name != NULL) {
4847 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4848 snapshot_name, &local_err);
4849 }
4850 if (local_err) {
4851 error_reportf_err(local_err, "Failed to load snapshot: ");
4852 goto out;
4853 }
4854 }
4855
4856 drv = bdrv_find_format(out_fmt);
4857 if (!drv) {
4858 error_report("Unknown file format '%s'", out_fmt);
4859 goto out;
4860 }
4861 if (!drv->create_opts) {
4862 error_report("Format driver '%s' does not support image creation",
4863 drv->format_name);
4864 goto out;
4865 }
4866
4867 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4868 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4869 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4870 if (options) {
4871 qemu_opts_do_parse(opts, options, NULL, &local_err);
4872 if (local_err) {
4873 error_report_err(local_err);
4874 error_report("Invalid options for file format '%s'", out_fmt);
4875 goto out;
4876 }
4877 }
4878 if (img_size != UINT64_MAX) {
4879 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4880 }
4881
4882 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4883 if (local_err) {
4884 error_report_err(local_err);
4885 goto out;
4886 }
4887
4888 if (output_format == OFORMAT_HUMAN) {
4889 printf("required size: %" PRIu64 "\n", info->required);
4890 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4891 } else {
4892 dump_json_block_measure_info(info);
4893 }
4894
4895 ret = 0;
4896
4897out:
4898 qapi_free_BlockMeasureInfo(info);
4899 qemu_opts_del(object_opts);
4900 qemu_opts_del(opts);
4901 qemu_opts_del(sn_opts);
4902 qemu_opts_free(create_opts);
4903 g_free(options);
4904 blk_unref(in_blk);
4905 return ret;
4906}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004907
Anthony Liguoric227f092009-10-01 16:12:16 -05004908static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004909#define DEF(option, callback, arg_string) \
4910 { option, callback },
4911#include "qemu-img-cmds.h"
4912#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004913 { NULL, NULL, },
4914};
4915
bellardea2384d2004-08-01 21:59:26 +00004916int main(int argc, char **argv)
4917{
Anthony Liguoric227f092009-10-01 16:12:16 -05004918 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004919 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004920 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004921 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004922 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004923 static const struct option long_options[] = {
4924 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004925 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004926 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004927 {0, 0, 0, 0}
4928 };
bellardea2384d2004-08-01 21:59:26 +00004929
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004930#ifdef CONFIG_POSIX
4931 signal(SIGPIPE, SIG_IGN);
4932#endif
4933
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01004934 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004935 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004936 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004937
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004938 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004939 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004940 exit(EXIT_FAILURE);
4941 }
4942
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004943 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004944
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004945 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004946 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004947 if (argc < 2) {
4948 error_exit("Not enough arguments");
4949 }
Stuart Brady153859b2009-06-07 00:42:17 +01004950
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004951 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004952 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004953 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004954
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004955 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004956 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004957 case ':':
4958 missing_argument(argv[optind - 1]);
4959 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004960 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004961 unrecognized_option(argv[optind - 1]);
4962 return 0;
4963 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004964 help();
4965 return 0;
4966 case 'V':
4967 printf(QEMU_IMG_VERSION);
4968 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004969 case 'T':
4970 g_free(trace_file);
4971 trace_file = trace_opt_parse(optarg);
4972 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004973 }
bellardea2384d2004-08-01 21:59:26 +00004974 }
Stuart Brady153859b2009-06-07 00:42:17 +01004975
Denis V. Lunev10985132016-06-17 17:44:13 +03004976 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004977
Denis V. Lunev10985132016-06-17 17:44:13 +03004978 /* reset getopt_long scanning */
4979 argc -= optind;
4980 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004981 return 0;
4982 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004983 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00004984 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03004985
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004986 if (!trace_init_backends()) {
4987 exit(1);
4988 }
4989 trace_init_file(trace_file);
4990 qemu_set_log(LOG_TRACE);
4991
Denis V. Lunev10985132016-06-17 17:44:13 +03004992 /* find the command */
4993 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4994 if (!strcmp(cmdname, cmd->name)) {
4995 return cmd->handler(argc, argv);
4996 }
4997 }
Jeff Cody7db16892014-04-25 17:02:32 -04004998
Stuart Brady153859b2009-06-07 00:42:17 +01004999 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005000 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005001}