blob: 384c6f38bc6250ce3afd9acbe1392399d491d7b7 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Markus Armbrustera8d25322019-05-23 16:35:08 +020028#include "qemu-common.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080029#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010030#include "qapi/error.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010031#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010032#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010033#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010034#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010035#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020036#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000037#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010038#include "qemu/option.h"
39#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030040#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020041#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020042#include "qemu/module.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020043#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000044#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020045#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010046#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020047#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080048#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010049#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030050#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000051
Thomas Huth7e563bf2018-02-15 12:06:47 +010052#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020053 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040054
Anthony Liguoric227f092009-10-01 16:12:16 -050055typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010056 const char *name;
57 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050058} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010059
Federico Simoncelli8599ea42013-01-28 06:59:47 -050060enum {
61 OPTION_OUTPUT = 256,
62 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000063 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000064 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020065 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020066 OPTION_FLUSH_INTERVAL = 261,
67 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010068 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010069 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020070 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030071 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020072 OPTION_SALVAGE = 267,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050073};
74
75typedef enum OutputFormat {
76 OFORMAT_JSON,
77 OFORMAT_HUMAN,
78} OutputFormat;
79
Kevin Wolfe6996142016-03-15 13:03:11 +010080/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040081#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000082
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010083static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000084{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010085 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000086}
87
Fam Zhengac1307a2014-04-22 13:36:11 +080088static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
89{
90 va_list ap;
91
Fam Zhengac1307a2014-04-22 13:36:11 +080092 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +020093 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +080094 va_end(ap);
95
Markus Armbrustere9e1d922019-04-17 21:06:27 +020096 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +080097 exit(EXIT_FAILURE);
98}
99
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800100static void QEMU_NORETURN missing_argument(const char *option)
101{
102 error_exit("missing argument for option '%s'", option);
103}
104
105static void QEMU_NORETURN unrecognized_option(const char *option)
106{
107 error_exit("unrecognized option '%s'", option);
108}
109
blueswir1d2c639d2009-01-24 18:19:25 +0000110/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800111static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000112{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100113 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400114 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300115 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300116 "QEMU disk image utility\n"
117 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300118 " '-h', '--help' display this help and exit\n"
119 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300120 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
121 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300122 "\n"
malc3f020d72010-02-08 12:04:56 +0300123 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100124#define DEF(option, callback, arg_string) \
125 " " arg_string "\n"
126#include "qemu-img-cmds.h"
127#undef DEF
malc3f020d72010-02-08 12:04:56 +0300128 "\n"
129 "Command parameters:\n"
130 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000131 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
132 " manual page for a description of the object properties. The most common\n"
133 " object type is a 'secret', which is used to supply passwords and/or\n"
134 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300135 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400136 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800137 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
138 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100139 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
140 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300141 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200142 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
143 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
144 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300145 " 'output_filename' is the destination disk image filename\n"
146 " 'output_fmt' is the destination format\n"
147 " 'options' is a comma separated list of format specific options in a\n"
148 " name=value format. Use -o ? for an overview of the options supported by the\n"
149 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800150 " 'snapshot_param' is param used for internal snapshot, format\n"
151 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
152 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300153 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300159 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200160 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100161 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
166 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200167 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300170 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200175 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200176 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
181 "\n"
malc3f020d72010-02-08 12:04:56 +0300182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100187 " '-l' lists all snapshots in the given image\n"
188 "\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
193 "\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
196 "(default: 512)\n"
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100201
202 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300203 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500204 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800205 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000206}
207
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000208static QemuOptsList qemu_object_opts = {
209 .name = "object",
210 .implied_opt_name = "qom-type",
211 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
212 .desc = {
213 { }
214 },
215};
216
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000217static QemuOptsList qemu_source_opts = {
218 .name = "source",
219 .implied_opt_name = "file",
220 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
221 .desc = {
222 { }
223 },
224};
225
Stefan Weil7c30f652013-06-16 17:01:05 +0200226static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100227{
228 int ret = 0;
229 if (!quiet) {
230 va_list args;
231 va_start(args, fmt);
232 ret = vprintf(fmt, args);
233 va_end(args);
234 }
235 return ret;
236}
237
bellardea2384d2004-08-01 21:59:26 +0000238
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100239static int print_block_option_help(const char *filename, const char *fmt)
240{
241 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800242 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500243 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100244
245 /* Find driver and parse its options */
246 drv = bdrv_find_format(fmt);
247 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100248 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100249 return 1;
250 }
251
Max Reitzd402b6a2018-05-09 23:00:21 +0200252 if (!drv->create_opts) {
253 error_report("Format driver '%s' does not support image creation", fmt);
254 return 1;
255 }
256
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800257 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100258 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500259 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100260 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100261 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800262 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100263 return 1;
264 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200265 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100266 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200267 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100268 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200269 return 1;
270 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800271 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100272 }
273
Max Reitzf4619af2019-04-13 17:20:37 +0200274 if (filename) {
275 printf("Supported options:\n");
276 } else {
277 printf("Supported %s options:\n", fmt);
278 }
Max Reitz63898712018-10-19 18:49:25 +0200279 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800280 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200281
282 if (!filename) {
283 printf("\n"
284 "The protocol level may support further options.\n"
285 "Specify the target filename to include those options.\n");
286 }
287
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100288 return 0;
289}
290
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000291
Max Reitzefaa7c42016-03-16 19:54:38 +0100292static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100293 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800294 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000295{
296 QDict *options;
297 Error *local_err = NULL;
298 BlockBackend *blk;
299 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800300 if (force_share) {
301 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200302 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800303 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200304 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800305 return NULL;
306 }
Max Reitz4615f872018-05-02 22:20:50 +0200307 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800308 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100309 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000310 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100311 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000312 return NULL;
313 }
Kevin Wolfce099542016-03-15 13:01:04 +0100314 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000315
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000316 return blk;
317}
318
Max Reitzefaa7c42016-03-16 19:54:38 +0100319static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100320 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000321 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800322 bool writethrough, bool quiet,
323 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000324{
325 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200326 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100327
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100328 if (!options) {
329 options = qdict_new();
330 }
bellard75c23802004-08-27 21:28:58 +0000331 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500332 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000333 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100334
Fam Zheng335e9932017-05-03 00:35:39 +0800335 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500336 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800337 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100338 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500339 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100340 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000341 return NULL;
bellard75c23802004-08-27 21:28:58 +0000342 }
Kevin Wolfce099542016-03-15 13:01:04 +0100343 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100344
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200345 return blk;
bellard75c23802004-08-27 21:28:58 +0000346}
347
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000348
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100349static int img_add_key_secrets(void *opaque,
350 const char *name, const char *value,
351 Error **errp)
352{
353 QDict *options = opaque;
354
355 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600356 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100357 }
358
359 return 0;
360}
361
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100362
Max Reitzefaa7c42016-03-16 19:54:38 +0100363static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000364 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100365 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800366 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000367{
368 BlockBackend *blk;
369 if (image_opts) {
370 QemuOpts *opts;
371 if (fmt) {
372 error_report("--image-opts and --format are mutually exclusive");
373 return NULL;
374 }
375 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
376 filename, true);
377 if (!opts) {
378 return NULL;
379 }
Fam Zheng335e9932017-05-03 00:35:39 +0800380 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
381 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000382 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100383 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800384 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000385 }
386 return blk;
387}
388
389
Chunyan Liu83d05212014-06-05 17:20:51 +0800390static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100391 const char *base_filename,
392 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200393{
Markus Armbruster6750e792015-02-12 17:43:08 +0100394 Error *err = NULL;
395
Kevin Wolfefa84d42009-05-18 16:42:12 +0200396 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100397 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100398 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100399 error_report("Backing file not supported for file format '%s'",
400 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100401 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900402 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200403 }
404 }
405 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100406 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100407 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100408 error_report("Backing file format not supported for file "
409 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100410 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900411 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200412 }
413 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900414 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200415}
416
Markus Armbruster606caa02017-02-21 21:14:04 +0100417static int64_t cvtnum(const char *s)
418{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100419 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100420 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100421
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100422 err = qemu_strtosz(s, NULL, &value);
423 if (err < 0) {
424 return err;
425 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100426 if (value > INT64_MAX) {
427 return -ERANGE;
428 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100429 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100430}
431
bellardea2384d2004-08-01 21:59:26 +0000432static int img_create(int argc, char **argv)
433{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200434 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100435 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000436 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000437 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000438 const char *filename;
439 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200440 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200441 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100442 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400443 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000444
bellardea2384d2004-08-01 21:59:26 +0000445 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000446 static const struct option long_options[] = {
447 {"help", no_argument, 0, 'h'},
448 {"object", required_argument, 0, OPTION_OBJECT},
449 {0, 0, 0, 0}
450 };
John Snow6e6e55f2017-07-17 20:34:22 -0400451 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000452 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100453 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000454 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100455 }
bellardea2384d2004-08-01 21:59:26 +0000456 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800457 case ':':
458 missing_argument(argv[optind - 1]);
459 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100460 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800461 unrecognized_option(argv[optind - 1]);
462 break;
bellardea2384d2004-08-01 21:59:26 +0000463 case 'h':
464 help();
465 break;
aliguori9230eaf2009-03-28 17:55:19 +0000466 case 'F':
467 base_fmt = optarg;
468 break;
bellardea2384d2004-08-01 21:59:26 +0000469 case 'b':
470 base_filename = optarg;
471 break;
472 case 'f':
473 fmt = optarg;
474 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200475 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100476 if (!is_valid_option_list(optarg)) {
477 error_report("Invalid option list: %s", optarg);
478 goto fail;
479 }
480 if (!options) {
481 options = g_strdup(optarg);
482 } else {
483 char *old_options = options;
484 options = g_strdup_printf("%s,%s", options, optarg);
485 g_free(old_options);
486 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200487 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100488 case 'q':
489 quiet = true;
490 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400491 case 'u':
492 flags |= BDRV_O_NO_BACKING;
493 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000494 case OPTION_OBJECT: {
495 QemuOpts *opts;
496 opts = qemu_opts_parse_noisily(&qemu_object_opts,
497 optarg, true);
498 if (!opts) {
499 goto fail;
500 }
501 } break;
bellardea2384d2004-08-01 21:59:26 +0000502 }
503 }
aliguori9230eaf2009-03-28 17:55:19 +0000504
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900505 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100506 filename = (optind < argc) ? argv[optind] : NULL;
507 if (options && has_help_option(options)) {
508 g_free(options);
509 return print_block_option_help(filename, fmt);
510 }
511
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100512 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800513 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100514 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100515 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900516
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000517 if (qemu_opts_foreach(&qemu_object_opts,
518 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000519 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000520 goto fail;
521 }
522
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100523 /* Get image size, if specified */
524 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100525 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100526
527 sval = cvtnum(argv[optind++]);
528 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800529 if (sval == -ERANGE) {
530 error_report("Image size must be less than 8 EiB!");
531 } else {
532 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200533 "G, T, P or E suffixes for ");
534 error_report("kilobytes, megabytes, gigabytes, terabytes, "
535 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800536 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100537 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100538 }
539 img_size = (uint64_t)sval;
540 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200541 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800542 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200543 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100544
Luiz Capitulino9b375252012-11-30 10:52:05 -0200545 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400546 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100547 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100548 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100549 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900550 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200551
Kevin Wolf77386bf2014-02-21 16:24:04 +0100552 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000553 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100554
555fail:
556 g_free(options);
557 return 1;
bellardea2384d2004-08-01 21:59:26 +0000558}
559
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100560static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500561{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500562 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500563 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100564 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600565
566 visit_type_ImageCheck(v, NULL, &check, &error_abort);
567 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500568 str = qobject_to_json_pretty(obj);
569 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100570 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200571 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600572 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200573 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500574}
575
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100576static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500577{
578 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100579 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500580 } else {
581 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100582 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
583 "Data may be corrupted, or further writes to the image "
584 "may corrupt it.\n",
585 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500586 }
587
588 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100589 qprintf(quiet,
590 "\n%" PRId64 " leaked clusters were found on the image.\n"
591 "This means waste of disk space, but no harm to data.\n",
592 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500593 }
594
595 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100596 qprintf(quiet,
597 "\n%" PRId64
598 " internal errors have occurred during the check.\n",
599 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500600 }
601 }
602
603 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100604 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
605 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
606 check->allocated_clusters, check->total_clusters,
607 check->allocated_clusters * 100.0 / check->total_clusters,
608 check->fragmented_clusters * 100.0 / check->allocated_clusters,
609 check->compressed_clusters * 100.0 /
610 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500611 }
612
613 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100614 qprintf(quiet,
615 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500616 }
617}
618
619static int collect_image_check(BlockDriverState *bs,
620 ImageCheck *check,
621 const char *filename,
622 const char *fmt,
623 int fix)
624{
625 int ret;
626 BdrvCheckResult result;
627
628 ret = bdrv_check(bs, &result, fix);
629 if (ret < 0) {
630 return ret;
631 }
632
633 check->filename = g_strdup(filename);
634 check->format = g_strdup(bdrv_get_format_name(bs));
635 check->check_errors = result.check_errors;
636 check->corruptions = result.corruptions;
637 check->has_corruptions = result.corruptions != 0;
638 check->leaks = result.leaks;
639 check->has_leaks = result.leaks != 0;
640 check->corruptions_fixed = result.corruptions_fixed;
641 check->has_corruptions_fixed = result.corruptions != 0;
642 check->leaks_fixed = result.leaks_fixed;
643 check->has_leaks_fixed = result.leaks != 0;
644 check->image_end_offset = result.image_end_offset;
645 check->has_image_end_offset = result.image_end_offset != 0;
646 check->total_clusters = result.bfi.total_clusters;
647 check->has_total_clusters = result.bfi.total_clusters != 0;
648 check->allocated_clusters = result.bfi.allocated_clusters;
649 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
650 check->fragmented_clusters = result.bfi.fragmented_clusters;
651 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100652 check->compressed_clusters = result.bfi.compressed_clusters;
653 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500654
655 return 0;
656}
657
Kevin Wolfe076f332010-06-29 11:43:13 +0200658/*
659 * Checks an image for consistency. Exit codes:
660 *
Max Reitzd6635c42014-06-02 22:15:21 +0200661 * 0 - Check completed, image is good
662 * 1 - Check not completed because of internal errors
663 * 2 - Check completed, image is corrupted
664 * 3 - Check completed, image has leaked clusters, but is good otherwise
665 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200666 */
aliguori15859692009-04-21 23:11:53 +0000667static int img_check(int argc, char **argv)
668{
669 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500670 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200671 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200672 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000673 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200674 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100675 int flags = BDRV_O_CHECK;
676 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200677 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100678 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000679 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800680 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000681
682 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500683 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200684 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100685
aliguori15859692009-04-21 23:11:53 +0000686 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500687 int option_index = 0;
688 static const struct option long_options[] = {
689 {"help", no_argument, 0, 'h'},
690 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530691 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500692 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000693 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000694 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800695 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500696 {0, 0, 0, 0}
697 };
Fam Zheng335e9932017-05-03 00:35:39 +0800698 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500699 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100700 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000701 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100702 }
aliguori15859692009-04-21 23:11:53 +0000703 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800704 case ':':
705 missing_argument(argv[optind - 1]);
706 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100707 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800708 unrecognized_option(argv[optind - 1]);
709 break;
aliguori15859692009-04-21 23:11:53 +0000710 case 'h':
711 help();
712 break;
713 case 'f':
714 fmt = optarg;
715 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200716 case 'r':
717 flags |= BDRV_O_RDWR;
718
719 if (!strcmp(optarg, "leaks")) {
720 fix = BDRV_FIX_LEAKS;
721 } else if (!strcmp(optarg, "all")) {
722 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
723 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800724 error_exit("Unknown option value for -r "
725 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200726 }
727 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500728 case OPTION_OUTPUT:
729 output = optarg;
730 break;
Max Reitz40055952014-07-22 22:58:42 +0200731 case 'T':
732 cache = optarg;
733 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100734 case 'q':
735 quiet = true;
736 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800737 case 'U':
738 force_share = true;
739 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000740 case OPTION_OBJECT: {
741 QemuOpts *opts;
742 opts = qemu_opts_parse_noisily(&qemu_object_opts,
743 optarg, true);
744 if (!opts) {
745 return 1;
746 }
747 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000748 case OPTION_IMAGE_OPTS:
749 image_opts = true;
750 break;
aliguori15859692009-04-21 23:11:53 +0000751 }
752 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200753 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800754 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100755 }
aliguori15859692009-04-21 23:11:53 +0000756 filename = argv[optind++];
757
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500758 if (output && !strcmp(output, "json")) {
759 output_format = OFORMAT_JSON;
760 } else if (output && !strcmp(output, "human")) {
761 output_format = OFORMAT_HUMAN;
762 } else if (output) {
763 error_report("--output must be used with human or json as argument.");
764 return 1;
765 }
766
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000767 if (qemu_opts_foreach(&qemu_object_opts,
768 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000769 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000770 return 1;
771 }
772
Kevin Wolfce099542016-03-15 13:01:04 +0100773 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200774 if (ret < 0) {
775 error_report("Invalid source cache option: %s", cache);
776 return 1;
777 }
778
Fam Zheng335e9932017-05-03 00:35:39 +0800779 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
780 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200781 if (!blk) {
782 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900783 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200784 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500785
786 check = g_new0(ImageCheck, 1);
787 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200788
789 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200790 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200791 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500792 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200793 }
794
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500795 if (check->corruptions_fixed || check->leaks_fixed) {
796 int corruptions_fixed, leaks_fixed;
797
798 leaks_fixed = check->leaks_fixed;
799 corruptions_fixed = check->corruptions_fixed;
800
801 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100802 qprintf(quiet,
803 "The following inconsistencies were found and repaired:\n\n"
804 " %" PRId64 " leaked clusters\n"
805 " %" PRId64 " corruptions\n\n"
806 "Double checking the fixed image now...\n",
807 check->leaks_fixed,
808 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500809 }
810
811 ret = collect_image_check(bs, check, filename, fmt, 0);
812
813 check->leaks_fixed = leaks_fixed;
814 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200815 }
816
Max Reitz832390a2014-10-23 15:29:12 +0200817 if (!ret) {
818 switch (output_format) {
819 case OFORMAT_HUMAN:
820 dump_human_image_check(check, quiet);
821 break;
822 case OFORMAT_JSON:
823 dump_json_image_check(check, quiet);
824 break;
825 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500826 }
827
828 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200829 if (ret) {
830 error_report("Check failed: %s", strerror(-ret));
831 } else {
832 error_report("Check failed");
833 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500834 ret = 1;
835 goto fail;
836 }
837
838 if (check->corruptions) {
839 ret = 2;
840 } else if (check->leaks) {
841 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200842 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500843 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000844 }
845
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500846fail:
847 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200848 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500849 return ret;
aliguori15859692009-04-21 23:11:53 +0000850}
851
Max Reitzd4a32382014-10-24 15:57:37 +0200852typedef struct CommonBlockJobCBInfo {
853 BlockDriverState *bs;
854 Error **errp;
855} CommonBlockJobCBInfo;
856
857static void common_block_job_cb(void *opaque, int ret)
858{
859 CommonBlockJobCBInfo *cbi = opaque;
860
861 if (ret < 0) {
862 error_setg_errno(cbi->errp, -ret, "Block job failed");
863 }
Max Reitzd4a32382014-10-24 15:57:37 +0200864}
865
866static void run_block_job(BlockJob *job, Error **errp)
867{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200868 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800869 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200870
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200871 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200872 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200873 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200874 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200875 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200876 if (job->job.progress_total) {
877 progress = (float)job->job.progress_current /
878 job->job.progress_total * 100.f;
879 }
880 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200881 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200882
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200883 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200884 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800885 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200886 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800887 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200888 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200889 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200890
sochin.jiang4172a002017-06-15 14:47:33 +0800891 /* publish completion progress only when success */
892 if (!ret) {
893 qemu_progress_print(100.f, 0);
894 }
Max Reitzd4a32382014-10-24 15:57:37 +0200895}
896
bellardea2384d2004-08-01 21:59:26 +0000897static int img_commit(int argc, char **argv)
898{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400899 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200900 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200901 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200902 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100903 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200904 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100905 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200906 Error *local_err = NULL;
907 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000908 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200909 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000910
911 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400912 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200913 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000914 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000915 static const struct option long_options[] = {
916 {"help", no_argument, 0, 'h'},
917 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000918 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000919 {0, 0, 0, 0}
920 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800921 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000922 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100923 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000924 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100925 }
bellardea2384d2004-08-01 21:59:26 +0000926 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800927 case ':':
928 missing_argument(argv[optind - 1]);
929 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100930 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800931 unrecognized_option(argv[optind - 1]);
932 break;
bellardea2384d2004-08-01 21:59:26 +0000933 case 'h':
934 help();
935 break;
936 case 'f':
937 fmt = optarg;
938 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400939 case 't':
940 cache = optarg;
941 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200942 case 'b':
943 base = optarg;
944 /* -b implies -d */
945 drop = true;
946 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200947 case 'd':
948 drop = true;
949 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200950 case 'p':
951 progress = true;
952 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100953 case 'q':
954 quiet = true;
955 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000956 case OPTION_OBJECT: {
957 QemuOpts *opts;
958 opts = qemu_opts_parse_noisily(&qemu_object_opts,
959 optarg, true);
960 if (!opts) {
961 return 1;
962 }
963 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000964 case OPTION_IMAGE_OPTS:
965 image_opts = true;
966 break;
bellardea2384d2004-08-01 21:59:26 +0000967 }
968 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200969
970 /* Progress is not shown in Quiet mode */
971 if (quiet) {
972 progress = false;
973 }
974
Kevin Wolffc11eb22013-08-05 10:53:04 +0200975 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800976 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100977 }
bellardea2384d2004-08-01 21:59:26 +0000978 filename = argv[optind++];
979
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000980 if (qemu_opts_foreach(&qemu_object_opts,
981 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000982 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000983 return 1;
984 }
985
Max Reitz9a86fe42014-10-24 15:57:38 +0200986 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100987 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400988 if (ret < 0) {
989 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100990 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400991 }
992
Fam Zheng335e9932017-05-03 00:35:39 +0800993 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
994 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200995 if (!blk) {
996 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900997 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200998 bs = blk_bs(blk);
999
Max Reitz687fa1d2014-10-24 15:57:39 +02001000 qemu_progress_init(progress, 1.f);
1001 qemu_progress_print(0.f, 100);
1002
Max Reitz1b22bff2014-10-24 15:57:40 +02001003 if (base) {
1004 base_bs = bdrv_find_backing_image(bs, base);
1005 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001006 error_setg(&local_err,
1007 "Did not find '%s' in the backing chain of '%s'",
1008 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001009 goto done;
1010 }
1011 } else {
1012 /* This is different from QMP, which by default uses the deepest file in
1013 * the backing chain (i.e., the very base); however, the traditional
1014 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001015 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001016 if (!base_bs) {
1017 error_setg(&local_err, "Image does not have a backing file");
1018 goto done;
1019 }
bellardea2384d2004-08-01 21:59:26 +00001020 }
1021
Max Reitzd4a32382014-10-24 15:57:37 +02001022 cbi = (CommonBlockJobCBInfo){
1023 .errp = &local_err,
1024 .bs = bs,
1025 };
1026
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001027 aio_context = bdrv_get_aio_context(bs);
1028 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001029 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001030 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001031 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001032 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001033 if (local_err) {
1034 goto done;
1035 }
1036
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001037 /* When the block job completes, the BlockBackend reference will point to
1038 * the old backing file. In order to avoid that the top image is already
1039 * deleted, so we can still empty it afterwards, increment the reference
1040 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001041 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001042 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001043 }
1044
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001045 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001046 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001047 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001048 if (local_err) {
1049 goto unref_backing;
1050 }
1051
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001052 if (!drop && bs->drv->bdrv_make_empty) {
1053 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001054 if (ret) {
1055 error_setg_errno(&local_err, -ret, "Could not empty %s",
1056 filename);
1057 goto unref_backing;
1058 }
1059 }
1060
1061unref_backing:
1062 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001063 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001064 }
Max Reitzd4a32382014-10-24 15:57:37 +02001065
1066done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001067 qemu_progress_end();
1068
Markus Armbruster26f54e92014-10-07 13:59:04 +02001069 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001070
1071 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001072 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001073 return 1;
1074 }
Max Reitzd4a32382014-10-24 15:57:37 +02001075
1076 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001077 return 0;
1078}
1079
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001080/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001081 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1082 * of the first sector boundary within buf where the sector contains a
1083 * non-zero byte. This function is robust to a buffer that is not
1084 * sector-aligned.
1085 */
1086static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1087{
1088 int64_t i;
1089 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1090
1091 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1092 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1093 return i;
1094 }
1095 }
1096 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1097 return i;
1098 }
1099 return -1;
1100}
1101
1102/*
thsf58c7b32008-06-05 21:53:49 +00001103 * Returns true iff the first sector pointed to by 'buf' contains at least
1104 * a non-NUL byte.
1105 *
1106 * 'pnum' is set to the number of sectors (including and immediately following
1107 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001108 * The function will try to align the end offset to alignment boundaries so
1109 * that the request will at least end aligned and consequtive requests will
1110 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001111 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001112static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1113 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001114{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001115 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001116 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001117
1118 if (n <= 0) {
1119 *pnum = 0;
1120 return 0;
1121 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001122 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001123 for(i = 1; i < n; i++) {
1124 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001125 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001126 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001127 }
bellardea2384d2004-08-01 21:59:26 +00001128 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001129
1130 tail = (sector_num + i) & (alignment - 1);
1131 if (tail) {
1132 if (is_zero && i <= tail) {
1133 /* treat unallocated areas which only consist
1134 * of a small tail as allocated. */
1135 is_zero = false;
1136 }
1137 if (!is_zero) {
1138 /* align up end offset of allocated areas. */
1139 i += alignment - tail;
1140 i = MIN(i, n);
1141 } else {
1142 /* align down end offset of zero areas. */
1143 i -= tail;
1144 }
1145 }
bellardea2384d2004-08-01 21:59:26 +00001146 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001147 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001148}
1149
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001150/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001151 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1152 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1153 * breaking up write requests for only small sparse areas.
1154 */
1155static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001156 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001157{
1158 int ret;
1159 int num_checked, num_used;
1160
1161 if (n < min) {
1162 min = n;
1163 }
1164
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001165 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001166 if (!ret) {
1167 return ret;
1168 }
1169
1170 num_used = *pnum;
1171 buf += BDRV_SECTOR_SIZE * *pnum;
1172 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001173 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001174 num_checked = num_used;
1175
1176 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001177 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001178
1179 buf += BDRV_SECTOR_SIZE * *pnum;
1180 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001181 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001182 num_checked += *pnum;
1183 if (ret) {
1184 num_used = num_checked;
1185 } else if (*pnum >= min) {
1186 break;
1187 }
1188 }
1189
1190 *pnum = num_used;
1191 return 1;
1192}
1193
1194/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001195 * Compares two buffers sector by sector. Returns 0 if the first
1196 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001197 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001198 * pnum is set to the sector-aligned size of the buffer prefix that
1199 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001200 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001201static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1202 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001203{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001204 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001205 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001206
Eric Blakedc61cd32017-10-11 22:47:14 -05001207 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001208
Eric Blakedc61cd32017-10-11 22:47:14 -05001209 res = !!memcmp(buf1, buf2, i);
1210 while (i < bytes) {
1211 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001212
Eric Blakedc61cd32017-10-11 22:47:14 -05001213 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001214 break;
1215 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001216 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001217 }
1218
1219 *pnum = i;
1220 return res;
1221}
1222
Stefano Garzarella97ede572019-05-08 12:43:24 +02001223#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001224
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001225/*
1226 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1227 *
Eric Blake0608e402017-10-11 22:47:12 -05001228 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1229 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1230 * failure), and 4 on error (the exit status for read errors), after emitting
1231 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001232 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001233 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001234 * @param offset: Starting offset to check
1235 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001236 * @param filename: Name of disk file we are checking (logging purpose)
1237 * @param buffer: Allocated buffer for storing read data
1238 * @param quiet: Flag for quiet mode
1239 */
Eric Blakec41508e2017-10-11 22:47:13 -05001240static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1241 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001242 uint8_t *buffer, bool quiet)
1243{
Eric Blakedebb38a2017-10-11 22:47:11 -05001244 int ret = 0;
1245 int64_t idx;
1246
Eric Blakec41508e2017-10-11 22:47:13 -05001247 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001248 if (ret < 0) {
1249 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001250 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001251 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001252 }
Eric Blakec41508e2017-10-11 22:47:13 -05001253 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001254 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001255 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001256 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001257 return 1;
1258 }
1259
1260 return 0;
1261}
1262
1263/*
1264 * Compares two images. Exit codes:
1265 *
1266 * 0 - Images are identical
1267 * 1 - Images differ
1268 * >1 - Error occurred
1269 */
1270static int img_compare(int argc, char **argv)
1271{
Max Reitz40055952014-07-22 22:58:42 +02001272 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001273 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001274 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001275 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001276 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001277 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001278 int allocated1, allocated2;
1279 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1280 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001281 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001282 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001283 int64_t total_size;
1284 int64_t offset = 0;
1285 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001286 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001288 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001289 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001290
Max Reitz40055952014-07-22 22:58:42 +02001291 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001292 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001293 static const struct option long_options[] = {
1294 {"help", no_argument, 0, 'h'},
1295 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001296 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001297 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001298 {0, 0, 0, 0}
1299 };
Fam Zheng335e9932017-05-03 00:35:39 +08001300 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001301 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001302 if (c == -1) {
1303 break;
1304 }
1305 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001306 case ':':
1307 missing_argument(argv[optind - 1]);
1308 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001309 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001310 unrecognized_option(argv[optind - 1]);
1311 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001312 case 'h':
1313 help();
1314 break;
1315 case 'f':
1316 fmt1 = optarg;
1317 break;
1318 case 'F':
1319 fmt2 = optarg;
1320 break;
Max Reitz40055952014-07-22 22:58:42 +02001321 case 'T':
1322 cache = optarg;
1323 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001324 case 'p':
1325 progress = true;
1326 break;
1327 case 'q':
1328 quiet = true;
1329 break;
1330 case 's':
1331 strict = true;
1332 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001333 case 'U':
1334 force_share = true;
1335 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001336 case OPTION_OBJECT: {
1337 QemuOpts *opts;
1338 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1339 optarg, true);
1340 if (!opts) {
1341 ret = 2;
1342 goto out4;
1343 }
1344 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001345 case OPTION_IMAGE_OPTS:
1346 image_opts = true;
1347 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001348 }
1349 }
1350
1351 /* Progress is not shown in Quiet mode */
1352 if (quiet) {
1353 progress = false;
1354 }
1355
1356
Kevin Wolffc11eb22013-08-05 10:53:04 +02001357 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001358 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001359 }
1360 filename1 = argv[optind++];
1361 filename2 = argv[optind++];
1362
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001363 if (qemu_opts_foreach(&qemu_object_opts,
1364 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00001365 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001366 ret = 2;
1367 goto out4;
1368 }
1369
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001370 /* Initialize before goto out */
1371 qemu_progress_init(progress, 2.0);
1372
Kevin Wolfce099542016-03-15 13:01:04 +01001373 flags = 0;
1374 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001375 if (ret < 0) {
1376 error_report("Invalid source cache option: %s", cache);
1377 ret = 2;
1378 goto out3;
1379 }
1380
Fam Zheng335e9932017-05-03 00:35:39 +08001381 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1382 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001383 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001384 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001385 goto out3;
1386 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001387
Fam Zheng335e9932017-05-03 00:35:39 +08001388 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1389 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001390 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001391 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001392 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001393 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001394 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001395 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001396
Max Reitzf1d3cd72015-02-05 13:58:18 -05001397 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1398 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001399 total_size1 = blk_getlength(blk1);
1400 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001401 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001402 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001403 ret = 4;
1404 goto out;
1405 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001406 total_size2 = blk_getlength(blk2);
1407 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001408 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001409 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001410 ret = 4;
1411 goto out;
1412 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001413 total_size = MIN(total_size1, total_size2);
1414 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415
1416 qemu_progress_print(0, 100);
1417
Eric Blake033d9fc2017-10-11 22:47:16 -05001418 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001419 ret = 1;
1420 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1421 goto out;
1422 }
1423
Eric Blake033d9fc2017-10-11 22:47:16 -05001424 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001425 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001426
Eric Blake033d9fc2017-10-11 22:47:16 -05001427 status1 = bdrv_block_status_above(bs1, NULL, offset,
1428 total_size1 - offset, &pnum1, NULL,
1429 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001430 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001431 ret = 3;
1432 error_report("Sector allocation test failed for %s", filename1);
1433 goto out;
1434 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001435 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001436
Eric Blake033d9fc2017-10-11 22:47:16 -05001437 status2 = bdrv_block_status_above(bs2, NULL, offset,
1438 total_size2 - offset, &pnum2, NULL,
1439 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001440 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001441 ret = 3;
1442 error_report("Sector allocation test failed for %s", filename2);
1443 goto out;
1444 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001445 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001446
1447 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001448 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001449
Fam Zheng25ad8e62016-01-13 16:37:41 +08001450 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001451 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001452 ret = 1;
1453 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001454 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001455 goto out;
1456 }
1457 }
1458 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001459 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001460 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001461 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001462 int64_t pnum;
1463
Eric Blake033d9fc2017-10-11 22:47:16 -05001464 chunk = MIN(chunk, IO_BUF_SIZE);
1465 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001466 if (ret < 0) {
1467 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001468 " of %s: %s",
1469 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001470 ret = 4;
1471 goto out;
1472 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001473 ret = blk_pread(blk2, offset, buf2, chunk);
1474 if (ret < 0) {
1475 error_report("Error while reading offset %" PRId64
1476 " of %s: %s",
1477 offset, filename2, strerror(-ret));
1478 ret = 4;
1479 goto out;
1480 }
1481 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1482 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001483 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001484 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001485 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001486 goto out;
1487 }
1488 }
1489 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001490 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001493 filename1, buf1, quiet);
1494 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001495 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001496 filename2, buf1, quiet);
1497 }
1498 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 goto out;
1500 }
1501 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001502 offset += chunk;
1503 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001504 }
1505
Eric Blake033d9fc2017-10-11 22:47:16 -05001506 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001507 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001508 const char *filename_over;
1509
1510 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001511 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001512 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001513 filename_over = filename1;
1514 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001515 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001516 filename_over = filename2;
1517 }
1518
Eric Blake033d9fc2017-10-11 22:47:16 -05001519 while (offset < progress_base) {
1520 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1521 progress_base - offset, &chunk,
1522 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001523 if (ret < 0) {
1524 ret = 3;
1525 error_report("Sector allocation test failed for %s",
1526 filename_over);
1527 goto out;
1528
1529 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001530 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001531 chunk = MIN(chunk, IO_BUF_SIZE);
1532 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001533 filename_over, buf1, quiet);
1534 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001535 goto out;
1536 }
1537 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001538 offset += chunk;
1539 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001540 }
1541 }
1542
1543 qprintf(quiet, "Images are identical.\n");
1544 ret = 0;
1545
1546out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001547 qemu_vfree(buf1);
1548 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001549 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001550out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001551 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001552out3:
1553 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001554out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001555 return ret;
1556}
1557
Kevin Wolf690c7302015-03-19 13:33:32 +01001558enum ImgConvertBlockStatus {
1559 BLK_DATA,
1560 BLK_ZERO,
1561 BLK_BACKING_FILE,
1562};
1563
Peter Lieven2d9187b2017-02-28 13:40:07 +01001564#define MAX_COROUTINES 16
1565
Kevin Wolf690c7302015-03-19 13:33:32 +01001566typedef struct ImgConvertState {
1567 BlockBackend **src;
1568 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001569 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001570 int64_t total_sectors;
1571 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001572 int64_t allocated_done;
1573 int64_t sector_num;
1574 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001575 enum ImgConvertBlockStatus status;
1576 int64_t sector_next_status;
1577 BlockBackend *target;
1578 bool has_zero_init;
1579 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001580 bool unallocated_blocks_are_zero;
Max Reitz4d7c4872019-07-24 19:12:29 +02001581 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001582 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001583 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001584 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001585 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001586 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001587 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001588 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001589 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001590 size_t cluster_sectors;
1591 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001592 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001593 int running_coroutines;
1594 Coroutine *co[MAX_COROUTINES];
1595 int64_t wait_sector_num[MAX_COROUTINES];
1596 CoMutex lock;
1597 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001598} ImgConvertState;
1599
Peter Lieven2d9187b2017-02-28 13:40:07 +01001600static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1601 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001602{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001603 *src_cur = 0;
1604 *src_cur_offset = 0;
1605 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1606 *src_cur_offset += s->src_sectors[*src_cur];
1607 (*src_cur)++;
1608 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001609 }
1610}
1611
1612static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1613{
Eric Blake31826642017-10-11 22:47:08 -05001614 int64_t src_cur_offset;
1615 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001616 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001617
Peter Lieven2d9187b2017-02-28 13:40:07 +01001618 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001619
1620 assert(s->total_sectors > sector_num);
1621 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1622
Max Reitz351c8ef2018-05-01 18:57:49 +02001623 if (s->target_backing_sectors >= 0) {
1624 if (sector_num >= s->target_backing_sectors) {
1625 post_backing_zero = s->unallocated_blocks_are_zero;
1626 } else if (sector_num + n > s->target_backing_sectors) {
1627 /* Split requests around target_backing_sectors (because
1628 * starting from there, zeros are handled differently) */
1629 n = s->target_backing_sectors - sector_num;
1630 }
1631 }
1632
Kevin Wolf690c7302015-03-19 13:33:32 +01001633 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001634 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1635 int64_t count;
Eric Blake31826642017-10-11 22:47:08 -05001636
Max Reitz8eaac022019-05-07 22:35:03 +02001637 do {
1638 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001639
Max Reitz8eaac022019-05-07 22:35:03 +02001640 if (s->target_has_backing) {
1641 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1642 count, &count, NULL, NULL);
1643 } else {
1644 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1645 offset, count, &count, NULL,
1646 NULL);
1647 }
1648
1649 if (ret < 0) {
1650 if (s->salvage) {
1651 if (n == 1) {
1652 if (!s->quiet) {
1653 warn_report("error while reading block status at "
1654 "offset %" PRIu64 ": %s", offset,
1655 strerror(-ret));
1656 }
1657 /* Just try to read the data, then */
1658 ret = BDRV_BLOCK_DATA;
1659 count = BDRV_SECTOR_SIZE;
1660 } else {
1661 /* Retry on a shorter range */
1662 n = DIV_ROUND_UP(n, 4);
1663 }
1664 } else {
1665 error_report("error while reading block status at offset "
1666 "%" PRIu64 ": %s", offset, strerror(-ret));
1667 return ret;
1668 }
1669 }
1670 } while (ret < 0);
1671
Eric Blake31826642017-10-11 22:47:08 -05001672 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001673
1674 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001675 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001676 } else if (ret & BDRV_BLOCK_DATA) {
1677 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001678 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001679 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001680 }
1681
1682 s->sector_next_status = sector_num + n;
1683 }
1684
1685 n = MIN(n, s->sector_next_status - sector_num);
1686 if (s->status == BLK_DATA) {
1687 n = MIN(n, s->buf_sectors);
1688 }
1689
1690 /* We need to write complete clusters for compressed images, so if an
1691 * unallocated area is shorter than that, we must consider the whole
1692 * cluster allocated. */
1693 if (s->compressed) {
1694 if (n < s->cluster_sectors) {
1695 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1696 s->status = BLK_DATA;
1697 } else {
1698 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1699 }
1700 }
1701
1702 return n;
1703}
1704
Peter Lieven2d9187b2017-02-28 13:40:07 +01001705static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1706 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001707{
Max Reitz8eaac022019-05-07 22:35:03 +02001708 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001709 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001710
Kevin Wolf690c7302015-03-19 13:33:32 +01001711 assert(nb_sectors <= s->buf_sectors);
1712 while (nb_sectors > 0) {
1713 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001714 int src_cur;
1715 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001716 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001717
1718 /* In the case of compression with multiple source files, we can get a
1719 * nb_sectors that spreads into the next part. So we must be able to
1720 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001721 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1722 blk = s->src[src_cur];
1723 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001724
Max Reitz8eaac022019-05-07 22:35:03 +02001725 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001726
Max Reitz8eaac022019-05-07 22:35:03 +02001727 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1728 if (single_read_until > offset) {
1729 n = 1;
1730 }
1731
1732 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001733 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001734 if (s->salvage) {
1735 if (n > 1) {
1736 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1737 continue;
1738 } else {
1739 if (!s->quiet) {
1740 warn_report("error while reading offset %" PRIu64
1741 ": %s", offset, strerror(-ret));
1742 }
1743 memset(buf, 0, BDRV_SECTOR_SIZE);
1744 }
1745 } else {
1746 return ret;
1747 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001748 }
1749
1750 sector_num += n;
1751 nb_sectors -= n;
1752 buf += n * BDRV_SECTOR_SIZE;
1753 }
1754
1755 return 0;
1756}
1757
Peter Lieven2d9187b2017-02-28 13:40:07 +01001758
1759static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1760 int nb_sectors, uint8_t *buf,
1761 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001762{
1763 int ret;
1764
1765 while (nb_sectors > 0) {
1766 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001767 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1768
Peter Lieven2d9187b2017-02-28 13:40:07 +01001769 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001770 case BLK_BACKING_FILE:
1771 /* If we have a backing file, leave clusters unallocated that are
1772 * unallocated in the source image, so that the backing file is
1773 * visible at the respective offset. */
1774 assert(s->target_has_backing);
1775 break;
1776
1777 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001778 /* If we're told to keep the target fully allocated (-S 0) or there
1779 * is real non-zero data, we must write it. Otherwise we can treat
1780 * it as zero sectors.
1781 * Compressed clusters need to be written as a whole, so in that
1782 * case we can only save the write if the buffer is completely
1783 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001784 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001785 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001786 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1787 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001788 (s->compressed &&
1789 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001790 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001791 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1792 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001793 if (ret < 0) {
1794 return ret;
1795 }
1796 break;
1797 }
1798 /* fall-through */
1799
1800 case BLK_ZERO:
1801 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001802 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001803 break;
1804 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001805 ret = blk_co_pwrite_zeroes(s->target,
1806 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001807 n << BDRV_SECTOR_BITS,
1808 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001809 if (ret < 0) {
1810 return ret;
1811 }
1812 break;
1813 }
1814
1815 sector_num += n;
1816 nb_sectors -= n;
1817 buf += n * BDRV_SECTOR_SIZE;
1818 }
1819
1820 return 0;
1821}
1822
Fam Zhengee5306d2018-06-01 17:26:48 +08001823static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1824 int nb_sectors)
1825{
1826 int n, ret;
1827
1828 while (nb_sectors > 0) {
1829 BlockBackend *blk;
1830 int src_cur;
1831 int64_t bs_sectors, src_cur_offset;
1832 int64_t offset;
1833
1834 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1835 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1836 blk = s->src[src_cur];
1837 bs_sectors = s->src_sectors[src_cur];
1838
1839 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1840
1841 ret = blk_co_copy_range(blk, offset, s->target,
1842 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001843 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001844 if (ret < 0) {
1845 return ret;
1846 }
1847
1848 sector_num += n;
1849 nb_sectors -= n;
1850 }
1851 return 0;
1852}
1853
Peter Lieven2d9187b2017-02-28 13:40:07 +01001854static void coroutine_fn convert_co_do_copy(void *opaque)
1855{
1856 ImgConvertState *s = opaque;
1857 uint8_t *buf = NULL;
1858 int ret, i;
1859 int index = -1;
1860
1861 for (i = 0; i < s->num_coroutines; i++) {
1862 if (s->co[i] == qemu_coroutine_self()) {
1863 index = i;
1864 break;
1865 }
1866 }
1867 assert(index >= 0);
1868
1869 s->running_coroutines++;
1870 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1871
1872 while (1) {
1873 int n;
1874 int64_t sector_num;
1875 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001876 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001877
1878 qemu_co_mutex_lock(&s->lock);
1879 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1880 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001881 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001882 }
1883 n = convert_iteration_sectors(s, s->sector_num);
1884 if (n < 0) {
1885 qemu_co_mutex_unlock(&s->lock);
1886 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001887 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001888 }
1889 /* save current sector and allocation status to local variables */
1890 sector_num = s->sector_num;
1891 status = s->status;
1892 if (!s->min_sparse && s->status == BLK_ZERO) {
1893 n = MIN(n, s->buf_sectors);
1894 }
1895 /* increment global sector counter so that other coroutines can
1896 * already continue reading beyond this request */
1897 s->sector_num += n;
1898 qemu_co_mutex_unlock(&s->lock);
1899
1900 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1901 s->allocated_done += n;
1902 qemu_progress_print(100.0 * s->allocated_done /
1903 s->allocated_sectors, 0);
1904 }
1905
Fam Zhengee5306d2018-06-01 17:26:48 +08001906retry:
1907 copy_range = s->copy_range && s->status == BLK_DATA;
1908 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001909 ret = convert_co_read(s, sector_num, n, buf);
1910 if (ret < 0) {
1911 error_report("error while reading sector %" PRId64
1912 ": %s", sector_num, strerror(-ret));
1913 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001914 }
1915 } else if (!s->min_sparse && status == BLK_ZERO) {
1916 status = BLK_DATA;
1917 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1918 }
1919
1920 if (s->wr_in_order) {
1921 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001922 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001923 s->wait_sector_num[index] = sector_num;
1924 qemu_coroutine_yield();
1925 }
1926 s->wait_sector_num[index] = -1;
1927 }
1928
Anton Nefedovb91127e2017-04-26 11:33:15 +03001929 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001930 if (copy_range) {
1931 ret = convert_co_copy_range(s, sector_num, n);
1932 if (ret) {
1933 s->copy_range = false;
1934 goto retry;
1935 }
1936 } else {
1937 ret = convert_co_write(s, sector_num, n, buf, status);
1938 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001939 if (ret < 0) {
1940 error_report("error while writing sector %" PRId64
1941 ": %s", sector_num, strerror(-ret));
1942 s->ret = ret;
1943 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001944 }
1945
1946 if (s->wr_in_order) {
1947 /* reenter the coroutine that might have waited
1948 * for this write to complete */
1949 s->wr_offs = sector_num + n;
1950 for (i = 0; i < s->num_coroutines; i++) {
1951 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1952 /*
1953 * A -> B -> A cannot occur because A has
1954 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1955 * B will never enter A during this time window.
1956 */
1957 qemu_coroutine_enter(s->co[i]);
1958 break;
1959 }
1960 }
1961 }
1962 }
1963
Peter Lieven2d9187b2017-02-28 13:40:07 +01001964 qemu_vfree(buf);
1965 s->co[index] = NULL;
1966 s->running_coroutines--;
1967 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1968 /* the convert job finished successfully */
1969 s->ret = 0;
1970 }
1971}
1972
Kevin Wolf690c7302015-03-19 13:33:32 +01001973static int convert_do_copy(ImgConvertState *s)
1974{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001975 int ret, i, n;
1976 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001977
1978 /* Check whether we have zero initialisation or can get it efficiently */
Max Reitz4d7c4872019-07-24 19:12:29 +02001979 if (s->target_is_new && s->min_sparse && !s->target_has_backing) {
1980 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
1981 } else {
1982 s->has_zero_init = false;
1983 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001984
1985 if (!s->has_zero_init && !s->target_has_backing &&
1986 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1987 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001988 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001989 if (ret == 0) {
1990 s->has_zero_init = true;
1991 }
1992 }
1993
1994 /* Allocate buffer for copied data. For compressed images, only one cluster
1995 * can be copied at a time. */
1996 if (s->compressed) {
1997 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1998 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001999 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002000 }
2001 s->buf_sectors = s->cluster_sectors;
2002 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002003
Kevin Wolf690c7302015-03-19 13:33:32 +01002004 while (sector_num < s->total_sectors) {
2005 n = convert_iteration_sectors(s, sector_num);
2006 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002007 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002008 }
Max Reitzaad15de2016-03-24 23:33:57 +01002009 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2010 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002011 s->allocated_sectors += n;
2012 }
2013 sector_num += n;
2014 }
2015
2016 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002017 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002018 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002019
Peter Lieven2d9187b2017-02-28 13:40:07 +01002020 qemu_co_mutex_init(&s->lock);
2021 for (i = 0; i < s->num_coroutines; i++) {
2022 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2023 s->wait_sector_num[i] = -1;
2024 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002025 }
2026
Anton Nefedovb91127e2017-04-26 11:33:15 +03002027 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002028 main_loop_wait(false);
2029 }
2030
2031 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002032 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002033 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002034 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002035 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002036 }
2037 }
2038
Peter Lieven2d9187b2017-02-28 13:40:07 +01002039 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002040}
2041
Peter Lieven6360ab22018-07-13 09:15:39 +02002042#define MAX_BUF_SECTORS 32768
2043
bellardea2384d2004-08-01 21:59:26 +00002044static int img_convert(int argc, char **argv)
2045{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002046 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002047 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002048 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2049 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002050 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002051 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002052 BlockDriverState *out_bs;
2053 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002054 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002055 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002056 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002057 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002058 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002059 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002060 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002061 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002062 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002063
Peter Lieven9fd77f92017-04-21 11:11:55 +02002064 ImgConvertState s = (ImgConvertState) {
2065 /* Need at least 4k of zeros for sparse detection */
2066 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002067 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002068 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2069 .wr_in_order = true,
2070 .num_coroutines = 8,
2071 };
2072
bellardea2384d2004-08-01 21:59:26 +00002073 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002074 static const struct option long_options[] = {
2075 {"help", no_argument, 0, 'h'},
2076 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002077 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002078 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002079 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002080 {"salvage", no_argument, 0, OPTION_SALVAGE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002081 {0, 0, 0, 0}
2082 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002083 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002084 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002085 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002086 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002087 }
bellardea2384d2004-08-01 21:59:26 +00002088 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002089 case ':':
2090 missing_argument(argv[optind - 1]);
2091 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002092 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002093 unrecognized_option(argv[optind - 1]);
2094 break;
bellardea2384d2004-08-01 21:59:26 +00002095 case 'h':
2096 help();
2097 break;
2098 case 'f':
2099 fmt = optarg;
2100 break;
2101 case 'O':
2102 out_fmt = optarg;
2103 break;
thsf58c7b32008-06-05 21:53:49 +00002104 case 'B':
2105 out_baseimg = optarg;
2106 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002107 case 'C':
2108 s.copy_range = true;
2109 break;
bellardea2384d2004-08-01 21:59:26 +00002110 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002111 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002112 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002113 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002114 if (!is_valid_option_list(optarg)) {
2115 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002116 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002117 }
2118 if (!options) {
2119 options = g_strdup(optarg);
2120 } else {
2121 char *old_options = options;
2122 options = g_strdup_printf("%s,%s", options, optarg);
2123 g_free(old_options);
2124 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002125 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002126 case 'l':
2127 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002128 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2129 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002130 if (!sn_opts) {
2131 error_report("Failed in parsing snapshot param '%s'",
2132 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002133 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002134 }
2135 } else {
2136 snapshot_name = optarg;
2137 }
2138 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002139 case 'S':
2140 {
2141 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002142
2143 sval = cvtnum(optarg);
Nir Soffer1bbbf322019-08-27 21:59:12 +03002144 if (sval < 0 || !QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002145 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2146 error_report("Invalid buffer size for sparse output specified. "
2147 "Valid sizes are multiples of %llu up to %llu. Select "
2148 "0 to disable sparse detection (fully allocates output).",
2149 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002150 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002151 }
2152
Peter Lieven9fd77f92017-04-21 11:11:55 +02002153 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002154 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002155 break;
2156 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002157 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002158 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002159 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002160 case 't':
2161 cache = optarg;
2162 break;
Max Reitz40055952014-07-22 22:58:42 +02002163 case 'T':
2164 src_cache = optarg;
2165 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002166 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002167 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002168 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002169 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002170 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002171 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002172 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002173 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2174 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002175 error_report("Invalid number of coroutines. Allowed number of"
2176 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002177 goto fail_getopt;
2178 }
2179 break;
2180 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002181 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002182 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002183 case 'U':
2184 force_share = true;
2185 break;
Max Reitz3258b912017-04-26 15:46:47 +02002186 case OPTION_OBJECT: {
2187 QemuOpts *object_opts;
2188 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2189 optarg, true);
2190 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002191 goto fail_getopt;
2192 }
2193 break;
Max Reitz3258b912017-04-26 15:46:47 +02002194 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002195 case OPTION_IMAGE_OPTS:
2196 image_opts = true;
2197 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002198 case OPTION_SALVAGE:
2199 s.salvage = true;
2200 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002201 case OPTION_TARGET_IMAGE_OPTS:
2202 tgt_image_opts = true;
2203 break;
bellardea2384d2004-08-01 21:59:26 +00002204 }
2205 }
ths3b46e622007-09-17 08:09:54 +00002206
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002207 if (!out_fmt && !tgt_image_opts) {
2208 out_fmt = "raw";
2209 }
2210
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002211 if (qemu_opts_foreach(&qemu_object_opts,
2212 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002213 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002214 goto fail_getopt;
2215 }
2216
Fam Zhenge11ce122018-07-27 11:34:01 +08002217 if (s.compressed && s.copy_range) {
2218 error_report("Cannot enable copy offloading when -c is used");
2219 goto fail_getopt;
2220 }
2221
2222 if (explict_min_sparse && s.copy_range) {
2223 error_report("Cannot enable copy offloading when -S is used");
2224 goto fail_getopt;
2225 }
2226
Max Reitz8eaac022019-05-07 22:35:03 +02002227 if (s.copy_range && s.salvage) {
2228 error_report("Cannot use copy offloading in salvaging mode");
2229 goto fail_getopt;
2230 }
2231
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002232 if (tgt_image_opts && !skip_create) {
2233 error_report("--target-image-opts requires use of -n flag");
2234 goto fail_getopt;
2235 }
2236
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002237 if (skip_create && options) {
2238 warn_report("-o has no effect when skipping image creation");
2239 warn_report("This will become an error in future QEMU versions.");
2240 }
2241
Peter Lieven9fd77f92017-04-21 11:11:55 +02002242 s.src_num = argc - optind - 1;
2243 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2244
2245 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002246 if (out_fmt) {
2247 ret = print_block_option_help(out_filename, out_fmt);
2248 goto fail_getopt;
2249 } else {
2250 error_report("Option help requires a format be specified");
2251 goto fail_getopt;
2252 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002253 }
2254
2255 if (s.src_num < 1) {
2256 error_report("Must specify image file name");
2257 goto fail_getopt;
2258 }
2259
2260
Peter Lieven9fd77f92017-04-21 11:11:55 +02002261 /* ret is still -EINVAL until here */
2262 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2263 if (ret < 0) {
2264 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002265 goto fail_getopt;
2266 }
2267
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002268 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002269 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002270 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002271 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002272 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002273 qemu_progress_print(0, 100);
2274
Peter Lieven9fd77f92017-04-21 11:11:55 +02002275 s.src = g_new0(BlockBackend *, s.src_num);
2276 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002277
Peter Lieven9fd77f92017-04-21 11:11:55 +02002278 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2279 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002280 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002281 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002282 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002283 ret = -1;
2284 goto out;
2285 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002286 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2287 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002288 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002289 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002290 ret = -1;
2291 goto out;
2292 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002293 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002294 }
bellardea2384d2004-08-01 21:59:26 +00002295
Wenchao Xiaef806542013-12-04 17:10:57 +08002296 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002297 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002298 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2299 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2300 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002301 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002302 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002303 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002304 ret = -1;
2305 goto out;
2306 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002307
Peter Lieven9fd77f92017-04-21 11:11:55 +02002308 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2309 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002310 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002311 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002312 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002313 ret = -1;
2314 goto out;
edison51ef6722010-09-21 19:58:41 -07002315 }
2316
Max Reitz2e024cd2015-02-11 09:58:46 -05002317 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002318 /* Find driver and parse its options */
2319 drv = bdrv_find_format(out_fmt);
2320 if (!drv) {
2321 error_report("Unknown file format '%s'", out_fmt);
2322 ret = -1;
2323 goto out;
2324 }
2325
2326 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2327 if (!proto_drv) {
2328 error_report_err(local_err);
2329 ret = -1;
2330 goto out;
2331 }
2332
Max Reitz2e024cd2015-02-11 09:58:46 -05002333 if (!drv->create_opts) {
2334 error_report("Format driver '%s' does not support image creation",
2335 drv->format_name);
2336 ret = -1;
2337 goto out;
2338 }
Max Reitzf75613c2014-12-02 18:32:46 +01002339
Max Reitz2e024cd2015-02-11 09:58:46 -05002340 if (!proto_drv->create_opts) {
2341 error_report("Protocol driver '%s' does not support image creation",
2342 proto_drv->format_name);
2343 ret = -1;
2344 goto out;
2345 }
Max Reitzf75613c2014-12-02 18:32:46 +01002346
Max Reitz2e024cd2015-02-11 09:58:46 -05002347 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2348 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002349
Max Reitz2e024cd2015-02-11 09:58:46 -05002350 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002351 if (options) {
2352 qemu_opts_do_parse(opts, options, NULL, &local_err);
2353 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002354 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002355 ret = -1;
2356 goto out;
2357 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002358 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002359
Peter Lieven9fd77f92017-04-21 11:11:55 +02002360 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002361 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002362 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2363 if (ret < 0) {
2364 goto out;
2365 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002366 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002367
Kevin Wolfa18953f2010-10-14 15:46:04 +02002368 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002369 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002370 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002371 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002372 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002373 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002374
Max Reitz48758a82017-04-26 15:46:48 +02002375 if (s.src_num > 1 && out_baseimg) {
2376 error_report("Having a backing file for the target makes no sense when "
2377 "concatenating multiple input images");
2378 ret = -1;
2379 goto out;
2380 }
2381
Kevin Wolfefa84d42009-05-18 16:42:12 +02002382 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002383 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002384 bool encryption =
2385 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002386 const char *encryptfmt =
2387 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002388 const char *preallocation =
2389 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002390
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002391 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002392 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002393 ret = -1;
2394 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002395 }
2396
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002397 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002398 error_report("Compression and encryption not supported at "
2399 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002400 ret = -1;
2401 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002402 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002403
Chunyan Liu83d05212014-06-05 17:20:51 +08002404 if (preallocation
2405 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002406 {
2407 error_report("Compression and preallocation not supported at "
2408 "the same time");
2409 ret = -1;
2410 goto out;
2411 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002412 }
2413
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002414 /*
2415 * The later open call will need any decryption secrets, and
2416 * bdrv_create() will purge "opts", so extract them now before
2417 * they are lost.
2418 */
2419 if (!skip_create) {
2420 open_opts = qdict_new();
2421 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2422 }
2423
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002424 if (!skip_create) {
2425 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002426 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002427 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002428 error_reportf_err(local_err, "%s: error while converting %s: ",
2429 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002430 goto out;
bellardea2384d2004-08-01 21:59:26 +00002431 }
2432 }
ths3b46e622007-09-17 08:09:54 +00002433
Max Reitz4d7c4872019-07-24 19:12:29 +02002434 s.target_is_new = !skip_create;
2435
Peter Lieven9fd77f92017-04-21 11:11:55 +02002436 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002437 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002438 if (ret < 0) {
2439 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002440 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002441 }
2442
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002443 if (skip_create) {
2444 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002445 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002446 } else {
2447 /* TODO ultimately we should allow --target-image-opts
2448 * to be used even when -n is not given.
2449 * That has to wait for bdrv_create to be improved
2450 * to allow filenames in option syntax
2451 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002452 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002453 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002454 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002455 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002456 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002457 ret = -1;
2458 goto out;
2459 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002460 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002461
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002462 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002463 error_report("Compression not supported for this file format");
2464 ret = -1;
2465 goto out;
2466 }
2467
Eric Blake5def6b82016-06-23 16:37:19 -06002468 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002469 * or discard_alignment of the out_bs is greater. Limit to
2470 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2471 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002472 MAX(s.buf_sectors,
2473 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2474 out_bs->bl.pdiscard_alignment >>
2475 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002476
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002477 /* try to align the write requests to the destination to avoid unnecessary
2478 * RMW cycles. */
2479 s.alignment = MAX(pow2floor(s.min_sparse),
2480 DIV_ROUND_UP(out_bs->bl.request_alignment,
2481 BDRV_SECTOR_SIZE));
2482 assert(is_power_of_2(s.alignment));
2483
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002484 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002485 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002486 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002487 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002488 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002489 ret = -1;
2490 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002491 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002492 error_report("output file is smaller than input file");
2493 ret = -1;
2494 goto out;
2495 }
2496 }
2497
Max Reitz351c8ef2018-05-01 18:57:49 +02002498 if (s.target_has_backing) {
2499 /* Errors are treated as "backing length unknown" (which means
2500 * s.target_backing_sectors has to be negative, which it will
2501 * be automatically). The backing file length is used only
2502 * for optimizations, so such a case is not fatal. */
2503 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2504 } else {
2505 s.target_backing_sectors = -1;
2506 }
2507
Peter Lieven24f833c2013-11-27 11:07:07 +01002508 ret = bdrv_get_info(out_bs, &bdi);
2509 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002510 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002511 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002512 goto out;
2513 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002514 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002515 s.compressed = s.compressed || bdi.needs_compressed_writes;
2516 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002517 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002518 }
2519
Peter Lieven9fd77f92017-04-21 11:11:55 +02002520 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002521out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002522 if (!ret) {
2523 qemu_progress_print(100, 0);
2524 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002525 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002526 qemu_opts_del(opts);
2527 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002528 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002529 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002530 blk_unref(s.target);
2531 if (s.src) {
2532 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2533 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002534 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002535 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002536 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002537 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002538fail_getopt:
2539 g_free(options);
2540
Peter Lieven9fd77f92017-04-21 11:11:55 +02002541 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002542}
2543
bellard57d1a2b2004-08-03 21:15:11 +00002544
bellardfaea38e2006-08-05 21:31:00 +00002545static void dump_snapshots(BlockDriverState *bs)
2546{
2547 QEMUSnapshotInfo *sn_tab, *sn;
2548 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002549
2550 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2551 if (nb_sns <= 0)
2552 return;
2553 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002554 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002555 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002556 for(i = 0; i < nb_sns; i++) {
2557 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002558 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002559 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002560 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002561 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002562}
2563
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002564static void dump_json_image_info_list(ImageInfoList *list)
2565{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002566 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002567 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002568 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002569
2570 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2571 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002572 str = qobject_to_json_pretty(obj);
2573 assert(str != NULL);
2574 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002575 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002576 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002577 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002578}
2579
Benoît Canetc054b3f2012-09-05 13:09:02 +02002580static void dump_json_image_info(ImageInfo *info)
2581{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002582 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002583 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002584 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002585
2586 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2587 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002588 str = qobject_to_json_pretty(obj);
2589 assert(str != NULL);
2590 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002591 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002592 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002593 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002594}
2595
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002596static void dump_human_image_info_list(ImageInfoList *list)
2597{
2598 ImageInfoList *elem;
2599 bool delim = false;
2600
2601 for (elem = list; elem; elem = elem->next) {
2602 if (delim) {
2603 printf("\n");
2604 }
2605 delim = true;
2606
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002607 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002608 }
2609}
2610
2611static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2612{
2613 return strcmp(a, b) == 0;
2614}
2615
2616/**
2617 * Open an image file chain and return an ImageInfoList
2618 *
2619 * @filename: topmost image filename
2620 * @fmt: topmost image format (may be NULL to autodetect)
2621 * @chain: true - enumerate entire backing file chain
2622 * false - only topmost image file
2623 *
2624 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2625 * image file. If there was an error a message will have been printed to
2626 * stderr.
2627 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002628static ImageInfoList *collect_image_info_list(bool image_opts,
2629 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002630 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002631 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002632{
2633 ImageInfoList *head = NULL;
2634 ImageInfoList **last = &head;
2635 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002636 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002637
2638 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2639
2640 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002641 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002642 BlockDriverState *bs;
2643 ImageInfo *info;
2644 ImageInfoList *elem;
2645
2646 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2647 error_report("Backing file '%s' creates an infinite loop.",
2648 filename);
2649 goto err;
2650 }
2651 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2652
Max Reitzefaa7c42016-03-16 19:54:38 +01002653 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002654 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2655 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002656 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002657 goto err;
2658 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002659 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002660
Wenchao Xia43526ec2013-06-06 12:27:58 +08002661 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002662 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002663 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002664 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002665 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002666 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002667
2668 elem = g_new0(ImageInfoList, 1);
2669 elem->value = info;
2670 *last = elem;
2671 last = &elem->next;
2672
Markus Armbruster26f54e92014-10-07 13:59:04 +02002673 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002674
2675 filename = fmt = NULL;
2676 if (chain) {
2677 if (info->has_full_backing_filename) {
2678 filename = info->full_backing_filename;
2679 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002680 error_report("Could not determine absolute backing filename,"
2681 " but backing filename '%s' present",
2682 info->backing_filename);
2683 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002684 }
2685 if (info->has_backing_filename_format) {
2686 fmt = info->backing_filename_format;
2687 }
2688 }
2689 }
2690 g_hash_table_destroy(filenames);
2691 return head;
2692
2693err:
2694 qapi_free_ImageInfoList(head);
2695 g_hash_table_destroy(filenames);
2696 return NULL;
2697}
2698
Benoît Canetc054b3f2012-09-05 13:09:02 +02002699static int img_info(int argc, char **argv)
2700{
2701 int c;
2702 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002703 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002704 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002705 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002706 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002707 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002708
bellardea2384d2004-08-01 21:59:26 +00002709 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002710 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002711 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002712 int option_index = 0;
2713 static const struct option long_options[] = {
2714 {"help", no_argument, 0, 'h'},
2715 {"format", required_argument, 0, 'f'},
2716 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002717 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002718 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002719 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002720 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002721 {0, 0, 0, 0}
2722 };
Fam Zheng335e9932017-05-03 00:35:39 +08002723 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002724 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002725 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002726 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002727 }
bellardea2384d2004-08-01 21:59:26 +00002728 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002729 case ':':
2730 missing_argument(argv[optind - 1]);
2731 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002732 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002733 unrecognized_option(argv[optind - 1]);
2734 break;
bellardea2384d2004-08-01 21:59:26 +00002735 case 'h':
2736 help();
2737 break;
2738 case 'f':
2739 fmt = optarg;
2740 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002741 case 'U':
2742 force_share = true;
2743 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002744 case OPTION_OUTPUT:
2745 output = optarg;
2746 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002747 case OPTION_BACKING_CHAIN:
2748 chain = true;
2749 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002750 case OPTION_OBJECT: {
2751 QemuOpts *opts;
2752 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2753 optarg, true);
2754 if (!opts) {
2755 return 1;
2756 }
2757 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002758 case OPTION_IMAGE_OPTS:
2759 image_opts = true;
2760 break;
bellardea2384d2004-08-01 21:59:26 +00002761 }
2762 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002763 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002764 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002765 }
bellardea2384d2004-08-01 21:59:26 +00002766 filename = argv[optind++];
2767
Benoît Canetc054b3f2012-09-05 13:09:02 +02002768 if (output && !strcmp(output, "json")) {
2769 output_format = OFORMAT_JSON;
2770 } else if (output && !strcmp(output, "human")) {
2771 output_format = OFORMAT_HUMAN;
2772 } else if (output) {
2773 error_report("--output must be used with human or json as argument.");
2774 return 1;
2775 }
2776
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002777 if (qemu_opts_foreach(&qemu_object_opts,
2778 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002779 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002780 return 1;
2781 }
2782
Fam Zheng335e9932017-05-03 00:35:39 +08002783 list = collect_image_info_list(image_opts, filename, fmt, chain,
2784 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002785 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002786 return 1;
2787 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002788
Benoît Canetc054b3f2012-09-05 13:09:02 +02002789 switch (output_format) {
2790 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002791 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002792 break;
2793 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002794 if (chain) {
2795 dump_json_image_info_list(list);
2796 } else {
2797 dump_json_image_info(list->value);
2798 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002799 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002800 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002801
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002802 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002803 return 0;
2804}
2805
Eric Blake30065d12019-03-26 13:40:43 -05002806static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2807 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002808{
2809 switch (output_format) {
2810 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002811 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002812 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002813 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002814 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002815 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002816 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002817 e->start, e->length,
2818 e->has_offset ? e->offset : 0,
2819 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002820 }
2821 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2822 * Modify the flags here to allow more coalescing.
2823 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002824 if (next && (!next->data || next->zero)) {
2825 next->data = false;
2826 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002827 }
2828 break;
2829 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002830 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2831 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002832 (e->start == 0 ? "[" : ",\n"),
2833 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002834 e->zero ? "true" : "false",
2835 e->data ? "true" : "false");
2836 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002837 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002838 }
2839 putchar('}');
2840
2841 if (!next) {
2842 printf("]\n");
2843 }
2844 break;
2845 }
Eric Blake30065d12019-03-26 13:40:43 -05002846 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002847}
2848
Eric Blake5e344dd2017-10-11 22:47:02 -05002849static int get_block_status(BlockDriverState *bs, int64_t offset,
2850 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002851{
Eric Blake237d78f2017-10-11 22:47:03 -05002852 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002853 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002854 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002855 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002856 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002857 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002858
2859 /* As an optimization, we could cache the current range of unallocated
2860 * clusters in each file of the chain, and avoid querying the same
2861 * range repeatedly.
2862 */
2863
2864 depth = 0;
2865 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002866 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002867 if (ret < 0) {
2868 return ret;
2869 }
Eric Blake237d78f2017-10-11 22:47:03 -05002870 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002871 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2872 break;
2873 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002874 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002875 if (bs == NULL) {
2876 ret = 0;
2877 break;
2878 }
2879
2880 depth++;
2881 }
2882
John Snow28756452016-02-05 13:12:33 -05002883 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2884
Max Reitzf30c66b2019-02-01 20:29:05 +01002885 if (file && has_offset) {
2886 bdrv_refresh_filename(file);
2887 filename = file->filename;
2888 }
2889
John Snow28756452016-02-05 13:12:33 -05002890 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002891 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002892 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002893 .data = !!(ret & BDRV_BLOCK_DATA),
2894 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002895 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002896 .has_offset = has_offset,
2897 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002898 .has_filename = filename,
2899 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002900 };
2901
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002902 return 0;
2903}
2904
Fam Zheng16b0d552016-01-26 11:59:02 +08002905static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2906{
2907 if (curr->length == 0) {
2908 return false;
2909 }
2910 if (curr->zero != next->zero ||
2911 curr->data != next->data ||
2912 curr->depth != next->depth ||
2913 curr->has_filename != next->has_filename ||
2914 curr->has_offset != next->has_offset) {
2915 return false;
2916 }
2917 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2918 return false;
2919 }
2920 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2921 return false;
2922 }
2923 return true;
2924}
2925
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002926static int img_map(int argc, char **argv)
2927{
2928 int c;
2929 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002930 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002931 BlockDriverState *bs;
2932 const char *filename, *fmt, *output;
2933 int64_t length;
2934 MapEntry curr = { .length = 0 }, next;
2935 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002936 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002937 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002938
2939 fmt = NULL;
2940 output = NULL;
2941 for (;;) {
2942 int option_index = 0;
2943 static const struct option long_options[] = {
2944 {"help", no_argument, 0, 'h'},
2945 {"format", required_argument, 0, 'f'},
2946 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002947 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002948 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002949 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002950 {0, 0, 0, 0}
2951 };
Fam Zheng335e9932017-05-03 00:35:39 +08002952 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002953 long_options, &option_index);
2954 if (c == -1) {
2955 break;
2956 }
2957 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002958 case ':':
2959 missing_argument(argv[optind - 1]);
2960 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002961 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002962 unrecognized_option(argv[optind - 1]);
2963 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002964 case 'h':
2965 help();
2966 break;
2967 case 'f':
2968 fmt = optarg;
2969 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002970 case 'U':
2971 force_share = true;
2972 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002973 case OPTION_OUTPUT:
2974 output = optarg;
2975 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002976 case OPTION_OBJECT: {
2977 QemuOpts *opts;
2978 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2979 optarg, true);
2980 if (!opts) {
2981 return 1;
2982 }
2983 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002984 case OPTION_IMAGE_OPTS:
2985 image_opts = true;
2986 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002987 }
2988 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002989 if (optind != argc - 1) {
2990 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002991 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002992 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002993
2994 if (output && !strcmp(output, "json")) {
2995 output_format = OFORMAT_JSON;
2996 } else if (output && !strcmp(output, "human")) {
2997 output_format = OFORMAT_HUMAN;
2998 } else if (output) {
2999 error_report("--output must be used with human or json as argument.");
3000 return 1;
3001 }
3002
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003003 if (qemu_opts_foreach(&qemu_object_opts,
3004 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003005 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003006 return 1;
3007 }
3008
Fam Zheng335e9932017-05-03 00:35:39 +08003009 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003010 if (!blk) {
3011 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003012 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003013 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003014
3015 if (output_format == OFORMAT_HUMAN) {
3016 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3017 }
3018
Max Reitzf1d3cd72015-02-05 13:58:18 -05003019 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003020 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003021 int64_t offset = curr.start + curr.length;
3022 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003023
3024 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02003025 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05003026 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003027
3028 if (ret < 0) {
3029 error_report("Could not read file metadata: %s", strerror(-ret));
3030 goto out;
3031 }
3032
Fam Zheng16b0d552016-01-26 11:59:02 +08003033 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003034 curr.length += next.length;
3035 continue;
3036 }
3037
3038 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003039 ret = dump_map_entry(output_format, &curr, &next);
3040 if (ret < 0) {
3041 goto out;
3042 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003043 }
3044 curr = next;
3045 }
3046
Eric Blake30065d12019-03-26 13:40:43 -05003047 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003048
3049out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003050 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003051 return ret < 0;
3052}
3053
aliguorif7b4a942009-01-07 17:40:15 +00003054#define SNAPSHOT_LIST 1
3055#define SNAPSHOT_CREATE 2
3056#define SNAPSHOT_APPLY 3
3057#define SNAPSHOT_DELETE 4
3058
Stuart Brady153859b2009-06-07 00:42:17 +01003059static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003060{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003061 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003062 BlockDriverState *bs;
3063 QEMUSnapshotInfo sn;
3064 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003065 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003066 int action = 0;
3067 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003068 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003069 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003070 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003071 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003072
Kevin Wolfce099542016-03-15 13:01:04 +01003073 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003074 /* Parse commandline parameters */
3075 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003076 static const struct option long_options[] = {
3077 {"help", no_argument, 0, 'h'},
3078 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003079 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003080 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003081 {0, 0, 0, 0}
3082 };
Fam Zheng335e9932017-05-03 00:35:39 +08003083 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003084 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003085 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003086 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003087 }
aliguorif7b4a942009-01-07 17:40:15 +00003088 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003089 case ':':
3090 missing_argument(argv[optind - 1]);
3091 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003092 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003093 unrecognized_option(argv[optind - 1]);
3094 break;
aliguorif7b4a942009-01-07 17:40:15 +00003095 case 'h':
3096 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003097 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003098 case 'l':
3099 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003100 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003101 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003102 }
3103 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003104 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003105 break;
3106 case 'a':
3107 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003108 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003109 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003110 }
3111 action = SNAPSHOT_APPLY;
3112 snapshot_name = optarg;
3113 break;
3114 case 'c':
3115 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003116 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003117 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003118 }
3119 action = SNAPSHOT_CREATE;
3120 snapshot_name = optarg;
3121 break;
3122 case 'd':
3123 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003124 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003125 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003126 }
3127 action = SNAPSHOT_DELETE;
3128 snapshot_name = optarg;
3129 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003130 case 'q':
3131 quiet = true;
3132 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003133 case 'U':
3134 force_share = true;
3135 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003136 case OPTION_OBJECT: {
3137 QemuOpts *opts;
3138 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3139 optarg, true);
3140 if (!opts) {
3141 return 1;
3142 }
3143 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003144 case OPTION_IMAGE_OPTS:
3145 image_opts = true;
3146 break;
aliguorif7b4a942009-01-07 17:40:15 +00003147 }
3148 }
3149
Kevin Wolffc11eb22013-08-05 10:53:04 +02003150 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003151 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003152 }
aliguorif7b4a942009-01-07 17:40:15 +00003153 filename = argv[optind++];
3154
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003155 if (qemu_opts_foreach(&qemu_object_opts,
3156 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003157 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003158 return 1;
3159 }
3160
aliguorif7b4a942009-01-07 17:40:15 +00003161 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003162 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3163 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003164 if (!blk) {
3165 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003166 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003167 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003168
3169 /* Perform the requested action */
3170 switch(action) {
3171 case SNAPSHOT_LIST:
3172 dump_snapshots(bs);
3173 break;
3174
3175 case SNAPSHOT_CREATE:
3176 memset(&sn, 0, sizeof(sn));
3177 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3178
3179 qemu_gettimeofday(&tv);
3180 sn.date_sec = tv.tv_sec;
3181 sn.date_nsec = tv.tv_usec * 1000;
3182
3183 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003184 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003185 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003186 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003187 }
aliguorif7b4a942009-01-07 17:40:15 +00003188 break;
3189
3190 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003191 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003192 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003193 error_reportf_err(err, "Could not apply snapshot '%s': ",
3194 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003195 }
aliguorif7b4a942009-01-07 17:40:15 +00003196 break;
3197
3198 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003199 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3200 if (ret < 0) {
3201 error_report("Could not delete snapshot '%s': snapshot not "
3202 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003203 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003204 } else {
3205 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3206 if (ret < 0) {
3207 error_reportf_err(err, "Could not delete snapshot '%s': ",
3208 snapshot_name);
3209 ret = 1;
3210 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003211 }
aliguorif7b4a942009-01-07 17:40:15 +00003212 break;
3213 }
3214
3215 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003216 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003217 if (ret) {
3218 return 1;
3219 }
Stuart Brady153859b2009-06-07 00:42:17 +01003220 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003221}
3222
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003223static int img_rebase(int argc, char **argv)
3224{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003225 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003226 uint8_t *buf_old = NULL;
3227 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003228 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003229 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003230 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3231 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003232 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003233 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003234 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003235 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003236 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003237 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003238 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003239
3240 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003241 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003242 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003243 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003244 out_baseimg = NULL;
3245 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003246 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003247 static const struct option long_options[] = {
3248 {"help", no_argument, 0, 'h'},
3249 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003250 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003251 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003252 {0, 0, 0, 0}
3253 };
Fam Zheng335e9932017-05-03 00:35:39 +08003254 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003255 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003256 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003257 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003258 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003259 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003260 case ':':
3261 missing_argument(argv[optind - 1]);
3262 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003263 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003264 unrecognized_option(argv[optind - 1]);
3265 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003266 case 'h':
3267 help();
3268 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003269 case 'f':
3270 fmt = optarg;
3271 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003272 case 'F':
3273 out_basefmt = optarg;
3274 break;
3275 case 'b':
3276 out_baseimg = optarg;
3277 break;
3278 case 'u':
3279 unsafe = 1;
3280 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003281 case 'p':
3282 progress = 1;
3283 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003284 case 't':
3285 cache = optarg;
3286 break;
Max Reitz40055952014-07-22 22:58:42 +02003287 case 'T':
3288 src_cache = optarg;
3289 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003290 case 'q':
3291 quiet = true;
3292 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003293 case OPTION_OBJECT: {
3294 QemuOpts *opts;
3295 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3296 optarg, true);
3297 if (!opts) {
3298 return 1;
3299 }
3300 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003301 case OPTION_IMAGE_OPTS:
3302 image_opts = true;
3303 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003304 case 'U':
3305 force_share = true;
3306 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003307 }
3308 }
3309
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003310 if (quiet) {
3311 progress = 0;
3312 }
3313
Fam Zhengac1307a2014-04-22 13:36:11 +08003314 if (optind != argc - 1) {
3315 error_exit("Expecting one image file name");
3316 }
3317 if (!unsafe && !out_baseimg) {
3318 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003319 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003320 filename = argv[optind++];
3321
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003322 if (qemu_opts_foreach(&qemu_object_opts,
3323 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003324 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003325 return 1;
3326 }
3327
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003328 qemu_progress_init(progress, 2.0);
3329 qemu_progress_print(0, 100);
3330
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003331 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003332 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003333 if (ret < 0) {
3334 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003335 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003336 }
3337
Kevin Wolfce099542016-03-15 13:01:04 +01003338 src_flags = 0;
3339 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003340 if (ret < 0) {
3341 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003342 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003343 }
3344
Kevin Wolfce099542016-03-15 13:01:04 +01003345 /* The source files are opened read-only, don't care about WCE */
3346 assert((src_flags & BDRV_O_RDWR) == 0);
3347 (void) src_writethrough;
3348
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003349 /*
3350 * Open the images.
3351 *
3352 * Ignore the old backing file for unsafe rebase in case we want to correct
3353 * the reference to a renamed or moved backing file.
3354 */
Fam Zheng335e9932017-05-03 00:35:39 +08003355 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3356 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003357 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003358 ret = -1;
3359 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003360 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003361 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003362
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003363 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003364 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003365 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003366 ret = -1;
3367 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003368 }
3369 }
3370
3371 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003372 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003373 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003374 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003375
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003376 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003377 blk_old_backing = blk_new(qemu_get_aio_context(),
3378 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003379 BLK_PERM_ALL);
3380 ret = blk_insert_bs(blk_old_backing, base_bs,
3381 &local_err);
3382 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003383 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003384 "Could not reuse old backing file '%s': ",
3385 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003386 goto out;
3387 }
3388 } else {
3389 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003390 }
Max Reitz644483d2015-02-05 13:58:17 -05003391
Alex Bligha6166732012-10-16 13:46:18 +01003392 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003393 const char *overlay_filename;
3394 char *out_real_path;
3395
Fam Zheng335e9932017-05-03 00:35:39 +08003396 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003397 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003398 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003399 }
3400 if (force_share) {
3401 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003402 }
3403
Max Reitzf30c66b2019-02-01 20:29:05 +01003404 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003405 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3406 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003407 out_real_path =
3408 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3409 out_baseimg,
3410 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003411 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003412 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003413 error_reportf_err(local_err,
3414 "Could not resolve backing filename: ");
3415 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003416 goto out;
3417 }
3418
Sam Eiderman863cc782019-05-23 19:33:36 +03003419 /*
3420 * Find out whether we rebase an image on top of a previous image
3421 * in its chain.
3422 */
3423 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003424 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003425 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003426 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003427
Kevin Wolfd861ab32019-04-25 14:25:10 +02003428 blk_new_backing = blk_new(qemu_get_aio_context(),
3429 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003430 BLK_PERM_ALL);
3431 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3432 &local_err);
3433 if (ret < 0) {
3434 error_reportf_err(local_err,
3435 "Could not reuse backing file '%s': ",
3436 out_baseimg);
3437 goto out;
3438 }
3439 } else {
3440 blk_new_backing = blk_new_open(out_real_path, NULL,
3441 options, src_flags, &local_err);
3442 g_free(out_real_path);
3443 if (!blk_new_backing) {
3444 error_reportf_err(local_err,
3445 "Could not open new backing file '%s': ",
3446 out_baseimg);
3447 ret = -1;
3448 goto out;
3449 }
Alex Bligha6166732012-10-16 13:46:18 +01003450 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003451 }
3452 }
3453
3454 /*
3455 * Check each unallocated cluster in the COW file. If it is unallocated,
3456 * accesses go to the backing file. We must therefore compare this cluster
3457 * in the old and new backing file, and if they differ we need to copy it
3458 * from the old backing file into the COW file.
3459 *
3460 * If qemu-img crashes during this step, no harm is done. The content of
3461 * the image is the same as the original one at any time.
3462 */
3463 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003464 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003465 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003466 int64_t new_backing_size = 0;
3467 uint64_t offset;
3468 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003469 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003470
Max Reitzf1d3cd72015-02-05 13:58:18 -05003471 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3472 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003473
Eric Blake41536282017-10-11 22:47:15 -05003474 size = blk_getlength(blk);
3475 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003476 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003477 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003478 ret = -1;
3479 goto out;
3480 }
Max Reitz35ddd932019-05-09 19:52:35 +02003481 if (blk_old_backing) {
3482 old_backing_size = blk_getlength(blk_old_backing);
3483 if (old_backing_size < 0) {
3484 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003485
Max Reitz35ddd932019-05-09 19:52:35 +02003486 bdrv_get_backing_filename(bs, backing_name,
3487 sizeof(backing_name));
3488 error_report("Could not get size of '%s': %s",
3489 backing_name, strerror(-old_backing_size));
3490 ret = -1;
3491 goto out;
3492 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003493 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003494 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003495 new_backing_size = blk_getlength(blk_new_backing);
3496 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003497 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003498 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003499 ret = -1;
3500 goto out;
3501 }
Alex Bligha6166732012-10-16 13:46:18 +01003502 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003503
Eric Blake41536282017-10-11 22:47:15 -05003504 if (size != 0) {
3505 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003506 }
3507
Eric Blake41536282017-10-11 22:47:15 -05003508 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003509 bool buf_old_is_zero = false;
3510
Eric Blake41536282017-10-11 22:47:15 -05003511 /* How many bytes can we handle with the next read? */
3512 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003513
3514 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003515 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003516 if (ret < 0) {
3517 error_report("error while reading image metadata: %s",
3518 strerror(-ret));
3519 goto out;
3520 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003521 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003522 continue;
3523 }
3524
Sam Eiderman863cc782019-05-23 19:33:36 +03003525 if (prefix_chain_bs) {
3526 /*
3527 * If cluster wasn't changed since prefix_chain, we don't need
3528 * to take action
3529 */
3530 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
Andrey Shinkevich170d3bd2019-05-29 20:56:14 +03003531 false, offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003532 if (ret < 0) {
3533 error_report("error while reading image metadata: %s",
3534 strerror(-ret));
3535 goto out;
3536 }
3537 if (!ret) {
3538 continue;
3539 }
3540 }
3541
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003542 /*
3543 * Read old and new backing file and take into consideration that
3544 * backing files may be smaller than the COW image.
3545 */
Eric Blake41536282017-10-11 22:47:15 -05003546 if (offset >= old_backing_size) {
3547 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003548 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003549 } else {
Eric Blake41536282017-10-11 22:47:15 -05003550 if (offset + n > old_backing_size) {
3551 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003552 }
3553
Eric Blake41536282017-10-11 22:47:15 -05003554 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003555 if (ret < 0) {
3556 error_report("error while reading from old backing file");
3557 goto out;
3558 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003559 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003560
Eric Blake41536282017-10-11 22:47:15 -05003561 if (offset >= new_backing_size || !blk_new_backing) {
3562 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003563 } else {
Eric Blake41536282017-10-11 22:47:15 -05003564 if (offset + n > new_backing_size) {
3565 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003566 }
3567
Eric Blake41536282017-10-11 22:47:15 -05003568 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003569 if (ret < 0) {
3570 error_report("error while reading from new backing file");
3571 goto out;
3572 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003573 }
3574
3575 /* If they differ, we need to write to the COW file */
3576 uint64_t written = 0;
3577
Eric Blake41536282017-10-11 22:47:15 -05003578 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003579 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003580
Eric Blake41536282017-10-11 22:47:15 -05003581 if (compare_buffers(buf_old + written, buf_new + written,
3582 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003583 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003584 if (buf_old_is_zero) {
3585 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3586 } else {
3587 ret = blk_pwrite(blk, offset + written,
3588 buf_old + written, pnum, 0);
3589 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003590 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003591 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003592 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003593 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003594 }
3595 }
3596
3597 written += pnum;
3598 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003599 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003600 }
3601 }
3602
3603 /*
3604 * Change the backing file. All clusters that are different from the old
3605 * backing file are overwritten in the COW file now, so the visible content
3606 * doesn't change when we switch the backing file.
3607 */
Alex Bligha6166732012-10-16 13:46:18 +01003608 if (out_baseimg && *out_baseimg) {
3609 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3610 } else {
3611 ret = bdrv_change_backing_file(bs, NULL, NULL);
3612 }
3613
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003614 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003615 error_report("Could not change the backing file to '%s': No "
3616 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003617 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003618 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003619 out_baseimg, strerror(-ret));
3620 }
3621
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003622 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003623 /*
3624 * TODO At this point it is possible to check if any clusters that are
3625 * allocated in the COW file are the same in the backing file. If so, they
3626 * could be dropped from the COW file. Don't do this before switching the
3627 * backing file, in case of a crash this would lead to corruption.
3628 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003629out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003630 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003631 /* Cleanup */
3632 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003633 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003634 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003635 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003636 qemu_vfree(buf_old);
3637 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003638
Markus Armbruster26f54e92014-10-07 13:59:04 +02003639 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003640 if (ret) {
3641 return 1;
3642 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003643 return 0;
3644}
3645
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003646static int img_resize(int argc, char **argv)
3647{
Markus Armbruster6750e792015-02-12 17:43:08 +01003648 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003649 int c, ret, relative;
3650 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003651 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003652 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003653 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003654 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003655 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003656
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003657 static QemuOptsList resize_options = {
3658 .name = "resize_options",
3659 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3660 .desc = {
3661 {
3662 .name = BLOCK_OPT_SIZE,
3663 .type = QEMU_OPT_SIZE,
3664 .help = "Virtual disk size"
3665 }, {
3666 /* end of list */
3667 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003668 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003669 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003670 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003671 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003672
Kevin Wolfe80fec72011-04-29 10:58:12 +02003673 /* Remove size from argv manually so that negative numbers are not treated
3674 * as options by getopt. */
3675 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003676 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003677 return 1;
3678 }
3679
3680 size = argv[--argc];
3681
3682 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003683 fmt = NULL;
3684 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003685 static const struct option long_options[] = {
3686 {"help", no_argument, 0, 'h'},
3687 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003688 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003689 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003690 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003691 {0, 0, 0, 0}
3692 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003693 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003694 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003695 if (c == -1) {
3696 break;
3697 }
3698 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003699 case ':':
3700 missing_argument(argv[optind - 1]);
3701 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003702 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003703 unrecognized_option(argv[optind - 1]);
3704 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003705 case 'h':
3706 help();
3707 break;
3708 case 'f':
3709 fmt = optarg;
3710 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003711 case 'q':
3712 quiet = true;
3713 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003714 case OPTION_OBJECT: {
3715 QemuOpts *opts;
3716 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3717 optarg, true);
3718 if (!opts) {
3719 return 1;
3720 }
3721 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003722 case OPTION_IMAGE_OPTS:
3723 image_opts = true;
3724 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003725 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003726 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003727 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003728 if (prealloc == PREALLOC_MODE__MAX) {
3729 error_report("Invalid preallocation mode '%s'", optarg);
3730 return 1;
3731 }
3732 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003733 case OPTION_SHRINK:
3734 shrink = true;
3735 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003736 }
3737 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003738 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003739 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003740 }
3741 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003742
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003743 if (qemu_opts_foreach(&qemu_object_opts,
3744 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003745 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003746 return 1;
3747 }
3748
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003749 /* Choose grow, shrink, or absolute resize mode */
3750 switch (size[0]) {
3751 case '+':
3752 relative = 1;
3753 size++;
3754 break;
3755 case '-':
3756 relative = -1;
3757 size++;
3758 break;
3759 default:
3760 relative = 0;
3761 break;
3762 }
3763
3764 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003765 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003766 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003767 if (err) {
3768 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003769 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003770 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003771 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003772 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003773 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3774 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003775
Max Reitzefaa7c42016-03-16 19:54:38 +01003776 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003777 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3778 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003779 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003780 ret = -1;
3781 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003782 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003783
Max Reitzdc5f6902017-06-13 22:20:55 +02003784 current_size = blk_getlength(blk);
3785 if (current_size < 0) {
3786 error_report("Failed to inquire current image length: %s",
3787 strerror(-current_size));
3788 ret = -1;
3789 goto out;
3790 }
3791
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003792 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003793 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003794 } else {
3795 total_size = n;
3796 }
3797 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003798 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003799 ret = -1;
3800 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003801 }
3802
Max Reitzdc5f6902017-06-13 22:20:55 +02003803 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3804 error_report("Preallocation can only be used for growing images");
3805 ret = -1;
3806 goto out;
3807 }
3808
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003809 if (total_size < current_size && !shrink) {
3810 warn_report("Shrinking an image will delete all data beyond the "
3811 "shrunken image's end. Before performing such an "
3812 "operation, make sure there is no important data there.");
3813
3814 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3815 error_report(
3816 "Use the --shrink option to perform a shrink operation.");
3817 ret = -1;
3818 goto out;
3819 } else {
3820 warn_report("Using the --shrink option will suppress this message. "
3821 "Note that future versions of qemu-img may refuse to "
3822 "shrink images without this option.");
3823 }
3824 }
3825
Max Reitzdc5f6902017-06-13 22:20:55 +02003826 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003827 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003828 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003829 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003830 }
Max Reitz5279b302018-04-21 18:39:57 +02003831
3832 new_size = blk_getlength(blk);
3833 if (new_size < 0) {
3834 error_report("Failed to verify truncated image length: %s",
3835 strerror(-new_size));
3836 ret = -1;
3837 goto out;
3838 }
3839
3840 /* Some block drivers implement a truncation method, but only so
3841 * the user can cause qemu to refresh the image's size from disk.
3842 * The idea is that the user resizes the image outside of qemu and
3843 * then invokes block_resize to inform qemu about it.
3844 * (This includes iscsi and file-posix for device files.)
3845 * Of course, that is not the behavior someone invoking
3846 * qemu-img resize would find useful, so we catch that behavior
3847 * here and tell the user. */
3848 if (new_size != total_size && new_size == current_size) {
3849 error_report("Image was not resized; resizing may not be supported "
3850 "for this image");
3851 ret = -1;
3852 goto out;
3853 }
3854
3855 if (new_size != total_size) {
3856 warn_report("Image should have been resized to %" PRIi64
3857 " bytes, but was resized to %" PRIi64 " bytes",
3858 total_size, new_size);
3859 }
3860
3861 qprintf(quiet, "Image resized.\n");
3862
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003863out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003864 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003865 if (ret) {
3866 return 1;
3867 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003868 return 0;
3869}
3870
Max Reitz76a3a342014-10-27 11:12:51 +01003871static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003872 int64_t offset, int64_t total_work_size,
3873 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003874{
3875 qemu_progress_print(100.f * offset / total_work_size, 0);
3876}
3877
Max Reitz51641352018-05-09 23:00:20 +02003878static int print_amend_option_help(const char *format)
3879{
3880 BlockDriver *drv;
3881
3882 /* Find driver and parse its options */
3883 drv = bdrv_find_format(format);
3884 if (!drv) {
3885 error_report("Unknown file format '%s'", format);
3886 return 1;
3887 }
3888
3889 if (!drv->bdrv_amend_options) {
3890 error_report("Format driver '%s' does not support option amendment",
3891 format);
3892 return 1;
3893 }
3894
3895 /* Every driver supporting amendment must have create_opts */
3896 assert(drv->create_opts);
3897
3898 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003899 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003900 printf("\nNote that not all of these options may be amendable.\n");
3901 return 0;
3902}
3903
Max Reitz6f176b42013-09-03 10:09:50 +02003904static int img_amend(int argc, char **argv)
3905{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003906 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003907 int c, ret = 0;
3908 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003909 QemuOptsList *create_opts = NULL;
3910 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003911 const char *fmt = NULL, *filename, *cache;
3912 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003913 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003914 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003915 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003916 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003917 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003918
Max Reitzbd39e6e2014-07-22 22:58:43 +02003919 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003920 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003921 static const struct option long_options[] = {
3922 {"help", no_argument, 0, 'h'},
3923 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003924 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003925 {0, 0, 0, 0}
3926 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003927 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003928 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003929 if (c == -1) {
3930 break;
3931 }
3932
3933 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003934 case ':':
3935 missing_argument(argv[optind - 1]);
3936 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003937 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003938 unrecognized_option(argv[optind - 1]);
3939 break;
3940 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003941 help();
3942 break;
3943 case 'o':
3944 if (!is_valid_option_list(optarg)) {
3945 error_report("Invalid option list: %s", optarg);
3946 ret = -1;
3947 goto out_no_progress;
3948 }
3949 if (!options) {
3950 options = g_strdup(optarg);
3951 } else {
3952 char *old_options = options;
3953 options = g_strdup_printf("%s,%s", options, optarg);
3954 g_free(old_options);
3955 }
3956 break;
3957 case 'f':
3958 fmt = optarg;
3959 break;
3960 case 't':
3961 cache = optarg;
3962 break;
3963 case 'p':
3964 progress = true;
3965 break;
3966 case 'q':
3967 quiet = true;
3968 break;
3969 case OPTION_OBJECT:
3970 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3971 optarg, true);
3972 if (!opts) {
3973 ret = -1;
3974 goto out_no_progress;
3975 }
3976 break;
3977 case OPTION_IMAGE_OPTS:
3978 image_opts = true;
3979 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003980 }
3981 }
3982
Max Reitz6f176b42013-09-03 10:09:50 +02003983 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003984 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003985 }
3986
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003987 if (qemu_opts_foreach(&qemu_object_opts,
3988 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003989 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003990 ret = -1;
3991 goto out_no_progress;
3992 }
3993
Max Reitz76a3a342014-10-27 11:12:51 +01003994 if (quiet) {
3995 progress = false;
3996 }
3997 qemu_progress_init(progress, 1.0);
3998
Kevin Wolfa283cb62014-02-21 16:24:07 +01003999 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4000 if (fmt && has_help_option(options)) {
4001 /* If a format is explicitly specified (and possibly no filename is
4002 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004003 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004004 goto out;
4005 }
4006
4007 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004008 error_report("Expecting one image file name");
4009 ret = -1;
4010 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004011 }
Max Reitz6f176b42013-09-03 10:09:50 +02004012
Kevin Wolfce099542016-03-15 13:01:04 +01004013 flags = BDRV_O_RDWR;
4014 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004015 if (ret < 0) {
4016 error_report("Invalid cache option: %s", cache);
4017 goto out;
4018 }
4019
Fam Zheng335e9932017-05-03 00:35:39 +08004020 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4021 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004022 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004023 ret = -1;
4024 goto out;
4025 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004026 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004027
4028 fmt = bs->drv->format_name;
4029
Kevin Wolf626f84f2014-02-21 16:24:06 +01004030 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004031 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004032 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004033 goto out;
4034 }
4035
Max Reitz1f996682018-05-09 23:00:17 +02004036 if (!bs->drv->bdrv_amend_options) {
4037 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004038 fmt);
4039 ret = -1;
4040 goto out;
4041 }
4042
Max Reitz1f996682018-05-09 23:00:17 +02004043 /* Every driver supporting amendment must have create_opts */
4044 assert(bs->drv->create_opts);
4045
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004046 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08004047 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01004048 qemu_opts_do_parse(opts, options, NULL, &err);
4049 if (err) {
4050 error_report_err(err);
4051 ret = -1;
4052 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004053 }
4054
Max Reitz76a3a342014-10-27 11:12:51 +01004055 /* In case the driver does not call amend_status_cb() */
4056 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02004057 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004058 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004059 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004060 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004061 goto out;
4062 }
4063
4064out:
Max Reitz76a3a342014-10-27 11:12:51 +01004065 qemu_progress_end();
4066
Max Reitze814dff2015-08-20 16:00:38 -07004067out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004068 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004069 qemu_opts_del(opts);
4070 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004071 g_free(options);
4072
Max Reitz6f176b42013-09-03 10:09:50 +02004073 if (ret) {
4074 return 1;
4075 }
4076 return 0;
4077}
4078
Kevin Wolfb6133b82014-08-05 14:17:13 +02004079typedef struct BenchData {
4080 BlockBackend *blk;
4081 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004082 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004083 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004084 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004085 int nrreq;
4086 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004087 int flush_interval;
4088 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004089 uint8_t *buf;
4090 QEMUIOVector *qiov;
4091
4092 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004093 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004094 uint64_t offset;
4095} BenchData;
4096
Kevin Wolf55d539c2016-06-03 13:59:41 +02004097static void bench_undrained_flush_cb(void *opaque, int ret)
4098{
4099 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004100 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004101 exit(EXIT_FAILURE);
4102 }
4103}
4104
Kevin Wolfb6133b82014-08-05 14:17:13 +02004105static void bench_cb(void *opaque, int ret)
4106{
4107 BenchData *b = opaque;
4108 BlockAIOCB *acb;
4109
4110 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004111 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004112 exit(EXIT_FAILURE);
4113 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004114
4115 if (b->in_flush) {
4116 /* Just finished a flush with drained queue: Start next requests */
4117 assert(b->in_flight == 0);
4118 b->in_flush = false;
4119 } else if (b->in_flight > 0) {
4120 int remaining = b->n - b->in_flight;
4121
Kevin Wolfb6133b82014-08-05 14:17:13 +02004122 b->n--;
4123 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004124
4125 /* Time for flush? Drain queue if requested, then flush */
4126 if (b->flush_interval && remaining % b->flush_interval == 0) {
4127 if (!b->in_flight || !b->drain_on_flush) {
4128 BlockCompletionFunc *cb;
4129
4130 if (b->drain_on_flush) {
4131 b->in_flush = true;
4132 cb = bench_cb;
4133 } else {
4134 cb = bench_undrained_flush_cb;
4135 }
4136
4137 acb = blk_aio_flush(b->blk, cb, b);
4138 if (!acb) {
4139 error_report("Failed to issue flush request");
4140 exit(EXIT_FAILURE);
4141 }
4142 }
4143 if (b->drain_on_flush) {
4144 return;
4145 }
4146 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004147 }
4148
4149 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004150 int64_t offset = b->offset;
4151 /* blk_aio_* might look for completed I/Os and kick bench_cb
4152 * again, so make sure this operation is counted by in_flight
4153 * and b->offset is ready for the next submission.
4154 */
4155 b->in_flight++;
4156 b->offset += b->step;
4157 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004158 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004159 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004160 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004161 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004162 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004163 if (!acb) {
4164 error_report("Failed to issue request");
4165 exit(EXIT_FAILURE);
4166 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004167 }
4168}
4169
4170static int img_bench(int argc, char **argv)
4171{
4172 int c, ret = 0;
4173 const char *fmt = NULL, *filename;
4174 bool quiet = false;
4175 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004176 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004177 int count = 75000;
4178 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004179 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004180 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004181 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004182 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004183 int flush_interval = 0;
4184 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004185 int64_t image_size;
4186 BlockBackend *blk = NULL;
4187 BenchData data = {};
4188 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004189 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004190 struct timeval t1, t2;
4191 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004192 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004193 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004194
4195 for (;;) {
4196 static const struct option long_options[] = {
4197 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004198 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004199 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004200 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004201 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004202 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004203 {0, 0, 0, 0}
4204 };
Fam Zheng335e9932017-05-03 00:35:39 +08004205 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004206 if (c == -1) {
4207 break;
4208 }
4209
4210 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004211 case ':':
4212 missing_argument(argv[optind - 1]);
4213 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004214 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004215 unrecognized_option(argv[optind - 1]);
4216 break;
4217 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004218 help();
4219 break;
4220 case 'c':
4221 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004222 unsigned long res;
4223
4224 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004225 error_report("Invalid request count specified");
4226 return 1;
4227 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004228 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004229 break;
4230 }
4231 case 'd':
4232 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004233 unsigned long res;
4234
4235 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004236 error_report("Invalid queue depth specified");
4237 return 1;
4238 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004239 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004240 break;
4241 }
4242 case 'f':
4243 fmt = optarg;
4244 break;
4245 case 'n':
4246 flags |= BDRV_O_NATIVE_AIO;
4247 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004248 case 'o':
4249 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004250 offset = cvtnum(optarg);
4251 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004252 error_report("Invalid offset specified");
4253 return 1;
4254 }
4255 break;
4256 }
4257 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004258 case 'q':
4259 quiet = true;
4260 break;
4261 case 's':
4262 {
4263 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004264
Markus Armbruster606caa02017-02-21 21:14:04 +01004265 sval = cvtnum(optarg);
4266 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004267 error_report("Invalid buffer size specified");
4268 return 1;
4269 }
4270
4271 bufsize = sval;
4272 break;
4273 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004274 case 'S':
4275 {
4276 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004277
Markus Armbruster606caa02017-02-21 21:14:04 +01004278 sval = cvtnum(optarg);
4279 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004280 error_report("Invalid step size specified");
4281 return 1;
4282 }
4283
4284 step = sval;
4285 break;
4286 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004287 case 't':
4288 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4289 if (ret < 0) {
4290 error_report("Invalid cache mode");
4291 ret = -1;
4292 goto out;
4293 }
4294 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004295 case 'w':
4296 flags |= BDRV_O_RDWR;
4297 is_write = true;
4298 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004299 case 'U':
4300 force_share = true;
4301 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004302 case OPTION_PATTERN:
4303 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004304 unsigned long res;
4305
4306 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004307 error_report("Invalid pattern byte specified");
4308 return 1;
4309 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004310 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004311 break;
4312 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004313 case OPTION_FLUSH_INTERVAL:
4314 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004315 unsigned long res;
4316
4317 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004318 error_report("Invalid flush interval specified");
4319 return 1;
4320 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004321 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004322 break;
4323 }
4324 case OPTION_NO_DRAIN:
4325 drain_on_flush = false;
4326 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004327 case OPTION_IMAGE_OPTS:
4328 image_opts = true;
4329 break;
4330 }
4331 }
4332
4333 if (optind != argc - 1) {
4334 error_exit("Expecting one image file name");
4335 }
4336 filename = argv[argc - 1];
4337
Kevin Wolf55d539c2016-06-03 13:59:41 +02004338 if (!is_write && flush_interval) {
4339 error_report("--flush-interval is only available in write tests");
4340 ret = -1;
4341 goto out;
4342 }
4343 if (flush_interval && flush_interval < depth) {
4344 error_report("Flush interval can't be smaller than depth");
4345 ret = -1;
4346 goto out;
4347 }
4348
Fam Zheng335e9932017-05-03 00:35:39 +08004349 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4350 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004351 if (!blk) {
4352 ret = -1;
4353 goto out;
4354 }
4355
4356 image_size = blk_getlength(blk);
4357 if (image_size < 0) {
4358 ret = image_size;
4359 goto out;
4360 }
4361
4362 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004363 .blk = blk,
4364 .image_size = image_size,
4365 .bufsize = bufsize,
4366 .step = step ?: bufsize,
4367 .nrreq = depth,
4368 .n = count,
4369 .offset = offset,
4370 .write = is_write,
4371 .flush_interval = flush_interval,
4372 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004373 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004374 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004375 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004376 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004377 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004378 if (flush_interval) {
4379 printf("Sending flush every %d requests\n", flush_interval);
4380 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004381
Fam Zheng79d46582018-01-16 14:08:58 +08004382 buf_size = data.nrreq * data.bufsize;
4383 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004384 memset(data.buf, pattern, data.nrreq * data.bufsize);
4385
Fam Zheng79d46582018-01-16 14:08:58 +08004386 blk_register_buf(blk, data.buf, buf_size);
4387
Kevin Wolfb6133b82014-08-05 14:17:13 +02004388 data.qiov = g_new(QEMUIOVector, data.nrreq);
4389 for (i = 0; i < data.nrreq; i++) {
4390 qemu_iovec_init(&data.qiov[i], 1);
4391 qemu_iovec_add(&data.qiov[i],
4392 data.buf + i * data.bufsize, data.bufsize);
4393 }
4394
4395 gettimeofday(&t1, NULL);
4396 bench_cb(&data, 0);
4397
4398 while (data.n > 0) {
4399 main_loop_wait(false);
4400 }
4401 gettimeofday(&t2, NULL);
4402
4403 printf("Run completed in %3.3f seconds.\n",
4404 (t2.tv_sec - t1.tv_sec)
4405 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4406
4407out:
Fam Zheng79d46582018-01-16 14:08:58 +08004408 if (data.buf) {
4409 blk_unregister_buf(blk, data.buf);
4410 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004411 qemu_vfree(data.buf);
4412 blk_unref(blk);
4413
4414 if (ret) {
4415 return 1;
4416 }
4417 return 0;
4418}
4419
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004420#define C_BS 01
4421#define C_COUNT 02
4422#define C_IF 04
4423#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004424#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004425
4426struct DdInfo {
4427 unsigned int flags;
4428 int64_t count;
4429};
4430
4431struct DdIo {
4432 int bsz; /* Block size */
4433 char *filename;
4434 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004435 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004436};
4437
4438struct DdOpts {
4439 const char *name;
4440 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4441 unsigned int flag;
4442};
4443
4444static int img_dd_bs(const char *arg,
4445 struct DdIo *in, struct DdIo *out,
4446 struct DdInfo *dd)
4447{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004448 int64_t res;
4449
Markus Armbruster606caa02017-02-21 21:14:04 +01004450 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004451
Markus Armbruster606caa02017-02-21 21:14:04 +01004452 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004453 error_report("invalid number: '%s'", arg);
4454 return 1;
4455 }
4456 in->bsz = out->bsz = res;
4457
4458 return 0;
4459}
4460
4461static int img_dd_count(const char *arg,
4462 struct DdIo *in, struct DdIo *out,
4463 struct DdInfo *dd)
4464{
Markus Armbruster606caa02017-02-21 21:14:04 +01004465 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004466
Markus Armbruster606caa02017-02-21 21:14:04 +01004467 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004468 error_report("invalid number: '%s'", arg);
4469 return 1;
4470 }
4471
4472 return 0;
4473}
4474
4475static int img_dd_if(const char *arg,
4476 struct DdIo *in, struct DdIo *out,
4477 struct DdInfo *dd)
4478{
4479 in->filename = g_strdup(arg);
4480
4481 return 0;
4482}
4483
4484static int img_dd_of(const char *arg,
4485 struct DdIo *in, struct DdIo *out,
4486 struct DdInfo *dd)
4487{
4488 out->filename = g_strdup(arg);
4489
4490 return 0;
4491}
4492
Reda Sallahif7c15532016-08-10 16:16:09 +02004493static int img_dd_skip(const char *arg,
4494 struct DdIo *in, struct DdIo *out,
4495 struct DdInfo *dd)
4496{
Markus Armbruster606caa02017-02-21 21:14:04 +01004497 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004498
Markus Armbruster606caa02017-02-21 21:14:04 +01004499 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004500 error_report("invalid number: '%s'", arg);
4501 return 1;
4502 }
4503
4504 return 0;
4505}
4506
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004507static int img_dd(int argc, char **argv)
4508{
4509 int ret = 0;
4510 char *arg = NULL;
4511 char *tmp;
4512 BlockDriver *drv = NULL, *proto_drv = NULL;
4513 BlockBackend *blk1 = NULL, *blk2 = NULL;
4514 QemuOpts *opts = NULL;
4515 QemuOptsList *create_opts = NULL;
4516 Error *local_err = NULL;
4517 bool image_opts = false;
4518 int c, i;
4519 const char *out_fmt = "raw";
4520 const char *fmt = NULL;
4521 int64_t size = 0;
4522 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004523 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004524 struct DdInfo dd = {
4525 .flags = 0,
4526 .count = 0,
4527 };
4528 struct DdIo in = {
4529 .bsz = 512, /* Block size is by default 512 bytes */
4530 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004531 .buf = NULL,
4532 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004533 };
4534 struct DdIo out = {
4535 .bsz = 512,
4536 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004537 .buf = NULL,
4538 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004539 };
4540
4541 const struct DdOpts options[] = {
4542 { "bs", img_dd_bs, C_BS },
4543 { "count", img_dd_count, C_COUNT },
4544 { "if", img_dd_if, C_IF },
4545 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004546 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004547 { NULL, NULL, 0 }
4548 };
4549 const struct option long_options[] = {
4550 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004551 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004552 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004553 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004554 { 0, 0, 0, 0 }
4555 };
4556
Fam Zheng335e9932017-05-03 00:35:39 +08004557 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004558 if (c == EOF) {
4559 break;
4560 }
4561 switch (c) {
4562 case 'O':
4563 out_fmt = optarg;
4564 break;
4565 case 'f':
4566 fmt = optarg;
4567 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004568 case ':':
4569 missing_argument(argv[optind - 1]);
4570 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004571 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004572 unrecognized_option(argv[optind - 1]);
4573 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004574 case 'h':
4575 help();
4576 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004577 case 'U':
4578 force_share = true;
4579 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004580 case OPTION_OBJECT:
4581 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004582 ret = -1;
4583 goto out;
4584 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004585 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004586 case OPTION_IMAGE_OPTS:
4587 image_opts = true;
4588 break;
4589 }
4590 }
4591
4592 for (i = optind; i < argc; i++) {
4593 int j;
4594 arg = g_strdup(argv[i]);
4595
4596 tmp = strchr(arg, '=');
4597 if (tmp == NULL) {
4598 error_report("unrecognized operand %s", arg);
4599 ret = -1;
4600 goto out;
4601 }
4602
4603 *tmp++ = '\0';
4604
4605 for (j = 0; options[j].name != NULL; j++) {
4606 if (!strcmp(arg, options[j].name)) {
4607 break;
4608 }
4609 }
4610 if (options[j].name == NULL) {
4611 error_report("unrecognized operand %s", arg);
4612 ret = -1;
4613 goto out;
4614 }
4615
4616 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4617 ret = -1;
4618 goto out;
4619 }
4620 dd.flags |= options[j].flag;
4621 g_free(arg);
4622 arg = NULL;
4623 }
4624
4625 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4626 error_report("Must specify both input and output files");
4627 ret = -1;
4628 goto out;
4629 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004630
4631 if (qemu_opts_foreach(&qemu_object_opts,
4632 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004633 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004634 ret = -1;
4635 goto out;
4636 }
4637
Fam Zheng335e9932017-05-03 00:35:39 +08004638 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4639 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004640
4641 if (!blk1) {
4642 ret = -1;
4643 goto out;
4644 }
4645
4646 drv = bdrv_find_format(out_fmt);
4647 if (!drv) {
4648 error_report("Unknown file format");
4649 ret = -1;
4650 goto out;
4651 }
4652 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4653
4654 if (!proto_drv) {
4655 error_report_err(local_err);
4656 ret = -1;
4657 goto out;
4658 }
4659 if (!drv->create_opts) {
4660 error_report("Format driver '%s' does not support image creation",
4661 drv->format_name);
4662 ret = -1;
4663 goto out;
4664 }
4665 if (!proto_drv->create_opts) {
4666 error_report("Protocol driver '%s' does not support image creation",
4667 proto_drv->format_name);
4668 ret = -1;
4669 goto out;
4670 }
4671 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4672 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4673
4674 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4675
4676 size = blk_getlength(blk1);
4677 if (size < 0) {
4678 error_report("Failed to get size for '%s'", in.filename);
4679 ret = -1;
4680 goto out;
4681 }
4682
4683 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4684 dd.count * in.bsz < size) {
4685 size = dd.count * in.bsz;
4686 }
4687
Reda Sallahif7c15532016-08-10 16:16:09 +02004688 /* Overflow means the specified offset is beyond input image's size */
4689 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4690 size < in.bsz * in.offset)) {
4691 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4692 } else {
4693 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4694 size - in.bsz * in.offset, &error_abort);
4695 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004696
4697 ret = bdrv_create(drv, out.filename, opts, &local_err);
4698 if (ret < 0) {
4699 error_reportf_err(local_err,
4700 "%s: error while creating output image: ",
4701 out.filename);
4702 ret = -1;
4703 goto out;
4704 }
4705
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004706 /* TODO, we can't honour --image-opts for the target,
4707 * since it needs to be given in a format compatible
4708 * with the bdrv_create() call above which does not
4709 * support image-opts style.
4710 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004711 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004712 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004713
4714 if (!blk2) {
4715 ret = -1;
4716 goto out;
4717 }
4718
Reda Sallahif7c15532016-08-10 16:16:09 +02004719 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4720 size < in.offset * in.bsz)) {
4721 /* We give a warning if the skip option is bigger than the input
4722 * size and create an empty output disk image (i.e. like dd(1)).
4723 */
4724 error_report("%s: cannot skip to specified offset", in.filename);
4725 in_pos = size;
4726 } else {
4727 in_pos = in.offset * in.bsz;
4728 }
4729
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004730 in.buf = g_new(uint8_t, in.bsz);
4731
Reda Sallahif7c15532016-08-10 16:16:09 +02004732 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004733 int in_ret, out_ret;
4734
4735 if (in_pos + in.bsz > size) {
4736 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4737 } else {
4738 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4739 }
4740 if (in_ret < 0) {
4741 error_report("error while reading from input image file: %s",
4742 strerror(-in_ret));
4743 ret = -1;
4744 goto out;
4745 }
4746 in_pos += in_ret;
4747
4748 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4749
4750 if (out_ret < 0) {
4751 error_report("error while writing to output image file: %s",
4752 strerror(-out_ret));
4753 ret = -1;
4754 goto out;
4755 }
4756 out_pos += out_ret;
4757 }
4758
4759out:
4760 g_free(arg);
4761 qemu_opts_del(opts);
4762 qemu_opts_free(create_opts);
4763 blk_unref(blk1);
4764 blk_unref(blk2);
4765 g_free(in.filename);
4766 g_free(out.filename);
4767 g_free(in.buf);
4768 g_free(out.buf);
4769
4770 if (ret) {
4771 return 1;
4772 }
4773 return 0;
4774}
4775
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004776static void dump_json_block_measure_info(BlockMeasureInfo *info)
4777{
4778 QString *str;
4779 QObject *obj;
4780 Visitor *v = qobject_output_visitor_new(&obj);
4781
4782 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4783 visit_complete(v, &obj);
4784 str = qobject_to_json_pretty(obj);
4785 assert(str != NULL);
4786 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004787 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004788 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004789 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004790}
4791
4792static int img_measure(int argc, char **argv)
4793{
4794 static const struct option long_options[] = {
4795 {"help", no_argument, 0, 'h'},
4796 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4797 {"object", required_argument, 0, OPTION_OBJECT},
4798 {"output", required_argument, 0, OPTION_OUTPUT},
4799 {"size", required_argument, 0, OPTION_SIZE},
4800 {"force-share", no_argument, 0, 'U'},
4801 {0, 0, 0, 0}
4802 };
4803 OutputFormat output_format = OFORMAT_HUMAN;
4804 BlockBackend *in_blk = NULL;
4805 BlockDriver *drv;
4806 const char *filename = NULL;
4807 const char *fmt = NULL;
4808 const char *out_fmt = "raw";
4809 char *options = NULL;
4810 char *snapshot_name = NULL;
4811 bool force_share = false;
4812 QemuOpts *opts = NULL;
4813 QemuOpts *object_opts = NULL;
4814 QemuOpts *sn_opts = NULL;
4815 QemuOptsList *create_opts = NULL;
4816 bool image_opts = false;
4817 uint64_t img_size = UINT64_MAX;
4818 BlockMeasureInfo *info = NULL;
4819 Error *local_err = NULL;
4820 int ret = 1;
4821 int c;
4822
4823 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4824 long_options, NULL)) != -1) {
4825 switch (c) {
4826 case '?':
4827 case 'h':
4828 help();
4829 break;
4830 case 'f':
4831 fmt = optarg;
4832 break;
4833 case 'O':
4834 out_fmt = optarg;
4835 break;
4836 case 'o':
4837 if (!is_valid_option_list(optarg)) {
4838 error_report("Invalid option list: %s", optarg);
4839 goto out;
4840 }
4841 if (!options) {
4842 options = g_strdup(optarg);
4843 } else {
4844 char *old_options = options;
4845 options = g_strdup_printf("%s,%s", options, optarg);
4846 g_free(old_options);
4847 }
4848 break;
4849 case 'l':
4850 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4851 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4852 optarg, false);
4853 if (!sn_opts) {
4854 error_report("Failed in parsing snapshot param '%s'",
4855 optarg);
4856 goto out;
4857 }
4858 } else {
4859 snapshot_name = optarg;
4860 }
4861 break;
4862 case 'U':
4863 force_share = true;
4864 break;
4865 case OPTION_OBJECT:
4866 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4867 optarg, true);
4868 if (!object_opts) {
4869 goto out;
4870 }
4871 break;
4872 case OPTION_IMAGE_OPTS:
4873 image_opts = true;
4874 break;
4875 case OPTION_OUTPUT:
4876 if (!strcmp(optarg, "json")) {
4877 output_format = OFORMAT_JSON;
4878 } else if (!strcmp(optarg, "human")) {
4879 output_format = OFORMAT_HUMAN;
4880 } else {
4881 error_report("--output must be used with human or json "
4882 "as argument.");
4883 goto out;
4884 }
4885 break;
4886 case OPTION_SIZE:
4887 {
4888 int64_t sval;
4889
4890 sval = cvtnum(optarg);
4891 if (sval < 0) {
4892 if (sval == -ERANGE) {
4893 error_report("Image size must be less than 8 EiB!");
4894 } else {
4895 error_report("Invalid image size specified! You may use "
4896 "k, M, G, T, P or E suffixes for ");
4897 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4898 "petabytes and exabytes.");
4899 }
4900 goto out;
4901 }
4902 img_size = (uint64_t)sval;
4903 }
4904 break;
4905 }
4906 }
4907
4908 if (qemu_opts_foreach(&qemu_object_opts,
4909 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004910 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004911 goto out;
4912 }
4913
4914 if (argc - optind > 1) {
4915 error_report("At most one filename argument is allowed.");
4916 goto out;
4917 } else if (argc - optind == 1) {
4918 filename = argv[optind];
4919 }
4920
4921 if (!filename &&
4922 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4923 error_report("--object, --image-opts, -f, and -l "
4924 "require a filename argument.");
4925 goto out;
4926 }
4927 if (filename && img_size != UINT64_MAX) {
4928 error_report("--size N cannot be used together with a filename.");
4929 goto out;
4930 }
4931 if (!filename && img_size == UINT64_MAX) {
4932 error_report("Either --size N or one filename must be specified.");
4933 goto out;
4934 }
4935
4936 if (filename) {
4937 in_blk = img_open(image_opts, filename, fmt, 0,
4938 false, false, force_share);
4939 if (!in_blk) {
4940 goto out;
4941 }
4942
4943 if (sn_opts) {
4944 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4945 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4946 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4947 &local_err);
4948 } else if (snapshot_name != NULL) {
4949 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4950 snapshot_name, &local_err);
4951 }
4952 if (local_err) {
4953 error_reportf_err(local_err, "Failed to load snapshot: ");
4954 goto out;
4955 }
4956 }
4957
4958 drv = bdrv_find_format(out_fmt);
4959 if (!drv) {
4960 error_report("Unknown file format '%s'", out_fmt);
4961 goto out;
4962 }
4963 if (!drv->create_opts) {
4964 error_report("Format driver '%s' does not support image creation",
4965 drv->format_name);
4966 goto out;
4967 }
4968
4969 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4970 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4971 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4972 if (options) {
4973 qemu_opts_do_parse(opts, options, NULL, &local_err);
4974 if (local_err) {
4975 error_report_err(local_err);
4976 error_report("Invalid options for file format '%s'", out_fmt);
4977 goto out;
4978 }
4979 }
4980 if (img_size != UINT64_MAX) {
4981 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4982 }
4983
4984 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4985 if (local_err) {
4986 error_report_err(local_err);
4987 goto out;
4988 }
4989
4990 if (output_format == OFORMAT_HUMAN) {
4991 printf("required size: %" PRIu64 "\n", info->required);
4992 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4993 } else {
4994 dump_json_block_measure_info(info);
4995 }
4996
4997 ret = 0;
4998
4999out:
5000 qapi_free_BlockMeasureInfo(info);
5001 qemu_opts_del(object_opts);
5002 qemu_opts_del(opts);
5003 qemu_opts_del(sn_opts);
5004 qemu_opts_free(create_opts);
5005 g_free(options);
5006 blk_unref(in_blk);
5007 return ret;
5008}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005009
Anthony Liguoric227f092009-10-01 16:12:16 -05005010static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005011#define DEF(option, callback, arg_string) \
5012 { option, callback },
5013#include "qemu-img-cmds.h"
5014#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005015 { NULL, NULL, },
5016};
5017
bellardea2384d2004-08-01 21:59:26 +00005018int main(int argc, char **argv)
5019{
Anthony Liguoric227f092009-10-01 16:12:16 -05005020 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005021 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005022 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005023 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005024 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005025 static const struct option long_options[] = {
5026 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005027 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005028 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005029 {0, 0, 0, 0}
5030 };
bellardea2384d2004-08-01 21:59:26 +00005031
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005032#ifdef CONFIG_POSIX
5033 signal(SIGPIPE, SIG_IGN);
5034#endif
5035
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005036 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005037 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005038 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005039
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005040 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005041 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005042 exit(EXIT_FAILURE);
5043 }
5044
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005045 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005046
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005047 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005048 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005049 if (argc < 2) {
5050 error_exit("Not enough arguments");
5051 }
Stuart Brady153859b2009-06-07 00:42:17 +01005052
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005053 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005054 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005055 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005056
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005057 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005058 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005059 case ':':
5060 missing_argument(argv[optind - 1]);
5061 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005062 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005063 unrecognized_option(argv[optind - 1]);
5064 return 0;
5065 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005066 help();
5067 return 0;
5068 case 'V':
5069 printf(QEMU_IMG_VERSION);
5070 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005071 case 'T':
5072 g_free(trace_file);
5073 trace_file = trace_opt_parse(optarg);
5074 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005075 }
bellardea2384d2004-08-01 21:59:26 +00005076 }
Stuart Brady153859b2009-06-07 00:42:17 +01005077
Denis V. Lunev10985132016-06-17 17:44:13 +03005078 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005079
Denis V. Lunev10985132016-06-17 17:44:13 +03005080 /* reset getopt_long scanning */
5081 argc -= optind;
5082 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005083 return 0;
5084 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005085 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005086 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005087
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005088 if (!trace_init_backends()) {
5089 exit(1);
5090 }
5091 trace_init_file(trace_file);
5092 qemu_set_log(LOG_TRACE);
5093
Denis V. Lunev10985132016-06-17 17:44:13 +03005094 /* find the command */
5095 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5096 if (!strcmp(cmdname, cmd->name)) {
5097 return cmd->handler(argc, argv);
5098 }
5099 }
Jeff Cody7db16892014-04-25 17:02:32 -04005100
Stuart Brady153859b2009-06-07 00:42:17 +01005101 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005102 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005103}