blob: 76a961df8247ac7018b6dfd6722fb7ef03732006 [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"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000040#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010041#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020042#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010043#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020044#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080045#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010046#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030047#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000048
Thomas Huth7e563bf2018-02-15 12:06:47 +010049#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020050 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040051
Anthony Liguoric227f092009-10-01 16:12:16 -050052typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010053 const char *name;
54 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050055} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010056
Federico Simoncelli8599ea42013-01-28 06:59:47 -050057enum {
58 OPTION_OUTPUT = 256,
59 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000060 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000061 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020062 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020063 OPTION_FLUSH_INTERVAL = 261,
64 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010065 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010066 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020067 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030068 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050069};
70
71typedef enum OutputFormat {
72 OFORMAT_JSON,
73 OFORMAT_HUMAN,
74} OutputFormat;
75
Kevin Wolfe6996142016-03-15 13:03:11 +010076/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040077#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000078
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010079static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000080{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010081 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000082}
83
Fam Zhengac1307a2014-04-22 13:36:11 +080084static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
85{
86 va_list ap;
87
88 error_printf("qemu-img: ");
89
90 va_start(ap, fmt);
91 error_vprintf(fmt, ap);
92 va_end(ap);
93
94 error_printf("\nTry 'qemu-img --help' for more information\n");
95 exit(EXIT_FAILURE);
96}
97
Stefan Hajnoczic9192972017-03-17 18:45:41 +080098static void QEMU_NORETURN missing_argument(const char *option)
99{
100 error_exit("missing argument for option '%s'", option);
101}
102
103static void QEMU_NORETURN unrecognized_option(const char *option)
104{
105 error_exit("unrecognized option '%s'", option);
106}
107
blueswir1d2c639d2009-01-24 18:19:25 +0000108/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800109static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000110{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100111 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400112 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300113 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300114 "QEMU disk image utility\n"
115 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300120 "\n"
malc3f020d72010-02-08 12:04:56 +0300121 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100122#define DEF(option, callback, arg_string) \
123 " " arg_string "\n"
124#include "qemu-img-cmds.h"
125#undef DEF
malc3f020d72010-02-08 12:04:56 +0300126 "\n"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300139 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300151 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400152 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
153 " new backing file match exactly. The image doesn't need a working\n"
154 " backing file before rebasing in this case (useful for renaming the\n"
155 " backing file). For image creation, allow creating without attempting\n"
156 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300157 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200158 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100159 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200160 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
161 " contain only zeros for qemu-img to create a sparse image during\n"
162 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
163 " unallocated or zero sectors, and the destination image will always be\n"
164 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200165 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100166 " '-n' skips the target volume creation (useful if the volume is created\n"
167 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300168 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200169 "Parameters to check subcommand:\n"
170 " '-r' tries to repair any inconsistencies that are found during the check.\n"
171 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
172 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200173 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200174 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100175 "Parameters to convert subcommand:\n"
176 " '-m' specifies how many coroutines work in parallel during the convert\n"
177 " process (defaults to 8)\n"
178 " '-W' allow to write to the target out of order rather than sequential\n"
179 "\n"
malc3f020d72010-02-08 12:04:56 +0300180 "Parameters to snapshot subcommand:\n"
181 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
182 " '-a' applies a snapshot (revert disk to saved state)\n"
183 " '-c' creates a snapshot\n"
184 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100185 " '-l' lists all snapshots in the given image\n"
186 "\n"
187 "Parameters to compare subcommand:\n"
188 " '-f' first image format\n"
189 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200190 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
191 "\n"
192 "Parameters to dd subcommand:\n"
193 " 'bs=BYTES' read and write up to BYTES bytes at a time "
194 "(default: 512)\n"
195 " 'count=N' copy only N input blocks\n"
196 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200197 " 'of=FILE' write to FILE\n"
198 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100199
200 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300201 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500202 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800203 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000204}
205
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000206static QemuOptsList qemu_object_opts = {
207 .name = "object",
208 .implied_opt_name = "qom-type",
209 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
210 .desc = {
211 { }
212 },
213};
214
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000215static QemuOptsList qemu_source_opts = {
216 .name = "source",
217 .implied_opt_name = "file",
218 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
219 .desc = {
220 { }
221 },
222};
223
Stefan Weil7c30f652013-06-16 17:01:05 +0200224static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100225{
226 int ret = 0;
227 if (!quiet) {
228 va_list args;
229 va_start(args, fmt);
230 ret = vprintf(fmt, args);
231 va_end(args);
232 }
233 return ret;
234}
235
bellardea2384d2004-08-01 21:59:26 +0000236
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100237static int print_block_option_help(const char *filename, const char *fmt)
238{
239 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800240 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500241 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100242
243 /* Find driver and parse its options */
244 drv = bdrv_find_format(fmt);
245 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100246 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100247 return 1;
248 }
249
Max Reitzd402b6a2018-05-09 23:00:21 +0200250 if (!drv->create_opts) {
251 error_report("Format driver '%s' does not support image creation", fmt);
252 return 1;
253 }
254
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800255 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100256 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500257 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100258 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100259 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800260 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100261 return 1;
262 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200263 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100264 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200265 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100266 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200267 return 1;
268 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800269 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100270 }
271
Max Reitz7f3fb002018-05-09 23:00:19 +0200272 printf("Supported options:\n");
Max Reitz63898712018-10-19 18:49:25 +0200273 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800274 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100275 return 0;
276}
277
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000278
Max Reitzefaa7c42016-03-16 19:54:38 +0100279static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100280 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800281 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000282{
283 QDict *options;
284 Error *local_err = NULL;
285 BlockBackend *blk;
286 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800287 if (force_share) {
288 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200289 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800290 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200291 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800292 return NULL;
293 }
Max Reitz4615f872018-05-02 22:20:50 +0200294 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800295 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100296 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000297 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100298 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000299 return NULL;
300 }
Kevin Wolfce099542016-03-15 13:01:04 +0100301 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000302
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000303 return blk;
304}
305
Max Reitzefaa7c42016-03-16 19:54:38 +0100306static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100307 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000308 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800309 bool writethrough, bool quiet,
310 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000311{
312 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200313 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100314
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100315 if (!options) {
316 options = qdict_new();
317 }
bellard75c23802004-08-27 21:28:58 +0000318 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500319 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000320 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100321
Fam Zheng335e9932017-05-03 00:35:39 +0800322 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500323 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800324 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100325 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500326 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100327 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000328 return NULL;
bellard75c23802004-08-27 21:28:58 +0000329 }
Kevin Wolfce099542016-03-15 13:01:04 +0100330 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100331
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200332 return blk;
bellard75c23802004-08-27 21:28:58 +0000333}
334
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000335
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100336static int img_add_key_secrets(void *opaque,
337 const char *name, const char *value,
338 Error **errp)
339{
340 QDict *options = opaque;
341
342 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600343 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100344 }
345
346 return 0;
347}
348
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100349
Max Reitzefaa7c42016-03-16 19:54:38 +0100350static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000351 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100352 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800353 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000354{
355 BlockBackend *blk;
356 if (image_opts) {
357 QemuOpts *opts;
358 if (fmt) {
359 error_report("--image-opts and --format are mutually exclusive");
360 return NULL;
361 }
362 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
363 filename, true);
364 if (!opts) {
365 return NULL;
366 }
Fam Zheng335e9932017-05-03 00:35:39 +0800367 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
368 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000369 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100370 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800371 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000372 }
373 return blk;
374}
375
376
Chunyan Liu83d05212014-06-05 17:20:51 +0800377static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100378 const char *base_filename,
379 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200380{
Markus Armbruster6750e792015-02-12 17:43:08 +0100381 Error *err = NULL;
382
Kevin Wolfefa84d42009-05-18 16:42:12 +0200383 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100384 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100385 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100386 error_report("Backing file not supported for file format '%s'",
387 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100388 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900389 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200390 }
391 }
392 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100393 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100394 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100395 error_report("Backing file format not supported for file "
396 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100397 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900398 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200399 }
400 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900401 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200402}
403
Markus Armbruster606caa02017-02-21 21:14:04 +0100404static int64_t cvtnum(const char *s)
405{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100406 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100407 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100408
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100409 err = qemu_strtosz(s, NULL, &value);
410 if (err < 0) {
411 return err;
412 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100413 if (value > INT64_MAX) {
414 return -ERANGE;
415 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100416 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100417}
418
bellardea2384d2004-08-01 21:59:26 +0000419static int img_create(int argc, char **argv)
420{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200421 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100422 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000423 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000424 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000425 const char *filename;
426 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200427 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200428 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100429 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400430 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000431
bellardea2384d2004-08-01 21:59:26 +0000432 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000433 static const struct option long_options[] = {
434 {"help", no_argument, 0, 'h'},
435 {"object", required_argument, 0, OPTION_OBJECT},
436 {0, 0, 0, 0}
437 };
John Snow6e6e55f2017-07-17 20:34:22 -0400438 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000439 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100440 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000441 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100442 }
bellardea2384d2004-08-01 21:59:26 +0000443 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800444 case ':':
445 missing_argument(argv[optind - 1]);
446 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100447 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800448 unrecognized_option(argv[optind - 1]);
449 break;
bellardea2384d2004-08-01 21:59:26 +0000450 case 'h':
451 help();
452 break;
aliguori9230eaf2009-03-28 17:55:19 +0000453 case 'F':
454 base_fmt = optarg;
455 break;
bellardea2384d2004-08-01 21:59:26 +0000456 case 'b':
457 base_filename = optarg;
458 break;
459 case 'f':
460 fmt = optarg;
461 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200462 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100463 if (!is_valid_option_list(optarg)) {
464 error_report("Invalid option list: %s", optarg);
465 goto fail;
466 }
467 if (!options) {
468 options = g_strdup(optarg);
469 } else {
470 char *old_options = options;
471 options = g_strdup_printf("%s,%s", options, optarg);
472 g_free(old_options);
473 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200474 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100475 case 'q':
476 quiet = true;
477 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400478 case 'u':
479 flags |= BDRV_O_NO_BACKING;
480 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000481 case OPTION_OBJECT: {
482 QemuOpts *opts;
483 opts = qemu_opts_parse_noisily(&qemu_object_opts,
484 optarg, true);
485 if (!opts) {
486 goto fail;
487 }
488 } break;
bellardea2384d2004-08-01 21:59:26 +0000489 }
490 }
aliguori9230eaf2009-03-28 17:55:19 +0000491
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900492 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100493 filename = (optind < argc) ? argv[optind] : NULL;
494 if (options && has_help_option(options)) {
495 g_free(options);
496 return print_block_option_help(filename, fmt);
497 }
498
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100499 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800500 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100501 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100502 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900503
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000504 if (qemu_opts_foreach(&qemu_object_opts,
505 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000506 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000507 goto fail;
508 }
509
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100510 /* Get image size, if specified */
511 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100512 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100513
514 sval = cvtnum(argv[optind++]);
515 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800516 if (sval == -ERANGE) {
517 error_report("Image size must be less than 8 EiB!");
518 } else {
519 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200520 "G, T, P or E suffixes for ");
521 error_report("kilobytes, megabytes, gigabytes, terabytes, "
522 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800523 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100524 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100525 }
526 img_size = (uint64_t)sval;
527 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200528 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800529 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200530 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100531
Luiz Capitulino9b375252012-11-30 10:52:05 -0200532 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400533 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100534 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100535 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100536 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900537 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200538
Kevin Wolf77386bf2014-02-21 16:24:04 +0100539 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000540 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100541
542fail:
543 g_free(options);
544 return 1;
bellardea2384d2004-08-01 21:59:26 +0000545}
546
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100547static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500548{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500549 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500550 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100551 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600552
553 visit_type_ImageCheck(v, NULL, &check, &error_abort);
554 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500555 str = qobject_to_json_pretty(obj);
556 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100557 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200558 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600559 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200560 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500561}
562
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100563static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500564{
565 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100566 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500567 } else {
568 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100569 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
570 "Data may be corrupted, or further writes to the image "
571 "may corrupt it.\n",
572 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500573 }
574
575 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100576 qprintf(quiet,
577 "\n%" PRId64 " leaked clusters were found on the image.\n"
578 "This means waste of disk space, but no harm to data.\n",
579 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500580 }
581
582 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100583 qprintf(quiet,
584 "\n%" PRId64
585 " internal errors have occurred during the check.\n",
586 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500587 }
588 }
589
590 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100591 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
592 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
593 check->allocated_clusters, check->total_clusters,
594 check->allocated_clusters * 100.0 / check->total_clusters,
595 check->fragmented_clusters * 100.0 / check->allocated_clusters,
596 check->compressed_clusters * 100.0 /
597 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500598 }
599
600 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100601 qprintf(quiet,
602 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500603 }
604}
605
606static int collect_image_check(BlockDriverState *bs,
607 ImageCheck *check,
608 const char *filename,
609 const char *fmt,
610 int fix)
611{
612 int ret;
613 BdrvCheckResult result;
614
615 ret = bdrv_check(bs, &result, fix);
616 if (ret < 0) {
617 return ret;
618 }
619
620 check->filename = g_strdup(filename);
621 check->format = g_strdup(bdrv_get_format_name(bs));
622 check->check_errors = result.check_errors;
623 check->corruptions = result.corruptions;
624 check->has_corruptions = result.corruptions != 0;
625 check->leaks = result.leaks;
626 check->has_leaks = result.leaks != 0;
627 check->corruptions_fixed = result.corruptions_fixed;
628 check->has_corruptions_fixed = result.corruptions != 0;
629 check->leaks_fixed = result.leaks_fixed;
630 check->has_leaks_fixed = result.leaks != 0;
631 check->image_end_offset = result.image_end_offset;
632 check->has_image_end_offset = result.image_end_offset != 0;
633 check->total_clusters = result.bfi.total_clusters;
634 check->has_total_clusters = result.bfi.total_clusters != 0;
635 check->allocated_clusters = result.bfi.allocated_clusters;
636 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
637 check->fragmented_clusters = result.bfi.fragmented_clusters;
638 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100639 check->compressed_clusters = result.bfi.compressed_clusters;
640 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500641
642 return 0;
643}
644
Kevin Wolfe076f332010-06-29 11:43:13 +0200645/*
646 * Checks an image for consistency. Exit codes:
647 *
Max Reitzd6635c42014-06-02 22:15:21 +0200648 * 0 - Check completed, image is good
649 * 1 - Check not completed because of internal errors
650 * 2 - Check completed, image is corrupted
651 * 3 - Check completed, image has leaked clusters, but is good otherwise
652 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200653 */
aliguori15859692009-04-21 23:11:53 +0000654static int img_check(int argc, char **argv)
655{
656 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500657 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200658 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200659 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000660 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200661 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100662 int flags = BDRV_O_CHECK;
663 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200664 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100665 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000666 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800667 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000668
669 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500670 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200671 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100672
aliguori15859692009-04-21 23:11:53 +0000673 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500674 int option_index = 0;
675 static const struct option long_options[] = {
676 {"help", no_argument, 0, 'h'},
677 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530678 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500679 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000680 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000681 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800682 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500683 {0, 0, 0, 0}
684 };
Fam Zheng335e9932017-05-03 00:35:39 +0800685 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500686 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100687 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000688 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100689 }
aliguori15859692009-04-21 23:11:53 +0000690 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800691 case ':':
692 missing_argument(argv[optind - 1]);
693 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100694 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800695 unrecognized_option(argv[optind - 1]);
696 break;
aliguori15859692009-04-21 23:11:53 +0000697 case 'h':
698 help();
699 break;
700 case 'f':
701 fmt = optarg;
702 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200703 case 'r':
704 flags |= BDRV_O_RDWR;
705
706 if (!strcmp(optarg, "leaks")) {
707 fix = BDRV_FIX_LEAKS;
708 } else if (!strcmp(optarg, "all")) {
709 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
710 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800711 error_exit("Unknown option value for -r "
712 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200713 }
714 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500715 case OPTION_OUTPUT:
716 output = optarg;
717 break;
Max Reitz40055952014-07-22 22:58:42 +0200718 case 'T':
719 cache = optarg;
720 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100721 case 'q':
722 quiet = true;
723 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800724 case 'U':
725 force_share = true;
726 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000727 case OPTION_OBJECT: {
728 QemuOpts *opts;
729 opts = qemu_opts_parse_noisily(&qemu_object_opts,
730 optarg, true);
731 if (!opts) {
732 return 1;
733 }
734 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000735 case OPTION_IMAGE_OPTS:
736 image_opts = true;
737 break;
aliguori15859692009-04-21 23:11:53 +0000738 }
739 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200740 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800741 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100742 }
aliguori15859692009-04-21 23:11:53 +0000743 filename = argv[optind++];
744
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500745 if (output && !strcmp(output, "json")) {
746 output_format = OFORMAT_JSON;
747 } else if (output && !strcmp(output, "human")) {
748 output_format = OFORMAT_HUMAN;
749 } else if (output) {
750 error_report("--output must be used with human or json as argument.");
751 return 1;
752 }
753
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000754 if (qemu_opts_foreach(&qemu_object_opts,
755 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000756 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000757 return 1;
758 }
759
Kevin Wolfce099542016-03-15 13:01:04 +0100760 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200761 if (ret < 0) {
762 error_report("Invalid source cache option: %s", cache);
763 return 1;
764 }
765
Fam Zheng335e9932017-05-03 00:35:39 +0800766 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
767 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200768 if (!blk) {
769 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900770 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200771 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500772
773 check = g_new0(ImageCheck, 1);
774 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200775
776 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200777 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200778 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500779 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200780 }
781
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500782 if (check->corruptions_fixed || check->leaks_fixed) {
783 int corruptions_fixed, leaks_fixed;
784
785 leaks_fixed = check->leaks_fixed;
786 corruptions_fixed = check->corruptions_fixed;
787
788 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100789 qprintf(quiet,
790 "The following inconsistencies were found and repaired:\n\n"
791 " %" PRId64 " leaked clusters\n"
792 " %" PRId64 " corruptions\n\n"
793 "Double checking the fixed image now...\n",
794 check->leaks_fixed,
795 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500796 }
797
798 ret = collect_image_check(bs, check, filename, fmt, 0);
799
800 check->leaks_fixed = leaks_fixed;
801 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200802 }
803
Max Reitz832390a2014-10-23 15:29:12 +0200804 if (!ret) {
805 switch (output_format) {
806 case OFORMAT_HUMAN:
807 dump_human_image_check(check, quiet);
808 break;
809 case OFORMAT_JSON:
810 dump_json_image_check(check, quiet);
811 break;
812 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500813 }
814
815 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200816 if (ret) {
817 error_report("Check failed: %s", strerror(-ret));
818 } else {
819 error_report("Check failed");
820 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500821 ret = 1;
822 goto fail;
823 }
824
825 if (check->corruptions) {
826 ret = 2;
827 } else if (check->leaks) {
828 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200829 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500830 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000831 }
832
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500833fail:
834 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200835 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500836 return ret;
aliguori15859692009-04-21 23:11:53 +0000837}
838
Max Reitzd4a32382014-10-24 15:57:37 +0200839typedef struct CommonBlockJobCBInfo {
840 BlockDriverState *bs;
841 Error **errp;
842} CommonBlockJobCBInfo;
843
844static void common_block_job_cb(void *opaque, int ret)
845{
846 CommonBlockJobCBInfo *cbi = opaque;
847
848 if (ret < 0) {
849 error_setg_errno(cbi->errp, -ret, "Block job failed");
850 }
Max Reitzd4a32382014-10-24 15:57:37 +0200851}
852
853static void run_block_job(BlockJob *job, Error **errp)
854{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200855 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800856 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200857
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200858 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200859 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200860 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200861 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200862 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200863 if (job->job.progress_total) {
864 progress = (float)job->job.progress_current /
865 job->job.progress_total * 100.f;
866 }
867 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200868 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200869
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200870 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200871 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800872 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200873 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800874 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200875 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200876 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200877
sochin.jiang4172a002017-06-15 14:47:33 +0800878 /* publish completion progress only when success */
879 if (!ret) {
880 qemu_progress_print(100.f, 0);
881 }
Max Reitzd4a32382014-10-24 15:57:37 +0200882}
883
bellardea2384d2004-08-01 21:59:26 +0000884static int img_commit(int argc, char **argv)
885{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400886 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200887 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200888 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200889 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100890 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200891 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100892 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200893 Error *local_err = NULL;
894 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000895 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200896 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000897
898 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400899 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200900 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000901 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000902 static const struct option long_options[] = {
903 {"help", no_argument, 0, 'h'},
904 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000905 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000906 {0, 0, 0, 0}
907 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800908 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000909 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100910 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000911 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100912 }
bellardea2384d2004-08-01 21:59:26 +0000913 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800914 case ':':
915 missing_argument(argv[optind - 1]);
916 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100917 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800918 unrecognized_option(argv[optind - 1]);
919 break;
bellardea2384d2004-08-01 21:59:26 +0000920 case 'h':
921 help();
922 break;
923 case 'f':
924 fmt = optarg;
925 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400926 case 't':
927 cache = optarg;
928 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200929 case 'b':
930 base = optarg;
931 /* -b implies -d */
932 drop = true;
933 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200934 case 'd':
935 drop = true;
936 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200937 case 'p':
938 progress = true;
939 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100940 case 'q':
941 quiet = true;
942 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000943 case OPTION_OBJECT: {
944 QemuOpts *opts;
945 opts = qemu_opts_parse_noisily(&qemu_object_opts,
946 optarg, true);
947 if (!opts) {
948 return 1;
949 }
950 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000951 case OPTION_IMAGE_OPTS:
952 image_opts = true;
953 break;
bellardea2384d2004-08-01 21:59:26 +0000954 }
955 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200956
957 /* Progress is not shown in Quiet mode */
958 if (quiet) {
959 progress = false;
960 }
961
Kevin Wolffc11eb22013-08-05 10:53:04 +0200962 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800963 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100964 }
bellardea2384d2004-08-01 21:59:26 +0000965 filename = argv[optind++];
966
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000967 if (qemu_opts_foreach(&qemu_object_opts,
968 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000969 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000970 return 1;
971 }
972
Max Reitz9a86fe42014-10-24 15:57:38 +0200973 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100974 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400975 if (ret < 0) {
976 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100977 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400978 }
979
Fam Zheng335e9932017-05-03 00:35:39 +0800980 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
981 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200982 if (!blk) {
983 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900984 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200985 bs = blk_bs(blk);
986
Max Reitz687fa1d2014-10-24 15:57:39 +0200987 qemu_progress_init(progress, 1.f);
988 qemu_progress_print(0.f, 100);
989
Max Reitz1b22bff2014-10-24 15:57:40 +0200990 if (base) {
991 base_bs = bdrv_find_backing_image(bs, base);
992 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100993 error_setg(&local_err,
994 "Did not find '%s' in the backing chain of '%s'",
995 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200996 goto done;
997 }
998 } else {
999 /* This is different from QMP, which by default uses the deepest file in
1000 * the backing chain (i.e., the very base); however, the traditional
1001 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001002 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001003 if (!base_bs) {
1004 error_setg(&local_err, "Image does not have a backing file");
1005 goto done;
1006 }
bellardea2384d2004-08-01 21:59:26 +00001007 }
1008
Max Reitzd4a32382014-10-24 15:57:37 +02001009 cbi = (CommonBlockJobCBInfo){
1010 .errp = &local_err,
1011 .bs = bs,
1012 };
1013
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001014 aio_context = bdrv_get_aio_context(bs);
1015 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001016 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001017 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001018 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001019 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001020 if (local_err) {
1021 goto done;
1022 }
1023
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001024 /* When the block job completes, the BlockBackend reference will point to
1025 * the old backing file. In order to avoid that the top image is already
1026 * deleted, so we can still empty it afterwards, increment the reference
1027 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001028 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001029 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001030 }
1031
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001032 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001033 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001034 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001035 if (local_err) {
1036 goto unref_backing;
1037 }
1038
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001039 if (!drop && bs->drv->bdrv_make_empty) {
1040 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001041 if (ret) {
1042 error_setg_errno(&local_err, -ret, "Could not empty %s",
1043 filename);
1044 goto unref_backing;
1045 }
1046 }
1047
1048unref_backing:
1049 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001050 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001051 }
Max Reitzd4a32382014-10-24 15:57:37 +02001052
1053done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001054 qemu_progress_end();
1055
Markus Armbruster26f54e92014-10-07 13:59:04 +02001056 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001057
1058 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001059 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001060 return 1;
1061 }
Max Reitzd4a32382014-10-24 15:57:37 +02001062
1063 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001064 return 0;
1065}
1066
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001067/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001068 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1069 * of the first sector boundary within buf where the sector contains a
1070 * non-zero byte. This function is robust to a buffer that is not
1071 * sector-aligned.
1072 */
1073static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1074{
1075 int64_t i;
1076 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1077
1078 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1079 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1080 return i;
1081 }
1082 }
1083 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1084 return i;
1085 }
1086 return -1;
1087}
1088
1089/*
thsf58c7b32008-06-05 21:53:49 +00001090 * Returns true iff the first sector pointed to by 'buf' contains at least
1091 * a non-NUL byte.
1092 *
1093 * 'pnum' is set to the number of sectors (including and immediately following
1094 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001095 * The function will try to align the end offset to alignment boundaries so
1096 * that the request will at least end aligned and consequtive requests will
1097 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001098 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001099static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1100 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001101{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001102 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001103 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001104
1105 if (n <= 0) {
1106 *pnum = 0;
1107 return 0;
1108 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001109 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001110 for(i = 1; i < n; i++) {
1111 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001112 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001113 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001114 }
bellardea2384d2004-08-01 21:59:26 +00001115 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001116
1117 tail = (sector_num + i) & (alignment - 1);
1118 if (tail) {
1119 if (is_zero && i <= tail) {
1120 /* treat unallocated areas which only consist
1121 * of a small tail as allocated. */
1122 is_zero = false;
1123 }
1124 if (!is_zero) {
1125 /* align up end offset of allocated areas. */
1126 i += alignment - tail;
1127 i = MIN(i, n);
1128 } else {
1129 /* align down end offset of zero areas. */
1130 i -= tail;
1131 }
1132 }
bellardea2384d2004-08-01 21:59:26 +00001133 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001134 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001135}
1136
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001137/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001138 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1139 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1140 * breaking up write requests for only small sparse areas.
1141 */
1142static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001143 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001144{
1145 int ret;
1146 int num_checked, num_used;
1147
1148 if (n < min) {
1149 min = n;
1150 }
1151
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001152 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001153 if (!ret) {
1154 return ret;
1155 }
1156
1157 num_used = *pnum;
1158 buf += BDRV_SECTOR_SIZE * *pnum;
1159 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001160 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001161 num_checked = num_used;
1162
1163 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001164 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001165
1166 buf += BDRV_SECTOR_SIZE * *pnum;
1167 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001168 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001169 num_checked += *pnum;
1170 if (ret) {
1171 num_used = num_checked;
1172 } else if (*pnum >= min) {
1173 break;
1174 }
1175 }
1176
1177 *pnum = num_used;
1178 return 1;
1179}
1180
1181/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001182 * Compares two buffers sector by sector. Returns 0 if the first
1183 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001184 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001185 * pnum is set to the sector-aligned size of the buffer prefix that
1186 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001187 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001188static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1189 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001190{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001191 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001192 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001193
Eric Blakedc61cd32017-10-11 22:47:14 -05001194 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001195
Eric Blakedc61cd32017-10-11 22:47:14 -05001196 res = !!memcmp(buf1, buf2, i);
1197 while (i < bytes) {
1198 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001199
Eric Blakedc61cd32017-10-11 22:47:14 -05001200 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001201 break;
1202 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001203 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001204 }
1205
1206 *pnum = i;
1207 return res;
1208}
1209
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001210#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001211
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001212/*
1213 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1214 *
Eric Blake0608e402017-10-11 22:47:12 -05001215 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1216 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1217 * failure), and 4 on error (the exit status for read errors), after emitting
1218 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001219 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001220 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001221 * @param offset: Starting offset to check
1222 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001223 * @param filename: Name of disk file we are checking (logging purpose)
1224 * @param buffer: Allocated buffer for storing read data
1225 * @param quiet: Flag for quiet mode
1226 */
Eric Blakec41508e2017-10-11 22:47:13 -05001227static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1228 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001229 uint8_t *buffer, bool quiet)
1230{
Eric Blakedebb38a2017-10-11 22:47:11 -05001231 int ret = 0;
1232 int64_t idx;
1233
Eric Blakec41508e2017-10-11 22:47:13 -05001234 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001235 if (ret < 0) {
1236 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001237 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001238 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001239 }
Eric Blakec41508e2017-10-11 22:47:13 -05001240 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001241 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001242 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001243 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001244 return 1;
1245 }
1246
1247 return 0;
1248}
1249
1250/*
1251 * Compares two images. Exit codes:
1252 *
1253 * 0 - Images are identical
1254 * 1 - Images differ
1255 * >1 - Error occurred
1256 */
1257static int img_compare(int argc, char **argv)
1258{
Max Reitz40055952014-07-22 22:58:42 +02001259 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001260 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001261 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001262 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001263 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001264 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001265 int allocated1, allocated2;
1266 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1267 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001268 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001269 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001270 int64_t total_size;
1271 int64_t offset = 0;
1272 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001273 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001274 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001275 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001276 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001277
Max Reitz40055952014-07-22 22:58:42 +02001278 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001279 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001280 static const struct option long_options[] = {
1281 {"help", no_argument, 0, 'h'},
1282 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001283 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001284 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001285 {0, 0, 0, 0}
1286 };
Fam Zheng335e9932017-05-03 00:35:39 +08001287 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001288 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001289 if (c == -1) {
1290 break;
1291 }
1292 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001293 case ':':
1294 missing_argument(argv[optind - 1]);
1295 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001296 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001297 unrecognized_option(argv[optind - 1]);
1298 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001299 case 'h':
1300 help();
1301 break;
1302 case 'f':
1303 fmt1 = optarg;
1304 break;
1305 case 'F':
1306 fmt2 = optarg;
1307 break;
Max Reitz40055952014-07-22 22:58:42 +02001308 case 'T':
1309 cache = optarg;
1310 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001311 case 'p':
1312 progress = true;
1313 break;
1314 case 'q':
1315 quiet = true;
1316 break;
1317 case 's':
1318 strict = true;
1319 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001320 case 'U':
1321 force_share = true;
1322 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001323 case OPTION_OBJECT: {
1324 QemuOpts *opts;
1325 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1326 optarg, true);
1327 if (!opts) {
1328 ret = 2;
1329 goto out4;
1330 }
1331 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001332 case OPTION_IMAGE_OPTS:
1333 image_opts = true;
1334 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001335 }
1336 }
1337
1338 /* Progress is not shown in Quiet mode */
1339 if (quiet) {
1340 progress = false;
1341 }
1342
1343
Kevin Wolffc11eb22013-08-05 10:53:04 +02001344 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001345 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001346 }
1347 filename1 = argv[optind++];
1348 filename2 = argv[optind++];
1349
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001350 if (qemu_opts_foreach(&qemu_object_opts,
1351 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00001352 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001353 ret = 2;
1354 goto out4;
1355 }
1356
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001357 /* Initialize before goto out */
1358 qemu_progress_init(progress, 2.0);
1359
Kevin Wolfce099542016-03-15 13:01:04 +01001360 flags = 0;
1361 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001362 if (ret < 0) {
1363 error_report("Invalid source cache option: %s", cache);
1364 ret = 2;
1365 goto out3;
1366 }
1367
Fam Zheng335e9932017-05-03 00:35:39 +08001368 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1369 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001370 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001371 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001372 goto out3;
1373 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001374
Fam Zheng335e9932017-05-03 00:35:39 +08001375 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1376 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001377 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001378 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001379 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001380 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001381 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001382 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001383
Max Reitzf1d3cd72015-02-05 13:58:18 -05001384 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1385 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001386 total_size1 = blk_getlength(blk1);
1387 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001388 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001389 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001390 ret = 4;
1391 goto out;
1392 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001393 total_size2 = blk_getlength(blk2);
1394 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001395 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001396 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001397 ret = 4;
1398 goto out;
1399 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001400 total_size = MIN(total_size1, total_size2);
1401 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001402
1403 qemu_progress_print(0, 100);
1404
Eric Blake033d9fc2017-10-11 22:47:16 -05001405 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001406 ret = 1;
1407 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1408 goto out;
1409 }
1410
Eric Blake033d9fc2017-10-11 22:47:16 -05001411 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001412 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001413
Eric Blake033d9fc2017-10-11 22:47:16 -05001414 status1 = bdrv_block_status_above(bs1, NULL, offset,
1415 total_size1 - offset, &pnum1, NULL,
1416 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001417 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001418 ret = 3;
1419 error_report("Sector allocation test failed for %s", filename1);
1420 goto out;
1421 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001422 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001423
Eric Blake033d9fc2017-10-11 22:47:16 -05001424 status2 = bdrv_block_status_above(bs2, NULL, offset,
1425 total_size2 - offset, &pnum2, NULL,
1426 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001427 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001428 ret = 3;
1429 error_report("Sector allocation test failed for %s", filename2);
1430 goto out;
1431 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001432 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001433
1434 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001435 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001436
Fam Zheng25ad8e62016-01-13 16:37:41 +08001437 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001438 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001439 ret = 1;
1440 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001441 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001442 goto out;
1443 }
1444 }
1445 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001446 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001447 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001448 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001449 int64_t pnum;
1450
Eric Blake033d9fc2017-10-11 22:47:16 -05001451 chunk = MIN(chunk, IO_BUF_SIZE);
1452 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001453 if (ret < 0) {
1454 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001455 " of %s: %s",
1456 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001457 ret = 4;
1458 goto out;
1459 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001460 ret = blk_pread(blk2, offset, buf2, chunk);
1461 if (ret < 0) {
1462 error_report("Error while reading offset %" PRId64
1463 " of %s: %s",
1464 offset, filename2, strerror(-ret));
1465 ret = 4;
1466 goto out;
1467 }
1468 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1469 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001470 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001471 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001472 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001473 goto out;
1474 }
1475 }
1476 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001477 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001478 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001479 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001480 filename1, buf1, quiet);
1481 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001482 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001483 filename2, buf1, quiet);
1484 }
1485 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001486 goto out;
1487 }
1488 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001489 offset += chunk;
1490 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 }
1492
Eric Blake033d9fc2017-10-11 22:47:16 -05001493 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001494 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001495 const char *filename_over;
1496
1497 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001498 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001499 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001500 filename_over = filename1;
1501 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001502 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001503 filename_over = filename2;
1504 }
1505
Eric Blake033d9fc2017-10-11 22:47:16 -05001506 while (offset < progress_base) {
1507 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1508 progress_base - offset, &chunk,
1509 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001510 if (ret < 0) {
1511 ret = 3;
1512 error_report("Sector allocation test failed for %s",
1513 filename_over);
1514 goto out;
1515
1516 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001517 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001518 chunk = MIN(chunk, IO_BUF_SIZE);
1519 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001520 filename_over, buf1, quiet);
1521 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001522 goto out;
1523 }
1524 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001525 offset += chunk;
1526 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001527 }
1528 }
1529
1530 qprintf(quiet, "Images are identical.\n");
1531 ret = 0;
1532
1533out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001534 qemu_vfree(buf1);
1535 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001536 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001537out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001538 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001539out3:
1540 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001541out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001542 return ret;
1543}
1544
Kevin Wolf690c7302015-03-19 13:33:32 +01001545enum ImgConvertBlockStatus {
1546 BLK_DATA,
1547 BLK_ZERO,
1548 BLK_BACKING_FILE,
1549};
1550
Peter Lieven2d9187b2017-02-28 13:40:07 +01001551#define MAX_COROUTINES 16
1552
Kevin Wolf690c7302015-03-19 13:33:32 +01001553typedef struct ImgConvertState {
1554 BlockBackend **src;
1555 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001556 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001557 int64_t total_sectors;
1558 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001559 int64_t allocated_done;
1560 int64_t sector_num;
1561 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001562 enum ImgConvertBlockStatus status;
1563 int64_t sector_next_status;
1564 BlockBackend *target;
1565 bool has_zero_init;
1566 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001567 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001568 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001569 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001570 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001571 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001572 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001573 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001574 size_t cluster_sectors;
1575 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001576 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001577 int running_coroutines;
1578 Coroutine *co[MAX_COROUTINES];
1579 int64_t wait_sector_num[MAX_COROUTINES];
1580 CoMutex lock;
1581 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001582} ImgConvertState;
1583
Peter Lieven2d9187b2017-02-28 13:40:07 +01001584static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1585 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001586{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001587 *src_cur = 0;
1588 *src_cur_offset = 0;
1589 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1590 *src_cur_offset += s->src_sectors[*src_cur];
1591 (*src_cur)++;
1592 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001593 }
1594}
1595
1596static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1597{
Eric Blake31826642017-10-11 22:47:08 -05001598 int64_t src_cur_offset;
1599 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001600 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001601
Peter Lieven2d9187b2017-02-28 13:40:07 +01001602 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001603
1604 assert(s->total_sectors > sector_num);
1605 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1606
Max Reitz351c8ef2018-05-01 18:57:49 +02001607 if (s->target_backing_sectors >= 0) {
1608 if (sector_num >= s->target_backing_sectors) {
1609 post_backing_zero = s->unallocated_blocks_are_zero;
1610 } else if (sector_num + n > s->target_backing_sectors) {
1611 /* Split requests around target_backing_sectors (because
1612 * starting from there, zeros are handled differently) */
1613 n = s->target_backing_sectors - sector_num;
1614 }
1615 }
1616
Kevin Wolf690c7302015-03-19 13:33:32 +01001617 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001618 int64_t count = n * BDRV_SECTOR_SIZE;
1619
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001620 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001621
1622 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1623 (sector_num - src_cur_offset) *
1624 BDRV_SECTOR_SIZE,
1625 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001626 } else {
Eric Blake31826642017-10-11 22:47:08 -05001627 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1628 (sector_num - src_cur_offset) *
1629 BDRV_SECTOR_SIZE,
1630 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001631 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001632 if (ret < 0) {
Eric Blake2058c2a2019-03-23 16:26:38 -05001633 error_report("error while reading block status of sector %" PRId64
1634 ": %s", sector_num, strerror(-ret));
Kevin Wolf690c7302015-03-19 13:33:32 +01001635 return ret;
1636 }
Eric Blake31826642017-10-11 22:47:08 -05001637 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001638
1639 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001640 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001641 } else if (ret & BDRV_BLOCK_DATA) {
1642 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001643 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001644 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001645 }
1646
1647 s->sector_next_status = sector_num + n;
1648 }
1649
1650 n = MIN(n, s->sector_next_status - sector_num);
1651 if (s->status == BLK_DATA) {
1652 n = MIN(n, s->buf_sectors);
1653 }
1654
1655 /* We need to write complete clusters for compressed images, so if an
1656 * unallocated area is shorter than that, we must consider the whole
1657 * cluster allocated. */
1658 if (s->compressed) {
1659 if (n < s->cluster_sectors) {
1660 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1661 s->status = BLK_DATA;
1662 } else {
1663 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1664 }
1665 }
1666
1667 return n;
1668}
1669
Peter Lieven2d9187b2017-02-28 13:40:07 +01001670static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1671 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001672{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001673 int n, ret;
1674 QEMUIOVector qiov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001675
Kevin Wolf690c7302015-03-19 13:33:32 +01001676 assert(nb_sectors <= s->buf_sectors);
1677 while (nb_sectors > 0) {
1678 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001679 int src_cur;
1680 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001681
1682 /* In the case of compression with multiple source files, we can get a
1683 * nb_sectors that spreads into the next part. So we must be able to
1684 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001685 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1686 blk = s->src[src_cur];
1687 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001688
Peter Lieven2d9187b2017-02-28 13:40:07 +01001689 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
Vladimir Sementsov-Ogievskiyc075a0a2019-02-18 17:09:21 +03001690 qemu_iovec_init_buf(&qiov, buf, n << BDRV_SECTOR_BITS);
Peter Lieven2d9187b2017-02-28 13:40:07 +01001691
1692 ret = blk_co_preadv(
1693 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1694 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001695 if (ret < 0) {
1696 return ret;
1697 }
1698
1699 sector_num += n;
1700 nb_sectors -= n;
1701 buf += n * BDRV_SECTOR_SIZE;
1702 }
1703
1704 return 0;
1705}
1706
Peter Lieven2d9187b2017-02-28 13:40:07 +01001707
1708static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1709 int nb_sectors, uint8_t *buf,
1710 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001711{
1712 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001713 QEMUIOVector qiov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001714
1715 while (nb_sectors > 0) {
1716 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001717 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1718
Peter Lieven2d9187b2017-02-28 13:40:07 +01001719 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001720 case BLK_BACKING_FILE:
1721 /* If we have a backing file, leave clusters unallocated that are
1722 * unallocated in the source image, so that the backing file is
1723 * visible at the respective offset. */
1724 assert(s->target_has_backing);
1725 break;
1726
1727 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001728 /* If we're told to keep the target fully allocated (-S 0) or there
1729 * is real non-zero data, we must write it. Otherwise we can treat
1730 * it as zero sectors.
1731 * Compressed clusters need to be written as a whole, so in that
1732 * case we can only save the write if the buffer is completely
1733 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001734 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001735 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001736 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1737 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001738 (s->compressed &&
1739 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001740 {
Vladimir Sementsov-Ogievskiyc075a0a2019-02-18 17:09:21 +03001741 qemu_iovec_init_buf(&qiov, buf, n << BDRV_SECTOR_BITS);
Peter Lieven2d9187b2017-02-28 13:40:07 +01001742
1743 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001744 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001745 if (ret < 0) {
1746 return ret;
1747 }
1748 break;
1749 }
1750 /* fall-through */
1751
1752 case BLK_ZERO:
1753 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001754 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001755 break;
1756 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001757 ret = blk_co_pwrite_zeroes(s->target,
1758 sector_num << BDRV_SECTOR_BITS,
1759 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001760 if (ret < 0) {
1761 return ret;
1762 }
1763 break;
1764 }
1765
1766 sector_num += n;
1767 nb_sectors -= n;
1768 buf += n * BDRV_SECTOR_SIZE;
1769 }
1770
1771 return 0;
1772}
1773
Fam Zhengee5306d2018-06-01 17:26:48 +08001774static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1775 int nb_sectors)
1776{
1777 int n, ret;
1778
1779 while (nb_sectors > 0) {
1780 BlockBackend *blk;
1781 int src_cur;
1782 int64_t bs_sectors, src_cur_offset;
1783 int64_t offset;
1784
1785 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1786 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1787 blk = s->src[src_cur];
1788 bs_sectors = s->src_sectors[src_cur];
1789
1790 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1791
1792 ret = blk_co_copy_range(blk, offset, s->target,
1793 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001794 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001795 if (ret < 0) {
1796 return ret;
1797 }
1798
1799 sector_num += n;
1800 nb_sectors -= n;
1801 }
1802 return 0;
1803}
1804
Peter Lieven2d9187b2017-02-28 13:40:07 +01001805static void coroutine_fn convert_co_do_copy(void *opaque)
1806{
1807 ImgConvertState *s = opaque;
1808 uint8_t *buf = NULL;
1809 int ret, i;
1810 int index = -1;
1811
1812 for (i = 0; i < s->num_coroutines; i++) {
1813 if (s->co[i] == qemu_coroutine_self()) {
1814 index = i;
1815 break;
1816 }
1817 }
1818 assert(index >= 0);
1819
1820 s->running_coroutines++;
1821 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1822
1823 while (1) {
1824 int n;
1825 int64_t sector_num;
1826 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001827 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001828
1829 qemu_co_mutex_lock(&s->lock);
1830 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1831 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001832 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001833 }
1834 n = convert_iteration_sectors(s, s->sector_num);
1835 if (n < 0) {
1836 qemu_co_mutex_unlock(&s->lock);
1837 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001838 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001839 }
1840 /* save current sector and allocation status to local variables */
1841 sector_num = s->sector_num;
1842 status = s->status;
1843 if (!s->min_sparse && s->status == BLK_ZERO) {
1844 n = MIN(n, s->buf_sectors);
1845 }
1846 /* increment global sector counter so that other coroutines can
1847 * already continue reading beyond this request */
1848 s->sector_num += n;
1849 qemu_co_mutex_unlock(&s->lock);
1850
1851 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1852 s->allocated_done += n;
1853 qemu_progress_print(100.0 * s->allocated_done /
1854 s->allocated_sectors, 0);
1855 }
1856
Fam Zhengee5306d2018-06-01 17:26:48 +08001857retry:
1858 copy_range = s->copy_range && s->status == BLK_DATA;
1859 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001860 ret = convert_co_read(s, sector_num, n, buf);
1861 if (ret < 0) {
1862 error_report("error while reading sector %" PRId64
1863 ": %s", sector_num, strerror(-ret));
1864 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001865 }
1866 } else if (!s->min_sparse && status == BLK_ZERO) {
1867 status = BLK_DATA;
1868 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1869 }
1870
1871 if (s->wr_in_order) {
1872 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001873 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001874 s->wait_sector_num[index] = sector_num;
1875 qemu_coroutine_yield();
1876 }
1877 s->wait_sector_num[index] = -1;
1878 }
1879
Anton Nefedovb91127e2017-04-26 11:33:15 +03001880 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001881 if (copy_range) {
1882 ret = convert_co_copy_range(s, sector_num, n);
1883 if (ret) {
1884 s->copy_range = false;
1885 goto retry;
1886 }
1887 } else {
1888 ret = convert_co_write(s, sector_num, n, buf, status);
1889 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001890 if (ret < 0) {
1891 error_report("error while writing sector %" PRId64
1892 ": %s", sector_num, strerror(-ret));
1893 s->ret = ret;
1894 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001895 }
1896
1897 if (s->wr_in_order) {
1898 /* reenter the coroutine that might have waited
1899 * for this write to complete */
1900 s->wr_offs = sector_num + n;
1901 for (i = 0; i < s->num_coroutines; i++) {
1902 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1903 /*
1904 * A -> B -> A cannot occur because A has
1905 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1906 * B will never enter A during this time window.
1907 */
1908 qemu_coroutine_enter(s->co[i]);
1909 break;
1910 }
1911 }
1912 }
1913 }
1914
Peter Lieven2d9187b2017-02-28 13:40:07 +01001915 qemu_vfree(buf);
1916 s->co[index] = NULL;
1917 s->running_coroutines--;
1918 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1919 /* the convert job finished successfully */
1920 s->ret = 0;
1921 }
1922}
1923
Kevin Wolf690c7302015-03-19 13:33:32 +01001924static int convert_do_copy(ImgConvertState *s)
1925{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001926 int ret, i, n;
1927 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001928
1929 /* Check whether we have zero initialisation or can get it efficiently */
1930 s->has_zero_init = s->min_sparse && !s->target_has_backing
1931 ? bdrv_has_zero_init(blk_bs(s->target))
1932 : false;
1933
1934 if (!s->has_zero_init && !s->target_has_backing &&
1935 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1936 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001937 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001938 if (ret == 0) {
1939 s->has_zero_init = true;
1940 }
1941 }
1942
1943 /* Allocate buffer for copied data. For compressed images, only one cluster
1944 * can be copied at a time. */
1945 if (s->compressed) {
1946 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1947 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001948 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001949 }
1950 s->buf_sectors = s->cluster_sectors;
1951 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001952
Kevin Wolf690c7302015-03-19 13:33:32 +01001953 while (sector_num < s->total_sectors) {
1954 n = convert_iteration_sectors(s, sector_num);
1955 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001956 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001957 }
Max Reitzaad15de2016-03-24 23:33:57 +01001958 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1959 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001960 s->allocated_sectors += n;
1961 }
1962 sector_num += n;
1963 }
1964
1965 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001966 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001967 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001968
Peter Lieven2d9187b2017-02-28 13:40:07 +01001969 qemu_co_mutex_init(&s->lock);
1970 for (i = 0; i < s->num_coroutines; i++) {
1971 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1972 s->wait_sector_num[i] = -1;
1973 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001974 }
1975
Anton Nefedovb91127e2017-04-26 11:33:15 +03001976 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001977 main_loop_wait(false);
1978 }
1979
1980 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001981 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001982 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001983 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001984 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001985 }
1986 }
1987
Peter Lieven2d9187b2017-02-28 13:40:07 +01001988 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001989}
1990
Peter Lieven6360ab22018-07-13 09:15:39 +02001991#define MAX_BUF_SECTORS 32768
1992
bellardea2384d2004-08-01 21:59:26 +00001993static int img_convert(int argc, char **argv)
1994{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001995 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001996 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001997 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1998 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001999 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002000 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002001 BlockDriverState *out_bs;
2002 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002003 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002004 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002005 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002006 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002007 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002008 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002009 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002010 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002011 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002012
Peter Lieven9fd77f92017-04-21 11:11:55 +02002013 ImgConvertState s = (ImgConvertState) {
2014 /* Need at least 4k of zeros for sparse detection */
2015 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002016 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002017 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2018 .wr_in_order = true,
2019 .num_coroutines = 8,
2020 };
2021
bellardea2384d2004-08-01 21:59:26 +00002022 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002023 static const struct option long_options[] = {
2024 {"help", no_argument, 0, 'h'},
2025 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002026 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002027 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002028 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002029 {0, 0, 0, 0}
2030 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002031 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002032 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002033 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002034 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002035 }
bellardea2384d2004-08-01 21:59:26 +00002036 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002037 case ':':
2038 missing_argument(argv[optind - 1]);
2039 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002040 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002041 unrecognized_option(argv[optind - 1]);
2042 break;
bellardea2384d2004-08-01 21:59:26 +00002043 case 'h':
2044 help();
2045 break;
2046 case 'f':
2047 fmt = optarg;
2048 break;
2049 case 'O':
2050 out_fmt = optarg;
2051 break;
thsf58c7b32008-06-05 21:53:49 +00002052 case 'B':
2053 out_baseimg = optarg;
2054 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002055 case 'C':
2056 s.copy_range = true;
2057 break;
bellardea2384d2004-08-01 21:59:26 +00002058 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002059 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002060 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002061 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002062 if (!is_valid_option_list(optarg)) {
2063 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002064 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002065 }
2066 if (!options) {
2067 options = g_strdup(optarg);
2068 } else {
2069 char *old_options = options;
2070 options = g_strdup_printf("%s,%s", options, optarg);
2071 g_free(old_options);
2072 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002073 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002074 case 'l':
2075 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002076 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2077 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002078 if (!sn_opts) {
2079 error_report("Failed in parsing snapshot param '%s'",
2080 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002081 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002082 }
2083 } else {
2084 snapshot_name = optarg;
2085 }
2086 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002087 case 'S':
2088 {
2089 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002090
2091 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002092 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2093 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2094 error_report("Invalid buffer size for sparse output specified. "
2095 "Valid sizes are multiples of %llu up to %llu. Select "
2096 "0 to disable sparse detection (fully allocates output).",
2097 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002098 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002099 }
2100
Peter Lieven9fd77f92017-04-21 11:11:55 +02002101 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002102 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002103 break;
2104 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002105 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002106 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002107 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002108 case 't':
2109 cache = optarg;
2110 break;
Max Reitz40055952014-07-22 22:58:42 +02002111 case 'T':
2112 src_cache = optarg;
2113 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002114 case 'q':
2115 quiet = true;
2116 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002117 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002118 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002119 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002120 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002121 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2122 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002123 error_report("Invalid number of coroutines. Allowed number of"
2124 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002125 goto fail_getopt;
2126 }
2127 break;
2128 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002129 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002130 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002131 case 'U':
2132 force_share = true;
2133 break;
Max Reitz3258b912017-04-26 15:46:47 +02002134 case OPTION_OBJECT: {
2135 QemuOpts *object_opts;
2136 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2137 optarg, true);
2138 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002139 goto fail_getopt;
2140 }
2141 break;
Max Reitz3258b912017-04-26 15:46:47 +02002142 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002143 case OPTION_IMAGE_OPTS:
2144 image_opts = true;
2145 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002146 case OPTION_TARGET_IMAGE_OPTS:
2147 tgt_image_opts = true;
2148 break;
bellardea2384d2004-08-01 21:59:26 +00002149 }
2150 }
ths3b46e622007-09-17 08:09:54 +00002151
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002152 if (!out_fmt && !tgt_image_opts) {
2153 out_fmt = "raw";
2154 }
2155
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002156 if (qemu_opts_foreach(&qemu_object_opts,
2157 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002158 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002159 goto fail_getopt;
2160 }
2161
Fam Zhenge11ce122018-07-27 11:34:01 +08002162 if (s.compressed && s.copy_range) {
2163 error_report("Cannot enable copy offloading when -c is used");
2164 goto fail_getopt;
2165 }
2166
2167 if (explict_min_sparse && s.copy_range) {
2168 error_report("Cannot enable copy offloading when -S is used");
2169 goto fail_getopt;
2170 }
2171
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002172 if (tgt_image_opts && !skip_create) {
2173 error_report("--target-image-opts requires use of -n flag");
2174 goto fail_getopt;
2175 }
2176
Peter Lieven9fd77f92017-04-21 11:11:55 +02002177 s.src_num = argc - optind - 1;
2178 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2179
2180 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002181 if (out_fmt) {
2182 ret = print_block_option_help(out_filename, out_fmt);
2183 goto fail_getopt;
2184 } else {
2185 error_report("Option help requires a format be specified");
2186 goto fail_getopt;
2187 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002188 }
2189
2190 if (s.src_num < 1) {
2191 error_report("Must specify image file name");
2192 goto fail_getopt;
2193 }
2194
2195
Peter Lieven9fd77f92017-04-21 11:11:55 +02002196 /* ret is still -EINVAL until here */
2197 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2198 if (ret < 0) {
2199 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002200 goto fail_getopt;
2201 }
2202
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002203 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002204 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002205 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002206 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002207 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002208 qemu_progress_print(0, 100);
2209
Peter Lieven9fd77f92017-04-21 11:11:55 +02002210 s.src = g_new0(BlockBackend *, s.src_num);
2211 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002212
Peter Lieven9fd77f92017-04-21 11:11:55 +02002213 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2214 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002215 fmt, src_flags, src_writethrough, quiet,
2216 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002217 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002218 ret = -1;
2219 goto out;
2220 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002221 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2222 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002223 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002224 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002225 ret = -1;
2226 goto out;
2227 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002228 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002229 }
bellardea2384d2004-08-01 21:59:26 +00002230
Wenchao Xiaef806542013-12-04 17:10:57 +08002231 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002232 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002233 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2234 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2235 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002236 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002237 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002238 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002239 ret = -1;
2240 goto out;
2241 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002242
Peter Lieven9fd77f92017-04-21 11:11:55 +02002243 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2244 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002245 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002246 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002247 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002248 ret = -1;
2249 goto out;
edison51ef6722010-09-21 19:58:41 -07002250 }
2251
Max Reitz2e024cd2015-02-11 09:58:46 -05002252 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002253 /* Find driver and parse its options */
2254 drv = bdrv_find_format(out_fmt);
2255 if (!drv) {
2256 error_report("Unknown file format '%s'", out_fmt);
2257 ret = -1;
2258 goto out;
2259 }
2260
2261 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2262 if (!proto_drv) {
2263 error_report_err(local_err);
2264 ret = -1;
2265 goto out;
2266 }
2267
Max Reitz2e024cd2015-02-11 09:58:46 -05002268 if (!drv->create_opts) {
2269 error_report("Format driver '%s' does not support image creation",
2270 drv->format_name);
2271 ret = -1;
2272 goto out;
2273 }
Max Reitzf75613c2014-12-02 18:32:46 +01002274
Max Reitz2e024cd2015-02-11 09:58:46 -05002275 if (!proto_drv->create_opts) {
2276 error_report("Protocol driver '%s' does not support image creation",
2277 proto_drv->format_name);
2278 ret = -1;
2279 goto out;
2280 }
Max Reitzf75613c2014-12-02 18:32:46 +01002281
Max Reitz2e024cd2015-02-11 09:58:46 -05002282 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2283 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002284
Max Reitz2e024cd2015-02-11 09:58:46 -05002285 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002286 if (options) {
2287 qemu_opts_do_parse(opts, options, NULL, &local_err);
2288 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002289 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002290 ret = -1;
2291 goto out;
2292 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002293 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002294
Peter Lieven9fd77f92017-04-21 11:11:55 +02002295 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002296 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002297 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2298 if (ret < 0) {
2299 goto out;
2300 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002301 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002302
Kevin Wolfa18953f2010-10-14 15:46:04 +02002303 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002304 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002305 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002306 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002307 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002308 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002309
Max Reitz48758a82017-04-26 15:46:48 +02002310 if (s.src_num > 1 && out_baseimg) {
2311 error_report("Having a backing file for the target makes no sense when "
2312 "concatenating multiple input images");
2313 ret = -1;
2314 goto out;
2315 }
2316
Kevin Wolfefa84d42009-05-18 16:42:12 +02002317 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002318 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002319 bool encryption =
2320 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002321 const char *encryptfmt =
2322 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002323 const char *preallocation =
2324 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002325
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002326 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002327 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002328 ret = -1;
2329 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002330 }
2331
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002332 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002333 error_report("Compression and encryption not supported at "
2334 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002335 ret = -1;
2336 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002337 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002338
Chunyan Liu83d05212014-06-05 17:20:51 +08002339 if (preallocation
2340 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002341 {
2342 error_report("Compression and preallocation not supported at "
2343 "the same time");
2344 ret = -1;
2345 goto out;
2346 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002347 }
2348
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002349 /*
2350 * The later open call will need any decryption secrets, and
2351 * bdrv_create() will purge "opts", so extract them now before
2352 * they are lost.
2353 */
2354 if (!skip_create) {
2355 open_opts = qdict_new();
2356 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2357 }
2358
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002359 if (!skip_create) {
2360 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002361 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002362 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002363 error_reportf_err(local_err, "%s: error while converting %s: ",
2364 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002365 goto out;
bellardea2384d2004-08-01 21:59:26 +00002366 }
2367 }
ths3b46e622007-09-17 08:09:54 +00002368
Peter Lieven9fd77f92017-04-21 11:11:55 +02002369 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002370 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002371 if (ret < 0) {
2372 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002373 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002374 }
2375
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002376 if (skip_create) {
2377 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2378 flags, writethrough, quiet, false);
2379 } else {
2380 /* TODO ultimately we should allow --target-image-opts
2381 * to be used even when -n is not given.
2382 * That has to wait for bdrv_create to be improved
2383 * to allow filenames in option syntax
2384 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002385 s.target = img_open_file(out_filename, open_opts, out_fmt,
2386 flags, writethrough, quiet, false);
2387 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002388 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002389 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002390 ret = -1;
2391 goto out;
2392 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002393 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002394
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002395 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2396 error_report("Compression not supported for this file format");
2397 ret = -1;
2398 goto out;
2399 }
2400
Eric Blake5def6b82016-06-23 16:37:19 -06002401 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002402 * or discard_alignment of the out_bs is greater. Limit to
2403 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2404 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002405 MAX(s.buf_sectors,
2406 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2407 out_bs->bl.pdiscard_alignment >>
2408 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002409
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002410 /* try to align the write requests to the destination to avoid unnecessary
2411 * RMW cycles. */
2412 s.alignment = MAX(pow2floor(s.min_sparse),
2413 DIV_ROUND_UP(out_bs->bl.request_alignment,
2414 BDRV_SECTOR_SIZE));
2415 assert(is_power_of_2(s.alignment));
2416
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002417 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002418 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002419 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002420 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002421 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002422 ret = -1;
2423 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002424 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002425 error_report("output file is smaller than input file");
2426 ret = -1;
2427 goto out;
2428 }
2429 }
2430
Max Reitz351c8ef2018-05-01 18:57:49 +02002431 if (s.target_has_backing) {
2432 /* Errors are treated as "backing length unknown" (which means
2433 * s.target_backing_sectors has to be negative, which it will
2434 * be automatically). The backing file length is used only
2435 * for optimizations, so such a case is not fatal. */
2436 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2437 } else {
2438 s.target_backing_sectors = -1;
2439 }
2440
Peter Lieven24f833c2013-11-27 11:07:07 +01002441 ret = bdrv_get_info(out_bs, &bdi);
2442 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002443 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002444 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002445 goto out;
2446 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002447 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002448 s.compressed = s.compressed || bdi.needs_compressed_writes;
2449 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002450 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002451 }
2452
Peter Lieven9fd77f92017-04-21 11:11:55 +02002453 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002454out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002455 if (!ret) {
2456 qemu_progress_print(100, 0);
2457 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002458 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002459 qemu_opts_del(opts);
2460 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002461 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002462 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002463 blk_unref(s.target);
2464 if (s.src) {
2465 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2466 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002467 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002468 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002469 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002470 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002471fail_getopt:
2472 g_free(options);
2473
Peter Lieven9fd77f92017-04-21 11:11:55 +02002474 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002475}
2476
bellard57d1a2b2004-08-03 21:15:11 +00002477
bellardfaea38e2006-08-05 21:31:00 +00002478static void dump_snapshots(BlockDriverState *bs)
2479{
2480 QEMUSnapshotInfo *sn_tab, *sn;
2481 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002482
2483 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2484 if (nb_sns <= 0)
2485 return;
2486 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002487 bdrv_snapshot_dump(fprintf, stdout, NULL);
2488 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002489 for(i = 0; i < nb_sns; i++) {
2490 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002491 bdrv_snapshot_dump(fprintf, stdout, sn);
2492 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002493 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002494 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002495}
2496
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002497static void dump_json_image_info_list(ImageInfoList *list)
2498{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002499 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002500 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002501 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002502
2503 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2504 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002505 str = qobject_to_json_pretty(obj);
2506 assert(str != NULL);
2507 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002508 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002509 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002510 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002511}
2512
Benoît Canetc054b3f2012-09-05 13:09:02 +02002513static void dump_json_image_info(ImageInfo *info)
2514{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002515 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002516 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002517 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002518
2519 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2520 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002521 str = qobject_to_json_pretty(obj);
2522 assert(str != NULL);
2523 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002524 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002525 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002526 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002527}
2528
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002529static void dump_human_image_info_list(ImageInfoList *list)
2530{
2531 ImageInfoList *elem;
2532 bool delim = false;
2533
2534 for (elem = list; elem; elem = elem->next) {
2535 if (delim) {
2536 printf("\n");
2537 }
2538 delim = true;
2539
Wenchao Xia5b917042013-05-25 11:09:45 +08002540 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002541 }
2542}
2543
2544static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2545{
2546 return strcmp(a, b) == 0;
2547}
2548
2549/**
2550 * Open an image file chain and return an ImageInfoList
2551 *
2552 * @filename: topmost image filename
2553 * @fmt: topmost image format (may be NULL to autodetect)
2554 * @chain: true - enumerate entire backing file chain
2555 * false - only topmost image file
2556 *
2557 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2558 * image file. If there was an error a message will have been printed to
2559 * stderr.
2560 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002561static ImageInfoList *collect_image_info_list(bool image_opts,
2562 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002563 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002564 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002565{
2566 ImageInfoList *head = NULL;
2567 ImageInfoList **last = &head;
2568 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002569 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002570
2571 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2572
2573 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002574 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002575 BlockDriverState *bs;
2576 ImageInfo *info;
2577 ImageInfoList *elem;
2578
2579 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2580 error_report("Backing file '%s' creates an infinite loop.",
2581 filename);
2582 goto err;
2583 }
2584 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2585
Max Reitzefaa7c42016-03-16 19:54:38 +01002586 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002587 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2588 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002589 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002590 goto err;
2591 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002592 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002593
Wenchao Xia43526ec2013-06-06 12:27:58 +08002594 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002595 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002596 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002597 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002598 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002599 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002600
2601 elem = g_new0(ImageInfoList, 1);
2602 elem->value = info;
2603 *last = elem;
2604 last = &elem->next;
2605
Markus Armbruster26f54e92014-10-07 13:59:04 +02002606 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002607
2608 filename = fmt = NULL;
2609 if (chain) {
2610 if (info->has_full_backing_filename) {
2611 filename = info->full_backing_filename;
2612 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002613 error_report("Could not determine absolute backing filename,"
2614 " but backing filename '%s' present",
2615 info->backing_filename);
2616 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002617 }
2618 if (info->has_backing_filename_format) {
2619 fmt = info->backing_filename_format;
2620 }
2621 }
2622 }
2623 g_hash_table_destroy(filenames);
2624 return head;
2625
2626err:
2627 qapi_free_ImageInfoList(head);
2628 g_hash_table_destroy(filenames);
2629 return NULL;
2630}
2631
Benoît Canetc054b3f2012-09-05 13:09:02 +02002632static int img_info(int argc, char **argv)
2633{
2634 int c;
2635 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002636 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002637 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002638 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002639 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002640 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002641
bellardea2384d2004-08-01 21:59:26 +00002642 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002643 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002644 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002645 int option_index = 0;
2646 static const struct option long_options[] = {
2647 {"help", no_argument, 0, 'h'},
2648 {"format", required_argument, 0, 'f'},
2649 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002650 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002651 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002652 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002653 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002654 {0, 0, 0, 0}
2655 };
Fam Zheng335e9932017-05-03 00:35:39 +08002656 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002657 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002658 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002659 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002660 }
bellardea2384d2004-08-01 21:59:26 +00002661 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002662 case ':':
2663 missing_argument(argv[optind - 1]);
2664 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002665 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002666 unrecognized_option(argv[optind - 1]);
2667 break;
bellardea2384d2004-08-01 21:59:26 +00002668 case 'h':
2669 help();
2670 break;
2671 case 'f':
2672 fmt = optarg;
2673 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002674 case 'U':
2675 force_share = true;
2676 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002677 case OPTION_OUTPUT:
2678 output = optarg;
2679 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002680 case OPTION_BACKING_CHAIN:
2681 chain = true;
2682 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002683 case OPTION_OBJECT: {
2684 QemuOpts *opts;
2685 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2686 optarg, true);
2687 if (!opts) {
2688 return 1;
2689 }
2690 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002691 case OPTION_IMAGE_OPTS:
2692 image_opts = true;
2693 break;
bellardea2384d2004-08-01 21:59:26 +00002694 }
2695 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002696 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002697 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002698 }
bellardea2384d2004-08-01 21:59:26 +00002699 filename = argv[optind++];
2700
Benoît Canetc054b3f2012-09-05 13:09:02 +02002701 if (output && !strcmp(output, "json")) {
2702 output_format = OFORMAT_JSON;
2703 } else if (output && !strcmp(output, "human")) {
2704 output_format = OFORMAT_HUMAN;
2705 } else if (output) {
2706 error_report("--output must be used with human or json as argument.");
2707 return 1;
2708 }
2709
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002710 if (qemu_opts_foreach(&qemu_object_opts,
2711 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002712 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002713 return 1;
2714 }
2715
Fam Zheng335e9932017-05-03 00:35:39 +08002716 list = collect_image_info_list(image_opts, filename, fmt, chain,
2717 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002718 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002719 return 1;
2720 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002721
Benoît Canetc054b3f2012-09-05 13:09:02 +02002722 switch (output_format) {
2723 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002724 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002725 break;
2726 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002727 if (chain) {
2728 dump_json_image_info_list(list);
2729 } else {
2730 dump_json_image_info(list->value);
2731 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002732 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002733 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002734
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002735 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002736 return 0;
2737}
2738
Eric Blake30065d12019-03-26 13:40:43 -05002739static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2740 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002741{
2742 switch (output_format) {
2743 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002744 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002745 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002746 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002747 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002748 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002749 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002750 e->start, e->length,
2751 e->has_offset ? e->offset : 0,
2752 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002753 }
2754 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2755 * Modify the flags here to allow more coalescing.
2756 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002757 if (next && (!next->data || next->zero)) {
2758 next->data = false;
2759 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002760 }
2761 break;
2762 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002763 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2764 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002765 (e->start == 0 ? "[" : ",\n"),
2766 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002767 e->zero ? "true" : "false",
2768 e->data ? "true" : "false");
2769 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002770 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002771 }
2772 putchar('}');
2773
2774 if (!next) {
2775 printf("]\n");
2776 }
2777 break;
2778 }
Eric Blake30065d12019-03-26 13:40:43 -05002779 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002780}
2781
Eric Blake5e344dd2017-10-11 22:47:02 -05002782static int get_block_status(BlockDriverState *bs, int64_t offset,
2783 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002784{
Eric Blake237d78f2017-10-11 22:47:03 -05002785 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002786 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002787 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002788 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002789 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002790 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002791
2792 /* As an optimization, we could cache the current range of unallocated
2793 * clusters in each file of the chain, and avoid querying the same
2794 * range repeatedly.
2795 */
2796
2797 depth = 0;
2798 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002799 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002800 if (ret < 0) {
2801 return ret;
2802 }
Eric Blake237d78f2017-10-11 22:47:03 -05002803 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002804 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2805 break;
2806 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002807 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002808 if (bs == NULL) {
2809 ret = 0;
2810 break;
2811 }
2812
2813 depth++;
2814 }
2815
John Snow28756452016-02-05 13:12:33 -05002816 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2817
Max Reitzf30c66b2019-02-01 20:29:05 +01002818 if (file && has_offset) {
2819 bdrv_refresh_filename(file);
2820 filename = file->filename;
2821 }
2822
John Snow28756452016-02-05 13:12:33 -05002823 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002824 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002825 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002826 .data = !!(ret & BDRV_BLOCK_DATA),
2827 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002828 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002829 .has_offset = has_offset,
2830 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002831 .has_filename = filename,
2832 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002833 };
2834
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002835 return 0;
2836}
2837
Fam Zheng16b0d552016-01-26 11:59:02 +08002838static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2839{
2840 if (curr->length == 0) {
2841 return false;
2842 }
2843 if (curr->zero != next->zero ||
2844 curr->data != next->data ||
2845 curr->depth != next->depth ||
2846 curr->has_filename != next->has_filename ||
2847 curr->has_offset != next->has_offset) {
2848 return false;
2849 }
2850 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2851 return false;
2852 }
2853 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2854 return false;
2855 }
2856 return true;
2857}
2858
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002859static int img_map(int argc, char **argv)
2860{
2861 int c;
2862 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002863 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002864 BlockDriverState *bs;
2865 const char *filename, *fmt, *output;
2866 int64_t length;
2867 MapEntry curr = { .length = 0 }, next;
2868 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002869 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002870 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002871
2872 fmt = NULL;
2873 output = NULL;
2874 for (;;) {
2875 int option_index = 0;
2876 static const struct option long_options[] = {
2877 {"help", no_argument, 0, 'h'},
2878 {"format", required_argument, 0, 'f'},
2879 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002880 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002881 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002882 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002883 {0, 0, 0, 0}
2884 };
Fam Zheng335e9932017-05-03 00:35:39 +08002885 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002886 long_options, &option_index);
2887 if (c == -1) {
2888 break;
2889 }
2890 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002891 case ':':
2892 missing_argument(argv[optind - 1]);
2893 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002894 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002895 unrecognized_option(argv[optind - 1]);
2896 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002897 case 'h':
2898 help();
2899 break;
2900 case 'f':
2901 fmt = optarg;
2902 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002903 case 'U':
2904 force_share = true;
2905 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002906 case OPTION_OUTPUT:
2907 output = optarg;
2908 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002909 case OPTION_OBJECT: {
2910 QemuOpts *opts;
2911 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2912 optarg, true);
2913 if (!opts) {
2914 return 1;
2915 }
2916 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002917 case OPTION_IMAGE_OPTS:
2918 image_opts = true;
2919 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002920 }
2921 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002922 if (optind != argc - 1) {
2923 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002924 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002925 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002926
2927 if (output && !strcmp(output, "json")) {
2928 output_format = OFORMAT_JSON;
2929 } else if (output && !strcmp(output, "human")) {
2930 output_format = OFORMAT_HUMAN;
2931 } else if (output) {
2932 error_report("--output must be used with human or json as argument.");
2933 return 1;
2934 }
2935
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002936 if (qemu_opts_foreach(&qemu_object_opts,
2937 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002938 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002939 return 1;
2940 }
2941
Fam Zheng335e9932017-05-03 00:35:39 +08002942 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002943 if (!blk) {
2944 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002945 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002946 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002947
2948 if (output_format == OFORMAT_HUMAN) {
2949 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2950 }
2951
Max Reitzf1d3cd72015-02-05 13:58:18 -05002952 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002953 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002954 int64_t offset = curr.start + curr.length;
2955 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002956
2957 /* Probe up to 1 GiB at a time. */
Eric Blakee0b371e2018-06-11 16:39:26 -05002958 n = MIN(1 << 30, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002959 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002960
2961 if (ret < 0) {
2962 error_report("Could not read file metadata: %s", strerror(-ret));
2963 goto out;
2964 }
2965
Fam Zheng16b0d552016-01-26 11:59:02 +08002966 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002967 curr.length += next.length;
2968 continue;
2969 }
2970
2971 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05002972 ret = dump_map_entry(output_format, &curr, &next);
2973 if (ret < 0) {
2974 goto out;
2975 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002976 }
2977 curr = next;
2978 }
2979
Eric Blake30065d12019-03-26 13:40:43 -05002980 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002981
2982out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002983 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002984 return ret < 0;
2985}
2986
aliguorif7b4a942009-01-07 17:40:15 +00002987#define SNAPSHOT_LIST 1
2988#define SNAPSHOT_CREATE 2
2989#define SNAPSHOT_APPLY 3
2990#define SNAPSHOT_DELETE 4
2991
Stuart Brady153859b2009-06-07 00:42:17 +01002992static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002993{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002994 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002995 BlockDriverState *bs;
2996 QEMUSnapshotInfo sn;
2997 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002998 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002999 int action = 0;
3000 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003001 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003002 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003003 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003004 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003005
Kevin Wolfce099542016-03-15 13:01:04 +01003006 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003007 /* Parse commandline parameters */
3008 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003009 static const struct option long_options[] = {
3010 {"help", no_argument, 0, 'h'},
3011 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003012 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003013 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003014 {0, 0, 0, 0}
3015 };
Fam Zheng335e9932017-05-03 00:35:39 +08003016 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003017 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003018 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003019 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003020 }
aliguorif7b4a942009-01-07 17:40:15 +00003021 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003022 case ':':
3023 missing_argument(argv[optind - 1]);
3024 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003025 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003026 unrecognized_option(argv[optind - 1]);
3027 break;
aliguorif7b4a942009-01-07 17:40:15 +00003028 case 'h':
3029 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003030 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003031 case 'l':
3032 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003033 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003034 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003035 }
3036 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003037 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003038 break;
3039 case 'a':
3040 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003041 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003042 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003043 }
3044 action = SNAPSHOT_APPLY;
3045 snapshot_name = optarg;
3046 break;
3047 case 'c':
3048 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003049 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003050 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003051 }
3052 action = SNAPSHOT_CREATE;
3053 snapshot_name = optarg;
3054 break;
3055 case 'd':
3056 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003057 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003058 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003059 }
3060 action = SNAPSHOT_DELETE;
3061 snapshot_name = optarg;
3062 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003063 case 'q':
3064 quiet = true;
3065 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003066 case 'U':
3067 force_share = true;
3068 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003069 case OPTION_OBJECT: {
3070 QemuOpts *opts;
3071 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3072 optarg, true);
3073 if (!opts) {
3074 return 1;
3075 }
3076 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003077 case OPTION_IMAGE_OPTS:
3078 image_opts = true;
3079 break;
aliguorif7b4a942009-01-07 17:40:15 +00003080 }
3081 }
3082
Kevin Wolffc11eb22013-08-05 10:53:04 +02003083 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003084 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003085 }
aliguorif7b4a942009-01-07 17:40:15 +00003086 filename = argv[optind++];
3087
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003088 if (qemu_opts_foreach(&qemu_object_opts,
3089 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003090 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003091 return 1;
3092 }
3093
aliguorif7b4a942009-01-07 17:40:15 +00003094 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003095 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3096 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003097 if (!blk) {
3098 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003099 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003100 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003101
3102 /* Perform the requested action */
3103 switch(action) {
3104 case SNAPSHOT_LIST:
3105 dump_snapshots(bs);
3106 break;
3107
3108 case SNAPSHOT_CREATE:
3109 memset(&sn, 0, sizeof(sn));
3110 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3111
3112 qemu_gettimeofday(&tv);
3113 sn.date_sec = tv.tv_sec;
3114 sn.date_nsec = tv.tv_usec * 1000;
3115
3116 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003117 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003118 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003119 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003120 }
aliguorif7b4a942009-01-07 17:40:15 +00003121 break;
3122
3123 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003124 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003125 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003126 error_reportf_err(err, "Could not apply snapshot '%s': ",
3127 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003128 }
aliguorif7b4a942009-01-07 17:40:15 +00003129 break;
3130
3131 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003132 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3133 if (ret < 0) {
3134 error_report("Could not delete snapshot '%s': snapshot not "
3135 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003136 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003137 } else {
3138 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3139 if (ret < 0) {
3140 error_reportf_err(err, "Could not delete snapshot '%s': ",
3141 snapshot_name);
3142 ret = 1;
3143 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003144 }
aliguorif7b4a942009-01-07 17:40:15 +00003145 break;
3146 }
3147
3148 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003149 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003150 if (ret) {
3151 return 1;
3152 }
Stuart Brady153859b2009-06-07 00:42:17 +01003153 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003154}
3155
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003156static int img_rebase(int argc, char **argv)
3157{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003158 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003159 uint8_t *buf_old = NULL;
3160 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003161 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003162 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003163 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3164 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003165 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003166 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003167 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003168 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003169 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003170 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003171 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003172
3173 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003174 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003175 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003176 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003177 out_baseimg = NULL;
3178 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003179 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003180 static const struct option long_options[] = {
3181 {"help", no_argument, 0, 'h'},
3182 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003183 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003184 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003185 {0, 0, 0, 0}
3186 };
Fam Zheng335e9932017-05-03 00:35:39 +08003187 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003188 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003189 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003190 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003191 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003192 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003193 case ':':
3194 missing_argument(argv[optind - 1]);
3195 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003196 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003197 unrecognized_option(argv[optind - 1]);
3198 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003199 case 'h':
3200 help();
3201 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003202 case 'f':
3203 fmt = optarg;
3204 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003205 case 'F':
3206 out_basefmt = optarg;
3207 break;
3208 case 'b':
3209 out_baseimg = optarg;
3210 break;
3211 case 'u':
3212 unsafe = 1;
3213 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003214 case 'p':
3215 progress = 1;
3216 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003217 case 't':
3218 cache = optarg;
3219 break;
Max Reitz40055952014-07-22 22:58:42 +02003220 case 'T':
3221 src_cache = optarg;
3222 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003223 case 'q':
3224 quiet = true;
3225 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003226 case OPTION_OBJECT: {
3227 QemuOpts *opts;
3228 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3229 optarg, true);
3230 if (!opts) {
3231 return 1;
3232 }
3233 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003234 case OPTION_IMAGE_OPTS:
3235 image_opts = true;
3236 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003237 case 'U':
3238 force_share = true;
3239 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003240 }
3241 }
3242
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003243 if (quiet) {
3244 progress = 0;
3245 }
3246
Fam Zhengac1307a2014-04-22 13:36:11 +08003247 if (optind != argc - 1) {
3248 error_exit("Expecting one image file name");
3249 }
3250 if (!unsafe && !out_baseimg) {
3251 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003252 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003253 filename = argv[optind++];
3254
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003255 if (qemu_opts_foreach(&qemu_object_opts,
3256 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003257 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003258 return 1;
3259 }
3260
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003261 qemu_progress_init(progress, 2.0);
3262 qemu_progress_print(0, 100);
3263
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003264 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003265 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003266 if (ret < 0) {
3267 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003268 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003269 }
3270
Kevin Wolfce099542016-03-15 13:01:04 +01003271 src_flags = 0;
3272 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003273 if (ret < 0) {
3274 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003275 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003276 }
3277
Kevin Wolfce099542016-03-15 13:01:04 +01003278 /* The source files are opened read-only, don't care about WCE */
3279 assert((src_flags & BDRV_O_RDWR) == 0);
3280 (void) src_writethrough;
3281
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003282 /*
3283 * Open the images.
3284 *
3285 * Ignore the old backing file for unsafe rebase in case we want to correct
3286 * the reference to a renamed or moved backing file.
3287 */
Fam Zheng335e9932017-05-03 00:35:39 +08003288 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3289 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003290 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003291 ret = -1;
3292 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003293 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003294 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003295
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003296 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003297 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003298 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003299 ret = -1;
3300 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003301 }
3302 }
3303
3304 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003305 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003306 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003307 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003308
Max Reitz644483d2015-02-05 13:58:17 -05003309 if (bs->backing_format[0] != '\0') {
3310 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003311 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003312 }
3313
Fam Zheng335e9932017-05-03 00:35:39 +08003314 if (force_share) {
3315 if (!options) {
3316 options = qdict_new();
3317 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003318 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003319 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003320 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003321 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003322 options, src_flags, &local_err);
3323 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003324 error_reportf_err(local_err,
3325 "Could not open old backing file '%s': ",
3326 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003327 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003328 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003329 }
Max Reitz644483d2015-02-05 13:58:17 -05003330
Alex Bligha6166732012-10-16 13:46:18 +01003331 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003332 const char *overlay_filename;
3333 char *out_real_path;
3334
Fam Zheng335e9932017-05-03 00:35:39 +08003335 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003336 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003337 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003338 }
3339 if (force_share) {
3340 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003341 }
3342
Max Reitzf30c66b2019-02-01 20:29:05 +01003343 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003344 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3345 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003346 out_real_path =
3347 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3348 out_baseimg,
3349 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003350 if (local_err) {
3351 error_reportf_err(local_err,
3352 "Could not resolve backing filename: ");
3353 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003354 goto out;
3355 }
3356
3357 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003358 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003359 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003360 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003361 error_reportf_err(local_err,
3362 "Could not open new backing file '%s': ",
3363 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003364 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003365 goto out;
3366 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003367 }
3368 }
3369
3370 /*
3371 * Check each unallocated cluster in the COW file. If it is unallocated,
3372 * accesses go to the backing file. We must therefore compare this cluster
3373 * in the old and new backing file, and if they differ we need to copy it
3374 * from the old backing file into the COW file.
3375 *
3376 * If qemu-img crashes during this step, no harm is done. The content of
3377 * the image is the same as the original one at any time.
3378 */
3379 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003380 int64_t size;
3381 int64_t old_backing_size;
3382 int64_t new_backing_size = 0;
3383 uint64_t offset;
3384 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003385 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003386
Max Reitzf1d3cd72015-02-05 13:58:18 -05003387 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3388 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003389
Eric Blake41536282017-10-11 22:47:15 -05003390 size = blk_getlength(blk);
3391 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003392 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003393 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003394 ret = -1;
3395 goto out;
3396 }
Eric Blake41536282017-10-11 22:47:15 -05003397 old_backing_size = blk_getlength(blk_old_backing);
3398 if (old_backing_size < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003399 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003400
3401 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3402 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003403 backing_name, strerror(-old_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003404 ret = -1;
3405 goto out;
3406 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003407 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003408 new_backing_size = blk_getlength(blk_new_backing);
3409 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003410 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003411 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003412 ret = -1;
3413 goto out;
3414 }
Alex Bligha6166732012-10-16 13:46:18 +01003415 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003416
Eric Blake41536282017-10-11 22:47:15 -05003417 if (size != 0) {
3418 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003419 }
3420
Eric Blake41536282017-10-11 22:47:15 -05003421 for (offset = 0; offset < size; offset += n) {
3422 /* How many bytes can we handle with the next read? */
3423 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003424
3425 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003426 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003427 if (ret < 0) {
3428 error_report("error while reading image metadata: %s",
3429 strerror(-ret));
3430 goto out;
3431 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003432 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003433 continue;
3434 }
3435
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003436 /*
3437 * Read old and new backing file and take into consideration that
3438 * backing files may be smaller than the COW image.
3439 */
Eric Blake41536282017-10-11 22:47:15 -05003440 if (offset >= old_backing_size) {
3441 memset(buf_old, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003442 } else {
Eric Blake41536282017-10-11 22:47:15 -05003443 if (offset + n > old_backing_size) {
3444 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003445 }
3446
Eric Blake41536282017-10-11 22:47:15 -05003447 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003448 if (ret < 0) {
3449 error_report("error while reading from old backing file");
3450 goto out;
3451 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003452 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003453
Eric Blake41536282017-10-11 22:47:15 -05003454 if (offset >= new_backing_size || !blk_new_backing) {
3455 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003456 } else {
Eric Blake41536282017-10-11 22:47:15 -05003457 if (offset + n > new_backing_size) {
3458 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003459 }
3460
Eric Blake41536282017-10-11 22:47:15 -05003461 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003462 if (ret < 0) {
3463 error_report("error while reading from new backing file");
3464 goto out;
3465 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003466 }
3467
3468 /* If they differ, we need to write to the COW file */
3469 uint64_t written = 0;
3470
Eric Blake41536282017-10-11 22:47:15 -05003471 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003472 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003473
Eric Blake41536282017-10-11 22:47:15 -05003474 if (compare_buffers(buf_old + written, buf_new + written,
3475 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003476 {
Eric Blake41536282017-10-11 22:47:15 -05003477 ret = blk_pwrite(blk, offset + written,
Eric Blakedc61cd32017-10-11 22:47:14 -05003478 buf_old + written, pnum, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003479 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003480 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003481 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003482 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003483 }
3484 }
3485
3486 written += pnum;
3487 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003488 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003489 }
3490 }
3491
3492 /*
3493 * Change the backing file. All clusters that are different from the old
3494 * backing file are overwritten in the COW file now, so the visible content
3495 * doesn't change when we switch the backing file.
3496 */
Alex Bligha6166732012-10-16 13:46:18 +01003497 if (out_baseimg && *out_baseimg) {
3498 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3499 } else {
3500 ret = bdrv_change_backing_file(bs, NULL, NULL);
3501 }
3502
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003503 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003504 error_report("Could not change the backing file to '%s': No "
3505 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003506 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003507 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003508 out_baseimg, strerror(-ret));
3509 }
3510
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003511 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003512 /*
3513 * TODO At this point it is possible to check if any clusters that are
3514 * allocated in the COW file are the same in the backing file. If so, they
3515 * could be dropped from the COW file. Don't do this before switching the
3516 * backing file, in case of a crash this would lead to corruption.
3517 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003518out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003519 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003520 /* Cleanup */
3521 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003522 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003523 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003524 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003525 qemu_vfree(buf_old);
3526 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003527
Markus Armbruster26f54e92014-10-07 13:59:04 +02003528 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003529 if (ret) {
3530 return 1;
3531 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003532 return 0;
3533}
3534
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003535static int img_resize(int argc, char **argv)
3536{
Markus Armbruster6750e792015-02-12 17:43:08 +01003537 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003538 int c, ret, relative;
3539 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003540 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003541 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003542 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003543 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003544 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003545
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003546 static QemuOptsList resize_options = {
3547 .name = "resize_options",
3548 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3549 .desc = {
3550 {
3551 .name = BLOCK_OPT_SIZE,
3552 .type = QEMU_OPT_SIZE,
3553 .help = "Virtual disk size"
3554 }, {
3555 /* end of list */
3556 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003557 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003558 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003559 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003560 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003561
Kevin Wolfe80fec72011-04-29 10:58:12 +02003562 /* Remove size from argv manually so that negative numbers are not treated
3563 * as options by getopt. */
3564 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003565 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003566 return 1;
3567 }
3568
3569 size = argv[--argc];
3570
3571 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003572 fmt = NULL;
3573 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003574 static const struct option long_options[] = {
3575 {"help", no_argument, 0, 'h'},
3576 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003577 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003578 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003579 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003580 {0, 0, 0, 0}
3581 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003582 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003583 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003584 if (c == -1) {
3585 break;
3586 }
3587 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003588 case ':':
3589 missing_argument(argv[optind - 1]);
3590 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003591 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003592 unrecognized_option(argv[optind - 1]);
3593 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003594 case 'h':
3595 help();
3596 break;
3597 case 'f':
3598 fmt = optarg;
3599 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003600 case 'q':
3601 quiet = true;
3602 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003603 case OPTION_OBJECT: {
3604 QemuOpts *opts;
3605 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3606 optarg, true);
3607 if (!opts) {
3608 return 1;
3609 }
3610 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003611 case OPTION_IMAGE_OPTS:
3612 image_opts = true;
3613 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003614 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003615 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003616 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003617 if (prealloc == PREALLOC_MODE__MAX) {
3618 error_report("Invalid preallocation mode '%s'", optarg);
3619 return 1;
3620 }
3621 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003622 case OPTION_SHRINK:
3623 shrink = true;
3624 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003625 }
3626 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003627 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003628 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003629 }
3630 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003631
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003632 if (qemu_opts_foreach(&qemu_object_opts,
3633 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003634 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003635 return 1;
3636 }
3637
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003638 /* Choose grow, shrink, or absolute resize mode */
3639 switch (size[0]) {
3640 case '+':
3641 relative = 1;
3642 size++;
3643 break;
3644 case '-':
3645 relative = -1;
3646 size++;
3647 break;
3648 default:
3649 relative = 0;
3650 break;
3651 }
3652
3653 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003654 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003655 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003656 if (err) {
3657 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003658 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003659 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003660 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003661 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003662 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3663 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003664
Max Reitzefaa7c42016-03-16 19:54:38 +01003665 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003666 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3667 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003668 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003669 ret = -1;
3670 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003671 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003672
Max Reitzdc5f6902017-06-13 22:20:55 +02003673 current_size = blk_getlength(blk);
3674 if (current_size < 0) {
3675 error_report("Failed to inquire current image length: %s",
3676 strerror(-current_size));
3677 ret = -1;
3678 goto out;
3679 }
3680
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003681 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003682 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003683 } else {
3684 total_size = n;
3685 }
3686 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003687 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003688 ret = -1;
3689 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003690 }
3691
Max Reitzdc5f6902017-06-13 22:20:55 +02003692 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3693 error_report("Preallocation can only be used for growing images");
3694 ret = -1;
3695 goto out;
3696 }
3697
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003698 if (total_size < current_size && !shrink) {
3699 warn_report("Shrinking an image will delete all data beyond the "
3700 "shrunken image's end. Before performing such an "
3701 "operation, make sure there is no important data there.");
3702
3703 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3704 error_report(
3705 "Use the --shrink option to perform a shrink operation.");
3706 ret = -1;
3707 goto out;
3708 } else {
3709 warn_report("Using the --shrink option will suppress this message. "
3710 "Note that future versions of qemu-img may refuse to "
3711 "shrink images without this option.");
3712 }
3713 }
3714
Max Reitzdc5f6902017-06-13 22:20:55 +02003715 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003716 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003717 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003718 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003719 }
Max Reitz5279b302018-04-21 18:39:57 +02003720
3721 new_size = blk_getlength(blk);
3722 if (new_size < 0) {
3723 error_report("Failed to verify truncated image length: %s",
3724 strerror(-new_size));
3725 ret = -1;
3726 goto out;
3727 }
3728
3729 /* Some block drivers implement a truncation method, but only so
3730 * the user can cause qemu to refresh the image's size from disk.
3731 * The idea is that the user resizes the image outside of qemu and
3732 * then invokes block_resize to inform qemu about it.
3733 * (This includes iscsi and file-posix for device files.)
3734 * Of course, that is not the behavior someone invoking
3735 * qemu-img resize would find useful, so we catch that behavior
3736 * here and tell the user. */
3737 if (new_size != total_size && new_size == current_size) {
3738 error_report("Image was not resized; resizing may not be supported "
3739 "for this image");
3740 ret = -1;
3741 goto out;
3742 }
3743
3744 if (new_size != total_size) {
3745 warn_report("Image should have been resized to %" PRIi64
3746 " bytes, but was resized to %" PRIi64 " bytes",
3747 total_size, new_size);
3748 }
3749
3750 qprintf(quiet, "Image resized.\n");
3751
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003752out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003753 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003754 if (ret) {
3755 return 1;
3756 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003757 return 0;
3758}
3759
Max Reitz76a3a342014-10-27 11:12:51 +01003760static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003761 int64_t offset, int64_t total_work_size,
3762 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003763{
3764 qemu_progress_print(100.f * offset / total_work_size, 0);
3765}
3766
Max Reitz51641352018-05-09 23:00:20 +02003767static int print_amend_option_help(const char *format)
3768{
3769 BlockDriver *drv;
3770
3771 /* Find driver and parse its options */
3772 drv = bdrv_find_format(format);
3773 if (!drv) {
3774 error_report("Unknown file format '%s'", format);
3775 return 1;
3776 }
3777
3778 if (!drv->bdrv_amend_options) {
3779 error_report("Format driver '%s' does not support option amendment",
3780 format);
3781 return 1;
3782 }
3783
3784 /* Every driver supporting amendment must have create_opts */
3785 assert(drv->create_opts);
3786
3787 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003788 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003789 printf("\nNote that not all of these options may be amendable.\n");
3790 return 0;
3791}
3792
Max Reitz6f176b42013-09-03 10:09:50 +02003793static int img_amend(int argc, char **argv)
3794{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003795 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003796 int c, ret = 0;
3797 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003798 QemuOptsList *create_opts = NULL;
3799 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003800 const char *fmt = NULL, *filename, *cache;
3801 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003802 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003803 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003804 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003805 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003806 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003807
Max Reitzbd39e6e2014-07-22 22:58:43 +02003808 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003809 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003810 static const struct option long_options[] = {
3811 {"help", no_argument, 0, 'h'},
3812 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003813 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003814 {0, 0, 0, 0}
3815 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003816 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003817 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003818 if (c == -1) {
3819 break;
3820 }
3821
3822 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003823 case ':':
3824 missing_argument(argv[optind - 1]);
3825 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003826 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003827 unrecognized_option(argv[optind - 1]);
3828 break;
3829 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003830 help();
3831 break;
3832 case 'o':
3833 if (!is_valid_option_list(optarg)) {
3834 error_report("Invalid option list: %s", optarg);
3835 ret = -1;
3836 goto out_no_progress;
3837 }
3838 if (!options) {
3839 options = g_strdup(optarg);
3840 } else {
3841 char *old_options = options;
3842 options = g_strdup_printf("%s,%s", options, optarg);
3843 g_free(old_options);
3844 }
3845 break;
3846 case 'f':
3847 fmt = optarg;
3848 break;
3849 case 't':
3850 cache = optarg;
3851 break;
3852 case 'p':
3853 progress = true;
3854 break;
3855 case 'q':
3856 quiet = true;
3857 break;
3858 case OPTION_OBJECT:
3859 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3860 optarg, true);
3861 if (!opts) {
3862 ret = -1;
3863 goto out_no_progress;
3864 }
3865 break;
3866 case OPTION_IMAGE_OPTS:
3867 image_opts = true;
3868 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003869 }
3870 }
3871
Max Reitz6f176b42013-09-03 10:09:50 +02003872 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003873 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003874 }
3875
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003876 if (qemu_opts_foreach(&qemu_object_opts,
3877 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003878 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003879 ret = -1;
3880 goto out_no_progress;
3881 }
3882
Max Reitz76a3a342014-10-27 11:12:51 +01003883 if (quiet) {
3884 progress = false;
3885 }
3886 qemu_progress_init(progress, 1.0);
3887
Kevin Wolfa283cb62014-02-21 16:24:07 +01003888 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3889 if (fmt && has_help_option(options)) {
3890 /* If a format is explicitly specified (and possibly no filename is
3891 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003892 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003893 goto out;
3894 }
3895
3896 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003897 error_report("Expecting one image file name");
3898 ret = -1;
3899 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003900 }
Max Reitz6f176b42013-09-03 10:09:50 +02003901
Kevin Wolfce099542016-03-15 13:01:04 +01003902 flags = BDRV_O_RDWR;
3903 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003904 if (ret < 0) {
3905 error_report("Invalid cache option: %s", cache);
3906 goto out;
3907 }
3908
Fam Zheng335e9932017-05-03 00:35:39 +08003909 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3910 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003911 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003912 ret = -1;
3913 goto out;
3914 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003915 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003916
3917 fmt = bs->drv->format_name;
3918
Kevin Wolf626f84f2014-02-21 16:24:06 +01003919 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003920 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003921 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003922 goto out;
3923 }
3924
Max Reitz1f996682018-05-09 23:00:17 +02003925 if (!bs->drv->bdrv_amend_options) {
3926 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003927 fmt);
3928 ret = -1;
3929 goto out;
3930 }
3931
Max Reitz1f996682018-05-09 23:00:17 +02003932 /* Every driver supporting amendment must have create_opts */
3933 assert(bs->drv->create_opts);
3934
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003935 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003936 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003937 qemu_opts_do_parse(opts, options, NULL, &err);
3938 if (err) {
3939 error_report_err(err);
3940 ret = -1;
3941 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003942 }
3943
Max Reitz76a3a342014-10-27 11:12:51 +01003944 /* In case the driver does not call amend_status_cb() */
3945 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003946 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003947 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003948 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003949 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003950 goto out;
3951 }
3952
3953out:
Max Reitz76a3a342014-10-27 11:12:51 +01003954 qemu_progress_end();
3955
Max Reitze814dff2015-08-20 16:00:38 -07003956out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003957 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003958 qemu_opts_del(opts);
3959 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003960 g_free(options);
3961
Max Reitz6f176b42013-09-03 10:09:50 +02003962 if (ret) {
3963 return 1;
3964 }
3965 return 0;
3966}
3967
Kevin Wolfb6133b82014-08-05 14:17:13 +02003968typedef struct BenchData {
3969 BlockBackend *blk;
3970 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003971 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003972 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003973 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003974 int nrreq;
3975 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003976 int flush_interval;
3977 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003978 uint8_t *buf;
3979 QEMUIOVector *qiov;
3980
3981 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003982 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003983 uint64_t offset;
3984} BenchData;
3985
Kevin Wolf55d539c2016-06-03 13:59:41 +02003986static void bench_undrained_flush_cb(void *opaque, int ret)
3987{
3988 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003989 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003990 exit(EXIT_FAILURE);
3991 }
3992}
3993
Kevin Wolfb6133b82014-08-05 14:17:13 +02003994static void bench_cb(void *opaque, int ret)
3995{
3996 BenchData *b = opaque;
3997 BlockAIOCB *acb;
3998
3999 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004000 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004001 exit(EXIT_FAILURE);
4002 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004003
4004 if (b->in_flush) {
4005 /* Just finished a flush with drained queue: Start next requests */
4006 assert(b->in_flight == 0);
4007 b->in_flush = false;
4008 } else if (b->in_flight > 0) {
4009 int remaining = b->n - b->in_flight;
4010
Kevin Wolfb6133b82014-08-05 14:17:13 +02004011 b->n--;
4012 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004013
4014 /* Time for flush? Drain queue if requested, then flush */
4015 if (b->flush_interval && remaining % b->flush_interval == 0) {
4016 if (!b->in_flight || !b->drain_on_flush) {
4017 BlockCompletionFunc *cb;
4018
4019 if (b->drain_on_flush) {
4020 b->in_flush = true;
4021 cb = bench_cb;
4022 } else {
4023 cb = bench_undrained_flush_cb;
4024 }
4025
4026 acb = blk_aio_flush(b->blk, cb, b);
4027 if (!acb) {
4028 error_report("Failed to issue flush request");
4029 exit(EXIT_FAILURE);
4030 }
4031 }
4032 if (b->drain_on_flush) {
4033 return;
4034 }
4035 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004036 }
4037
4038 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004039 int64_t offset = b->offset;
4040 /* blk_aio_* might look for completed I/Os and kick bench_cb
4041 * again, so make sure this operation is counted by in_flight
4042 * and b->offset is ready for the next submission.
4043 */
4044 b->in_flight++;
4045 b->offset += b->step;
4046 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004047 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004048 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004049 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004050 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004051 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004052 if (!acb) {
4053 error_report("Failed to issue request");
4054 exit(EXIT_FAILURE);
4055 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004056 }
4057}
4058
4059static int img_bench(int argc, char **argv)
4060{
4061 int c, ret = 0;
4062 const char *fmt = NULL, *filename;
4063 bool quiet = false;
4064 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004065 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004066 int count = 75000;
4067 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004068 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004069 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004070 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004071 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004072 int flush_interval = 0;
4073 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004074 int64_t image_size;
4075 BlockBackend *blk = NULL;
4076 BenchData data = {};
4077 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004078 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004079 struct timeval t1, t2;
4080 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004081 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004082 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004083
4084 for (;;) {
4085 static const struct option long_options[] = {
4086 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004087 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004088 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004089 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004090 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004091 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004092 {0, 0, 0, 0}
4093 };
Fam Zheng335e9932017-05-03 00:35:39 +08004094 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004095 if (c == -1) {
4096 break;
4097 }
4098
4099 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004100 case ':':
4101 missing_argument(argv[optind - 1]);
4102 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004103 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004104 unrecognized_option(argv[optind - 1]);
4105 break;
4106 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004107 help();
4108 break;
4109 case 'c':
4110 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004111 unsigned long res;
4112
4113 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004114 error_report("Invalid request count specified");
4115 return 1;
4116 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004117 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004118 break;
4119 }
4120 case 'd':
4121 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004122 unsigned long res;
4123
4124 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004125 error_report("Invalid queue depth specified");
4126 return 1;
4127 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004128 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004129 break;
4130 }
4131 case 'f':
4132 fmt = optarg;
4133 break;
4134 case 'n':
4135 flags |= BDRV_O_NATIVE_AIO;
4136 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004137 case 'o':
4138 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004139 offset = cvtnum(optarg);
4140 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004141 error_report("Invalid offset specified");
4142 return 1;
4143 }
4144 break;
4145 }
4146 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004147 case 'q':
4148 quiet = true;
4149 break;
4150 case 's':
4151 {
4152 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004153
Markus Armbruster606caa02017-02-21 21:14:04 +01004154 sval = cvtnum(optarg);
4155 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004156 error_report("Invalid buffer size specified");
4157 return 1;
4158 }
4159
4160 bufsize = sval;
4161 break;
4162 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004163 case 'S':
4164 {
4165 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004166
Markus Armbruster606caa02017-02-21 21:14:04 +01004167 sval = cvtnum(optarg);
4168 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004169 error_report("Invalid step size specified");
4170 return 1;
4171 }
4172
4173 step = sval;
4174 break;
4175 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004176 case 't':
4177 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4178 if (ret < 0) {
4179 error_report("Invalid cache mode");
4180 ret = -1;
4181 goto out;
4182 }
4183 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004184 case 'w':
4185 flags |= BDRV_O_RDWR;
4186 is_write = true;
4187 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004188 case 'U':
4189 force_share = true;
4190 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004191 case OPTION_PATTERN:
4192 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004193 unsigned long res;
4194
4195 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004196 error_report("Invalid pattern byte specified");
4197 return 1;
4198 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004199 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004200 break;
4201 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004202 case OPTION_FLUSH_INTERVAL:
4203 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004204 unsigned long res;
4205
4206 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004207 error_report("Invalid flush interval specified");
4208 return 1;
4209 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004210 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004211 break;
4212 }
4213 case OPTION_NO_DRAIN:
4214 drain_on_flush = false;
4215 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004216 case OPTION_IMAGE_OPTS:
4217 image_opts = true;
4218 break;
4219 }
4220 }
4221
4222 if (optind != argc - 1) {
4223 error_exit("Expecting one image file name");
4224 }
4225 filename = argv[argc - 1];
4226
Kevin Wolf55d539c2016-06-03 13:59:41 +02004227 if (!is_write && flush_interval) {
4228 error_report("--flush-interval is only available in write tests");
4229 ret = -1;
4230 goto out;
4231 }
4232 if (flush_interval && flush_interval < depth) {
4233 error_report("Flush interval can't be smaller than depth");
4234 ret = -1;
4235 goto out;
4236 }
4237
Fam Zheng335e9932017-05-03 00:35:39 +08004238 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4239 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004240 if (!blk) {
4241 ret = -1;
4242 goto out;
4243 }
4244
4245 image_size = blk_getlength(blk);
4246 if (image_size < 0) {
4247 ret = image_size;
4248 goto out;
4249 }
4250
4251 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004252 .blk = blk,
4253 .image_size = image_size,
4254 .bufsize = bufsize,
4255 .step = step ?: bufsize,
4256 .nrreq = depth,
4257 .n = count,
4258 .offset = offset,
4259 .write = is_write,
4260 .flush_interval = flush_interval,
4261 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004262 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004263 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004264 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004265 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004266 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004267 if (flush_interval) {
4268 printf("Sending flush every %d requests\n", flush_interval);
4269 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004270
Fam Zheng79d46582018-01-16 14:08:58 +08004271 buf_size = data.nrreq * data.bufsize;
4272 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004273 memset(data.buf, pattern, data.nrreq * data.bufsize);
4274
Fam Zheng79d46582018-01-16 14:08:58 +08004275 blk_register_buf(blk, data.buf, buf_size);
4276
Kevin Wolfb6133b82014-08-05 14:17:13 +02004277 data.qiov = g_new(QEMUIOVector, data.nrreq);
4278 for (i = 0; i < data.nrreq; i++) {
4279 qemu_iovec_init(&data.qiov[i], 1);
4280 qemu_iovec_add(&data.qiov[i],
4281 data.buf + i * data.bufsize, data.bufsize);
4282 }
4283
4284 gettimeofday(&t1, NULL);
4285 bench_cb(&data, 0);
4286
4287 while (data.n > 0) {
4288 main_loop_wait(false);
4289 }
4290 gettimeofday(&t2, NULL);
4291
4292 printf("Run completed in %3.3f seconds.\n",
4293 (t2.tv_sec - t1.tv_sec)
4294 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4295
4296out:
Fam Zheng79d46582018-01-16 14:08:58 +08004297 if (data.buf) {
4298 blk_unregister_buf(blk, data.buf);
4299 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004300 qemu_vfree(data.buf);
4301 blk_unref(blk);
4302
4303 if (ret) {
4304 return 1;
4305 }
4306 return 0;
4307}
4308
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004309#define C_BS 01
4310#define C_COUNT 02
4311#define C_IF 04
4312#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004313#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004314
4315struct DdInfo {
4316 unsigned int flags;
4317 int64_t count;
4318};
4319
4320struct DdIo {
4321 int bsz; /* Block size */
4322 char *filename;
4323 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004324 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004325};
4326
4327struct DdOpts {
4328 const char *name;
4329 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4330 unsigned int flag;
4331};
4332
4333static int img_dd_bs(const char *arg,
4334 struct DdIo *in, struct DdIo *out,
4335 struct DdInfo *dd)
4336{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004337 int64_t res;
4338
Markus Armbruster606caa02017-02-21 21:14:04 +01004339 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004340
Markus Armbruster606caa02017-02-21 21:14:04 +01004341 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004342 error_report("invalid number: '%s'", arg);
4343 return 1;
4344 }
4345 in->bsz = out->bsz = res;
4346
4347 return 0;
4348}
4349
4350static int img_dd_count(const char *arg,
4351 struct DdIo *in, struct DdIo *out,
4352 struct DdInfo *dd)
4353{
Markus Armbruster606caa02017-02-21 21:14:04 +01004354 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004355
Markus Armbruster606caa02017-02-21 21:14:04 +01004356 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004357 error_report("invalid number: '%s'", arg);
4358 return 1;
4359 }
4360
4361 return 0;
4362}
4363
4364static int img_dd_if(const char *arg,
4365 struct DdIo *in, struct DdIo *out,
4366 struct DdInfo *dd)
4367{
4368 in->filename = g_strdup(arg);
4369
4370 return 0;
4371}
4372
4373static int img_dd_of(const char *arg,
4374 struct DdIo *in, struct DdIo *out,
4375 struct DdInfo *dd)
4376{
4377 out->filename = g_strdup(arg);
4378
4379 return 0;
4380}
4381
Reda Sallahif7c15532016-08-10 16:16:09 +02004382static int img_dd_skip(const char *arg,
4383 struct DdIo *in, struct DdIo *out,
4384 struct DdInfo *dd)
4385{
Markus Armbruster606caa02017-02-21 21:14:04 +01004386 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004387
Markus Armbruster606caa02017-02-21 21:14:04 +01004388 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004389 error_report("invalid number: '%s'", arg);
4390 return 1;
4391 }
4392
4393 return 0;
4394}
4395
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004396static int img_dd(int argc, char **argv)
4397{
4398 int ret = 0;
4399 char *arg = NULL;
4400 char *tmp;
4401 BlockDriver *drv = NULL, *proto_drv = NULL;
4402 BlockBackend *blk1 = NULL, *blk2 = NULL;
4403 QemuOpts *opts = NULL;
4404 QemuOptsList *create_opts = NULL;
4405 Error *local_err = NULL;
4406 bool image_opts = false;
4407 int c, i;
4408 const char *out_fmt = "raw";
4409 const char *fmt = NULL;
4410 int64_t size = 0;
4411 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004412 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004413 struct DdInfo dd = {
4414 .flags = 0,
4415 .count = 0,
4416 };
4417 struct DdIo in = {
4418 .bsz = 512, /* Block size is by default 512 bytes */
4419 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004420 .buf = NULL,
4421 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004422 };
4423 struct DdIo out = {
4424 .bsz = 512,
4425 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004426 .buf = NULL,
4427 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004428 };
4429
4430 const struct DdOpts options[] = {
4431 { "bs", img_dd_bs, C_BS },
4432 { "count", img_dd_count, C_COUNT },
4433 { "if", img_dd_if, C_IF },
4434 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004435 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004436 { NULL, NULL, 0 }
4437 };
4438 const struct option long_options[] = {
4439 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004440 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004441 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004442 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004443 { 0, 0, 0, 0 }
4444 };
4445
Fam Zheng335e9932017-05-03 00:35:39 +08004446 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004447 if (c == EOF) {
4448 break;
4449 }
4450 switch (c) {
4451 case 'O':
4452 out_fmt = optarg;
4453 break;
4454 case 'f':
4455 fmt = optarg;
4456 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004457 case ':':
4458 missing_argument(argv[optind - 1]);
4459 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004460 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004461 unrecognized_option(argv[optind - 1]);
4462 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004463 case 'h':
4464 help();
4465 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004466 case 'U':
4467 force_share = true;
4468 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004469 case OPTION_OBJECT:
4470 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004471 ret = -1;
4472 goto out;
4473 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004474 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004475 case OPTION_IMAGE_OPTS:
4476 image_opts = true;
4477 break;
4478 }
4479 }
4480
4481 for (i = optind; i < argc; i++) {
4482 int j;
4483 arg = g_strdup(argv[i]);
4484
4485 tmp = strchr(arg, '=');
4486 if (tmp == NULL) {
4487 error_report("unrecognized operand %s", arg);
4488 ret = -1;
4489 goto out;
4490 }
4491
4492 *tmp++ = '\0';
4493
4494 for (j = 0; options[j].name != NULL; j++) {
4495 if (!strcmp(arg, options[j].name)) {
4496 break;
4497 }
4498 }
4499 if (options[j].name == NULL) {
4500 error_report("unrecognized operand %s", arg);
4501 ret = -1;
4502 goto out;
4503 }
4504
4505 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4506 ret = -1;
4507 goto out;
4508 }
4509 dd.flags |= options[j].flag;
4510 g_free(arg);
4511 arg = NULL;
4512 }
4513
4514 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4515 error_report("Must specify both input and output files");
4516 ret = -1;
4517 goto out;
4518 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004519
4520 if (qemu_opts_foreach(&qemu_object_opts,
4521 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004522 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004523 ret = -1;
4524 goto out;
4525 }
4526
Fam Zheng335e9932017-05-03 00:35:39 +08004527 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4528 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004529
4530 if (!blk1) {
4531 ret = -1;
4532 goto out;
4533 }
4534
4535 drv = bdrv_find_format(out_fmt);
4536 if (!drv) {
4537 error_report("Unknown file format");
4538 ret = -1;
4539 goto out;
4540 }
4541 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4542
4543 if (!proto_drv) {
4544 error_report_err(local_err);
4545 ret = -1;
4546 goto out;
4547 }
4548 if (!drv->create_opts) {
4549 error_report("Format driver '%s' does not support image creation",
4550 drv->format_name);
4551 ret = -1;
4552 goto out;
4553 }
4554 if (!proto_drv->create_opts) {
4555 error_report("Protocol driver '%s' does not support image creation",
4556 proto_drv->format_name);
4557 ret = -1;
4558 goto out;
4559 }
4560 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4561 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4562
4563 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4564
4565 size = blk_getlength(blk1);
4566 if (size < 0) {
4567 error_report("Failed to get size for '%s'", in.filename);
4568 ret = -1;
4569 goto out;
4570 }
4571
4572 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4573 dd.count * in.bsz < size) {
4574 size = dd.count * in.bsz;
4575 }
4576
Reda Sallahif7c15532016-08-10 16:16:09 +02004577 /* Overflow means the specified offset is beyond input image's size */
4578 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4579 size < in.bsz * in.offset)) {
4580 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4581 } else {
4582 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4583 size - in.bsz * in.offset, &error_abort);
4584 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004585
4586 ret = bdrv_create(drv, out.filename, opts, &local_err);
4587 if (ret < 0) {
4588 error_reportf_err(local_err,
4589 "%s: error while creating output image: ",
4590 out.filename);
4591 ret = -1;
4592 goto out;
4593 }
4594
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004595 /* TODO, we can't honour --image-opts for the target,
4596 * since it needs to be given in a format compatible
4597 * with the bdrv_create() call above which does not
4598 * support image-opts style.
4599 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004600 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004601 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004602
4603 if (!blk2) {
4604 ret = -1;
4605 goto out;
4606 }
4607
Reda Sallahif7c15532016-08-10 16:16:09 +02004608 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4609 size < in.offset * in.bsz)) {
4610 /* We give a warning if the skip option is bigger than the input
4611 * size and create an empty output disk image (i.e. like dd(1)).
4612 */
4613 error_report("%s: cannot skip to specified offset", in.filename);
4614 in_pos = size;
4615 } else {
4616 in_pos = in.offset * in.bsz;
4617 }
4618
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004619 in.buf = g_new(uint8_t, in.bsz);
4620
Reda Sallahif7c15532016-08-10 16:16:09 +02004621 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004622 int in_ret, out_ret;
4623
4624 if (in_pos + in.bsz > size) {
4625 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4626 } else {
4627 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4628 }
4629 if (in_ret < 0) {
4630 error_report("error while reading from input image file: %s",
4631 strerror(-in_ret));
4632 ret = -1;
4633 goto out;
4634 }
4635 in_pos += in_ret;
4636
4637 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4638
4639 if (out_ret < 0) {
4640 error_report("error while writing to output image file: %s",
4641 strerror(-out_ret));
4642 ret = -1;
4643 goto out;
4644 }
4645 out_pos += out_ret;
4646 }
4647
4648out:
4649 g_free(arg);
4650 qemu_opts_del(opts);
4651 qemu_opts_free(create_opts);
4652 blk_unref(blk1);
4653 blk_unref(blk2);
4654 g_free(in.filename);
4655 g_free(out.filename);
4656 g_free(in.buf);
4657 g_free(out.buf);
4658
4659 if (ret) {
4660 return 1;
4661 }
4662 return 0;
4663}
4664
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004665static void dump_json_block_measure_info(BlockMeasureInfo *info)
4666{
4667 QString *str;
4668 QObject *obj;
4669 Visitor *v = qobject_output_visitor_new(&obj);
4670
4671 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4672 visit_complete(v, &obj);
4673 str = qobject_to_json_pretty(obj);
4674 assert(str != NULL);
4675 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004676 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004677 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004678 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004679}
4680
4681static int img_measure(int argc, char **argv)
4682{
4683 static const struct option long_options[] = {
4684 {"help", no_argument, 0, 'h'},
4685 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4686 {"object", required_argument, 0, OPTION_OBJECT},
4687 {"output", required_argument, 0, OPTION_OUTPUT},
4688 {"size", required_argument, 0, OPTION_SIZE},
4689 {"force-share", no_argument, 0, 'U'},
4690 {0, 0, 0, 0}
4691 };
4692 OutputFormat output_format = OFORMAT_HUMAN;
4693 BlockBackend *in_blk = NULL;
4694 BlockDriver *drv;
4695 const char *filename = NULL;
4696 const char *fmt = NULL;
4697 const char *out_fmt = "raw";
4698 char *options = NULL;
4699 char *snapshot_name = NULL;
4700 bool force_share = false;
4701 QemuOpts *opts = NULL;
4702 QemuOpts *object_opts = NULL;
4703 QemuOpts *sn_opts = NULL;
4704 QemuOptsList *create_opts = NULL;
4705 bool image_opts = false;
4706 uint64_t img_size = UINT64_MAX;
4707 BlockMeasureInfo *info = NULL;
4708 Error *local_err = NULL;
4709 int ret = 1;
4710 int c;
4711
4712 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4713 long_options, NULL)) != -1) {
4714 switch (c) {
4715 case '?':
4716 case 'h':
4717 help();
4718 break;
4719 case 'f':
4720 fmt = optarg;
4721 break;
4722 case 'O':
4723 out_fmt = optarg;
4724 break;
4725 case 'o':
4726 if (!is_valid_option_list(optarg)) {
4727 error_report("Invalid option list: %s", optarg);
4728 goto out;
4729 }
4730 if (!options) {
4731 options = g_strdup(optarg);
4732 } else {
4733 char *old_options = options;
4734 options = g_strdup_printf("%s,%s", options, optarg);
4735 g_free(old_options);
4736 }
4737 break;
4738 case 'l':
4739 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4740 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4741 optarg, false);
4742 if (!sn_opts) {
4743 error_report("Failed in parsing snapshot param '%s'",
4744 optarg);
4745 goto out;
4746 }
4747 } else {
4748 snapshot_name = optarg;
4749 }
4750 break;
4751 case 'U':
4752 force_share = true;
4753 break;
4754 case OPTION_OBJECT:
4755 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4756 optarg, true);
4757 if (!object_opts) {
4758 goto out;
4759 }
4760 break;
4761 case OPTION_IMAGE_OPTS:
4762 image_opts = true;
4763 break;
4764 case OPTION_OUTPUT:
4765 if (!strcmp(optarg, "json")) {
4766 output_format = OFORMAT_JSON;
4767 } else if (!strcmp(optarg, "human")) {
4768 output_format = OFORMAT_HUMAN;
4769 } else {
4770 error_report("--output must be used with human or json "
4771 "as argument.");
4772 goto out;
4773 }
4774 break;
4775 case OPTION_SIZE:
4776 {
4777 int64_t sval;
4778
4779 sval = cvtnum(optarg);
4780 if (sval < 0) {
4781 if (sval == -ERANGE) {
4782 error_report("Image size must be less than 8 EiB!");
4783 } else {
4784 error_report("Invalid image size specified! You may use "
4785 "k, M, G, T, P or E suffixes for ");
4786 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4787 "petabytes and exabytes.");
4788 }
4789 goto out;
4790 }
4791 img_size = (uint64_t)sval;
4792 }
4793 break;
4794 }
4795 }
4796
4797 if (qemu_opts_foreach(&qemu_object_opts,
4798 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004799 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004800 goto out;
4801 }
4802
4803 if (argc - optind > 1) {
4804 error_report("At most one filename argument is allowed.");
4805 goto out;
4806 } else if (argc - optind == 1) {
4807 filename = argv[optind];
4808 }
4809
4810 if (!filename &&
4811 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4812 error_report("--object, --image-opts, -f, and -l "
4813 "require a filename argument.");
4814 goto out;
4815 }
4816 if (filename && img_size != UINT64_MAX) {
4817 error_report("--size N cannot be used together with a filename.");
4818 goto out;
4819 }
4820 if (!filename && img_size == UINT64_MAX) {
4821 error_report("Either --size N or one filename must be specified.");
4822 goto out;
4823 }
4824
4825 if (filename) {
4826 in_blk = img_open(image_opts, filename, fmt, 0,
4827 false, false, force_share);
4828 if (!in_blk) {
4829 goto out;
4830 }
4831
4832 if (sn_opts) {
4833 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4834 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4835 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4836 &local_err);
4837 } else if (snapshot_name != NULL) {
4838 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4839 snapshot_name, &local_err);
4840 }
4841 if (local_err) {
4842 error_reportf_err(local_err, "Failed to load snapshot: ");
4843 goto out;
4844 }
4845 }
4846
4847 drv = bdrv_find_format(out_fmt);
4848 if (!drv) {
4849 error_report("Unknown file format '%s'", out_fmt);
4850 goto out;
4851 }
4852 if (!drv->create_opts) {
4853 error_report("Format driver '%s' does not support image creation",
4854 drv->format_name);
4855 goto out;
4856 }
4857
4858 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4859 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4860 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4861 if (options) {
4862 qemu_opts_do_parse(opts, options, NULL, &local_err);
4863 if (local_err) {
4864 error_report_err(local_err);
4865 error_report("Invalid options for file format '%s'", out_fmt);
4866 goto out;
4867 }
4868 }
4869 if (img_size != UINT64_MAX) {
4870 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4871 }
4872
4873 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4874 if (local_err) {
4875 error_report_err(local_err);
4876 goto out;
4877 }
4878
4879 if (output_format == OFORMAT_HUMAN) {
4880 printf("required size: %" PRIu64 "\n", info->required);
4881 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4882 } else {
4883 dump_json_block_measure_info(info);
4884 }
4885
4886 ret = 0;
4887
4888out:
4889 qapi_free_BlockMeasureInfo(info);
4890 qemu_opts_del(object_opts);
4891 qemu_opts_del(opts);
4892 qemu_opts_del(sn_opts);
4893 qemu_opts_free(create_opts);
4894 g_free(options);
4895 blk_unref(in_blk);
4896 return ret;
4897}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004898
Anthony Liguoric227f092009-10-01 16:12:16 -05004899static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004900#define DEF(option, callback, arg_string) \
4901 { option, callback },
4902#include "qemu-img-cmds.h"
4903#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004904 { NULL, NULL, },
4905};
4906
bellardea2384d2004-08-01 21:59:26 +00004907int main(int argc, char **argv)
4908{
Anthony Liguoric227f092009-10-01 16:12:16 -05004909 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004910 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004911 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004912 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004913 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004914 static const struct option long_options[] = {
4915 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004916 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004917 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004918 {0, 0, 0, 0}
4919 };
bellardea2384d2004-08-01 21:59:26 +00004920
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004921#ifdef CONFIG_POSIX
4922 signal(SIGPIPE, SIG_IGN);
4923#endif
4924
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004925 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004926 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004927 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004928
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004929 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004930 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004931 exit(EXIT_FAILURE);
4932 }
4933
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004934 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004935
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004936 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004937 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004938 if (argc < 2) {
4939 error_exit("Not enough arguments");
4940 }
Stuart Brady153859b2009-06-07 00:42:17 +01004941
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004942 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004943 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004944 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004945
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004946 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004947 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004948 case ':':
4949 missing_argument(argv[optind - 1]);
4950 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004951 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004952 unrecognized_option(argv[optind - 1]);
4953 return 0;
4954 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004955 help();
4956 return 0;
4957 case 'V':
4958 printf(QEMU_IMG_VERSION);
4959 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004960 case 'T':
4961 g_free(trace_file);
4962 trace_file = trace_opt_parse(optarg);
4963 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004964 }
bellardea2384d2004-08-01 21:59:26 +00004965 }
Stuart Brady153859b2009-06-07 00:42:17 +01004966
Denis V. Lunev10985132016-06-17 17:44:13 +03004967 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004968
Denis V. Lunev10985132016-06-17 17:44:13 +03004969 /* reset getopt_long scanning */
4970 argc -= optind;
4971 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004972 return 0;
4973 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004974 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00004975 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03004976
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004977 if (!trace_init_backends()) {
4978 exit(1);
4979 }
4980 trace_init_file(trace_file);
4981 qemu_set_log(LOG_TRACE);
4982
Denis V. Lunev10985132016-06-17 17:44:13 +03004983 /* find the command */
4984 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4985 if (!strcmp(cmdname, cmd->name)) {
4986 return cmd->handler(argc, argv);
4987 }
4988 }
Jeff Cody7db16892014-04-25 17:02:32 -04004989
Stuart Brady153859b2009-06-07 00:42:17 +01004990 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004991 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004992}