blob: c221e3cb24253bd9127b66bb39df7b12b9732cf1 [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"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020040#include "qemu/module.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020041#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000042#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010043#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020044#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010045#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020046#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080047#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010048#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030049#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000050
Thomas Huth7e563bf2018-02-15 12:06:47 +010051#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020052 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040053
Anthony Liguoric227f092009-10-01 16:12:16 -050054typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010055 const char *name;
56 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050057} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010058
Federico Simoncelli8599ea42013-01-28 06:59:47 -050059enum {
60 OPTION_OUTPUT = 256,
61 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000062 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000063 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020064 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020065 OPTION_FLUSH_INTERVAL = 261,
66 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010067 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010068 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020069 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030070 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050071};
72
73typedef enum OutputFormat {
74 OFORMAT_JSON,
75 OFORMAT_HUMAN,
76} OutputFormat;
77
Kevin Wolfe6996142016-03-15 13:03:11 +010078/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040079#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000080
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010081static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000082{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010083 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000084}
85
Fam Zhengac1307a2014-04-22 13:36:11 +080086static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
87{
88 va_list ap;
89
Fam Zhengac1307a2014-04-22 13:36:11 +080090 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +020091 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +080092 va_end(ap);
93
Markus Armbrustere9e1d922019-04-17 21:06:27 +020094 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +080095 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 Reitzf4619af2019-04-13 17:20:37 +0200272 if (filename) {
273 printf("Supported options:\n");
274 } else {
275 printf("Supported %s options:\n", fmt);
276 }
Max Reitz63898712018-10-19 18:49:25 +0200277 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800278 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200279
280 if (!filename) {
281 printf("\n"
282 "The protocol level may support further options.\n"
283 "Specify the target filename to include those options.\n");
284 }
285
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100286 return 0;
287}
288
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000289
Max Reitzefaa7c42016-03-16 19:54:38 +0100290static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100291 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800292 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000293{
294 QDict *options;
295 Error *local_err = NULL;
296 BlockBackend *blk;
297 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800298 if (force_share) {
299 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200300 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800301 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200302 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800303 return NULL;
304 }
Max Reitz4615f872018-05-02 22:20:50 +0200305 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800306 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100307 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000308 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100309 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000310 return NULL;
311 }
Kevin Wolfce099542016-03-15 13:01:04 +0100312 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000313
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000314 return blk;
315}
316
Max Reitzefaa7c42016-03-16 19:54:38 +0100317static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100318 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000319 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800320 bool writethrough, bool quiet,
321 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000322{
323 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200324 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100325
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100326 if (!options) {
327 options = qdict_new();
328 }
bellard75c23802004-08-27 21:28:58 +0000329 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500330 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000331 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100332
Fam Zheng335e9932017-05-03 00:35:39 +0800333 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500334 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800335 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100336 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500337 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100338 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000339 return NULL;
bellard75c23802004-08-27 21:28:58 +0000340 }
Kevin Wolfce099542016-03-15 13:01:04 +0100341 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100342
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200343 return blk;
bellard75c23802004-08-27 21:28:58 +0000344}
345
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000346
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100347static int img_add_key_secrets(void *opaque,
348 const char *name, const char *value,
349 Error **errp)
350{
351 QDict *options = opaque;
352
353 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600354 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100355 }
356
357 return 0;
358}
359
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100360
Max Reitzefaa7c42016-03-16 19:54:38 +0100361static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000362 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100363 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800364 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000365{
366 BlockBackend *blk;
367 if (image_opts) {
368 QemuOpts *opts;
369 if (fmt) {
370 error_report("--image-opts and --format are mutually exclusive");
371 return NULL;
372 }
373 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
374 filename, true);
375 if (!opts) {
376 return NULL;
377 }
Fam Zheng335e9932017-05-03 00:35:39 +0800378 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
379 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000380 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100381 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800382 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000383 }
384 return blk;
385}
386
387
Chunyan Liu83d05212014-06-05 17:20:51 +0800388static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100389 const char *base_filename,
390 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200391{
Markus Armbruster6750e792015-02-12 17:43:08 +0100392 Error *err = NULL;
393
Kevin Wolfefa84d42009-05-18 16:42:12 +0200394 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100395 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100396 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100397 error_report("Backing file not supported for file format '%s'",
398 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100399 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900400 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200401 }
402 }
403 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100404 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100405 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100406 error_report("Backing file format not supported for file "
407 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100408 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900409 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200410 }
411 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900412 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200413}
414
Markus Armbruster606caa02017-02-21 21:14:04 +0100415static int64_t cvtnum(const char *s)
416{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100417 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100418 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100419
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100420 err = qemu_strtosz(s, NULL, &value);
421 if (err < 0) {
422 return err;
423 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100424 if (value > INT64_MAX) {
425 return -ERANGE;
426 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100427 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100428}
429
bellardea2384d2004-08-01 21:59:26 +0000430static int img_create(int argc, char **argv)
431{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200432 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100433 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000434 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000435 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000436 const char *filename;
437 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200438 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200439 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100440 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400441 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000442
bellardea2384d2004-08-01 21:59:26 +0000443 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000444 static const struct option long_options[] = {
445 {"help", no_argument, 0, 'h'},
446 {"object", required_argument, 0, OPTION_OBJECT},
447 {0, 0, 0, 0}
448 };
John Snow6e6e55f2017-07-17 20:34:22 -0400449 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000450 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100451 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000452 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100453 }
bellardea2384d2004-08-01 21:59:26 +0000454 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800455 case ':':
456 missing_argument(argv[optind - 1]);
457 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100458 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800459 unrecognized_option(argv[optind - 1]);
460 break;
bellardea2384d2004-08-01 21:59:26 +0000461 case 'h':
462 help();
463 break;
aliguori9230eaf2009-03-28 17:55:19 +0000464 case 'F':
465 base_fmt = optarg;
466 break;
bellardea2384d2004-08-01 21:59:26 +0000467 case 'b':
468 base_filename = optarg;
469 break;
470 case 'f':
471 fmt = optarg;
472 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200473 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100474 if (!is_valid_option_list(optarg)) {
475 error_report("Invalid option list: %s", optarg);
476 goto fail;
477 }
478 if (!options) {
479 options = g_strdup(optarg);
480 } else {
481 char *old_options = options;
482 options = g_strdup_printf("%s,%s", options, optarg);
483 g_free(old_options);
484 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200485 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100486 case 'q':
487 quiet = true;
488 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400489 case 'u':
490 flags |= BDRV_O_NO_BACKING;
491 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000492 case OPTION_OBJECT: {
493 QemuOpts *opts;
494 opts = qemu_opts_parse_noisily(&qemu_object_opts,
495 optarg, true);
496 if (!opts) {
497 goto fail;
498 }
499 } break;
bellardea2384d2004-08-01 21:59:26 +0000500 }
501 }
aliguori9230eaf2009-03-28 17:55:19 +0000502
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900503 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100504 filename = (optind < argc) ? argv[optind] : NULL;
505 if (options && has_help_option(options)) {
506 g_free(options);
507 return print_block_option_help(filename, fmt);
508 }
509
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100510 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800511 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100512 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100513 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900514
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000515 if (qemu_opts_foreach(&qemu_object_opts,
516 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000517 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000518 goto fail;
519 }
520
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100521 /* Get image size, if specified */
522 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100523 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100524
525 sval = cvtnum(argv[optind++]);
526 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800527 if (sval == -ERANGE) {
528 error_report("Image size must be less than 8 EiB!");
529 } else {
530 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200531 "G, T, P or E suffixes for ");
532 error_report("kilobytes, megabytes, gigabytes, terabytes, "
533 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800534 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100535 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100536 }
537 img_size = (uint64_t)sval;
538 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200539 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800540 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200541 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100542
Luiz Capitulino9b375252012-11-30 10:52:05 -0200543 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400544 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100545 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100546 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100547 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900548 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200549
Kevin Wolf77386bf2014-02-21 16:24:04 +0100550 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000551 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100552
553fail:
554 g_free(options);
555 return 1;
bellardea2384d2004-08-01 21:59:26 +0000556}
557
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100558static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500559{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500561 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100562 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600563
564 visit_type_ImageCheck(v, NULL, &check, &error_abort);
565 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500566 str = qobject_to_json_pretty(obj);
567 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100568 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200569 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600570 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200571 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500572}
573
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100574static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500575{
576 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100577 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500578 } else {
579 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100580 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
581 "Data may be corrupted, or further writes to the image "
582 "may corrupt it.\n",
583 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500584 }
585
586 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100587 qprintf(quiet,
588 "\n%" PRId64 " leaked clusters were found on the image.\n"
589 "This means waste of disk space, but no harm to data.\n",
590 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500591 }
592
593 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100594 qprintf(quiet,
595 "\n%" PRId64
596 " internal errors have occurred during the check.\n",
597 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500598 }
599 }
600
601 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100602 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
603 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
604 check->allocated_clusters, check->total_clusters,
605 check->allocated_clusters * 100.0 / check->total_clusters,
606 check->fragmented_clusters * 100.0 / check->allocated_clusters,
607 check->compressed_clusters * 100.0 /
608 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500609 }
610
611 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100612 qprintf(quiet,
613 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500614 }
615}
616
617static int collect_image_check(BlockDriverState *bs,
618 ImageCheck *check,
619 const char *filename,
620 const char *fmt,
621 int fix)
622{
623 int ret;
624 BdrvCheckResult result;
625
626 ret = bdrv_check(bs, &result, fix);
627 if (ret < 0) {
628 return ret;
629 }
630
631 check->filename = g_strdup(filename);
632 check->format = g_strdup(bdrv_get_format_name(bs));
633 check->check_errors = result.check_errors;
634 check->corruptions = result.corruptions;
635 check->has_corruptions = result.corruptions != 0;
636 check->leaks = result.leaks;
637 check->has_leaks = result.leaks != 0;
638 check->corruptions_fixed = result.corruptions_fixed;
639 check->has_corruptions_fixed = result.corruptions != 0;
640 check->leaks_fixed = result.leaks_fixed;
641 check->has_leaks_fixed = result.leaks != 0;
642 check->image_end_offset = result.image_end_offset;
643 check->has_image_end_offset = result.image_end_offset != 0;
644 check->total_clusters = result.bfi.total_clusters;
645 check->has_total_clusters = result.bfi.total_clusters != 0;
646 check->allocated_clusters = result.bfi.allocated_clusters;
647 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
648 check->fragmented_clusters = result.bfi.fragmented_clusters;
649 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100650 check->compressed_clusters = result.bfi.compressed_clusters;
651 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500652
653 return 0;
654}
655
Kevin Wolfe076f332010-06-29 11:43:13 +0200656/*
657 * Checks an image for consistency. Exit codes:
658 *
Max Reitzd6635c42014-06-02 22:15:21 +0200659 * 0 - Check completed, image is good
660 * 1 - Check not completed because of internal errors
661 * 2 - Check completed, image is corrupted
662 * 3 - Check completed, image has leaked clusters, but is good otherwise
663 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200664 */
aliguori15859692009-04-21 23:11:53 +0000665static int img_check(int argc, char **argv)
666{
667 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500668 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200669 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200670 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000671 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200672 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100673 int flags = BDRV_O_CHECK;
674 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200675 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100676 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000677 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800678 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000679
680 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500681 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200682 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100683
aliguori15859692009-04-21 23:11:53 +0000684 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500685 int option_index = 0;
686 static const struct option long_options[] = {
687 {"help", no_argument, 0, 'h'},
688 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530689 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500690 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000691 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000692 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800693 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500694 {0, 0, 0, 0}
695 };
Fam Zheng335e9932017-05-03 00:35:39 +0800696 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500697 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100698 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000699 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100700 }
aliguori15859692009-04-21 23:11:53 +0000701 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800702 case ':':
703 missing_argument(argv[optind - 1]);
704 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100705 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800706 unrecognized_option(argv[optind - 1]);
707 break;
aliguori15859692009-04-21 23:11:53 +0000708 case 'h':
709 help();
710 break;
711 case 'f':
712 fmt = optarg;
713 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200714 case 'r':
715 flags |= BDRV_O_RDWR;
716
717 if (!strcmp(optarg, "leaks")) {
718 fix = BDRV_FIX_LEAKS;
719 } else if (!strcmp(optarg, "all")) {
720 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
721 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800722 error_exit("Unknown option value for -r "
723 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200724 }
725 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500726 case OPTION_OUTPUT:
727 output = optarg;
728 break;
Max Reitz40055952014-07-22 22:58:42 +0200729 case 'T':
730 cache = optarg;
731 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100732 case 'q':
733 quiet = true;
734 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800735 case 'U':
736 force_share = true;
737 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000738 case OPTION_OBJECT: {
739 QemuOpts *opts;
740 opts = qemu_opts_parse_noisily(&qemu_object_opts,
741 optarg, true);
742 if (!opts) {
743 return 1;
744 }
745 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000746 case OPTION_IMAGE_OPTS:
747 image_opts = true;
748 break;
aliguori15859692009-04-21 23:11:53 +0000749 }
750 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200751 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800752 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100753 }
aliguori15859692009-04-21 23:11:53 +0000754 filename = argv[optind++];
755
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500756 if (output && !strcmp(output, "json")) {
757 output_format = OFORMAT_JSON;
758 } else if (output && !strcmp(output, "human")) {
759 output_format = OFORMAT_HUMAN;
760 } else if (output) {
761 error_report("--output must be used with human or json as argument.");
762 return 1;
763 }
764
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000765 if (qemu_opts_foreach(&qemu_object_opts,
766 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000767 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000768 return 1;
769 }
770
Kevin Wolfce099542016-03-15 13:01:04 +0100771 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200772 if (ret < 0) {
773 error_report("Invalid source cache option: %s", cache);
774 return 1;
775 }
776
Fam Zheng335e9932017-05-03 00:35:39 +0800777 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
778 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200779 if (!blk) {
780 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900781 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200782 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500783
784 check = g_new0(ImageCheck, 1);
785 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200786
787 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200788 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200789 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500790 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200791 }
792
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500793 if (check->corruptions_fixed || check->leaks_fixed) {
794 int corruptions_fixed, leaks_fixed;
795
796 leaks_fixed = check->leaks_fixed;
797 corruptions_fixed = check->corruptions_fixed;
798
799 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100800 qprintf(quiet,
801 "The following inconsistencies were found and repaired:\n\n"
802 " %" PRId64 " leaked clusters\n"
803 " %" PRId64 " corruptions\n\n"
804 "Double checking the fixed image now...\n",
805 check->leaks_fixed,
806 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500807 }
808
809 ret = collect_image_check(bs, check, filename, fmt, 0);
810
811 check->leaks_fixed = leaks_fixed;
812 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200813 }
814
Max Reitz832390a2014-10-23 15:29:12 +0200815 if (!ret) {
816 switch (output_format) {
817 case OFORMAT_HUMAN:
818 dump_human_image_check(check, quiet);
819 break;
820 case OFORMAT_JSON:
821 dump_json_image_check(check, quiet);
822 break;
823 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500824 }
825
826 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200827 if (ret) {
828 error_report("Check failed: %s", strerror(-ret));
829 } else {
830 error_report("Check failed");
831 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500832 ret = 1;
833 goto fail;
834 }
835
836 if (check->corruptions) {
837 ret = 2;
838 } else if (check->leaks) {
839 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200840 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500841 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000842 }
843
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500844fail:
845 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200846 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500847 return ret;
aliguori15859692009-04-21 23:11:53 +0000848}
849
Max Reitzd4a32382014-10-24 15:57:37 +0200850typedef struct CommonBlockJobCBInfo {
851 BlockDriverState *bs;
852 Error **errp;
853} CommonBlockJobCBInfo;
854
855static void common_block_job_cb(void *opaque, int ret)
856{
857 CommonBlockJobCBInfo *cbi = opaque;
858
859 if (ret < 0) {
860 error_setg_errno(cbi->errp, -ret, "Block job failed");
861 }
Max Reitzd4a32382014-10-24 15:57:37 +0200862}
863
864static void run_block_job(BlockJob *job, Error **errp)
865{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200866 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800867 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200868
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200869 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200870 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200871 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200872 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200873 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200874 if (job->job.progress_total) {
875 progress = (float)job->job.progress_current /
876 job->job.progress_total * 100.f;
877 }
878 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200879 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200880
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200881 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200882 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800883 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200884 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800885 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200886 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200887 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200888
sochin.jiang4172a002017-06-15 14:47:33 +0800889 /* publish completion progress only when success */
890 if (!ret) {
891 qemu_progress_print(100.f, 0);
892 }
Max Reitzd4a32382014-10-24 15:57:37 +0200893}
894
bellardea2384d2004-08-01 21:59:26 +0000895static int img_commit(int argc, char **argv)
896{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400897 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200898 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200899 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200900 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100901 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200902 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100903 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200904 Error *local_err = NULL;
905 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000906 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200907 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000908
909 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400910 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200911 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000912 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000913 static const struct option long_options[] = {
914 {"help", no_argument, 0, 'h'},
915 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000916 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000917 {0, 0, 0, 0}
918 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800919 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000920 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100921 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000922 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100923 }
bellardea2384d2004-08-01 21:59:26 +0000924 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800925 case ':':
926 missing_argument(argv[optind - 1]);
927 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100928 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800929 unrecognized_option(argv[optind - 1]);
930 break;
bellardea2384d2004-08-01 21:59:26 +0000931 case 'h':
932 help();
933 break;
934 case 'f':
935 fmt = optarg;
936 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400937 case 't':
938 cache = optarg;
939 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200940 case 'b':
941 base = optarg;
942 /* -b implies -d */
943 drop = true;
944 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200945 case 'd':
946 drop = true;
947 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200948 case 'p':
949 progress = true;
950 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100951 case 'q':
952 quiet = true;
953 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000954 case OPTION_OBJECT: {
955 QemuOpts *opts;
956 opts = qemu_opts_parse_noisily(&qemu_object_opts,
957 optarg, true);
958 if (!opts) {
959 return 1;
960 }
961 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000962 case OPTION_IMAGE_OPTS:
963 image_opts = true;
964 break;
bellardea2384d2004-08-01 21:59:26 +0000965 }
966 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200967
968 /* Progress is not shown in Quiet mode */
969 if (quiet) {
970 progress = false;
971 }
972
Kevin Wolffc11eb22013-08-05 10:53:04 +0200973 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800974 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100975 }
bellardea2384d2004-08-01 21:59:26 +0000976 filename = argv[optind++];
977
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000978 if (qemu_opts_foreach(&qemu_object_opts,
979 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000980 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000981 return 1;
982 }
983
Max Reitz9a86fe42014-10-24 15:57:38 +0200984 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100985 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400986 if (ret < 0) {
987 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100988 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400989 }
990
Fam Zheng335e9932017-05-03 00:35:39 +0800991 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
992 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200993 if (!blk) {
994 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900995 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200996 bs = blk_bs(blk);
997
Max Reitz687fa1d2014-10-24 15:57:39 +0200998 qemu_progress_init(progress, 1.f);
999 qemu_progress_print(0.f, 100);
1000
Max Reitz1b22bff2014-10-24 15:57:40 +02001001 if (base) {
1002 base_bs = bdrv_find_backing_image(bs, base);
1003 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001004 error_setg(&local_err,
1005 "Did not find '%s' in the backing chain of '%s'",
1006 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001007 goto done;
1008 }
1009 } else {
1010 /* This is different from QMP, which by default uses the deepest file in
1011 * the backing chain (i.e., the very base); however, the traditional
1012 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001013 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001014 if (!base_bs) {
1015 error_setg(&local_err, "Image does not have a backing file");
1016 goto done;
1017 }
bellardea2384d2004-08-01 21:59:26 +00001018 }
1019
Max Reitzd4a32382014-10-24 15:57:37 +02001020 cbi = (CommonBlockJobCBInfo){
1021 .errp = &local_err,
1022 .bs = bs,
1023 };
1024
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001025 aio_context = bdrv_get_aio_context(bs);
1026 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001027 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001028 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001029 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001030 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001031 if (local_err) {
1032 goto done;
1033 }
1034
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001035 /* When the block job completes, the BlockBackend reference will point to
1036 * the old backing file. In order to avoid that the top image is already
1037 * deleted, so we can still empty it afterwards, increment the reference
1038 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001039 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001040 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001041 }
1042
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001043 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001044 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001045 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001046 if (local_err) {
1047 goto unref_backing;
1048 }
1049
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001050 if (!drop && bs->drv->bdrv_make_empty) {
1051 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001052 if (ret) {
1053 error_setg_errno(&local_err, -ret, "Could not empty %s",
1054 filename);
1055 goto unref_backing;
1056 }
1057 }
1058
1059unref_backing:
1060 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001061 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001062 }
Max Reitzd4a32382014-10-24 15:57:37 +02001063
1064done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001065 qemu_progress_end();
1066
Markus Armbruster26f54e92014-10-07 13:59:04 +02001067 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001068
1069 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001070 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001071 return 1;
1072 }
Max Reitzd4a32382014-10-24 15:57:37 +02001073
1074 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001075 return 0;
1076}
1077
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001078/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001079 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1080 * of the first sector boundary within buf where the sector contains a
1081 * non-zero byte. This function is robust to a buffer that is not
1082 * sector-aligned.
1083 */
1084static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1085{
1086 int64_t i;
1087 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1088
1089 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1090 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1091 return i;
1092 }
1093 }
1094 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1095 return i;
1096 }
1097 return -1;
1098}
1099
1100/*
thsf58c7b32008-06-05 21:53:49 +00001101 * Returns true iff the first sector pointed to by 'buf' contains at least
1102 * a non-NUL byte.
1103 *
1104 * 'pnum' is set to the number of sectors (including and immediately following
1105 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001106 * The function will try to align the end offset to alignment boundaries so
1107 * that the request will at least end aligned and consequtive requests will
1108 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001109 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001110static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1111 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001112{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001113 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001114 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001115
1116 if (n <= 0) {
1117 *pnum = 0;
1118 return 0;
1119 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001120 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001121 for(i = 1; i < n; i++) {
1122 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001123 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001124 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001125 }
bellardea2384d2004-08-01 21:59:26 +00001126 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001127
1128 tail = (sector_num + i) & (alignment - 1);
1129 if (tail) {
1130 if (is_zero && i <= tail) {
1131 /* treat unallocated areas which only consist
1132 * of a small tail as allocated. */
1133 is_zero = false;
1134 }
1135 if (!is_zero) {
1136 /* align up end offset of allocated areas. */
1137 i += alignment - tail;
1138 i = MIN(i, n);
1139 } else {
1140 /* align down end offset of zero areas. */
1141 i -= tail;
1142 }
1143 }
bellardea2384d2004-08-01 21:59:26 +00001144 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001145 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001146}
1147
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001148/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001149 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1150 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1151 * breaking up write requests for only small sparse areas.
1152 */
1153static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001154 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001155{
1156 int ret;
1157 int num_checked, num_used;
1158
1159 if (n < min) {
1160 min = n;
1161 }
1162
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001163 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001164 if (!ret) {
1165 return ret;
1166 }
1167
1168 num_used = *pnum;
1169 buf += BDRV_SECTOR_SIZE * *pnum;
1170 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001171 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001172 num_checked = num_used;
1173
1174 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001175 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001176
1177 buf += BDRV_SECTOR_SIZE * *pnum;
1178 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001179 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001180 num_checked += *pnum;
1181 if (ret) {
1182 num_used = num_checked;
1183 } else if (*pnum >= min) {
1184 break;
1185 }
1186 }
1187
1188 *pnum = num_used;
1189 return 1;
1190}
1191
1192/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001193 * Compares two buffers sector by sector. Returns 0 if the first
1194 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001195 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001196 * pnum is set to the sector-aligned size of the buffer prefix that
1197 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001198 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001199static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1200 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001201{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001202 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001203 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001204
Eric Blakedc61cd32017-10-11 22:47:14 -05001205 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001206
Eric Blakedc61cd32017-10-11 22:47:14 -05001207 res = !!memcmp(buf1, buf2, i);
1208 while (i < bytes) {
1209 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001210
Eric Blakedc61cd32017-10-11 22:47:14 -05001211 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001212 break;
1213 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001214 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001215 }
1216
1217 *pnum = i;
1218 return res;
1219}
1220
Stefano Garzarella97ede572019-05-08 12:43:24 +02001221#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001222
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001223/*
1224 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1225 *
Eric Blake0608e402017-10-11 22:47:12 -05001226 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1227 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1228 * failure), and 4 on error (the exit status for read errors), after emitting
1229 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001230 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001231 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001232 * @param offset: Starting offset to check
1233 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001234 * @param filename: Name of disk file we are checking (logging purpose)
1235 * @param buffer: Allocated buffer for storing read data
1236 * @param quiet: Flag for quiet mode
1237 */
Eric Blakec41508e2017-10-11 22:47:13 -05001238static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1239 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001240 uint8_t *buffer, bool quiet)
1241{
Eric Blakedebb38a2017-10-11 22:47:11 -05001242 int ret = 0;
1243 int64_t idx;
1244
Eric Blakec41508e2017-10-11 22:47:13 -05001245 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001246 if (ret < 0) {
1247 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001248 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001249 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001250 }
Eric Blakec41508e2017-10-11 22:47:13 -05001251 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001252 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001253 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001254 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001255 return 1;
1256 }
1257
1258 return 0;
1259}
1260
1261/*
1262 * Compares two images. Exit codes:
1263 *
1264 * 0 - Images are identical
1265 * 1 - Images differ
1266 * >1 - Error occurred
1267 */
1268static int img_compare(int argc, char **argv)
1269{
Max Reitz40055952014-07-22 22:58:42 +02001270 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001271 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001272 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001273 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001274 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001275 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001276 int allocated1, allocated2;
1277 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1278 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001279 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001280 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001281 int64_t total_size;
1282 int64_t offset = 0;
1283 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001284 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001285 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001286 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001287 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001288
Max Reitz40055952014-07-22 22:58:42 +02001289 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001290 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001291 static const struct option long_options[] = {
1292 {"help", no_argument, 0, 'h'},
1293 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001294 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001295 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001296 {0, 0, 0, 0}
1297 };
Fam Zheng335e9932017-05-03 00:35:39 +08001298 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001299 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001300 if (c == -1) {
1301 break;
1302 }
1303 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001304 case ':':
1305 missing_argument(argv[optind - 1]);
1306 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001307 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001308 unrecognized_option(argv[optind - 1]);
1309 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001310 case 'h':
1311 help();
1312 break;
1313 case 'f':
1314 fmt1 = optarg;
1315 break;
1316 case 'F':
1317 fmt2 = optarg;
1318 break;
Max Reitz40055952014-07-22 22:58:42 +02001319 case 'T':
1320 cache = optarg;
1321 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001322 case 'p':
1323 progress = true;
1324 break;
1325 case 'q':
1326 quiet = true;
1327 break;
1328 case 's':
1329 strict = true;
1330 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001331 case 'U':
1332 force_share = true;
1333 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001334 case OPTION_OBJECT: {
1335 QemuOpts *opts;
1336 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1337 optarg, true);
1338 if (!opts) {
1339 ret = 2;
1340 goto out4;
1341 }
1342 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001343 case OPTION_IMAGE_OPTS:
1344 image_opts = true;
1345 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001346 }
1347 }
1348
1349 /* Progress is not shown in Quiet mode */
1350 if (quiet) {
1351 progress = false;
1352 }
1353
1354
Kevin Wolffc11eb22013-08-05 10:53:04 +02001355 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001356 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001357 }
1358 filename1 = argv[optind++];
1359 filename2 = argv[optind++];
1360
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001361 if (qemu_opts_foreach(&qemu_object_opts,
1362 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00001363 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001364 ret = 2;
1365 goto out4;
1366 }
1367
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001368 /* Initialize before goto out */
1369 qemu_progress_init(progress, 2.0);
1370
Kevin Wolfce099542016-03-15 13:01:04 +01001371 flags = 0;
1372 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001373 if (ret < 0) {
1374 error_report("Invalid source cache option: %s", cache);
1375 ret = 2;
1376 goto out3;
1377 }
1378
Fam Zheng335e9932017-05-03 00:35:39 +08001379 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1380 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001381 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001382 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001383 goto out3;
1384 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001385
Fam Zheng335e9932017-05-03 00:35:39 +08001386 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1387 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001388 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001389 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001390 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001391 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001392 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001393 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001394
Max Reitzf1d3cd72015-02-05 13:58:18 -05001395 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1396 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001397 total_size1 = blk_getlength(blk1);
1398 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001399 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001400 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001401 ret = 4;
1402 goto out;
1403 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001404 total_size2 = blk_getlength(blk2);
1405 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001406 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001407 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001408 ret = 4;
1409 goto out;
1410 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001411 total_size = MIN(total_size1, total_size2);
1412 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001413
1414 qemu_progress_print(0, 100);
1415
Eric Blake033d9fc2017-10-11 22:47:16 -05001416 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001417 ret = 1;
1418 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1419 goto out;
1420 }
1421
Eric Blake033d9fc2017-10-11 22:47:16 -05001422 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001423 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001424
Eric Blake033d9fc2017-10-11 22:47:16 -05001425 status1 = bdrv_block_status_above(bs1, NULL, offset,
1426 total_size1 - offset, &pnum1, NULL,
1427 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001428 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001429 ret = 3;
1430 error_report("Sector allocation test failed for %s", filename1);
1431 goto out;
1432 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001433 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001434
Eric Blake033d9fc2017-10-11 22:47:16 -05001435 status2 = bdrv_block_status_above(bs2, NULL, offset,
1436 total_size2 - offset, &pnum2, NULL,
1437 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001438 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001439 ret = 3;
1440 error_report("Sector allocation test failed for %s", filename2);
1441 goto out;
1442 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001443 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001444
1445 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001446 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001447
Fam Zheng25ad8e62016-01-13 16:37:41 +08001448 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001449 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001450 ret = 1;
1451 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001452 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001453 goto out;
1454 }
1455 }
1456 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001457 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001458 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001459 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001460 int64_t pnum;
1461
Eric Blake033d9fc2017-10-11 22:47:16 -05001462 chunk = MIN(chunk, IO_BUF_SIZE);
1463 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001464 if (ret < 0) {
1465 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001466 " of %s: %s",
1467 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001468 ret = 4;
1469 goto out;
1470 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001471 ret = blk_pread(blk2, offset, buf2, chunk);
1472 if (ret < 0) {
1473 error_report("Error while reading offset %" PRId64
1474 " of %s: %s",
1475 offset, filename2, strerror(-ret));
1476 ret = 4;
1477 goto out;
1478 }
1479 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1480 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001481 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001482 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001483 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001484 goto out;
1485 }
1486 }
1487 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001488 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001489 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001490 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 filename1, buf1, quiet);
1492 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001493 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001494 filename2, buf1, quiet);
1495 }
1496 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001497 goto out;
1498 }
1499 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001500 offset += chunk;
1501 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001502 }
1503
Eric Blake033d9fc2017-10-11 22:47:16 -05001504 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001505 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001506 const char *filename_over;
1507
1508 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001509 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001510 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001511 filename_over = filename1;
1512 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001513 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001514 filename_over = filename2;
1515 }
1516
Eric Blake033d9fc2017-10-11 22:47:16 -05001517 while (offset < progress_base) {
1518 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1519 progress_base - offset, &chunk,
1520 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001521 if (ret < 0) {
1522 ret = 3;
1523 error_report("Sector allocation test failed for %s",
1524 filename_over);
1525 goto out;
1526
1527 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001528 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001529 chunk = MIN(chunk, IO_BUF_SIZE);
1530 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001531 filename_over, buf1, quiet);
1532 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001533 goto out;
1534 }
1535 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001536 offset += chunk;
1537 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001538 }
1539 }
1540
1541 qprintf(quiet, "Images are identical.\n");
1542 ret = 0;
1543
1544out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001545 qemu_vfree(buf1);
1546 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001547 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001548out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001549 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001550out3:
1551 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001552out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001553 return ret;
1554}
1555
Kevin Wolf690c7302015-03-19 13:33:32 +01001556enum ImgConvertBlockStatus {
1557 BLK_DATA,
1558 BLK_ZERO,
1559 BLK_BACKING_FILE,
1560};
1561
Peter Lieven2d9187b2017-02-28 13:40:07 +01001562#define MAX_COROUTINES 16
1563
Kevin Wolf690c7302015-03-19 13:33:32 +01001564typedef struct ImgConvertState {
1565 BlockBackend **src;
1566 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001567 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001568 int64_t total_sectors;
1569 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001570 int64_t allocated_done;
1571 int64_t sector_num;
1572 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001573 enum ImgConvertBlockStatus status;
1574 int64_t sector_next_status;
1575 BlockBackend *target;
1576 bool has_zero_init;
1577 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001578 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001579 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001580 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001581 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001582 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001583 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001584 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001585 size_t cluster_sectors;
1586 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001587 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001588 int running_coroutines;
1589 Coroutine *co[MAX_COROUTINES];
1590 int64_t wait_sector_num[MAX_COROUTINES];
1591 CoMutex lock;
1592 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001593} ImgConvertState;
1594
Peter Lieven2d9187b2017-02-28 13:40:07 +01001595static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1596 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001597{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001598 *src_cur = 0;
1599 *src_cur_offset = 0;
1600 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1601 *src_cur_offset += s->src_sectors[*src_cur];
1602 (*src_cur)++;
1603 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001604 }
1605}
1606
1607static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1608{
Eric Blake31826642017-10-11 22:47:08 -05001609 int64_t src_cur_offset;
1610 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001611 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001612
Peter Lieven2d9187b2017-02-28 13:40:07 +01001613 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001614
1615 assert(s->total_sectors > sector_num);
1616 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1617
Max Reitz351c8ef2018-05-01 18:57:49 +02001618 if (s->target_backing_sectors >= 0) {
1619 if (sector_num >= s->target_backing_sectors) {
1620 post_backing_zero = s->unallocated_blocks_are_zero;
1621 } else if (sector_num + n > s->target_backing_sectors) {
1622 /* Split requests around target_backing_sectors (because
1623 * starting from there, zeros are handled differently) */
1624 n = s->target_backing_sectors - sector_num;
1625 }
1626 }
1627
Kevin Wolf690c7302015-03-19 13:33:32 +01001628 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001629 int64_t count = n * BDRV_SECTOR_SIZE;
1630
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001631 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001632
1633 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1634 (sector_num - src_cur_offset) *
1635 BDRV_SECTOR_SIZE,
1636 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001637 } else {
Eric Blake31826642017-10-11 22:47:08 -05001638 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1639 (sector_num - src_cur_offset) *
1640 BDRV_SECTOR_SIZE,
1641 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001642 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001643 if (ret < 0) {
Eric Blake2058c2a2019-03-23 16:26:38 -05001644 error_report("error while reading block status of sector %" PRId64
1645 ": %s", sector_num, strerror(-ret));
Kevin Wolf690c7302015-03-19 13:33:32 +01001646 return ret;
1647 }
Eric Blake31826642017-10-11 22:47:08 -05001648 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001649
1650 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001651 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001652 } else if (ret & BDRV_BLOCK_DATA) {
1653 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001654 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001655 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001656 }
1657
1658 s->sector_next_status = sector_num + n;
1659 }
1660
1661 n = MIN(n, s->sector_next_status - sector_num);
1662 if (s->status == BLK_DATA) {
1663 n = MIN(n, s->buf_sectors);
1664 }
1665
1666 /* We need to write complete clusters for compressed images, so if an
1667 * unallocated area is shorter than that, we must consider the whole
1668 * cluster allocated. */
1669 if (s->compressed) {
1670 if (n < s->cluster_sectors) {
1671 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1672 s->status = BLK_DATA;
1673 } else {
1674 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1675 }
1676 }
1677
1678 return n;
1679}
1680
Peter Lieven2d9187b2017-02-28 13:40:07 +01001681static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1682 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001683{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001684 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001685
Kevin Wolf690c7302015-03-19 13:33:32 +01001686 assert(nb_sectors <= s->buf_sectors);
1687 while (nb_sectors > 0) {
1688 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001689 int src_cur;
1690 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001691
1692 /* In the case of compression with multiple source files, we can get a
1693 * nb_sectors that spreads into the next part. So we must be able to
1694 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001695 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1696 blk = s->src[src_cur];
1697 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001698
Peter Lieven2d9187b2017-02-28 13:40:07 +01001699 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
Peter Lieven2d9187b2017-02-28 13:40:07 +01001700
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001701 ret = blk_co_pread(
Peter Lieven2d9187b2017-02-28 13:40:07 +01001702 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001703 n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001704 if (ret < 0) {
1705 return ret;
1706 }
1707
1708 sector_num += n;
1709 nb_sectors -= n;
1710 buf += n * BDRV_SECTOR_SIZE;
1711 }
1712
1713 return 0;
1714}
1715
Peter Lieven2d9187b2017-02-28 13:40:07 +01001716
1717static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1718 int nb_sectors, uint8_t *buf,
1719 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001720{
1721 int ret;
1722
1723 while (nb_sectors > 0) {
1724 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001725 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1726
Peter Lieven2d9187b2017-02-28 13:40:07 +01001727 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001728 case BLK_BACKING_FILE:
1729 /* If we have a backing file, leave clusters unallocated that are
1730 * unallocated in the source image, so that the backing file is
1731 * visible at the respective offset. */
1732 assert(s->target_has_backing);
1733 break;
1734
1735 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001736 /* If we're told to keep the target fully allocated (-S 0) or there
1737 * is real non-zero data, we must write it. Otherwise we can treat
1738 * it as zero sectors.
1739 * Compressed clusters need to be written as a whole, so in that
1740 * case we can only save the write if the buffer is completely
1741 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001742 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001743 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001744 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1745 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001746 (s->compressed &&
1747 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001748 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001749 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1750 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001751 if (ret < 0) {
1752 return ret;
1753 }
1754 break;
1755 }
1756 /* fall-through */
1757
1758 case BLK_ZERO:
1759 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001760 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001761 break;
1762 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001763 ret = blk_co_pwrite_zeroes(s->target,
1764 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001765 n << BDRV_SECTOR_BITS,
1766 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001767 if (ret < 0) {
1768 return ret;
1769 }
1770 break;
1771 }
1772
1773 sector_num += n;
1774 nb_sectors -= n;
1775 buf += n * BDRV_SECTOR_SIZE;
1776 }
1777
1778 return 0;
1779}
1780
Fam Zhengee5306d2018-06-01 17:26:48 +08001781static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1782 int nb_sectors)
1783{
1784 int n, ret;
1785
1786 while (nb_sectors > 0) {
1787 BlockBackend *blk;
1788 int src_cur;
1789 int64_t bs_sectors, src_cur_offset;
1790 int64_t offset;
1791
1792 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1793 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1794 blk = s->src[src_cur];
1795 bs_sectors = s->src_sectors[src_cur];
1796
1797 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1798
1799 ret = blk_co_copy_range(blk, offset, s->target,
1800 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001801 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001802 if (ret < 0) {
1803 return ret;
1804 }
1805
1806 sector_num += n;
1807 nb_sectors -= n;
1808 }
1809 return 0;
1810}
1811
Peter Lieven2d9187b2017-02-28 13:40:07 +01001812static void coroutine_fn convert_co_do_copy(void *opaque)
1813{
1814 ImgConvertState *s = opaque;
1815 uint8_t *buf = NULL;
1816 int ret, i;
1817 int index = -1;
1818
1819 for (i = 0; i < s->num_coroutines; i++) {
1820 if (s->co[i] == qemu_coroutine_self()) {
1821 index = i;
1822 break;
1823 }
1824 }
1825 assert(index >= 0);
1826
1827 s->running_coroutines++;
1828 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1829
1830 while (1) {
1831 int n;
1832 int64_t sector_num;
1833 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001834 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001835
1836 qemu_co_mutex_lock(&s->lock);
1837 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1838 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001839 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001840 }
1841 n = convert_iteration_sectors(s, s->sector_num);
1842 if (n < 0) {
1843 qemu_co_mutex_unlock(&s->lock);
1844 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001845 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001846 }
1847 /* save current sector and allocation status to local variables */
1848 sector_num = s->sector_num;
1849 status = s->status;
1850 if (!s->min_sparse && s->status == BLK_ZERO) {
1851 n = MIN(n, s->buf_sectors);
1852 }
1853 /* increment global sector counter so that other coroutines can
1854 * already continue reading beyond this request */
1855 s->sector_num += n;
1856 qemu_co_mutex_unlock(&s->lock);
1857
1858 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1859 s->allocated_done += n;
1860 qemu_progress_print(100.0 * s->allocated_done /
1861 s->allocated_sectors, 0);
1862 }
1863
Fam Zhengee5306d2018-06-01 17:26:48 +08001864retry:
1865 copy_range = s->copy_range && s->status == BLK_DATA;
1866 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001867 ret = convert_co_read(s, sector_num, n, buf);
1868 if (ret < 0) {
1869 error_report("error while reading sector %" PRId64
1870 ": %s", sector_num, strerror(-ret));
1871 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001872 }
1873 } else if (!s->min_sparse && status == BLK_ZERO) {
1874 status = BLK_DATA;
1875 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1876 }
1877
1878 if (s->wr_in_order) {
1879 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001880 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001881 s->wait_sector_num[index] = sector_num;
1882 qemu_coroutine_yield();
1883 }
1884 s->wait_sector_num[index] = -1;
1885 }
1886
Anton Nefedovb91127e2017-04-26 11:33:15 +03001887 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001888 if (copy_range) {
1889 ret = convert_co_copy_range(s, sector_num, n);
1890 if (ret) {
1891 s->copy_range = false;
1892 goto retry;
1893 }
1894 } else {
1895 ret = convert_co_write(s, sector_num, n, buf, status);
1896 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001897 if (ret < 0) {
1898 error_report("error while writing sector %" PRId64
1899 ": %s", sector_num, strerror(-ret));
1900 s->ret = ret;
1901 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001902 }
1903
1904 if (s->wr_in_order) {
1905 /* reenter the coroutine that might have waited
1906 * for this write to complete */
1907 s->wr_offs = sector_num + n;
1908 for (i = 0; i < s->num_coroutines; i++) {
1909 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1910 /*
1911 * A -> B -> A cannot occur because A has
1912 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1913 * B will never enter A during this time window.
1914 */
1915 qemu_coroutine_enter(s->co[i]);
1916 break;
1917 }
1918 }
1919 }
1920 }
1921
Peter Lieven2d9187b2017-02-28 13:40:07 +01001922 qemu_vfree(buf);
1923 s->co[index] = NULL;
1924 s->running_coroutines--;
1925 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1926 /* the convert job finished successfully */
1927 s->ret = 0;
1928 }
1929}
1930
Kevin Wolf690c7302015-03-19 13:33:32 +01001931static int convert_do_copy(ImgConvertState *s)
1932{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001933 int ret, i, n;
1934 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001935
1936 /* Check whether we have zero initialisation or can get it efficiently */
1937 s->has_zero_init = s->min_sparse && !s->target_has_backing
1938 ? bdrv_has_zero_init(blk_bs(s->target))
1939 : false;
1940
1941 if (!s->has_zero_init && !s->target_has_backing &&
1942 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1943 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001944 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001945 if (ret == 0) {
1946 s->has_zero_init = true;
1947 }
1948 }
1949
1950 /* Allocate buffer for copied data. For compressed images, only one cluster
1951 * can be copied at a time. */
1952 if (s->compressed) {
1953 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1954 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001955 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001956 }
1957 s->buf_sectors = s->cluster_sectors;
1958 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001959
Kevin Wolf690c7302015-03-19 13:33:32 +01001960 while (sector_num < s->total_sectors) {
1961 n = convert_iteration_sectors(s, sector_num);
1962 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001963 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001964 }
Max Reitzaad15de2016-03-24 23:33:57 +01001965 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1966 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001967 s->allocated_sectors += n;
1968 }
1969 sector_num += n;
1970 }
1971
1972 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001973 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001974 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001975
Peter Lieven2d9187b2017-02-28 13:40:07 +01001976 qemu_co_mutex_init(&s->lock);
1977 for (i = 0; i < s->num_coroutines; i++) {
1978 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1979 s->wait_sector_num[i] = -1;
1980 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001981 }
1982
Anton Nefedovb91127e2017-04-26 11:33:15 +03001983 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001984 main_loop_wait(false);
1985 }
1986
1987 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001988 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001989 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001990 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001991 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001992 }
1993 }
1994
Peter Lieven2d9187b2017-02-28 13:40:07 +01001995 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001996}
1997
Peter Lieven6360ab22018-07-13 09:15:39 +02001998#define MAX_BUF_SECTORS 32768
1999
bellardea2384d2004-08-01 21:59:26 +00002000static int img_convert(int argc, char **argv)
2001{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002002 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002003 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002004 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2005 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002006 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002007 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002008 BlockDriverState *out_bs;
2009 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002010 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002011 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002012 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002013 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002014 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002015 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002016 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002017 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002018 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002019
Peter Lieven9fd77f92017-04-21 11:11:55 +02002020 ImgConvertState s = (ImgConvertState) {
2021 /* Need at least 4k of zeros for sparse detection */
2022 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002023 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002024 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2025 .wr_in_order = true,
2026 .num_coroutines = 8,
2027 };
2028
bellardea2384d2004-08-01 21:59:26 +00002029 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002030 static const struct option long_options[] = {
2031 {"help", no_argument, 0, 'h'},
2032 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002033 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002034 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002035 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002036 {0, 0, 0, 0}
2037 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002038 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002039 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002040 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002041 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002042 }
bellardea2384d2004-08-01 21:59:26 +00002043 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002044 case ':':
2045 missing_argument(argv[optind - 1]);
2046 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002047 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002048 unrecognized_option(argv[optind - 1]);
2049 break;
bellardea2384d2004-08-01 21:59:26 +00002050 case 'h':
2051 help();
2052 break;
2053 case 'f':
2054 fmt = optarg;
2055 break;
2056 case 'O':
2057 out_fmt = optarg;
2058 break;
thsf58c7b32008-06-05 21:53:49 +00002059 case 'B':
2060 out_baseimg = optarg;
2061 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002062 case 'C':
2063 s.copy_range = true;
2064 break;
bellardea2384d2004-08-01 21:59:26 +00002065 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002066 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002067 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002068 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002069 if (!is_valid_option_list(optarg)) {
2070 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002071 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002072 }
2073 if (!options) {
2074 options = g_strdup(optarg);
2075 } else {
2076 char *old_options = options;
2077 options = g_strdup_printf("%s,%s", options, optarg);
2078 g_free(old_options);
2079 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002080 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002081 case 'l':
2082 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002083 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2084 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002085 if (!sn_opts) {
2086 error_report("Failed in parsing snapshot param '%s'",
2087 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002088 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002089 }
2090 } else {
2091 snapshot_name = optarg;
2092 }
2093 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002094 case 'S':
2095 {
2096 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002097
2098 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002099 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2100 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2101 error_report("Invalid buffer size for sparse output specified. "
2102 "Valid sizes are multiples of %llu up to %llu. Select "
2103 "0 to disable sparse detection (fully allocates output).",
2104 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002105 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002106 }
2107
Peter Lieven9fd77f92017-04-21 11:11:55 +02002108 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002109 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002110 break;
2111 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002112 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002113 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002114 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002115 case 't':
2116 cache = optarg;
2117 break;
Max Reitz40055952014-07-22 22:58:42 +02002118 case 'T':
2119 src_cache = optarg;
2120 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002121 case 'q':
2122 quiet = true;
2123 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002124 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002125 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002126 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002127 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002128 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2129 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002130 error_report("Invalid number of coroutines. Allowed number of"
2131 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002132 goto fail_getopt;
2133 }
2134 break;
2135 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002136 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002137 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002138 case 'U':
2139 force_share = true;
2140 break;
Max Reitz3258b912017-04-26 15:46:47 +02002141 case OPTION_OBJECT: {
2142 QemuOpts *object_opts;
2143 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2144 optarg, true);
2145 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002146 goto fail_getopt;
2147 }
2148 break;
Max Reitz3258b912017-04-26 15:46:47 +02002149 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002150 case OPTION_IMAGE_OPTS:
2151 image_opts = true;
2152 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002153 case OPTION_TARGET_IMAGE_OPTS:
2154 tgt_image_opts = true;
2155 break;
bellardea2384d2004-08-01 21:59:26 +00002156 }
2157 }
ths3b46e622007-09-17 08:09:54 +00002158
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002159 if (!out_fmt && !tgt_image_opts) {
2160 out_fmt = "raw";
2161 }
2162
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002163 if (qemu_opts_foreach(&qemu_object_opts,
2164 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002165 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002166 goto fail_getopt;
2167 }
2168
Fam Zhenge11ce122018-07-27 11:34:01 +08002169 if (s.compressed && s.copy_range) {
2170 error_report("Cannot enable copy offloading when -c is used");
2171 goto fail_getopt;
2172 }
2173
2174 if (explict_min_sparse && s.copy_range) {
2175 error_report("Cannot enable copy offloading when -S is used");
2176 goto fail_getopt;
2177 }
2178
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002179 if (tgt_image_opts && !skip_create) {
2180 error_report("--target-image-opts requires use of -n flag");
2181 goto fail_getopt;
2182 }
2183
Peter Lieven9fd77f92017-04-21 11:11:55 +02002184 s.src_num = argc - optind - 1;
2185 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2186
2187 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002188 if (out_fmt) {
2189 ret = print_block_option_help(out_filename, out_fmt);
2190 goto fail_getopt;
2191 } else {
2192 error_report("Option help requires a format be specified");
2193 goto fail_getopt;
2194 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002195 }
2196
2197 if (s.src_num < 1) {
2198 error_report("Must specify image file name");
2199 goto fail_getopt;
2200 }
2201
2202
Peter Lieven9fd77f92017-04-21 11:11:55 +02002203 /* ret is still -EINVAL until here */
2204 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2205 if (ret < 0) {
2206 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002207 goto fail_getopt;
2208 }
2209
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002210 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002211 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002212 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002213 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002214 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002215 qemu_progress_print(0, 100);
2216
Peter Lieven9fd77f92017-04-21 11:11:55 +02002217 s.src = g_new0(BlockBackend *, s.src_num);
2218 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002219
Peter Lieven9fd77f92017-04-21 11:11:55 +02002220 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2221 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002222 fmt, src_flags, src_writethrough, quiet,
2223 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002224 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002225 ret = -1;
2226 goto out;
2227 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002228 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2229 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002230 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002231 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002232 ret = -1;
2233 goto out;
2234 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002235 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002236 }
bellardea2384d2004-08-01 21:59:26 +00002237
Wenchao Xiaef806542013-12-04 17:10:57 +08002238 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002239 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002240 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2241 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2242 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002243 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002244 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002245 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002246 ret = -1;
2247 goto out;
2248 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002249
Peter Lieven9fd77f92017-04-21 11:11:55 +02002250 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2251 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002252 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002253 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002254 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002255 ret = -1;
2256 goto out;
edison51ef6722010-09-21 19:58:41 -07002257 }
2258
Max Reitz2e024cd2015-02-11 09:58:46 -05002259 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002260 /* Find driver and parse its options */
2261 drv = bdrv_find_format(out_fmt);
2262 if (!drv) {
2263 error_report("Unknown file format '%s'", out_fmt);
2264 ret = -1;
2265 goto out;
2266 }
2267
2268 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2269 if (!proto_drv) {
2270 error_report_err(local_err);
2271 ret = -1;
2272 goto out;
2273 }
2274
Max Reitz2e024cd2015-02-11 09:58:46 -05002275 if (!drv->create_opts) {
2276 error_report("Format driver '%s' does not support image creation",
2277 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 if (!proto_drv->create_opts) {
2283 error_report("Protocol driver '%s' does not support image creation",
2284 proto_drv->format_name);
2285 ret = -1;
2286 goto out;
2287 }
Max Reitzf75613c2014-12-02 18:32:46 +01002288
Max Reitz2e024cd2015-02-11 09:58:46 -05002289 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2290 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002291
Max Reitz2e024cd2015-02-11 09:58:46 -05002292 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002293 if (options) {
2294 qemu_opts_do_parse(opts, options, NULL, &local_err);
2295 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002296 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002297 ret = -1;
2298 goto out;
2299 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002300 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002301
Peter Lieven9fd77f92017-04-21 11:11:55 +02002302 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002303 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002304 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2305 if (ret < 0) {
2306 goto out;
2307 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002308 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002309
Kevin Wolfa18953f2010-10-14 15:46:04 +02002310 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002311 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002312 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002313 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002314 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002315 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002316
Max Reitz48758a82017-04-26 15:46:48 +02002317 if (s.src_num > 1 && out_baseimg) {
2318 error_report("Having a backing file for the target makes no sense when "
2319 "concatenating multiple input images");
2320 ret = -1;
2321 goto out;
2322 }
2323
Kevin Wolfefa84d42009-05-18 16:42:12 +02002324 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002325 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002326 bool encryption =
2327 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002328 const char *encryptfmt =
2329 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002330 const char *preallocation =
2331 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002332
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002333 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002334 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002335 ret = -1;
2336 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002337 }
2338
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002339 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002340 error_report("Compression and encryption not supported at "
2341 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002342 ret = -1;
2343 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002344 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002345
Chunyan Liu83d05212014-06-05 17:20:51 +08002346 if (preallocation
2347 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002348 {
2349 error_report("Compression and preallocation not supported at "
2350 "the same time");
2351 ret = -1;
2352 goto out;
2353 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002354 }
2355
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002356 /*
2357 * The later open call will need any decryption secrets, and
2358 * bdrv_create() will purge "opts", so extract them now before
2359 * they are lost.
2360 */
2361 if (!skip_create) {
2362 open_opts = qdict_new();
2363 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2364 }
2365
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002366 if (!skip_create) {
2367 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002368 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002369 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002370 error_reportf_err(local_err, "%s: error while converting %s: ",
2371 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002372 goto out;
bellardea2384d2004-08-01 21:59:26 +00002373 }
2374 }
ths3b46e622007-09-17 08:09:54 +00002375
Peter Lieven9fd77f92017-04-21 11:11:55 +02002376 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002377 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002378 if (ret < 0) {
2379 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002380 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002381 }
2382
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002383 if (skip_create) {
2384 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2385 flags, writethrough, quiet, false);
2386 } else {
2387 /* TODO ultimately we should allow --target-image-opts
2388 * to be used even when -n is not given.
2389 * That has to wait for bdrv_create to be improved
2390 * to allow filenames in option syntax
2391 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002392 s.target = img_open_file(out_filename, open_opts, out_fmt,
2393 flags, writethrough, quiet, false);
2394 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002395 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002396 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002397 ret = -1;
2398 goto out;
2399 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002400 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002401
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002402 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2403 error_report("Compression not supported for this file format");
2404 ret = -1;
2405 goto out;
2406 }
2407
Eric Blake5def6b82016-06-23 16:37:19 -06002408 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002409 * or discard_alignment of the out_bs is greater. Limit to
2410 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2411 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002412 MAX(s.buf_sectors,
2413 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2414 out_bs->bl.pdiscard_alignment >>
2415 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002416
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002417 /* try to align the write requests to the destination to avoid unnecessary
2418 * RMW cycles. */
2419 s.alignment = MAX(pow2floor(s.min_sparse),
2420 DIV_ROUND_UP(out_bs->bl.request_alignment,
2421 BDRV_SECTOR_SIZE));
2422 assert(is_power_of_2(s.alignment));
2423
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002424 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002425 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002426 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002427 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002428 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002429 ret = -1;
2430 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002431 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002432 error_report("output file is smaller than input file");
2433 ret = -1;
2434 goto out;
2435 }
2436 }
2437
Max Reitz351c8ef2018-05-01 18:57:49 +02002438 if (s.target_has_backing) {
2439 /* Errors are treated as "backing length unknown" (which means
2440 * s.target_backing_sectors has to be negative, which it will
2441 * be automatically). The backing file length is used only
2442 * for optimizations, so such a case is not fatal. */
2443 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2444 } else {
2445 s.target_backing_sectors = -1;
2446 }
2447
Peter Lieven24f833c2013-11-27 11:07:07 +01002448 ret = bdrv_get_info(out_bs, &bdi);
2449 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002450 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002451 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002452 goto out;
2453 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002454 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002455 s.compressed = s.compressed || bdi.needs_compressed_writes;
2456 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002457 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002458 }
2459
Peter Lieven9fd77f92017-04-21 11:11:55 +02002460 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002461out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002462 if (!ret) {
2463 qemu_progress_print(100, 0);
2464 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002465 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002466 qemu_opts_del(opts);
2467 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002468 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002469 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002470 blk_unref(s.target);
2471 if (s.src) {
2472 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2473 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002474 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002475 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002476 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002477 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002478fail_getopt:
2479 g_free(options);
2480
Peter Lieven9fd77f92017-04-21 11:11:55 +02002481 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002482}
2483
bellard57d1a2b2004-08-03 21:15:11 +00002484
bellardfaea38e2006-08-05 21:31:00 +00002485static void dump_snapshots(BlockDriverState *bs)
2486{
2487 QEMUSnapshotInfo *sn_tab, *sn;
2488 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002489
2490 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2491 if (nb_sns <= 0)
2492 return;
2493 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002494 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002495 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002496 for(i = 0; i < nb_sns; i++) {
2497 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002498 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002499 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002500 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002501 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002502}
2503
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002504static void dump_json_image_info_list(ImageInfoList *list)
2505{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002506 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002507 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002508 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002509
2510 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2511 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002512 str = qobject_to_json_pretty(obj);
2513 assert(str != NULL);
2514 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002515 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002516 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002517 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002518}
2519
Benoît Canetc054b3f2012-09-05 13:09:02 +02002520static void dump_json_image_info(ImageInfo *info)
2521{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002522 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002523 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002524 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002525
2526 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2527 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002528 str = qobject_to_json_pretty(obj);
2529 assert(str != NULL);
2530 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002531 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002532 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002533 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002534}
2535
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002536static void dump_human_image_info_list(ImageInfoList *list)
2537{
2538 ImageInfoList *elem;
2539 bool delim = false;
2540
2541 for (elem = list; elem; elem = elem->next) {
2542 if (delim) {
2543 printf("\n");
2544 }
2545 delim = true;
2546
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002547 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002548 }
2549}
2550
2551static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2552{
2553 return strcmp(a, b) == 0;
2554}
2555
2556/**
2557 * Open an image file chain and return an ImageInfoList
2558 *
2559 * @filename: topmost image filename
2560 * @fmt: topmost image format (may be NULL to autodetect)
2561 * @chain: true - enumerate entire backing file chain
2562 * false - only topmost image file
2563 *
2564 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2565 * image file. If there was an error a message will have been printed to
2566 * stderr.
2567 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002568static ImageInfoList *collect_image_info_list(bool image_opts,
2569 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002570 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002571 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002572{
2573 ImageInfoList *head = NULL;
2574 ImageInfoList **last = &head;
2575 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002576 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002577
2578 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2579
2580 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002581 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002582 BlockDriverState *bs;
2583 ImageInfo *info;
2584 ImageInfoList *elem;
2585
2586 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2587 error_report("Backing file '%s' creates an infinite loop.",
2588 filename);
2589 goto err;
2590 }
2591 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2592
Max Reitzefaa7c42016-03-16 19:54:38 +01002593 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002594 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2595 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002596 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002597 goto err;
2598 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002599 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002600
Wenchao Xia43526ec2013-06-06 12:27:58 +08002601 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002602 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002603 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002604 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002605 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002606 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002607
2608 elem = g_new0(ImageInfoList, 1);
2609 elem->value = info;
2610 *last = elem;
2611 last = &elem->next;
2612
Markus Armbruster26f54e92014-10-07 13:59:04 +02002613 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002614
2615 filename = fmt = NULL;
2616 if (chain) {
2617 if (info->has_full_backing_filename) {
2618 filename = info->full_backing_filename;
2619 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002620 error_report("Could not determine absolute backing filename,"
2621 " but backing filename '%s' present",
2622 info->backing_filename);
2623 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002624 }
2625 if (info->has_backing_filename_format) {
2626 fmt = info->backing_filename_format;
2627 }
2628 }
2629 }
2630 g_hash_table_destroy(filenames);
2631 return head;
2632
2633err:
2634 qapi_free_ImageInfoList(head);
2635 g_hash_table_destroy(filenames);
2636 return NULL;
2637}
2638
Benoît Canetc054b3f2012-09-05 13:09:02 +02002639static int img_info(int argc, char **argv)
2640{
2641 int c;
2642 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002643 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002644 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002645 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002646 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002647 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002648
bellardea2384d2004-08-01 21:59:26 +00002649 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002650 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002651 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002652 int option_index = 0;
2653 static const struct option long_options[] = {
2654 {"help", no_argument, 0, 'h'},
2655 {"format", required_argument, 0, 'f'},
2656 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002657 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002658 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002659 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002660 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002661 {0, 0, 0, 0}
2662 };
Fam Zheng335e9932017-05-03 00:35:39 +08002663 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002664 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002665 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002666 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002667 }
bellardea2384d2004-08-01 21:59:26 +00002668 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002669 case ':':
2670 missing_argument(argv[optind - 1]);
2671 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002672 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002673 unrecognized_option(argv[optind - 1]);
2674 break;
bellardea2384d2004-08-01 21:59:26 +00002675 case 'h':
2676 help();
2677 break;
2678 case 'f':
2679 fmt = optarg;
2680 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002681 case 'U':
2682 force_share = true;
2683 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002684 case OPTION_OUTPUT:
2685 output = optarg;
2686 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002687 case OPTION_BACKING_CHAIN:
2688 chain = true;
2689 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002690 case OPTION_OBJECT: {
2691 QemuOpts *opts;
2692 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2693 optarg, true);
2694 if (!opts) {
2695 return 1;
2696 }
2697 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002698 case OPTION_IMAGE_OPTS:
2699 image_opts = true;
2700 break;
bellardea2384d2004-08-01 21:59:26 +00002701 }
2702 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002703 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002704 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002705 }
bellardea2384d2004-08-01 21:59:26 +00002706 filename = argv[optind++];
2707
Benoît Canetc054b3f2012-09-05 13:09:02 +02002708 if (output && !strcmp(output, "json")) {
2709 output_format = OFORMAT_JSON;
2710 } else if (output && !strcmp(output, "human")) {
2711 output_format = OFORMAT_HUMAN;
2712 } else if (output) {
2713 error_report("--output must be used with human or json as argument.");
2714 return 1;
2715 }
2716
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002717 if (qemu_opts_foreach(&qemu_object_opts,
2718 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002719 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002720 return 1;
2721 }
2722
Fam Zheng335e9932017-05-03 00:35:39 +08002723 list = collect_image_info_list(image_opts, filename, fmt, chain,
2724 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002725 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002726 return 1;
2727 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002728
Benoît Canetc054b3f2012-09-05 13:09:02 +02002729 switch (output_format) {
2730 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002731 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002732 break;
2733 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002734 if (chain) {
2735 dump_json_image_info_list(list);
2736 } else {
2737 dump_json_image_info(list->value);
2738 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002739 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002740 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002741
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002742 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002743 return 0;
2744}
2745
Eric Blake30065d12019-03-26 13:40:43 -05002746static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2747 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002748{
2749 switch (output_format) {
2750 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002751 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002752 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002753 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002754 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002755 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002756 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002757 e->start, e->length,
2758 e->has_offset ? e->offset : 0,
2759 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002760 }
2761 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2762 * Modify the flags here to allow more coalescing.
2763 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002764 if (next && (!next->data || next->zero)) {
2765 next->data = false;
2766 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002767 }
2768 break;
2769 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002770 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2771 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002772 (e->start == 0 ? "[" : ",\n"),
2773 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002774 e->zero ? "true" : "false",
2775 e->data ? "true" : "false");
2776 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002777 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002778 }
2779 putchar('}');
2780
2781 if (!next) {
2782 printf("]\n");
2783 }
2784 break;
2785 }
Eric Blake30065d12019-03-26 13:40:43 -05002786 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002787}
2788
Eric Blake5e344dd2017-10-11 22:47:02 -05002789static int get_block_status(BlockDriverState *bs, int64_t offset,
2790 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002791{
Eric Blake237d78f2017-10-11 22:47:03 -05002792 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002793 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002794 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002795 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002796 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002797 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002798
2799 /* As an optimization, we could cache the current range of unallocated
2800 * clusters in each file of the chain, and avoid querying the same
2801 * range repeatedly.
2802 */
2803
2804 depth = 0;
2805 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002806 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002807 if (ret < 0) {
2808 return ret;
2809 }
Eric Blake237d78f2017-10-11 22:47:03 -05002810 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002811 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2812 break;
2813 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002814 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002815 if (bs == NULL) {
2816 ret = 0;
2817 break;
2818 }
2819
2820 depth++;
2821 }
2822
John Snow28756452016-02-05 13:12:33 -05002823 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2824
Max Reitzf30c66b2019-02-01 20:29:05 +01002825 if (file && has_offset) {
2826 bdrv_refresh_filename(file);
2827 filename = file->filename;
2828 }
2829
John Snow28756452016-02-05 13:12:33 -05002830 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002831 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002832 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002833 .data = !!(ret & BDRV_BLOCK_DATA),
2834 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002835 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002836 .has_offset = has_offset,
2837 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002838 .has_filename = filename,
2839 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002840 };
2841
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002842 return 0;
2843}
2844
Fam Zheng16b0d552016-01-26 11:59:02 +08002845static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2846{
2847 if (curr->length == 0) {
2848 return false;
2849 }
2850 if (curr->zero != next->zero ||
2851 curr->data != next->data ||
2852 curr->depth != next->depth ||
2853 curr->has_filename != next->has_filename ||
2854 curr->has_offset != next->has_offset) {
2855 return false;
2856 }
2857 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2858 return false;
2859 }
2860 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2861 return false;
2862 }
2863 return true;
2864}
2865
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002866static int img_map(int argc, char **argv)
2867{
2868 int c;
2869 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002870 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002871 BlockDriverState *bs;
2872 const char *filename, *fmt, *output;
2873 int64_t length;
2874 MapEntry curr = { .length = 0 }, next;
2875 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002876 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002877 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002878
2879 fmt = NULL;
2880 output = NULL;
2881 for (;;) {
2882 int option_index = 0;
2883 static const struct option long_options[] = {
2884 {"help", no_argument, 0, 'h'},
2885 {"format", required_argument, 0, 'f'},
2886 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002887 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002888 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002889 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002890 {0, 0, 0, 0}
2891 };
Fam Zheng335e9932017-05-03 00:35:39 +08002892 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002893 long_options, &option_index);
2894 if (c == -1) {
2895 break;
2896 }
2897 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002898 case ':':
2899 missing_argument(argv[optind - 1]);
2900 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002901 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002902 unrecognized_option(argv[optind - 1]);
2903 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002904 case 'h':
2905 help();
2906 break;
2907 case 'f':
2908 fmt = optarg;
2909 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002910 case 'U':
2911 force_share = true;
2912 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002913 case OPTION_OUTPUT:
2914 output = optarg;
2915 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002916 case OPTION_OBJECT: {
2917 QemuOpts *opts;
2918 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2919 optarg, true);
2920 if (!opts) {
2921 return 1;
2922 }
2923 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002924 case OPTION_IMAGE_OPTS:
2925 image_opts = true;
2926 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002927 }
2928 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002929 if (optind != argc - 1) {
2930 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002931 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002932 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002933
2934 if (output && !strcmp(output, "json")) {
2935 output_format = OFORMAT_JSON;
2936 } else if (output && !strcmp(output, "human")) {
2937 output_format = OFORMAT_HUMAN;
2938 } else if (output) {
2939 error_report("--output must be used with human or json as argument.");
2940 return 1;
2941 }
2942
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002943 if (qemu_opts_foreach(&qemu_object_opts,
2944 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002945 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002946 return 1;
2947 }
2948
Fam Zheng335e9932017-05-03 00:35:39 +08002949 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002950 if (!blk) {
2951 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002952 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002953 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002954
2955 if (output_format == OFORMAT_HUMAN) {
2956 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2957 }
2958
Max Reitzf1d3cd72015-02-05 13:58:18 -05002959 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002960 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002961 int64_t offset = curr.start + curr.length;
2962 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002963
2964 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02002965 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002966 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002967
2968 if (ret < 0) {
2969 error_report("Could not read file metadata: %s", strerror(-ret));
2970 goto out;
2971 }
2972
Fam Zheng16b0d552016-01-26 11:59:02 +08002973 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002974 curr.length += next.length;
2975 continue;
2976 }
2977
2978 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05002979 ret = dump_map_entry(output_format, &curr, &next);
2980 if (ret < 0) {
2981 goto out;
2982 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002983 }
2984 curr = next;
2985 }
2986
Eric Blake30065d12019-03-26 13:40:43 -05002987 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002988
2989out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002990 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002991 return ret < 0;
2992}
2993
aliguorif7b4a942009-01-07 17:40:15 +00002994#define SNAPSHOT_LIST 1
2995#define SNAPSHOT_CREATE 2
2996#define SNAPSHOT_APPLY 3
2997#define SNAPSHOT_DELETE 4
2998
Stuart Brady153859b2009-06-07 00:42:17 +01002999static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003000{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003001 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003002 BlockDriverState *bs;
3003 QEMUSnapshotInfo sn;
3004 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003005 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003006 int action = 0;
3007 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003008 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003009 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003010 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003011 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003012
Kevin Wolfce099542016-03-15 13:01:04 +01003013 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003014 /* Parse commandline parameters */
3015 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003016 static const struct option long_options[] = {
3017 {"help", no_argument, 0, 'h'},
3018 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003019 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003020 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003021 {0, 0, 0, 0}
3022 };
Fam Zheng335e9932017-05-03 00:35:39 +08003023 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003024 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003025 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003026 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003027 }
aliguorif7b4a942009-01-07 17:40:15 +00003028 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003029 case ':':
3030 missing_argument(argv[optind - 1]);
3031 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003032 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003033 unrecognized_option(argv[optind - 1]);
3034 break;
aliguorif7b4a942009-01-07 17:40:15 +00003035 case 'h':
3036 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003037 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003038 case 'l':
3039 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003040 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003041 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003042 }
3043 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003044 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003045 break;
3046 case 'a':
3047 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003048 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003049 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003050 }
3051 action = SNAPSHOT_APPLY;
3052 snapshot_name = optarg;
3053 break;
3054 case 'c':
3055 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003056 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003057 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003058 }
3059 action = SNAPSHOT_CREATE;
3060 snapshot_name = optarg;
3061 break;
3062 case 'd':
3063 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003064 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003065 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003066 }
3067 action = SNAPSHOT_DELETE;
3068 snapshot_name = optarg;
3069 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003070 case 'q':
3071 quiet = true;
3072 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003073 case 'U':
3074 force_share = true;
3075 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003076 case OPTION_OBJECT: {
3077 QemuOpts *opts;
3078 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3079 optarg, true);
3080 if (!opts) {
3081 return 1;
3082 }
3083 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003084 case OPTION_IMAGE_OPTS:
3085 image_opts = true;
3086 break;
aliguorif7b4a942009-01-07 17:40:15 +00003087 }
3088 }
3089
Kevin Wolffc11eb22013-08-05 10:53:04 +02003090 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003091 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003092 }
aliguorif7b4a942009-01-07 17:40:15 +00003093 filename = argv[optind++];
3094
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003095 if (qemu_opts_foreach(&qemu_object_opts,
3096 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003097 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003098 return 1;
3099 }
3100
aliguorif7b4a942009-01-07 17:40:15 +00003101 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003102 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3103 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003104 if (!blk) {
3105 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003106 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003107 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003108
3109 /* Perform the requested action */
3110 switch(action) {
3111 case SNAPSHOT_LIST:
3112 dump_snapshots(bs);
3113 break;
3114
3115 case SNAPSHOT_CREATE:
3116 memset(&sn, 0, sizeof(sn));
3117 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3118
3119 qemu_gettimeofday(&tv);
3120 sn.date_sec = tv.tv_sec;
3121 sn.date_nsec = tv.tv_usec * 1000;
3122
3123 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003124 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003125 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003126 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003127 }
aliguorif7b4a942009-01-07 17:40:15 +00003128 break;
3129
3130 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003131 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003132 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003133 error_reportf_err(err, "Could not apply snapshot '%s': ",
3134 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003135 }
aliguorif7b4a942009-01-07 17:40:15 +00003136 break;
3137
3138 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003139 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3140 if (ret < 0) {
3141 error_report("Could not delete snapshot '%s': snapshot not "
3142 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003143 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003144 } else {
3145 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3146 if (ret < 0) {
3147 error_reportf_err(err, "Could not delete snapshot '%s': ",
3148 snapshot_name);
3149 ret = 1;
3150 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003151 }
aliguorif7b4a942009-01-07 17:40:15 +00003152 break;
3153 }
3154
3155 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003156 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003157 if (ret) {
3158 return 1;
3159 }
Stuart Brady153859b2009-06-07 00:42:17 +01003160 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003161}
3162
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003163static int img_rebase(int argc, char **argv)
3164{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003165 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003166 uint8_t *buf_old = NULL;
3167 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003168 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003169 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003170 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3171 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003172 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003173 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003174 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003175 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003176 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003177 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003178 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003179
3180 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003181 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003182 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003183 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003184 out_baseimg = NULL;
3185 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003186 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003187 static const struct option long_options[] = {
3188 {"help", no_argument, 0, 'h'},
3189 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003190 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003191 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003192 {0, 0, 0, 0}
3193 };
Fam Zheng335e9932017-05-03 00:35:39 +08003194 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003195 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003196 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003197 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003198 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003199 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003200 case ':':
3201 missing_argument(argv[optind - 1]);
3202 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003203 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003204 unrecognized_option(argv[optind - 1]);
3205 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003206 case 'h':
3207 help();
3208 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003209 case 'f':
3210 fmt = optarg;
3211 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003212 case 'F':
3213 out_basefmt = optarg;
3214 break;
3215 case 'b':
3216 out_baseimg = optarg;
3217 break;
3218 case 'u':
3219 unsafe = 1;
3220 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003221 case 'p':
3222 progress = 1;
3223 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003224 case 't':
3225 cache = optarg;
3226 break;
Max Reitz40055952014-07-22 22:58:42 +02003227 case 'T':
3228 src_cache = optarg;
3229 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003230 case 'q':
3231 quiet = true;
3232 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003233 case OPTION_OBJECT: {
3234 QemuOpts *opts;
3235 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3236 optarg, true);
3237 if (!opts) {
3238 return 1;
3239 }
3240 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003241 case OPTION_IMAGE_OPTS:
3242 image_opts = true;
3243 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003244 case 'U':
3245 force_share = true;
3246 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003247 }
3248 }
3249
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003250 if (quiet) {
3251 progress = 0;
3252 }
3253
Fam Zhengac1307a2014-04-22 13:36:11 +08003254 if (optind != argc - 1) {
3255 error_exit("Expecting one image file name");
3256 }
3257 if (!unsafe && !out_baseimg) {
3258 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003259 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003260 filename = argv[optind++];
3261
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003262 if (qemu_opts_foreach(&qemu_object_opts,
3263 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003264 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003265 return 1;
3266 }
3267
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003268 qemu_progress_init(progress, 2.0);
3269 qemu_progress_print(0, 100);
3270
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003271 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003272 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003273 if (ret < 0) {
3274 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003275 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003276 }
3277
Kevin Wolfce099542016-03-15 13:01:04 +01003278 src_flags = 0;
3279 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003280 if (ret < 0) {
3281 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003282 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003283 }
3284
Kevin Wolfce099542016-03-15 13:01:04 +01003285 /* The source files are opened read-only, don't care about WCE */
3286 assert((src_flags & BDRV_O_RDWR) == 0);
3287 (void) src_writethrough;
3288
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003289 /*
3290 * Open the images.
3291 *
3292 * Ignore the old backing file for unsafe rebase in case we want to correct
3293 * the reference to a renamed or moved backing file.
3294 */
Fam Zheng335e9932017-05-03 00:35:39 +08003295 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3296 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003297 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003298 ret = -1;
3299 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003300 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003301 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003302
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003303 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003304 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003305 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003306 ret = -1;
3307 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003308 }
3309 }
3310
3311 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003312 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003313 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003314 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003315
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003316 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003317 blk_old_backing = blk_new(qemu_get_aio_context(),
3318 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003319 BLK_PERM_ALL);
3320 ret = blk_insert_bs(blk_old_backing, base_bs,
3321 &local_err);
3322 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003323 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003324 "Could not reuse old backing file '%s': ",
3325 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003326 goto out;
3327 }
3328 } else {
3329 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003330 }
Max Reitz644483d2015-02-05 13:58:17 -05003331
Alex Bligha6166732012-10-16 13:46:18 +01003332 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003333 const char *overlay_filename;
3334 char *out_real_path;
3335
Fam Zheng335e9932017-05-03 00:35:39 +08003336 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003337 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003338 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003339 }
3340 if (force_share) {
3341 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003342 }
3343
Max Reitzf30c66b2019-02-01 20:29:05 +01003344 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003345 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3346 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003347 out_real_path =
3348 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3349 out_baseimg,
3350 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003351 if (local_err) {
3352 error_reportf_err(local_err,
3353 "Could not resolve backing filename: ");
3354 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003355 goto out;
3356 }
3357
Sam Eiderman863cc782019-05-23 19:33:36 +03003358 /*
3359 * Find out whether we rebase an image on top of a previous image
3360 * in its chain.
3361 */
3362 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003363 if (prefix_chain_bs) {
3364 g_free(out_real_path);
Kevin Wolfd861ab32019-04-25 14:25:10 +02003365 blk_new_backing = blk_new(qemu_get_aio_context(),
3366 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003367 BLK_PERM_ALL);
3368 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3369 &local_err);
3370 if (ret < 0) {
3371 error_reportf_err(local_err,
3372 "Could not reuse backing file '%s': ",
3373 out_baseimg);
3374 goto out;
3375 }
3376 } else {
3377 blk_new_backing = blk_new_open(out_real_path, NULL,
3378 options, src_flags, &local_err);
3379 g_free(out_real_path);
3380 if (!blk_new_backing) {
3381 error_reportf_err(local_err,
3382 "Could not open new backing file '%s': ",
3383 out_baseimg);
3384 ret = -1;
3385 goto out;
3386 }
Alex Bligha6166732012-10-16 13:46:18 +01003387 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003388 }
3389 }
3390
3391 /*
3392 * Check each unallocated cluster in the COW file. If it is unallocated,
3393 * accesses go to the backing file. We must therefore compare this cluster
3394 * in the old and new backing file, and if they differ we need to copy it
3395 * from the old backing file into the COW file.
3396 *
3397 * If qemu-img crashes during this step, no harm is done. The content of
3398 * the image is the same as the original one at any time.
3399 */
3400 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003401 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003402 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003403 int64_t new_backing_size = 0;
3404 uint64_t offset;
3405 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003406 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003407
Max Reitzf1d3cd72015-02-05 13:58:18 -05003408 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3409 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003410
Eric Blake41536282017-10-11 22:47:15 -05003411 size = blk_getlength(blk);
3412 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003413 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003414 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003415 ret = -1;
3416 goto out;
3417 }
Max Reitz35ddd932019-05-09 19:52:35 +02003418 if (blk_old_backing) {
3419 old_backing_size = blk_getlength(blk_old_backing);
3420 if (old_backing_size < 0) {
3421 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003422
Max Reitz35ddd932019-05-09 19:52:35 +02003423 bdrv_get_backing_filename(bs, backing_name,
3424 sizeof(backing_name));
3425 error_report("Could not get size of '%s': %s",
3426 backing_name, strerror(-old_backing_size));
3427 ret = -1;
3428 goto out;
3429 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003430 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003431 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003432 new_backing_size = blk_getlength(blk_new_backing);
3433 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003434 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003435 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003436 ret = -1;
3437 goto out;
3438 }
Alex Bligha6166732012-10-16 13:46:18 +01003439 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003440
Eric Blake41536282017-10-11 22:47:15 -05003441 if (size != 0) {
3442 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003443 }
3444
Eric Blake41536282017-10-11 22:47:15 -05003445 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003446 bool buf_old_is_zero = false;
3447
Eric Blake41536282017-10-11 22:47:15 -05003448 /* How many bytes can we handle with the next read? */
3449 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003450
3451 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003452 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003453 if (ret < 0) {
3454 error_report("error while reading image metadata: %s",
3455 strerror(-ret));
3456 goto out;
3457 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003458 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003459 continue;
3460 }
3461
Sam Eiderman863cc782019-05-23 19:33:36 +03003462 if (prefix_chain_bs) {
3463 /*
3464 * If cluster wasn't changed since prefix_chain, we don't need
3465 * to take action
3466 */
3467 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3468 offset, n, &n);
3469 if (ret < 0) {
3470 error_report("error while reading image metadata: %s",
3471 strerror(-ret));
3472 goto out;
3473 }
3474 if (!ret) {
3475 continue;
3476 }
3477 }
3478
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003479 /*
3480 * Read old and new backing file and take into consideration that
3481 * backing files may be smaller than the COW image.
3482 */
Eric Blake41536282017-10-11 22:47:15 -05003483 if (offset >= old_backing_size) {
3484 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003485 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003486 } else {
Eric Blake41536282017-10-11 22:47:15 -05003487 if (offset + n > old_backing_size) {
3488 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003489 }
3490
Eric Blake41536282017-10-11 22:47:15 -05003491 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003492 if (ret < 0) {
3493 error_report("error while reading from old backing file");
3494 goto out;
3495 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003496 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003497
Eric Blake41536282017-10-11 22:47:15 -05003498 if (offset >= new_backing_size || !blk_new_backing) {
3499 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003500 } else {
Eric Blake41536282017-10-11 22:47:15 -05003501 if (offset + n > new_backing_size) {
3502 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003503 }
3504
Eric Blake41536282017-10-11 22:47:15 -05003505 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003506 if (ret < 0) {
3507 error_report("error while reading from new backing file");
3508 goto out;
3509 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003510 }
3511
3512 /* If they differ, we need to write to the COW file */
3513 uint64_t written = 0;
3514
Eric Blake41536282017-10-11 22:47:15 -05003515 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003516 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003517
Eric Blake41536282017-10-11 22:47:15 -05003518 if (compare_buffers(buf_old + written, buf_new + written,
3519 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003520 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003521 if (buf_old_is_zero) {
3522 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3523 } else {
3524 ret = blk_pwrite(blk, offset + written,
3525 buf_old + written, pnum, 0);
3526 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003527 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003528 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003529 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003530 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003531 }
3532 }
3533
3534 written += pnum;
3535 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003536 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003537 }
3538 }
3539
3540 /*
3541 * Change the backing file. All clusters that are different from the old
3542 * backing file are overwritten in the COW file now, so the visible content
3543 * doesn't change when we switch the backing file.
3544 */
Alex Bligha6166732012-10-16 13:46:18 +01003545 if (out_baseimg && *out_baseimg) {
3546 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3547 } else {
3548 ret = bdrv_change_backing_file(bs, NULL, NULL);
3549 }
3550
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003551 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003552 error_report("Could not change the backing file to '%s': No "
3553 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003554 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003555 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003556 out_baseimg, strerror(-ret));
3557 }
3558
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003559 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003560 /*
3561 * TODO At this point it is possible to check if any clusters that are
3562 * allocated in the COW file are the same in the backing file. If so, they
3563 * could be dropped from the COW file. Don't do this before switching the
3564 * backing file, in case of a crash this would lead to corruption.
3565 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003566out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003567 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003568 /* Cleanup */
3569 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003570 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003571 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003572 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003573 qemu_vfree(buf_old);
3574 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003575
Markus Armbruster26f54e92014-10-07 13:59:04 +02003576 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003577 if (ret) {
3578 return 1;
3579 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003580 return 0;
3581}
3582
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003583static int img_resize(int argc, char **argv)
3584{
Markus Armbruster6750e792015-02-12 17:43:08 +01003585 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003586 int c, ret, relative;
3587 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003588 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003589 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003590 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003591 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003592 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003593
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003594 static QemuOptsList resize_options = {
3595 .name = "resize_options",
3596 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3597 .desc = {
3598 {
3599 .name = BLOCK_OPT_SIZE,
3600 .type = QEMU_OPT_SIZE,
3601 .help = "Virtual disk size"
3602 }, {
3603 /* end of list */
3604 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003605 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003606 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003607 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003608 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003609
Kevin Wolfe80fec72011-04-29 10:58:12 +02003610 /* Remove size from argv manually so that negative numbers are not treated
3611 * as options by getopt. */
3612 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003613 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003614 return 1;
3615 }
3616
3617 size = argv[--argc];
3618
3619 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003620 fmt = NULL;
3621 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003622 static const struct option long_options[] = {
3623 {"help", no_argument, 0, 'h'},
3624 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003625 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003626 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003627 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003628 {0, 0, 0, 0}
3629 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003630 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003631 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003632 if (c == -1) {
3633 break;
3634 }
3635 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003636 case ':':
3637 missing_argument(argv[optind - 1]);
3638 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003639 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003640 unrecognized_option(argv[optind - 1]);
3641 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003642 case 'h':
3643 help();
3644 break;
3645 case 'f':
3646 fmt = optarg;
3647 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003648 case 'q':
3649 quiet = true;
3650 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003651 case OPTION_OBJECT: {
3652 QemuOpts *opts;
3653 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3654 optarg, true);
3655 if (!opts) {
3656 return 1;
3657 }
3658 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003659 case OPTION_IMAGE_OPTS:
3660 image_opts = true;
3661 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003662 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003663 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003664 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003665 if (prealloc == PREALLOC_MODE__MAX) {
3666 error_report("Invalid preallocation mode '%s'", optarg);
3667 return 1;
3668 }
3669 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003670 case OPTION_SHRINK:
3671 shrink = true;
3672 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003673 }
3674 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003675 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003676 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003677 }
3678 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003679
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003680 if (qemu_opts_foreach(&qemu_object_opts,
3681 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003682 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003683 return 1;
3684 }
3685
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003686 /* Choose grow, shrink, or absolute resize mode */
3687 switch (size[0]) {
3688 case '+':
3689 relative = 1;
3690 size++;
3691 break;
3692 case '-':
3693 relative = -1;
3694 size++;
3695 break;
3696 default:
3697 relative = 0;
3698 break;
3699 }
3700
3701 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003702 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003703 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003704 if (err) {
3705 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003706 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003707 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003708 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003709 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003710 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3711 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003712
Max Reitzefaa7c42016-03-16 19:54:38 +01003713 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003714 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3715 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003716 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003717 ret = -1;
3718 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003719 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003720
Max Reitzdc5f6902017-06-13 22:20:55 +02003721 current_size = blk_getlength(blk);
3722 if (current_size < 0) {
3723 error_report("Failed to inquire current image length: %s",
3724 strerror(-current_size));
3725 ret = -1;
3726 goto out;
3727 }
3728
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003729 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003730 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003731 } else {
3732 total_size = n;
3733 }
3734 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003735 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003736 ret = -1;
3737 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003738 }
3739
Max Reitzdc5f6902017-06-13 22:20:55 +02003740 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3741 error_report("Preallocation can only be used for growing images");
3742 ret = -1;
3743 goto out;
3744 }
3745
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003746 if (total_size < current_size && !shrink) {
3747 warn_report("Shrinking an image will delete all data beyond the "
3748 "shrunken image's end. Before performing such an "
3749 "operation, make sure there is no important data there.");
3750
3751 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3752 error_report(
3753 "Use the --shrink option to perform a shrink operation.");
3754 ret = -1;
3755 goto out;
3756 } else {
3757 warn_report("Using the --shrink option will suppress this message. "
3758 "Note that future versions of qemu-img may refuse to "
3759 "shrink images without this option.");
3760 }
3761 }
3762
Max Reitzdc5f6902017-06-13 22:20:55 +02003763 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003764 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003765 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003766 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003767 }
Max Reitz5279b302018-04-21 18:39:57 +02003768
3769 new_size = blk_getlength(blk);
3770 if (new_size < 0) {
3771 error_report("Failed to verify truncated image length: %s",
3772 strerror(-new_size));
3773 ret = -1;
3774 goto out;
3775 }
3776
3777 /* Some block drivers implement a truncation method, but only so
3778 * the user can cause qemu to refresh the image's size from disk.
3779 * The idea is that the user resizes the image outside of qemu and
3780 * then invokes block_resize to inform qemu about it.
3781 * (This includes iscsi and file-posix for device files.)
3782 * Of course, that is not the behavior someone invoking
3783 * qemu-img resize would find useful, so we catch that behavior
3784 * here and tell the user. */
3785 if (new_size != total_size && new_size == current_size) {
3786 error_report("Image was not resized; resizing may not be supported "
3787 "for this image");
3788 ret = -1;
3789 goto out;
3790 }
3791
3792 if (new_size != total_size) {
3793 warn_report("Image should have been resized to %" PRIi64
3794 " bytes, but was resized to %" PRIi64 " bytes",
3795 total_size, new_size);
3796 }
3797
3798 qprintf(quiet, "Image resized.\n");
3799
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003800out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003801 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003802 if (ret) {
3803 return 1;
3804 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003805 return 0;
3806}
3807
Max Reitz76a3a342014-10-27 11:12:51 +01003808static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003809 int64_t offset, int64_t total_work_size,
3810 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003811{
3812 qemu_progress_print(100.f * offset / total_work_size, 0);
3813}
3814
Max Reitz51641352018-05-09 23:00:20 +02003815static int print_amend_option_help(const char *format)
3816{
3817 BlockDriver *drv;
3818
3819 /* Find driver and parse its options */
3820 drv = bdrv_find_format(format);
3821 if (!drv) {
3822 error_report("Unknown file format '%s'", format);
3823 return 1;
3824 }
3825
3826 if (!drv->bdrv_amend_options) {
3827 error_report("Format driver '%s' does not support option amendment",
3828 format);
3829 return 1;
3830 }
3831
3832 /* Every driver supporting amendment must have create_opts */
3833 assert(drv->create_opts);
3834
3835 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003836 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003837 printf("\nNote that not all of these options may be amendable.\n");
3838 return 0;
3839}
3840
Max Reitz6f176b42013-09-03 10:09:50 +02003841static int img_amend(int argc, char **argv)
3842{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003843 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003844 int c, ret = 0;
3845 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003846 QemuOptsList *create_opts = NULL;
3847 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003848 const char *fmt = NULL, *filename, *cache;
3849 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003850 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003851 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003852 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003853 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003854 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003855
Max Reitzbd39e6e2014-07-22 22:58:43 +02003856 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003857 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003858 static const struct option long_options[] = {
3859 {"help", no_argument, 0, 'h'},
3860 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003861 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003862 {0, 0, 0, 0}
3863 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003864 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003865 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003866 if (c == -1) {
3867 break;
3868 }
3869
3870 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003871 case ':':
3872 missing_argument(argv[optind - 1]);
3873 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003874 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003875 unrecognized_option(argv[optind - 1]);
3876 break;
3877 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003878 help();
3879 break;
3880 case 'o':
3881 if (!is_valid_option_list(optarg)) {
3882 error_report("Invalid option list: %s", optarg);
3883 ret = -1;
3884 goto out_no_progress;
3885 }
3886 if (!options) {
3887 options = g_strdup(optarg);
3888 } else {
3889 char *old_options = options;
3890 options = g_strdup_printf("%s,%s", options, optarg);
3891 g_free(old_options);
3892 }
3893 break;
3894 case 'f':
3895 fmt = optarg;
3896 break;
3897 case 't':
3898 cache = optarg;
3899 break;
3900 case 'p':
3901 progress = true;
3902 break;
3903 case 'q':
3904 quiet = true;
3905 break;
3906 case OPTION_OBJECT:
3907 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3908 optarg, true);
3909 if (!opts) {
3910 ret = -1;
3911 goto out_no_progress;
3912 }
3913 break;
3914 case OPTION_IMAGE_OPTS:
3915 image_opts = true;
3916 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003917 }
3918 }
3919
Max Reitz6f176b42013-09-03 10:09:50 +02003920 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003921 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003922 }
3923
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003924 if (qemu_opts_foreach(&qemu_object_opts,
3925 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003926 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003927 ret = -1;
3928 goto out_no_progress;
3929 }
3930
Max Reitz76a3a342014-10-27 11:12:51 +01003931 if (quiet) {
3932 progress = false;
3933 }
3934 qemu_progress_init(progress, 1.0);
3935
Kevin Wolfa283cb62014-02-21 16:24:07 +01003936 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3937 if (fmt && has_help_option(options)) {
3938 /* If a format is explicitly specified (and possibly no filename is
3939 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003940 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003941 goto out;
3942 }
3943
3944 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003945 error_report("Expecting one image file name");
3946 ret = -1;
3947 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003948 }
Max Reitz6f176b42013-09-03 10:09:50 +02003949
Kevin Wolfce099542016-03-15 13:01:04 +01003950 flags = BDRV_O_RDWR;
3951 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003952 if (ret < 0) {
3953 error_report("Invalid cache option: %s", cache);
3954 goto out;
3955 }
3956
Fam Zheng335e9932017-05-03 00:35:39 +08003957 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3958 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003959 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003960 ret = -1;
3961 goto out;
3962 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003963 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003964
3965 fmt = bs->drv->format_name;
3966
Kevin Wolf626f84f2014-02-21 16:24:06 +01003967 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003968 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003969 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003970 goto out;
3971 }
3972
Max Reitz1f996682018-05-09 23:00:17 +02003973 if (!bs->drv->bdrv_amend_options) {
3974 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003975 fmt);
3976 ret = -1;
3977 goto out;
3978 }
3979
Max Reitz1f996682018-05-09 23:00:17 +02003980 /* Every driver supporting amendment must have create_opts */
3981 assert(bs->drv->create_opts);
3982
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003983 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003984 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003985 qemu_opts_do_parse(opts, options, NULL, &err);
3986 if (err) {
3987 error_report_err(err);
3988 ret = -1;
3989 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003990 }
3991
Max Reitz76a3a342014-10-27 11:12:51 +01003992 /* In case the driver does not call amend_status_cb() */
3993 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003994 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003995 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003996 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003997 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003998 goto out;
3999 }
4000
4001out:
Max Reitz76a3a342014-10-27 11:12:51 +01004002 qemu_progress_end();
4003
Max Reitze814dff2015-08-20 16:00:38 -07004004out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004005 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004006 qemu_opts_del(opts);
4007 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004008 g_free(options);
4009
Max Reitz6f176b42013-09-03 10:09:50 +02004010 if (ret) {
4011 return 1;
4012 }
4013 return 0;
4014}
4015
Kevin Wolfb6133b82014-08-05 14:17:13 +02004016typedef struct BenchData {
4017 BlockBackend *blk;
4018 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004019 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004020 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004021 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004022 int nrreq;
4023 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004024 int flush_interval;
4025 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004026 uint8_t *buf;
4027 QEMUIOVector *qiov;
4028
4029 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004030 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004031 uint64_t offset;
4032} BenchData;
4033
Kevin Wolf55d539c2016-06-03 13:59:41 +02004034static void bench_undrained_flush_cb(void *opaque, int ret)
4035{
4036 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004037 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004038 exit(EXIT_FAILURE);
4039 }
4040}
4041
Kevin Wolfb6133b82014-08-05 14:17:13 +02004042static void bench_cb(void *opaque, int ret)
4043{
4044 BenchData *b = opaque;
4045 BlockAIOCB *acb;
4046
4047 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004048 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004049 exit(EXIT_FAILURE);
4050 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004051
4052 if (b->in_flush) {
4053 /* Just finished a flush with drained queue: Start next requests */
4054 assert(b->in_flight == 0);
4055 b->in_flush = false;
4056 } else if (b->in_flight > 0) {
4057 int remaining = b->n - b->in_flight;
4058
Kevin Wolfb6133b82014-08-05 14:17:13 +02004059 b->n--;
4060 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004061
4062 /* Time for flush? Drain queue if requested, then flush */
4063 if (b->flush_interval && remaining % b->flush_interval == 0) {
4064 if (!b->in_flight || !b->drain_on_flush) {
4065 BlockCompletionFunc *cb;
4066
4067 if (b->drain_on_flush) {
4068 b->in_flush = true;
4069 cb = bench_cb;
4070 } else {
4071 cb = bench_undrained_flush_cb;
4072 }
4073
4074 acb = blk_aio_flush(b->blk, cb, b);
4075 if (!acb) {
4076 error_report("Failed to issue flush request");
4077 exit(EXIT_FAILURE);
4078 }
4079 }
4080 if (b->drain_on_flush) {
4081 return;
4082 }
4083 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004084 }
4085
4086 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004087 int64_t offset = b->offset;
4088 /* blk_aio_* might look for completed I/Os and kick bench_cb
4089 * again, so make sure this operation is counted by in_flight
4090 * and b->offset is ready for the next submission.
4091 */
4092 b->in_flight++;
4093 b->offset += b->step;
4094 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004095 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004096 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004097 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004098 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004099 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004100 if (!acb) {
4101 error_report("Failed to issue request");
4102 exit(EXIT_FAILURE);
4103 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004104 }
4105}
4106
4107static int img_bench(int argc, char **argv)
4108{
4109 int c, ret = 0;
4110 const char *fmt = NULL, *filename;
4111 bool quiet = false;
4112 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004113 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004114 int count = 75000;
4115 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004116 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004117 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004118 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004119 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004120 int flush_interval = 0;
4121 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004122 int64_t image_size;
4123 BlockBackend *blk = NULL;
4124 BenchData data = {};
4125 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004126 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004127 struct timeval t1, t2;
4128 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004129 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004130 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004131
4132 for (;;) {
4133 static const struct option long_options[] = {
4134 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004135 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004136 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004137 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004138 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004139 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004140 {0, 0, 0, 0}
4141 };
Fam Zheng335e9932017-05-03 00:35:39 +08004142 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004143 if (c == -1) {
4144 break;
4145 }
4146
4147 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004148 case ':':
4149 missing_argument(argv[optind - 1]);
4150 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004151 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004152 unrecognized_option(argv[optind - 1]);
4153 break;
4154 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004155 help();
4156 break;
4157 case 'c':
4158 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004159 unsigned long res;
4160
4161 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004162 error_report("Invalid request count specified");
4163 return 1;
4164 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004165 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004166 break;
4167 }
4168 case 'd':
4169 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004170 unsigned long res;
4171
4172 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004173 error_report("Invalid queue depth specified");
4174 return 1;
4175 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004176 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004177 break;
4178 }
4179 case 'f':
4180 fmt = optarg;
4181 break;
4182 case 'n':
4183 flags |= BDRV_O_NATIVE_AIO;
4184 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004185 case 'o':
4186 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004187 offset = cvtnum(optarg);
4188 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004189 error_report("Invalid offset specified");
4190 return 1;
4191 }
4192 break;
4193 }
4194 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004195 case 'q':
4196 quiet = true;
4197 break;
4198 case 's':
4199 {
4200 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004201
Markus Armbruster606caa02017-02-21 21:14:04 +01004202 sval = cvtnum(optarg);
4203 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004204 error_report("Invalid buffer size specified");
4205 return 1;
4206 }
4207
4208 bufsize = sval;
4209 break;
4210 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004211 case 'S':
4212 {
4213 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004214
Markus Armbruster606caa02017-02-21 21:14:04 +01004215 sval = cvtnum(optarg);
4216 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004217 error_report("Invalid step size specified");
4218 return 1;
4219 }
4220
4221 step = sval;
4222 break;
4223 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004224 case 't':
4225 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4226 if (ret < 0) {
4227 error_report("Invalid cache mode");
4228 ret = -1;
4229 goto out;
4230 }
4231 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004232 case 'w':
4233 flags |= BDRV_O_RDWR;
4234 is_write = true;
4235 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004236 case 'U':
4237 force_share = true;
4238 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004239 case OPTION_PATTERN:
4240 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004241 unsigned long res;
4242
4243 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004244 error_report("Invalid pattern byte specified");
4245 return 1;
4246 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004247 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004248 break;
4249 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004250 case OPTION_FLUSH_INTERVAL:
4251 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004252 unsigned long res;
4253
4254 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004255 error_report("Invalid flush interval specified");
4256 return 1;
4257 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004258 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004259 break;
4260 }
4261 case OPTION_NO_DRAIN:
4262 drain_on_flush = false;
4263 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004264 case OPTION_IMAGE_OPTS:
4265 image_opts = true;
4266 break;
4267 }
4268 }
4269
4270 if (optind != argc - 1) {
4271 error_exit("Expecting one image file name");
4272 }
4273 filename = argv[argc - 1];
4274
Kevin Wolf55d539c2016-06-03 13:59:41 +02004275 if (!is_write && flush_interval) {
4276 error_report("--flush-interval is only available in write tests");
4277 ret = -1;
4278 goto out;
4279 }
4280 if (flush_interval && flush_interval < depth) {
4281 error_report("Flush interval can't be smaller than depth");
4282 ret = -1;
4283 goto out;
4284 }
4285
Fam Zheng335e9932017-05-03 00:35:39 +08004286 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4287 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004288 if (!blk) {
4289 ret = -1;
4290 goto out;
4291 }
4292
4293 image_size = blk_getlength(blk);
4294 if (image_size < 0) {
4295 ret = image_size;
4296 goto out;
4297 }
4298
4299 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004300 .blk = blk,
4301 .image_size = image_size,
4302 .bufsize = bufsize,
4303 .step = step ?: bufsize,
4304 .nrreq = depth,
4305 .n = count,
4306 .offset = offset,
4307 .write = is_write,
4308 .flush_interval = flush_interval,
4309 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004310 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004311 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004312 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004313 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004314 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004315 if (flush_interval) {
4316 printf("Sending flush every %d requests\n", flush_interval);
4317 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004318
Fam Zheng79d46582018-01-16 14:08:58 +08004319 buf_size = data.nrreq * data.bufsize;
4320 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004321 memset(data.buf, pattern, data.nrreq * data.bufsize);
4322
Fam Zheng79d46582018-01-16 14:08:58 +08004323 blk_register_buf(blk, data.buf, buf_size);
4324
Kevin Wolfb6133b82014-08-05 14:17:13 +02004325 data.qiov = g_new(QEMUIOVector, data.nrreq);
4326 for (i = 0; i < data.nrreq; i++) {
4327 qemu_iovec_init(&data.qiov[i], 1);
4328 qemu_iovec_add(&data.qiov[i],
4329 data.buf + i * data.bufsize, data.bufsize);
4330 }
4331
4332 gettimeofday(&t1, NULL);
4333 bench_cb(&data, 0);
4334
4335 while (data.n > 0) {
4336 main_loop_wait(false);
4337 }
4338 gettimeofday(&t2, NULL);
4339
4340 printf("Run completed in %3.3f seconds.\n",
4341 (t2.tv_sec - t1.tv_sec)
4342 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4343
4344out:
Fam Zheng79d46582018-01-16 14:08:58 +08004345 if (data.buf) {
4346 blk_unregister_buf(blk, data.buf);
4347 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004348 qemu_vfree(data.buf);
4349 blk_unref(blk);
4350
4351 if (ret) {
4352 return 1;
4353 }
4354 return 0;
4355}
4356
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004357#define C_BS 01
4358#define C_COUNT 02
4359#define C_IF 04
4360#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004361#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004362
4363struct DdInfo {
4364 unsigned int flags;
4365 int64_t count;
4366};
4367
4368struct DdIo {
4369 int bsz; /* Block size */
4370 char *filename;
4371 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004372 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004373};
4374
4375struct DdOpts {
4376 const char *name;
4377 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4378 unsigned int flag;
4379};
4380
4381static int img_dd_bs(const char *arg,
4382 struct DdIo *in, struct DdIo *out,
4383 struct DdInfo *dd)
4384{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004385 int64_t res;
4386
Markus Armbruster606caa02017-02-21 21:14:04 +01004387 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004388
Markus Armbruster606caa02017-02-21 21:14:04 +01004389 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004390 error_report("invalid number: '%s'", arg);
4391 return 1;
4392 }
4393 in->bsz = out->bsz = res;
4394
4395 return 0;
4396}
4397
4398static int img_dd_count(const char *arg,
4399 struct DdIo *in, struct DdIo *out,
4400 struct DdInfo *dd)
4401{
Markus Armbruster606caa02017-02-21 21:14:04 +01004402 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004403
Markus Armbruster606caa02017-02-21 21:14:04 +01004404 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004405 error_report("invalid number: '%s'", arg);
4406 return 1;
4407 }
4408
4409 return 0;
4410}
4411
4412static int img_dd_if(const char *arg,
4413 struct DdIo *in, struct DdIo *out,
4414 struct DdInfo *dd)
4415{
4416 in->filename = g_strdup(arg);
4417
4418 return 0;
4419}
4420
4421static int img_dd_of(const char *arg,
4422 struct DdIo *in, struct DdIo *out,
4423 struct DdInfo *dd)
4424{
4425 out->filename = g_strdup(arg);
4426
4427 return 0;
4428}
4429
Reda Sallahif7c15532016-08-10 16:16:09 +02004430static int img_dd_skip(const char *arg,
4431 struct DdIo *in, struct DdIo *out,
4432 struct DdInfo *dd)
4433{
Markus Armbruster606caa02017-02-21 21:14:04 +01004434 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004435
Markus Armbruster606caa02017-02-21 21:14:04 +01004436 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004437 error_report("invalid number: '%s'", arg);
4438 return 1;
4439 }
4440
4441 return 0;
4442}
4443
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004444static int img_dd(int argc, char **argv)
4445{
4446 int ret = 0;
4447 char *arg = NULL;
4448 char *tmp;
4449 BlockDriver *drv = NULL, *proto_drv = NULL;
4450 BlockBackend *blk1 = NULL, *blk2 = NULL;
4451 QemuOpts *opts = NULL;
4452 QemuOptsList *create_opts = NULL;
4453 Error *local_err = NULL;
4454 bool image_opts = false;
4455 int c, i;
4456 const char *out_fmt = "raw";
4457 const char *fmt = NULL;
4458 int64_t size = 0;
4459 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004460 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004461 struct DdInfo dd = {
4462 .flags = 0,
4463 .count = 0,
4464 };
4465 struct DdIo in = {
4466 .bsz = 512, /* Block size is by default 512 bytes */
4467 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004468 .buf = NULL,
4469 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004470 };
4471 struct DdIo out = {
4472 .bsz = 512,
4473 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004474 .buf = NULL,
4475 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004476 };
4477
4478 const struct DdOpts options[] = {
4479 { "bs", img_dd_bs, C_BS },
4480 { "count", img_dd_count, C_COUNT },
4481 { "if", img_dd_if, C_IF },
4482 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004483 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004484 { NULL, NULL, 0 }
4485 };
4486 const struct option long_options[] = {
4487 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004488 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004489 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004490 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004491 { 0, 0, 0, 0 }
4492 };
4493
Fam Zheng335e9932017-05-03 00:35:39 +08004494 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004495 if (c == EOF) {
4496 break;
4497 }
4498 switch (c) {
4499 case 'O':
4500 out_fmt = optarg;
4501 break;
4502 case 'f':
4503 fmt = optarg;
4504 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004505 case ':':
4506 missing_argument(argv[optind - 1]);
4507 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004508 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004509 unrecognized_option(argv[optind - 1]);
4510 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004511 case 'h':
4512 help();
4513 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004514 case 'U':
4515 force_share = true;
4516 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004517 case OPTION_OBJECT:
4518 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004519 ret = -1;
4520 goto out;
4521 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004522 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004523 case OPTION_IMAGE_OPTS:
4524 image_opts = true;
4525 break;
4526 }
4527 }
4528
4529 for (i = optind; i < argc; i++) {
4530 int j;
4531 arg = g_strdup(argv[i]);
4532
4533 tmp = strchr(arg, '=');
4534 if (tmp == NULL) {
4535 error_report("unrecognized operand %s", arg);
4536 ret = -1;
4537 goto out;
4538 }
4539
4540 *tmp++ = '\0';
4541
4542 for (j = 0; options[j].name != NULL; j++) {
4543 if (!strcmp(arg, options[j].name)) {
4544 break;
4545 }
4546 }
4547 if (options[j].name == NULL) {
4548 error_report("unrecognized operand %s", arg);
4549 ret = -1;
4550 goto out;
4551 }
4552
4553 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4554 ret = -1;
4555 goto out;
4556 }
4557 dd.flags |= options[j].flag;
4558 g_free(arg);
4559 arg = NULL;
4560 }
4561
4562 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4563 error_report("Must specify both input and output files");
4564 ret = -1;
4565 goto out;
4566 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004567
4568 if (qemu_opts_foreach(&qemu_object_opts,
4569 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004570 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004571 ret = -1;
4572 goto out;
4573 }
4574
Fam Zheng335e9932017-05-03 00:35:39 +08004575 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4576 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004577
4578 if (!blk1) {
4579 ret = -1;
4580 goto out;
4581 }
4582
4583 drv = bdrv_find_format(out_fmt);
4584 if (!drv) {
4585 error_report("Unknown file format");
4586 ret = -1;
4587 goto out;
4588 }
4589 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4590
4591 if (!proto_drv) {
4592 error_report_err(local_err);
4593 ret = -1;
4594 goto out;
4595 }
4596 if (!drv->create_opts) {
4597 error_report("Format driver '%s' does not support image creation",
4598 drv->format_name);
4599 ret = -1;
4600 goto out;
4601 }
4602 if (!proto_drv->create_opts) {
4603 error_report("Protocol driver '%s' does not support image creation",
4604 proto_drv->format_name);
4605 ret = -1;
4606 goto out;
4607 }
4608 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4609 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4610
4611 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4612
4613 size = blk_getlength(blk1);
4614 if (size < 0) {
4615 error_report("Failed to get size for '%s'", in.filename);
4616 ret = -1;
4617 goto out;
4618 }
4619
4620 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4621 dd.count * in.bsz < size) {
4622 size = dd.count * in.bsz;
4623 }
4624
Reda Sallahif7c15532016-08-10 16:16:09 +02004625 /* Overflow means the specified offset is beyond input image's size */
4626 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4627 size < in.bsz * in.offset)) {
4628 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4629 } else {
4630 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4631 size - in.bsz * in.offset, &error_abort);
4632 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004633
4634 ret = bdrv_create(drv, out.filename, opts, &local_err);
4635 if (ret < 0) {
4636 error_reportf_err(local_err,
4637 "%s: error while creating output image: ",
4638 out.filename);
4639 ret = -1;
4640 goto out;
4641 }
4642
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004643 /* TODO, we can't honour --image-opts for the target,
4644 * since it needs to be given in a format compatible
4645 * with the bdrv_create() call above which does not
4646 * support image-opts style.
4647 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004648 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004649 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004650
4651 if (!blk2) {
4652 ret = -1;
4653 goto out;
4654 }
4655
Reda Sallahif7c15532016-08-10 16:16:09 +02004656 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4657 size < in.offset * in.bsz)) {
4658 /* We give a warning if the skip option is bigger than the input
4659 * size and create an empty output disk image (i.e. like dd(1)).
4660 */
4661 error_report("%s: cannot skip to specified offset", in.filename);
4662 in_pos = size;
4663 } else {
4664 in_pos = in.offset * in.bsz;
4665 }
4666
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004667 in.buf = g_new(uint8_t, in.bsz);
4668
Reda Sallahif7c15532016-08-10 16:16:09 +02004669 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004670 int in_ret, out_ret;
4671
4672 if (in_pos + in.bsz > size) {
4673 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4674 } else {
4675 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4676 }
4677 if (in_ret < 0) {
4678 error_report("error while reading from input image file: %s",
4679 strerror(-in_ret));
4680 ret = -1;
4681 goto out;
4682 }
4683 in_pos += in_ret;
4684
4685 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4686
4687 if (out_ret < 0) {
4688 error_report("error while writing to output image file: %s",
4689 strerror(-out_ret));
4690 ret = -1;
4691 goto out;
4692 }
4693 out_pos += out_ret;
4694 }
4695
4696out:
4697 g_free(arg);
4698 qemu_opts_del(opts);
4699 qemu_opts_free(create_opts);
4700 blk_unref(blk1);
4701 blk_unref(blk2);
4702 g_free(in.filename);
4703 g_free(out.filename);
4704 g_free(in.buf);
4705 g_free(out.buf);
4706
4707 if (ret) {
4708 return 1;
4709 }
4710 return 0;
4711}
4712
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004713static void dump_json_block_measure_info(BlockMeasureInfo *info)
4714{
4715 QString *str;
4716 QObject *obj;
4717 Visitor *v = qobject_output_visitor_new(&obj);
4718
4719 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4720 visit_complete(v, &obj);
4721 str = qobject_to_json_pretty(obj);
4722 assert(str != NULL);
4723 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004724 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004725 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004726 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004727}
4728
4729static int img_measure(int argc, char **argv)
4730{
4731 static const struct option long_options[] = {
4732 {"help", no_argument, 0, 'h'},
4733 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4734 {"object", required_argument, 0, OPTION_OBJECT},
4735 {"output", required_argument, 0, OPTION_OUTPUT},
4736 {"size", required_argument, 0, OPTION_SIZE},
4737 {"force-share", no_argument, 0, 'U'},
4738 {0, 0, 0, 0}
4739 };
4740 OutputFormat output_format = OFORMAT_HUMAN;
4741 BlockBackend *in_blk = NULL;
4742 BlockDriver *drv;
4743 const char *filename = NULL;
4744 const char *fmt = NULL;
4745 const char *out_fmt = "raw";
4746 char *options = NULL;
4747 char *snapshot_name = NULL;
4748 bool force_share = false;
4749 QemuOpts *opts = NULL;
4750 QemuOpts *object_opts = NULL;
4751 QemuOpts *sn_opts = NULL;
4752 QemuOptsList *create_opts = NULL;
4753 bool image_opts = false;
4754 uint64_t img_size = UINT64_MAX;
4755 BlockMeasureInfo *info = NULL;
4756 Error *local_err = NULL;
4757 int ret = 1;
4758 int c;
4759
4760 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4761 long_options, NULL)) != -1) {
4762 switch (c) {
4763 case '?':
4764 case 'h':
4765 help();
4766 break;
4767 case 'f':
4768 fmt = optarg;
4769 break;
4770 case 'O':
4771 out_fmt = optarg;
4772 break;
4773 case 'o':
4774 if (!is_valid_option_list(optarg)) {
4775 error_report("Invalid option list: %s", optarg);
4776 goto out;
4777 }
4778 if (!options) {
4779 options = g_strdup(optarg);
4780 } else {
4781 char *old_options = options;
4782 options = g_strdup_printf("%s,%s", options, optarg);
4783 g_free(old_options);
4784 }
4785 break;
4786 case 'l':
4787 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4788 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4789 optarg, false);
4790 if (!sn_opts) {
4791 error_report("Failed in parsing snapshot param '%s'",
4792 optarg);
4793 goto out;
4794 }
4795 } else {
4796 snapshot_name = optarg;
4797 }
4798 break;
4799 case 'U':
4800 force_share = true;
4801 break;
4802 case OPTION_OBJECT:
4803 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4804 optarg, true);
4805 if (!object_opts) {
4806 goto out;
4807 }
4808 break;
4809 case OPTION_IMAGE_OPTS:
4810 image_opts = true;
4811 break;
4812 case OPTION_OUTPUT:
4813 if (!strcmp(optarg, "json")) {
4814 output_format = OFORMAT_JSON;
4815 } else if (!strcmp(optarg, "human")) {
4816 output_format = OFORMAT_HUMAN;
4817 } else {
4818 error_report("--output must be used with human or json "
4819 "as argument.");
4820 goto out;
4821 }
4822 break;
4823 case OPTION_SIZE:
4824 {
4825 int64_t sval;
4826
4827 sval = cvtnum(optarg);
4828 if (sval < 0) {
4829 if (sval == -ERANGE) {
4830 error_report("Image size must be less than 8 EiB!");
4831 } else {
4832 error_report("Invalid image size specified! You may use "
4833 "k, M, G, T, P or E suffixes for ");
4834 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4835 "petabytes and exabytes.");
4836 }
4837 goto out;
4838 }
4839 img_size = (uint64_t)sval;
4840 }
4841 break;
4842 }
4843 }
4844
4845 if (qemu_opts_foreach(&qemu_object_opts,
4846 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004847 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004848 goto out;
4849 }
4850
4851 if (argc - optind > 1) {
4852 error_report("At most one filename argument is allowed.");
4853 goto out;
4854 } else if (argc - optind == 1) {
4855 filename = argv[optind];
4856 }
4857
4858 if (!filename &&
4859 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4860 error_report("--object, --image-opts, -f, and -l "
4861 "require a filename argument.");
4862 goto out;
4863 }
4864 if (filename && img_size != UINT64_MAX) {
4865 error_report("--size N cannot be used together with a filename.");
4866 goto out;
4867 }
4868 if (!filename && img_size == UINT64_MAX) {
4869 error_report("Either --size N or one filename must be specified.");
4870 goto out;
4871 }
4872
4873 if (filename) {
4874 in_blk = img_open(image_opts, filename, fmt, 0,
4875 false, false, force_share);
4876 if (!in_blk) {
4877 goto out;
4878 }
4879
4880 if (sn_opts) {
4881 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4882 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4883 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4884 &local_err);
4885 } else if (snapshot_name != NULL) {
4886 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4887 snapshot_name, &local_err);
4888 }
4889 if (local_err) {
4890 error_reportf_err(local_err, "Failed to load snapshot: ");
4891 goto out;
4892 }
4893 }
4894
4895 drv = bdrv_find_format(out_fmt);
4896 if (!drv) {
4897 error_report("Unknown file format '%s'", out_fmt);
4898 goto out;
4899 }
4900 if (!drv->create_opts) {
4901 error_report("Format driver '%s' does not support image creation",
4902 drv->format_name);
4903 goto out;
4904 }
4905
4906 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4907 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4908 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4909 if (options) {
4910 qemu_opts_do_parse(opts, options, NULL, &local_err);
4911 if (local_err) {
4912 error_report_err(local_err);
4913 error_report("Invalid options for file format '%s'", out_fmt);
4914 goto out;
4915 }
4916 }
4917 if (img_size != UINT64_MAX) {
4918 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4919 }
4920
4921 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4922 if (local_err) {
4923 error_report_err(local_err);
4924 goto out;
4925 }
4926
4927 if (output_format == OFORMAT_HUMAN) {
4928 printf("required size: %" PRIu64 "\n", info->required);
4929 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4930 } else {
4931 dump_json_block_measure_info(info);
4932 }
4933
4934 ret = 0;
4935
4936out:
4937 qapi_free_BlockMeasureInfo(info);
4938 qemu_opts_del(object_opts);
4939 qemu_opts_del(opts);
4940 qemu_opts_del(sn_opts);
4941 qemu_opts_free(create_opts);
4942 g_free(options);
4943 blk_unref(in_blk);
4944 return ret;
4945}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004946
Anthony Liguoric227f092009-10-01 16:12:16 -05004947static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004948#define DEF(option, callback, arg_string) \
4949 { option, callback },
4950#include "qemu-img-cmds.h"
4951#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004952 { NULL, NULL, },
4953};
4954
bellardea2384d2004-08-01 21:59:26 +00004955int main(int argc, char **argv)
4956{
Anthony Liguoric227f092009-10-01 16:12:16 -05004957 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004958 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004959 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004960 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004961 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004962 static const struct option long_options[] = {
4963 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004964 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004965 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004966 {0, 0, 0, 0}
4967 };
bellardea2384d2004-08-01 21:59:26 +00004968
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004969#ifdef CONFIG_POSIX
4970 signal(SIGPIPE, SIG_IGN);
4971#endif
4972
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01004973 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004974 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004975 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004976
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004977 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004978 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004979 exit(EXIT_FAILURE);
4980 }
4981
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004982 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004983
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004984 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004985 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004986 if (argc < 2) {
4987 error_exit("Not enough arguments");
4988 }
Stuart Brady153859b2009-06-07 00:42:17 +01004989
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004990 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004991 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004992 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004993
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004994 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004995 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004996 case ':':
4997 missing_argument(argv[optind - 1]);
4998 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004999 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005000 unrecognized_option(argv[optind - 1]);
5001 return 0;
5002 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005003 help();
5004 return 0;
5005 case 'V':
5006 printf(QEMU_IMG_VERSION);
5007 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005008 case 'T':
5009 g_free(trace_file);
5010 trace_file = trace_opt_parse(optarg);
5011 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005012 }
bellardea2384d2004-08-01 21:59:26 +00005013 }
Stuart Brady153859b2009-06-07 00:42:17 +01005014
Denis V. Lunev10985132016-06-17 17:44:13 +03005015 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005016
Denis V. Lunev10985132016-06-17 17:44:13 +03005017 /* reset getopt_long scanning */
5018 argc -= optind;
5019 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005020 return 0;
5021 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005022 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005023 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005024
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005025 if (!trace_init_backends()) {
5026 exit(1);
5027 }
5028 trace_init_file(trace_file);
5029 qemu_set_log(LOG_TRACE);
5030
Denis V. Lunev10985132016-06-17 17:44:13 +03005031 /* find the command */
5032 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5033 if (!strcmp(cmdname, cmd->name)) {
5034 return cmd->handler(argc, argv);
5035 }
5036 }
Jeff Cody7db16892014-04-25 17:02:32 -04005037
Stuart Brady153859b2009-06-07 00:42:17 +01005038 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005039 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005040}