blob: 28fba1e7a7b12590bcea125f6873a904e989b128 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Fam Zheng67a1de02016-06-01 17:44:21 +080028#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010029#include "qapi/error.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010030#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010031#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010032#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010033#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010034#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020035#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000036#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010037#include "qemu/option.h"
38#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030039#include "qemu/log.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020040#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000041#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010042#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020043#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010044#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020045#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080046#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010047#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030048#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000049
Thomas Huth7e563bf2018-02-15 12:06:47 +010050#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020051 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040052
Anthony Liguoric227f092009-10-01 16:12:16 -050053typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010054 const char *name;
55 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050056} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010057
Federico Simoncelli8599ea42013-01-28 06:59:47 -050058enum {
59 OPTION_OUTPUT = 256,
60 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000061 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000062 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020063 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020064 OPTION_FLUSH_INTERVAL = 261,
65 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010066 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010067 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020068 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030069 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050070};
71
72typedef enum OutputFormat {
73 OFORMAT_JSON,
74 OFORMAT_HUMAN,
75} OutputFormat;
76
Kevin Wolfe6996142016-03-15 13:03:11 +010077/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040078#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000079
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010080static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000081{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010082 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000083}
84
Fam Zhengac1307a2014-04-22 13:36:11 +080085static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
86{
87 va_list ap;
88
Fam Zhengac1307a2014-04-22 13:36:11 +080089 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +020090 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +080091 va_end(ap);
92
Markus Armbrustere9e1d922019-04-17 21:06:27 +020093 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +080094 exit(EXIT_FAILURE);
95}
96
Stefan Hajnoczic9192972017-03-17 18:45:41 +080097static void QEMU_NORETURN missing_argument(const char *option)
98{
99 error_exit("missing argument for option '%s'", option);
100}
101
102static void QEMU_NORETURN unrecognized_option(const char *option)
103{
104 error_exit("unrecognized option '%s'", option);
105}
106
blueswir1d2c639d2009-01-24 18:19:25 +0000107/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800108static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000109{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100110 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400111 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300112 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300113 "QEMU disk image utility\n"
114 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300115 " '-h', '--help' display this help and exit\n"
116 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300117 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300119 "\n"
malc3f020d72010-02-08 12:04:56 +0300120 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100121#define DEF(option, callback, arg_string) \
122 " " arg_string "\n"
123#include "qemu-img-cmds.h"
124#undef DEF
malc3f020d72010-02-08 12:04:56 +0300125 "\n"
126 "Command parameters:\n"
127 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000128 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
129 " manual page for a description of the object properties. The most common\n"
130 " object type is a 'secret', which is used to supply passwords and/or\n"
131 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300132 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400133 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800134 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
135 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100136 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
137 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300138 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200139 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
140 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
141 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300142 " 'output_filename' is the destination disk image filename\n"
143 " 'output_fmt' is the destination format\n"
144 " 'options' is a comma separated list of format specific options in a\n"
145 " name=value format. Use -o ? for an overview of the options supported by the\n"
146 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800147 " 'snapshot_param' is param used for internal snapshot, format\n"
148 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
149 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300150 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400151 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
152 " new backing file match exactly. The image doesn't need a working\n"
153 " backing file before rebasing in this case (useful for renaming the\n"
154 " backing file). For image creation, allow creating without attempting\n"
155 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300156 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200157 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100158 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200159 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
160 " contain only zeros for qemu-img to create a sparse image during\n"
161 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
162 " unallocated or zero sectors, and the destination image will always be\n"
163 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200164 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100165 " '-n' skips the target volume creation (useful if the volume is created\n"
166 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300167 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200168 "Parameters to check subcommand:\n"
169 " '-r' tries to repair any inconsistencies that are found during the check.\n"
170 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
171 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200172 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200173 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100174 "Parameters to convert subcommand:\n"
175 " '-m' specifies how many coroutines work in parallel during the convert\n"
176 " process (defaults to 8)\n"
177 " '-W' allow to write to the target out of order rather than sequential\n"
178 "\n"
malc3f020d72010-02-08 12:04:56 +0300179 "Parameters to snapshot subcommand:\n"
180 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
181 " '-a' applies a snapshot (revert disk to saved state)\n"
182 " '-c' creates a snapshot\n"
183 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100184 " '-l' lists all snapshots in the given image\n"
185 "\n"
186 "Parameters to compare subcommand:\n"
187 " '-f' first image format\n"
188 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200189 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
190 "\n"
191 "Parameters to dd subcommand:\n"
192 " 'bs=BYTES' read and write up to BYTES bytes at a time "
193 "(default: 512)\n"
194 " 'count=N' copy only N input blocks\n"
195 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200196 " 'of=FILE' write to FILE\n"
197 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100198
199 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300200 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500201 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800202 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000203}
204
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000205static QemuOptsList qemu_object_opts = {
206 .name = "object",
207 .implied_opt_name = "qom-type",
208 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
209 .desc = {
210 { }
211 },
212};
213
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000214static QemuOptsList qemu_source_opts = {
215 .name = "source",
216 .implied_opt_name = "file",
217 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
218 .desc = {
219 { }
220 },
221};
222
Stefan Weil7c30f652013-06-16 17:01:05 +0200223static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100224{
225 int ret = 0;
226 if (!quiet) {
227 va_list args;
228 va_start(args, fmt);
229 ret = vprintf(fmt, args);
230 va_end(args);
231 }
232 return ret;
233}
234
bellardea2384d2004-08-01 21:59:26 +0000235
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100236static int print_block_option_help(const char *filename, const char *fmt)
237{
238 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800239 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500240 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100241
242 /* Find driver and parse its options */
243 drv = bdrv_find_format(fmt);
244 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100245 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100246 return 1;
247 }
248
Max Reitzd402b6a2018-05-09 23:00:21 +0200249 if (!drv->create_opts) {
250 error_report("Format driver '%s' does not support image creation", fmt);
251 return 1;
252 }
253
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800254 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100255 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500256 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100257 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100258 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800259 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100260 return 1;
261 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200262 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100263 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200264 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100265 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200266 return 1;
267 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800268 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100269 }
270
Max Reitzf4619af2019-04-13 17:20:37 +0200271 if (filename) {
272 printf("Supported options:\n");
273 } else {
274 printf("Supported %s options:\n", fmt);
275 }
Max Reitz63898712018-10-19 18:49:25 +0200276 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800277 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200278
279 if (!filename) {
280 printf("\n"
281 "The protocol level may support further options.\n"
282 "Specify the target filename to include those options.\n");
283 }
284
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100285 return 0;
286}
287
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000288
Max Reitzefaa7c42016-03-16 19:54:38 +0100289static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100290 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800291 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000292{
293 QDict *options;
294 Error *local_err = NULL;
295 BlockBackend *blk;
296 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800297 if (force_share) {
298 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200299 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800300 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200301 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800302 return NULL;
303 }
Max Reitz4615f872018-05-02 22:20:50 +0200304 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800305 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100306 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000307 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100308 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000309 return NULL;
310 }
Kevin Wolfce099542016-03-15 13:01:04 +0100311 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000312
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000313 return blk;
314}
315
Max Reitzefaa7c42016-03-16 19:54:38 +0100316static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100317 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000318 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800319 bool writethrough, bool quiet,
320 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000321{
322 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200323 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100324
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100325 if (!options) {
326 options = qdict_new();
327 }
bellard75c23802004-08-27 21:28:58 +0000328 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500329 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000330 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100331
Fam Zheng335e9932017-05-03 00:35:39 +0800332 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500333 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800334 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100335 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500336 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100337 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000338 return NULL;
bellard75c23802004-08-27 21:28:58 +0000339 }
Kevin Wolfce099542016-03-15 13:01:04 +0100340 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100341
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200342 return blk;
bellard75c23802004-08-27 21:28:58 +0000343}
344
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000345
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100346static int img_add_key_secrets(void *opaque,
347 const char *name, const char *value,
348 Error **errp)
349{
350 QDict *options = opaque;
351
352 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600353 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100354 }
355
356 return 0;
357}
358
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100359
Max Reitzefaa7c42016-03-16 19:54:38 +0100360static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000361 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100362 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800363 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000364{
365 BlockBackend *blk;
366 if (image_opts) {
367 QemuOpts *opts;
368 if (fmt) {
369 error_report("--image-opts and --format are mutually exclusive");
370 return NULL;
371 }
372 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
373 filename, true);
374 if (!opts) {
375 return NULL;
376 }
Fam Zheng335e9932017-05-03 00:35:39 +0800377 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
378 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000379 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100380 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800381 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000382 }
383 return blk;
384}
385
386
Chunyan Liu83d05212014-06-05 17:20:51 +0800387static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100388 const char *base_filename,
389 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200390{
Markus Armbruster6750e792015-02-12 17:43:08 +0100391 Error *err = NULL;
392
Kevin Wolfefa84d42009-05-18 16:42:12 +0200393 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100394 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100395 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100396 error_report("Backing file not supported for file format '%s'",
397 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100398 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900399 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200400 }
401 }
402 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100403 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100404 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100405 error_report("Backing file format not supported for file "
406 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100407 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900408 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200409 }
410 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900411 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200412}
413
Markus Armbruster606caa02017-02-21 21:14:04 +0100414static int64_t cvtnum(const char *s)
415{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100416 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100417 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100418
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100419 err = qemu_strtosz(s, NULL, &value);
420 if (err < 0) {
421 return err;
422 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100423 if (value > INT64_MAX) {
424 return -ERANGE;
425 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100426 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100427}
428
bellardea2384d2004-08-01 21:59:26 +0000429static int img_create(int argc, char **argv)
430{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200431 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100432 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000433 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000434 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000435 const char *filename;
436 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200437 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200438 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100439 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400440 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000441
bellardea2384d2004-08-01 21:59:26 +0000442 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000443 static const struct option long_options[] = {
444 {"help", no_argument, 0, 'h'},
445 {"object", required_argument, 0, OPTION_OBJECT},
446 {0, 0, 0, 0}
447 };
John Snow6e6e55f2017-07-17 20:34:22 -0400448 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000449 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100450 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000451 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100452 }
bellardea2384d2004-08-01 21:59:26 +0000453 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800454 case ':':
455 missing_argument(argv[optind - 1]);
456 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100457 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800458 unrecognized_option(argv[optind - 1]);
459 break;
bellardea2384d2004-08-01 21:59:26 +0000460 case 'h':
461 help();
462 break;
aliguori9230eaf2009-03-28 17:55:19 +0000463 case 'F':
464 base_fmt = optarg;
465 break;
bellardea2384d2004-08-01 21:59:26 +0000466 case 'b':
467 base_filename = optarg;
468 break;
469 case 'f':
470 fmt = optarg;
471 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200472 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100473 if (!is_valid_option_list(optarg)) {
474 error_report("Invalid option list: %s", optarg);
475 goto fail;
476 }
477 if (!options) {
478 options = g_strdup(optarg);
479 } else {
480 char *old_options = options;
481 options = g_strdup_printf("%s,%s", options, optarg);
482 g_free(old_options);
483 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200484 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100485 case 'q':
486 quiet = true;
487 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400488 case 'u':
489 flags |= BDRV_O_NO_BACKING;
490 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000491 case OPTION_OBJECT: {
492 QemuOpts *opts;
493 opts = qemu_opts_parse_noisily(&qemu_object_opts,
494 optarg, true);
495 if (!opts) {
496 goto fail;
497 }
498 } break;
bellardea2384d2004-08-01 21:59:26 +0000499 }
500 }
aliguori9230eaf2009-03-28 17:55:19 +0000501
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900502 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100503 filename = (optind < argc) ? argv[optind] : NULL;
504 if (options && has_help_option(options)) {
505 g_free(options);
506 return print_block_option_help(filename, fmt);
507 }
508
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100509 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800510 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100511 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100512 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900513
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000514 if (qemu_opts_foreach(&qemu_object_opts,
515 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000516 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000517 goto fail;
518 }
519
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100520 /* Get image size, if specified */
521 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100522 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100523
524 sval = cvtnum(argv[optind++]);
525 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800526 if (sval == -ERANGE) {
527 error_report("Image size must be less than 8 EiB!");
528 } else {
529 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200530 "G, T, P or E suffixes for ");
531 error_report("kilobytes, megabytes, gigabytes, terabytes, "
532 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800533 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100534 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100535 }
536 img_size = (uint64_t)sval;
537 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200538 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800539 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200540 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100541
Luiz Capitulino9b375252012-11-30 10:52:05 -0200542 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400543 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100544 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100545 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100546 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900547 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200548
Kevin Wolf77386bf2014-02-21 16:24:04 +0100549 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000550 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100551
552fail:
553 g_free(options);
554 return 1;
bellardea2384d2004-08-01 21:59:26 +0000555}
556
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100557static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500558{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500559 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100561 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600562
563 visit_type_ImageCheck(v, NULL, &check, &error_abort);
564 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500565 str = qobject_to_json_pretty(obj);
566 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100567 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200568 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600569 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200570 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500571}
572
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100573static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500574{
575 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100576 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500577 } else {
578 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100579 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
580 "Data may be corrupted, or further writes to the image "
581 "may corrupt it.\n",
582 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500583 }
584
585 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100586 qprintf(quiet,
587 "\n%" PRId64 " leaked clusters were found on the image.\n"
588 "This means waste of disk space, but no harm to data.\n",
589 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500590 }
591
592 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100593 qprintf(quiet,
594 "\n%" PRId64
595 " internal errors have occurred during the check.\n",
596 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500597 }
598 }
599
600 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100601 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
602 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
603 check->allocated_clusters, check->total_clusters,
604 check->allocated_clusters * 100.0 / check->total_clusters,
605 check->fragmented_clusters * 100.0 / check->allocated_clusters,
606 check->compressed_clusters * 100.0 /
607 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608 }
609
610 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100611 qprintf(quiet,
612 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500613 }
614}
615
616static int collect_image_check(BlockDriverState *bs,
617 ImageCheck *check,
618 const char *filename,
619 const char *fmt,
620 int fix)
621{
622 int ret;
623 BdrvCheckResult result;
624
625 ret = bdrv_check(bs, &result, fix);
626 if (ret < 0) {
627 return ret;
628 }
629
630 check->filename = g_strdup(filename);
631 check->format = g_strdup(bdrv_get_format_name(bs));
632 check->check_errors = result.check_errors;
633 check->corruptions = result.corruptions;
634 check->has_corruptions = result.corruptions != 0;
635 check->leaks = result.leaks;
636 check->has_leaks = result.leaks != 0;
637 check->corruptions_fixed = result.corruptions_fixed;
638 check->has_corruptions_fixed = result.corruptions != 0;
639 check->leaks_fixed = result.leaks_fixed;
640 check->has_leaks_fixed = result.leaks != 0;
641 check->image_end_offset = result.image_end_offset;
642 check->has_image_end_offset = result.image_end_offset != 0;
643 check->total_clusters = result.bfi.total_clusters;
644 check->has_total_clusters = result.bfi.total_clusters != 0;
645 check->allocated_clusters = result.bfi.allocated_clusters;
646 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
647 check->fragmented_clusters = result.bfi.fragmented_clusters;
648 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100649 check->compressed_clusters = result.bfi.compressed_clusters;
650 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500651
652 return 0;
653}
654
Kevin Wolfe076f332010-06-29 11:43:13 +0200655/*
656 * Checks an image for consistency. Exit codes:
657 *
Max Reitzd6635c42014-06-02 22:15:21 +0200658 * 0 - Check completed, image is good
659 * 1 - Check not completed because of internal errors
660 * 2 - Check completed, image is corrupted
661 * 3 - Check completed, image has leaked clusters, but is good otherwise
662 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200663 */
aliguori15859692009-04-21 23:11:53 +0000664static int img_check(int argc, char **argv)
665{
666 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500667 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200668 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200669 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000670 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200671 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100672 int flags = BDRV_O_CHECK;
673 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200674 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100675 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000676 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800677 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000678
679 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500680 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200681 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100682
aliguori15859692009-04-21 23:11:53 +0000683 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 int option_index = 0;
685 static const struct option long_options[] = {
686 {"help", no_argument, 0, 'h'},
687 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530688 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500689 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000690 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000691 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800692 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500693 {0, 0, 0, 0}
694 };
Fam Zheng335e9932017-05-03 00:35:39 +0800695 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500696 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100697 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000698 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100699 }
aliguori15859692009-04-21 23:11:53 +0000700 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800701 case ':':
702 missing_argument(argv[optind - 1]);
703 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100704 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800705 unrecognized_option(argv[optind - 1]);
706 break;
aliguori15859692009-04-21 23:11:53 +0000707 case 'h':
708 help();
709 break;
710 case 'f':
711 fmt = optarg;
712 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200713 case 'r':
714 flags |= BDRV_O_RDWR;
715
716 if (!strcmp(optarg, "leaks")) {
717 fix = BDRV_FIX_LEAKS;
718 } else if (!strcmp(optarg, "all")) {
719 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
720 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800721 error_exit("Unknown option value for -r "
722 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200723 }
724 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500725 case OPTION_OUTPUT:
726 output = optarg;
727 break;
Max Reitz40055952014-07-22 22:58:42 +0200728 case 'T':
729 cache = optarg;
730 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100731 case 'q':
732 quiet = true;
733 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800734 case 'U':
735 force_share = true;
736 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000737 case OPTION_OBJECT: {
738 QemuOpts *opts;
739 opts = qemu_opts_parse_noisily(&qemu_object_opts,
740 optarg, true);
741 if (!opts) {
742 return 1;
743 }
744 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000745 case OPTION_IMAGE_OPTS:
746 image_opts = true;
747 break;
aliguori15859692009-04-21 23:11:53 +0000748 }
749 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200750 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800751 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100752 }
aliguori15859692009-04-21 23:11:53 +0000753 filename = argv[optind++];
754
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500755 if (output && !strcmp(output, "json")) {
756 output_format = OFORMAT_JSON;
757 } else if (output && !strcmp(output, "human")) {
758 output_format = OFORMAT_HUMAN;
759 } else if (output) {
760 error_report("--output must be used with human or json as argument.");
761 return 1;
762 }
763
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000764 if (qemu_opts_foreach(&qemu_object_opts,
765 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000766 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000767 return 1;
768 }
769
Kevin Wolfce099542016-03-15 13:01:04 +0100770 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200771 if (ret < 0) {
772 error_report("Invalid source cache option: %s", cache);
773 return 1;
774 }
775
Fam Zheng335e9932017-05-03 00:35:39 +0800776 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
777 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200778 if (!blk) {
779 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900780 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200781 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500782
783 check = g_new0(ImageCheck, 1);
784 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200785
786 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200787 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200788 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500789 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200790 }
791
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500792 if (check->corruptions_fixed || check->leaks_fixed) {
793 int corruptions_fixed, leaks_fixed;
794
795 leaks_fixed = check->leaks_fixed;
796 corruptions_fixed = check->corruptions_fixed;
797
798 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100799 qprintf(quiet,
800 "The following inconsistencies were found and repaired:\n\n"
801 " %" PRId64 " leaked clusters\n"
802 " %" PRId64 " corruptions\n\n"
803 "Double checking the fixed image now...\n",
804 check->leaks_fixed,
805 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500806 }
807
808 ret = collect_image_check(bs, check, filename, fmt, 0);
809
810 check->leaks_fixed = leaks_fixed;
811 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200812 }
813
Max Reitz832390a2014-10-23 15:29:12 +0200814 if (!ret) {
815 switch (output_format) {
816 case OFORMAT_HUMAN:
817 dump_human_image_check(check, quiet);
818 break;
819 case OFORMAT_JSON:
820 dump_json_image_check(check, quiet);
821 break;
822 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500823 }
824
825 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200826 if (ret) {
827 error_report("Check failed: %s", strerror(-ret));
828 } else {
829 error_report("Check failed");
830 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500831 ret = 1;
832 goto fail;
833 }
834
835 if (check->corruptions) {
836 ret = 2;
837 } else if (check->leaks) {
838 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200839 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500840 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000841 }
842
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500843fail:
844 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200845 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500846 return ret;
aliguori15859692009-04-21 23:11:53 +0000847}
848
Max Reitzd4a32382014-10-24 15:57:37 +0200849typedef struct CommonBlockJobCBInfo {
850 BlockDriverState *bs;
851 Error **errp;
852} CommonBlockJobCBInfo;
853
854static void common_block_job_cb(void *opaque, int ret)
855{
856 CommonBlockJobCBInfo *cbi = opaque;
857
858 if (ret < 0) {
859 error_setg_errno(cbi->errp, -ret, "Block job failed");
860 }
Max Reitzd4a32382014-10-24 15:57:37 +0200861}
862
863static void run_block_job(BlockJob *job, Error **errp)
864{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200865 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800866 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200867
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200868 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200869 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200870 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200871 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200872 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200873 if (job->job.progress_total) {
874 progress = (float)job->job.progress_current /
875 job->job.progress_total * 100.f;
876 }
877 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200878 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200879
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200880 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200881 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800882 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200883 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800884 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200885 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200886 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200887
sochin.jiang4172a002017-06-15 14:47:33 +0800888 /* publish completion progress only when success */
889 if (!ret) {
890 qemu_progress_print(100.f, 0);
891 }
Max Reitzd4a32382014-10-24 15:57:37 +0200892}
893
bellardea2384d2004-08-01 21:59:26 +0000894static int img_commit(int argc, char **argv)
895{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400896 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200897 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200898 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200899 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100900 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200901 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100902 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200903 Error *local_err = NULL;
904 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000905 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200906 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000907
908 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400909 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200910 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000911 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000912 static const struct option long_options[] = {
913 {"help", no_argument, 0, 'h'},
914 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000915 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000916 {0, 0, 0, 0}
917 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800918 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000919 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100920 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000921 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100922 }
bellardea2384d2004-08-01 21:59:26 +0000923 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800924 case ':':
925 missing_argument(argv[optind - 1]);
926 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100927 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800928 unrecognized_option(argv[optind - 1]);
929 break;
bellardea2384d2004-08-01 21:59:26 +0000930 case 'h':
931 help();
932 break;
933 case 'f':
934 fmt = optarg;
935 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400936 case 't':
937 cache = optarg;
938 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200939 case 'b':
940 base = optarg;
941 /* -b implies -d */
942 drop = true;
943 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200944 case 'd':
945 drop = true;
946 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200947 case 'p':
948 progress = true;
949 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100950 case 'q':
951 quiet = true;
952 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000953 case OPTION_OBJECT: {
954 QemuOpts *opts;
955 opts = qemu_opts_parse_noisily(&qemu_object_opts,
956 optarg, true);
957 if (!opts) {
958 return 1;
959 }
960 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000961 case OPTION_IMAGE_OPTS:
962 image_opts = true;
963 break;
bellardea2384d2004-08-01 21:59:26 +0000964 }
965 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200966
967 /* Progress is not shown in Quiet mode */
968 if (quiet) {
969 progress = false;
970 }
971
Kevin Wolffc11eb22013-08-05 10:53:04 +0200972 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800973 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100974 }
bellardea2384d2004-08-01 21:59:26 +0000975 filename = argv[optind++];
976
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000977 if (qemu_opts_foreach(&qemu_object_opts,
978 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000979 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000980 return 1;
981 }
982
Max Reitz9a86fe42014-10-24 15:57:38 +0200983 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100984 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400985 if (ret < 0) {
986 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100987 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400988 }
989
Fam Zheng335e9932017-05-03 00:35:39 +0800990 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
991 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200992 if (!blk) {
993 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900994 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200995 bs = blk_bs(blk);
996
Max Reitz687fa1d2014-10-24 15:57:39 +0200997 qemu_progress_init(progress, 1.f);
998 qemu_progress_print(0.f, 100);
999
Max Reitz1b22bff2014-10-24 15:57:40 +02001000 if (base) {
1001 base_bs = bdrv_find_backing_image(bs, base);
1002 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001003 error_setg(&local_err,
1004 "Did not find '%s' in the backing chain of '%s'",
1005 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001006 goto done;
1007 }
1008 } else {
1009 /* This is different from QMP, which by default uses the deepest file in
1010 * the backing chain (i.e., the very base); however, the traditional
1011 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001012 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001013 if (!base_bs) {
1014 error_setg(&local_err, "Image does not have a backing file");
1015 goto done;
1016 }
bellardea2384d2004-08-01 21:59:26 +00001017 }
1018
Max Reitzd4a32382014-10-24 15:57:37 +02001019 cbi = (CommonBlockJobCBInfo){
1020 .errp = &local_err,
1021 .bs = bs,
1022 };
1023
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001024 aio_context = bdrv_get_aio_context(bs);
1025 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001026 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001027 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001028 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001029 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001030 if (local_err) {
1031 goto done;
1032 }
1033
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001034 /* When the block job completes, the BlockBackend reference will point to
1035 * the old backing file. In order to avoid that the top image is already
1036 * deleted, so we can still empty it afterwards, increment the reference
1037 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001038 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001039 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001040 }
1041
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001042 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001043 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001044 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001045 if (local_err) {
1046 goto unref_backing;
1047 }
1048
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001049 if (!drop && bs->drv->bdrv_make_empty) {
1050 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001051 if (ret) {
1052 error_setg_errno(&local_err, -ret, "Could not empty %s",
1053 filename);
1054 goto unref_backing;
1055 }
1056 }
1057
1058unref_backing:
1059 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001060 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001061 }
Max Reitzd4a32382014-10-24 15:57:37 +02001062
1063done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001064 qemu_progress_end();
1065
Markus Armbruster26f54e92014-10-07 13:59:04 +02001066 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001067
1068 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001069 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001070 return 1;
1071 }
Max Reitzd4a32382014-10-24 15:57:37 +02001072
1073 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001074 return 0;
1075}
1076
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001077/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001078 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1079 * of the first sector boundary within buf where the sector contains a
1080 * non-zero byte. This function is robust to a buffer that is not
1081 * sector-aligned.
1082 */
1083static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1084{
1085 int64_t i;
1086 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1087
1088 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1089 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1090 return i;
1091 }
1092 }
1093 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1094 return i;
1095 }
1096 return -1;
1097}
1098
1099/*
thsf58c7b32008-06-05 21:53:49 +00001100 * Returns true iff the first sector pointed to by 'buf' contains at least
1101 * a non-NUL byte.
1102 *
1103 * 'pnum' is set to the number of sectors (including and immediately following
1104 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001105 * The function will try to align the end offset to alignment boundaries so
1106 * that the request will at least end aligned and consequtive requests will
1107 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001108 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001109static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1110 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001111{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001112 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001113 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001114
1115 if (n <= 0) {
1116 *pnum = 0;
1117 return 0;
1118 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001119 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001120 for(i = 1; i < n; i++) {
1121 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001122 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001123 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001124 }
bellardea2384d2004-08-01 21:59:26 +00001125 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001126
1127 tail = (sector_num + i) & (alignment - 1);
1128 if (tail) {
1129 if (is_zero && i <= tail) {
1130 /* treat unallocated areas which only consist
1131 * of a small tail as allocated. */
1132 is_zero = false;
1133 }
1134 if (!is_zero) {
1135 /* align up end offset of allocated areas. */
1136 i += alignment - tail;
1137 i = MIN(i, n);
1138 } else {
1139 /* align down end offset of zero areas. */
1140 i -= tail;
1141 }
1142 }
bellardea2384d2004-08-01 21:59:26 +00001143 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001144 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001145}
1146
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001147/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001148 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1149 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1150 * breaking up write requests for only small sparse areas.
1151 */
1152static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001153 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001154{
1155 int ret;
1156 int num_checked, num_used;
1157
1158 if (n < min) {
1159 min = n;
1160 }
1161
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001162 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001163 if (!ret) {
1164 return ret;
1165 }
1166
1167 num_used = *pnum;
1168 buf += BDRV_SECTOR_SIZE * *pnum;
1169 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001170 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001171 num_checked = num_used;
1172
1173 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001174 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001175
1176 buf += BDRV_SECTOR_SIZE * *pnum;
1177 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001178 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001179 num_checked += *pnum;
1180 if (ret) {
1181 num_used = num_checked;
1182 } else if (*pnum >= min) {
1183 break;
1184 }
1185 }
1186
1187 *pnum = num_used;
1188 return 1;
1189}
1190
1191/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001192 * Compares two buffers sector by sector. Returns 0 if the first
1193 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001194 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001195 * pnum is set to the sector-aligned size of the buffer prefix that
1196 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001197 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001198static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1199 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001200{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001201 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001202 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001203
Eric Blakedc61cd32017-10-11 22:47:14 -05001204 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001205
Eric Blakedc61cd32017-10-11 22:47:14 -05001206 res = !!memcmp(buf1, buf2, i);
1207 while (i < bytes) {
1208 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001209
Eric Blakedc61cd32017-10-11 22:47:14 -05001210 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001211 break;
1212 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001213 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001214 }
1215
1216 *pnum = i;
1217 return res;
1218}
1219
Stefano Garzarella97ede572019-05-08 12:43:24 +02001220#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001221
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001222/*
1223 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1224 *
Eric Blake0608e402017-10-11 22:47:12 -05001225 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1226 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1227 * failure), and 4 on error (the exit status for read errors), after emitting
1228 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001229 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001230 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001231 * @param offset: Starting offset to check
1232 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001233 * @param filename: Name of disk file we are checking (logging purpose)
1234 * @param buffer: Allocated buffer for storing read data
1235 * @param quiet: Flag for quiet mode
1236 */
Eric Blakec41508e2017-10-11 22:47:13 -05001237static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1238 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001239 uint8_t *buffer, bool quiet)
1240{
Eric Blakedebb38a2017-10-11 22:47:11 -05001241 int ret = 0;
1242 int64_t idx;
1243
Eric Blakec41508e2017-10-11 22:47:13 -05001244 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001245 if (ret < 0) {
1246 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001247 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001248 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001249 }
Eric Blakec41508e2017-10-11 22:47:13 -05001250 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001251 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001252 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001253 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001254 return 1;
1255 }
1256
1257 return 0;
1258}
1259
1260/*
1261 * Compares two images. Exit codes:
1262 *
1263 * 0 - Images are identical
1264 * 1 - Images differ
1265 * >1 - Error occurred
1266 */
1267static int img_compare(int argc, char **argv)
1268{
Max Reitz40055952014-07-22 22:58:42 +02001269 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001270 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001271 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001272 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001273 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001274 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001275 int allocated1, allocated2;
1276 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1277 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001278 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001279 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001280 int64_t total_size;
1281 int64_t offset = 0;
1282 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001283 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001284 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001285 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001286 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287
Max Reitz40055952014-07-22 22:58:42 +02001288 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001289 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001290 static const struct option long_options[] = {
1291 {"help", no_argument, 0, 'h'},
1292 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001293 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001294 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001295 {0, 0, 0, 0}
1296 };
Fam Zheng335e9932017-05-03 00:35:39 +08001297 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001298 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001299 if (c == -1) {
1300 break;
1301 }
1302 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001303 case ':':
1304 missing_argument(argv[optind - 1]);
1305 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001306 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001307 unrecognized_option(argv[optind - 1]);
1308 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001309 case 'h':
1310 help();
1311 break;
1312 case 'f':
1313 fmt1 = optarg;
1314 break;
1315 case 'F':
1316 fmt2 = optarg;
1317 break;
Max Reitz40055952014-07-22 22:58:42 +02001318 case 'T':
1319 cache = optarg;
1320 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001321 case 'p':
1322 progress = true;
1323 break;
1324 case 'q':
1325 quiet = true;
1326 break;
1327 case 's':
1328 strict = true;
1329 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001330 case 'U':
1331 force_share = true;
1332 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001333 case OPTION_OBJECT: {
1334 QemuOpts *opts;
1335 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1336 optarg, true);
1337 if (!opts) {
1338 ret = 2;
1339 goto out4;
1340 }
1341 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001342 case OPTION_IMAGE_OPTS:
1343 image_opts = true;
1344 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001345 }
1346 }
1347
1348 /* Progress is not shown in Quiet mode */
1349 if (quiet) {
1350 progress = false;
1351 }
1352
1353
Kevin Wolffc11eb22013-08-05 10:53:04 +02001354 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001355 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001356 }
1357 filename1 = argv[optind++];
1358 filename2 = argv[optind++];
1359
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001360 if (qemu_opts_foreach(&qemu_object_opts,
1361 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00001362 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001363 ret = 2;
1364 goto out4;
1365 }
1366
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001367 /* Initialize before goto out */
1368 qemu_progress_init(progress, 2.0);
1369
Kevin Wolfce099542016-03-15 13:01:04 +01001370 flags = 0;
1371 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001372 if (ret < 0) {
1373 error_report("Invalid source cache option: %s", cache);
1374 ret = 2;
1375 goto out3;
1376 }
1377
Fam Zheng335e9932017-05-03 00:35:39 +08001378 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1379 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001380 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001381 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001382 goto out3;
1383 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001384
Fam Zheng335e9932017-05-03 00:35:39 +08001385 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1386 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001387 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001388 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001389 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001390 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001391 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001392 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001393
Max Reitzf1d3cd72015-02-05 13:58:18 -05001394 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1395 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001396 total_size1 = blk_getlength(blk1);
1397 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001398 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001399 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001400 ret = 4;
1401 goto out;
1402 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001403 total_size2 = blk_getlength(blk2);
1404 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001405 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001406 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001407 ret = 4;
1408 goto out;
1409 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001410 total_size = MIN(total_size1, total_size2);
1411 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001412
1413 qemu_progress_print(0, 100);
1414
Eric Blake033d9fc2017-10-11 22:47:16 -05001415 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001416 ret = 1;
1417 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1418 goto out;
1419 }
1420
Eric Blake033d9fc2017-10-11 22:47:16 -05001421 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001422 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001423
Eric Blake033d9fc2017-10-11 22:47:16 -05001424 status1 = bdrv_block_status_above(bs1, NULL, offset,
1425 total_size1 - offset, &pnum1, NULL,
1426 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001427 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001428 ret = 3;
1429 error_report("Sector allocation test failed for %s", filename1);
1430 goto out;
1431 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001432 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001433
Eric Blake033d9fc2017-10-11 22:47:16 -05001434 status2 = bdrv_block_status_above(bs2, NULL, offset,
1435 total_size2 - offset, &pnum2, NULL,
1436 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001437 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001438 ret = 3;
1439 error_report("Sector allocation test failed for %s", filename2);
1440 goto out;
1441 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001442 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001443
1444 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001445 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001446
Fam Zheng25ad8e62016-01-13 16:37:41 +08001447 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001448 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001449 ret = 1;
1450 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001451 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001452 goto out;
1453 }
1454 }
1455 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001456 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001457 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001458 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001459 int64_t pnum;
1460
Eric Blake033d9fc2017-10-11 22:47:16 -05001461 chunk = MIN(chunk, IO_BUF_SIZE);
1462 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001463 if (ret < 0) {
1464 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001465 " of %s: %s",
1466 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001467 ret = 4;
1468 goto out;
1469 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001470 ret = blk_pread(blk2, offset, buf2, chunk);
1471 if (ret < 0) {
1472 error_report("Error while reading offset %" PRId64
1473 " of %s: %s",
1474 offset, filename2, strerror(-ret));
1475 ret = 4;
1476 goto out;
1477 }
1478 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1479 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001480 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001481 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001482 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001483 goto out;
1484 }
1485 }
1486 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001487 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001488 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001489 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001490 filename1, buf1, quiet);
1491 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001493 filename2, buf1, quiet);
1494 }
1495 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001496 goto out;
1497 }
1498 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001499 offset += chunk;
1500 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001501 }
1502
Eric Blake033d9fc2017-10-11 22:47:16 -05001503 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001504 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001505 const char *filename_over;
1506
1507 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001508 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001509 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001510 filename_over = filename1;
1511 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001512 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001513 filename_over = filename2;
1514 }
1515
Eric Blake033d9fc2017-10-11 22:47:16 -05001516 while (offset < progress_base) {
1517 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1518 progress_base - offset, &chunk,
1519 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001520 if (ret < 0) {
1521 ret = 3;
1522 error_report("Sector allocation test failed for %s",
1523 filename_over);
1524 goto out;
1525
1526 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001527 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001528 chunk = MIN(chunk, IO_BUF_SIZE);
1529 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001530 filename_over, buf1, quiet);
1531 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 goto out;
1533 }
1534 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001535 offset += chunk;
1536 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001537 }
1538 }
1539
1540 qprintf(quiet, "Images are identical.\n");
1541 ret = 0;
1542
1543out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001544 qemu_vfree(buf1);
1545 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001546 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001547out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001548 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001549out3:
1550 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001551out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001552 return ret;
1553}
1554
Kevin Wolf690c7302015-03-19 13:33:32 +01001555enum ImgConvertBlockStatus {
1556 BLK_DATA,
1557 BLK_ZERO,
1558 BLK_BACKING_FILE,
1559};
1560
Peter Lieven2d9187b2017-02-28 13:40:07 +01001561#define MAX_COROUTINES 16
1562
Kevin Wolf690c7302015-03-19 13:33:32 +01001563typedef struct ImgConvertState {
1564 BlockBackend **src;
1565 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001566 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001567 int64_t total_sectors;
1568 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001569 int64_t allocated_done;
1570 int64_t sector_num;
1571 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001572 enum ImgConvertBlockStatus status;
1573 int64_t sector_next_status;
1574 BlockBackend *target;
1575 bool has_zero_init;
1576 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001577 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001578 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001579 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001580 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001581 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001582 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001583 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001584 size_t cluster_sectors;
1585 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001586 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001587 int running_coroutines;
1588 Coroutine *co[MAX_COROUTINES];
1589 int64_t wait_sector_num[MAX_COROUTINES];
1590 CoMutex lock;
1591 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001592} ImgConvertState;
1593
Peter Lieven2d9187b2017-02-28 13:40:07 +01001594static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1595 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001596{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001597 *src_cur = 0;
1598 *src_cur_offset = 0;
1599 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1600 *src_cur_offset += s->src_sectors[*src_cur];
1601 (*src_cur)++;
1602 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001603 }
1604}
1605
1606static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1607{
Eric Blake31826642017-10-11 22:47:08 -05001608 int64_t src_cur_offset;
1609 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001610 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001611
Peter Lieven2d9187b2017-02-28 13:40:07 +01001612 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001613
1614 assert(s->total_sectors > sector_num);
1615 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1616
Max Reitz351c8ef2018-05-01 18:57:49 +02001617 if (s->target_backing_sectors >= 0) {
1618 if (sector_num >= s->target_backing_sectors) {
1619 post_backing_zero = s->unallocated_blocks_are_zero;
1620 } else if (sector_num + n > s->target_backing_sectors) {
1621 /* Split requests around target_backing_sectors (because
1622 * starting from there, zeros are handled differently) */
1623 n = s->target_backing_sectors - sector_num;
1624 }
1625 }
1626
Kevin Wolf690c7302015-03-19 13:33:32 +01001627 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001628 int64_t count = n * BDRV_SECTOR_SIZE;
1629
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001630 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001631
1632 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1633 (sector_num - src_cur_offset) *
1634 BDRV_SECTOR_SIZE,
1635 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001636 } else {
Eric Blake31826642017-10-11 22:47:08 -05001637 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1638 (sector_num - src_cur_offset) *
1639 BDRV_SECTOR_SIZE,
1640 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001641 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001642 if (ret < 0) {
Eric Blake2058c2a2019-03-23 16:26:38 -05001643 error_report("error while reading block status of sector %" PRId64
1644 ": %s", sector_num, strerror(-ret));
Kevin Wolf690c7302015-03-19 13:33:32 +01001645 return ret;
1646 }
Eric Blake31826642017-10-11 22:47:08 -05001647 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001648
1649 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001650 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001651 } else if (ret & BDRV_BLOCK_DATA) {
1652 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001653 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001654 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001655 }
1656
1657 s->sector_next_status = sector_num + n;
1658 }
1659
1660 n = MIN(n, s->sector_next_status - sector_num);
1661 if (s->status == BLK_DATA) {
1662 n = MIN(n, s->buf_sectors);
1663 }
1664
1665 /* We need to write complete clusters for compressed images, so if an
1666 * unallocated area is shorter than that, we must consider the whole
1667 * cluster allocated. */
1668 if (s->compressed) {
1669 if (n < s->cluster_sectors) {
1670 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1671 s->status = BLK_DATA;
1672 } else {
1673 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1674 }
1675 }
1676
1677 return n;
1678}
1679
Peter Lieven2d9187b2017-02-28 13:40:07 +01001680static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1681 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001682{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001683 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001684
Kevin Wolf690c7302015-03-19 13:33:32 +01001685 assert(nb_sectors <= s->buf_sectors);
1686 while (nb_sectors > 0) {
1687 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001688 int src_cur;
1689 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001690
1691 /* In the case of compression with multiple source files, we can get a
1692 * nb_sectors that spreads into the next part. So we must be able to
1693 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001694 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1695 blk = s->src[src_cur];
1696 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001697
Peter Lieven2d9187b2017-02-28 13:40:07 +01001698 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
Peter Lieven2d9187b2017-02-28 13:40:07 +01001699
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001700 ret = blk_co_pread(
Peter Lieven2d9187b2017-02-28 13:40:07 +01001701 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001702 n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001703 if (ret < 0) {
1704 return ret;
1705 }
1706
1707 sector_num += n;
1708 nb_sectors -= n;
1709 buf += n * BDRV_SECTOR_SIZE;
1710 }
1711
1712 return 0;
1713}
1714
Peter Lieven2d9187b2017-02-28 13:40:07 +01001715
1716static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1717 int nb_sectors, uint8_t *buf,
1718 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001719{
1720 int ret;
1721
1722 while (nb_sectors > 0) {
1723 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001724 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1725
Peter Lieven2d9187b2017-02-28 13:40:07 +01001726 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001727 case BLK_BACKING_FILE:
1728 /* If we have a backing file, leave clusters unallocated that are
1729 * unallocated in the source image, so that the backing file is
1730 * visible at the respective offset. */
1731 assert(s->target_has_backing);
1732 break;
1733
1734 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001735 /* If we're told to keep the target fully allocated (-S 0) or there
1736 * is real non-zero data, we must write it. Otherwise we can treat
1737 * it as zero sectors.
1738 * Compressed clusters need to be written as a whole, so in that
1739 * case we can only save the write if the buffer is completely
1740 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001741 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001742 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001743 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1744 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001745 (s->compressed &&
1746 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001747 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001748 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1749 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001750 if (ret < 0) {
1751 return ret;
1752 }
1753 break;
1754 }
1755 /* fall-through */
1756
1757 case BLK_ZERO:
1758 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001759 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001760 break;
1761 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001762 ret = blk_co_pwrite_zeroes(s->target,
1763 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001764 n << BDRV_SECTOR_BITS,
1765 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001766 if (ret < 0) {
1767 return ret;
1768 }
1769 break;
1770 }
1771
1772 sector_num += n;
1773 nb_sectors -= n;
1774 buf += n * BDRV_SECTOR_SIZE;
1775 }
1776
1777 return 0;
1778}
1779
Fam Zhengee5306d2018-06-01 17:26:48 +08001780static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1781 int nb_sectors)
1782{
1783 int n, ret;
1784
1785 while (nb_sectors > 0) {
1786 BlockBackend *blk;
1787 int src_cur;
1788 int64_t bs_sectors, src_cur_offset;
1789 int64_t offset;
1790
1791 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1792 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1793 blk = s->src[src_cur];
1794 bs_sectors = s->src_sectors[src_cur];
1795
1796 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1797
1798 ret = blk_co_copy_range(blk, offset, s->target,
1799 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001800 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001801 if (ret < 0) {
1802 return ret;
1803 }
1804
1805 sector_num += n;
1806 nb_sectors -= n;
1807 }
1808 return 0;
1809}
1810
Peter Lieven2d9187b2017-02-28 13:40:07 +01001811static void coroutine_fn convert_co_do_copy(void *opaque)
1812{
1813 ImgConvertState *s = opaque;
1814 uint8_t *buf = NULL;
1815 int ret, i;
1816 int index = -1;
1817
1818 for (i = 0; i < s->num_coroutines; i++) {
1819 if (s->co[i] == qemu_coroutine_self()) {
1820 index = i;
1821 break;
1822 }
1823 }
1824 assert(index >= 0);
1825
1826 s->running_coroutines++;
1827 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1828
1829 while (1) {
1830 int n;
1831 int64_t sector_num;
1832 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001833 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001834
1835 qemu_co_mutex_lock(&s->lock);
1836 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1837 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001838 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001839 }
1840 n = convert_iteration_sectors(s, s->sector_num);
1841 if (n < 0) {
1842 qemu_co_mutex_unlock(&s->lock);
1843 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001844 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001845 }
1846 /* save current sector and allocation status to local variables */
1847 sector_num = s->sector_num;
1848 status = s->status;
1849 if (!s->min_sparse && s->status == BLK_ZERO) {
1850 n = MIN(n, s->buf_sectors);
1851 }
1852 /* increment global sector counter so that other coroutines can
1853 * already continue reading beyond this request */
1854 s->sector_num += n;
1855 qemu_co_mutex_unlock(&s->lock);
1856
1857 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1858 s->allocated_done += n;
1859 qemu_progress_print(100.0 * s->allocated_done /
1860 s->allocated_sectors, 0);
1861 }
1862
Fam Zhengee5306d2018-06-01 17:26:48 +08001863retry:
1864 copy_range = s->copy_range && s->status == BLK_DATA;
1865 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001866 ret = convert_co_read(s, sector_num, n, buf);
1867 if (ret < 0) {
1868 error_report("error while reading sector %" PRId64
1869 ": %s", sector_num, strerror(-ret));
1870 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001871 }
1872 } else if (!s->min_sparse && status == BLK_ZERO) {
1873 status = BLK_DATA;
1874 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1875 }
1876
1877 if (s->wr_in_order) {
1878 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001879 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001880 s->wait_sector_num[index] = sector_num;
1881 qemu_coroutine_yield();
1882 }
1883 s->wait_sector_num[index] = -1;
1884 }
1885
Anton Nefedovb91127e2017-04-26 11:33:15 +03001886 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001887 if (copy_range) {
1888 ret = convert_co_copy_range(s, sector_num, n);
1889 if (ret) {
1890 s->copy_range = false;
1891 goto retry;
1892 }
1893 } else {
1894 ret = convert_co_write(s, sector_num, n, buf, status);
1895 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001896 if (ret < 0) {
1897 error_report("error while writing sector %" PRId64
1898 ": %s", sector_num, strerror(-ret));
1899 s->ret = ret;
1900 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001901 }
1902
1903 if (s->wr_in_order) {
1904 /* reenter the coroutine that might have waited
1905 * for this write to complete */
1906 s->wr_offs = sector_num + n;
1907 for (i = 0; i < s->num_coroutines; i++) {
1908 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1909 /*
1910 * A -> B -> A cannot occur because A has
1911 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1912 * B will never enter A during this time window.
1913 */
1914 qemu_coroutine_enter(s->co[i]);
1915 break;
1916 }
1917 }
1918 }
1919 }
1920
Peter Lieven2d9187b2017-02-28 13:40:07 +01001921 qemu_vfree(buf);
1922 s->co[index] = NULL;
1923 s->running_coroutines--;
1924 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1925 /* the convert job finished successfully */
1926 s->ret = 0;
1927 }
1928}
1929
Kevin Wolf690c7302015-03-19 13:33:32 +01001930static int convert_do_copy(ImgConvertState *s)
1931{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001932 int ret, i, n;
1933 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001934
1935 /* Check whether we have zero initialisation or can get it efficiently */
1936 s->has_zero_init = s->min_sparse && !s->target_has_backing
1937 ? bdrv_has_zero_init(blk_bs(s->target))
1938 : false;
1939
1940 if (!s->has_zero_init && !s->target_has_backing &&
1941 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1942 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001943 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001944 if (ret == 0) {
1945 s->has_zero_init = true;
1946 }
1947 }
1948
1949 /* Allocate buffer for copied data. For compressed images, only one cluster
1950 * can be copied at a time. */
1951 if (s->compressed) {
1952 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1953 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001954 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001955 }
1956 s->buf_sectors = s->cluster_sectors;
1957 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001958
Kevin Wolf690c7302015-03-19 13:33:32 +01001959 while (sector_num < s->total_sectors) {
1960 n = convert_iteration_sectors(s, sector_num);
1961 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001962 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001963 }
Max Reitzaad15de2016-03-24 23:33:57 +01001964 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1965 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001966 s->allocated_sectors += n;
1967 }
1968 sector_num += n;
1969 }
1970
1971 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001972 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001973 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001974
Peter Lieven2d9187b2017-02-28 13:40:07 +01001975 qemu_co_mutex_init(&s->lock);
1976 for (i = 0; i < s->num_coroutines; i++) {
1977 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1978 s->wait_sector_num[i] = -1;
1979 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001980 }
1981
Anton Nefedovb91127e2017-04-26 11:33:15 +03001982 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001983 main_loop_wait(false);
1984 }
1985
1986 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001987 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001988 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001989 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001990 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001991 }
1992 }
1993
Peter Lieven2d9187b2017-02-28 13:40:07 +01001994 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001995}
1996
Peter Lieven6360ab22018-07-13 09:15:39 +02001997#define MAX_BUF_SECTORS 32768
1998
bellardea2384d2004-08-01 21:59:26 +00001999static int img_convert(int argc, char **argv)
2000{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002001 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002002 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002003 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2004 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002005 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002006 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002007 BlockDriverState *out_bs;
2008 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002009 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002010 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002011 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002012 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002013 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002014 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002015 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002016 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002017 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002018
Peter Lieven9fd77f92017-04-21 11:11:55 +02002019 ImgConvertState s = (ImgConvertState) {
2020 /* Need at least 4k of zeros for sparse detection */
2021 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002022 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002023 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2024 .wr_in_order = true,
2025 .num_coroutines = 8,
2026 };
2027
bellardea2384d2004-08-01 21:59:26 +00002028 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002029 static const struct option long_options[] = {
2030 {"help", no_argument, 0, 'h'},
2031 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002032 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002033 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002034 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002035 {0, 0, 0, 0}
2036 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002037 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002038 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002039 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002040 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002041 }
bellardea2384d2004-08-01 21:59:26 +00002042 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002043 case ':':
2044 missing_argument(argv[optind - 1]);
2045 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002046 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002047 unrecognized_option(argv[optind - 1]);
2048 break;
bellardea2384d2004-08-01 21:59:26 +00002049 case 'h':
2050 help();
2051 break;
2052 case 'f':
2053 fmt = optarg;
2054 break;
2055 case 'O':
2056 out_fmt = optarg;
2057 break;
thsf58c7b32008-06-05 21:53:49 +00002058 case 'B':
2059 out_baseimg = optarg;
2060 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002061 case 'C':
2062 s.copy_range = true;
2063 break;
bellardea2384d2004-08-01 21:59:26 +00002064 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002065 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002066 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002067 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002068 if (!is_valid_option_list(optarg)) {
2069 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002070 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002071 }
2072 if (!options) {
2073 options = g_strdup(optarg);
2074 } else {
2075 char *old_options = options;
2076 options = g_strdup_printf("%s,%s", options, optarg);
2077 g_free(old_options);
2078 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002079 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002080 case 'l':
2081 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002082 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2083 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002084 if (!sn_opts) {
2085 error_report("Failed in parsing snapshot param '%s'",
2086 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002087 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002088 }
2089 } else {
2090 snapshot_name = optarg;
2091 }
2092 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002093 case 'S':
2094 {
2095 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002096
2097 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002098 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2099 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2100 error_report("Invalid buffer size for sparse output specified. "
2101 "Valid sizes are multiples of %llu up to %llu. Select "
2102 "0 to disable sparse detection (fully allocates output).",
2103 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002104 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002105 }
2106
Peter Lieven9fd77f92017-04-21 11:11:55 +02002107 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002108 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002109 break;
2110 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002111 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002112 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002113 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002114 case 't':
2115 cache = optarg;
2116 break;
Max Reitz40055952014-07-22 22:58:42 +02002117 case 'T':
2118 src_cache = optarg;
2119 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002120 case 'q':
2121 quiet = true;
2122 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002123 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002124 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002125 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002126 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002127 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2128 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002129 error_report("Invalid number of coroutines. Allowed number of"
2130 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002131 goto fail_getopt;
2132 }
2133 break;
2134 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002135 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002136 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002137 case 'U':
2138 force_share = true;
2139 break;
Max Reitz3258b912017-04-26 15:46:47 +02002140 case OPTION_OBJECT: {
2141 QemuOpts *object_opts;
2142 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2143 optarg, true);
2144 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002145 goto fail_getopt;
2146 }
2147 break;
Max Reitz3258b912017-04-26 15:46:47 +02002148 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002149 case OPTION_IMAGE_OPTS:
2150 image_opts = true;
2151 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002152 case OPTION_TARGET_IMAGE_OPTS:
2153 tgt_image_opts = true;
2154 break;
bellardea2384d2004-08-01 21:59:26 +00002155 }
2156 }
ths3b46e622007-09-17 08:09:54 +00002157
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002158 if (!out_fmt && !tgt_image_opts) {
2159 out_fmt = "raw";
2160 }
2161
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002162 if (qemu_opts_foreach(&qemu_object_opts,
2163 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002164 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002165 goto fail_getopt;
2166 }
2167
Fam Zhenge11ce122018-07-27 11:34:01 +08002168 if (s.compressed && s.copy_range) {
2169 error_report("Cannot enable copy offloading when -c is used");
2170 goto fail_getopt;
2171 }
2172
2173 if (explict_min_sparse && s.copy_range) {
2174 error_report("Cannot enable copy offloading when -S is used");
2175 goto fail_getopt;
2176 }
2177
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002178 if (tgt_image_opts && !skip_create) {
2179 error_report("--target-image-opts requires use of -n flag");
2180 goto fail_getopt;
2181 }
2182
Peter Lieven9fd77f92017-04-21 11:11:55 +02002183 s.src_num = argc - optind - 1;
2184 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2185
2186 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002187 if (out_fmt) {
2188 ret = print_block_option_help(out_filename, out_fmt);
2189 goto fail_getopt;
2190 } else {
2191 error_report("Option help requires a format be specified");
2192 goto fail_getopt;
2193 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002194 }
2195
2196 if (s.src_num < 1) {
2197 error_report("Must specify image file name");
2198 goto fail_getopt;
2199 }
2200
2201
Peter Lieven9fd77f92017-04-21 11:11:55 +02002202 /* ret is still -EINVAL until here */
2203 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2204 if (ret < 0) {
2205 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002206 goto fail_getopt;
2207 }
2208
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002209 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002210 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002211 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002212 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002213 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002214 qemu_progress_print(0, 100);
2215
Peter Lieven9fd77f92017-04-21 11:11:55 +02002216 s.src = g_new0(BlockBackend *, s.src_num);
2217 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002218
Peter Lieven9fd77f92017-04-21 11:11:55 +02002219 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2220 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002221 fmt, src_flags, src_writethrough, quiet,
2222 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002223 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002224 ret = -1;
2225 goto out;
2226 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002227 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2228 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002229 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002230 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002231 ret = -1;
2232 goto out;
2233 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002234 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002235 }
bellardea2384d2004-08-01 21:59:26 +00002236
Wenchao Xiaef806542013-12-04 17:10:57 +08002237 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002238 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002239 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2240 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2241 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002242 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002243 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002244 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002245 ret = -1;
2246 goto out;
2247 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002248
Peter Lieven9fd77f92017-04-21 11:11:55 +02002249 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2250 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002251 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002252 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002253 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002254 ret = -1;
2255 goto out;
edison51ef6722010-09-21 19:58:41 -07002256 }
2257
Max Reitz2e024cd2015-02-11 09:58:46 -05002258 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002259 /* Find driver and parse its options */
2260 drv = bdrv_find_format(out_fmt);
2261 if (!drv) {
2262 error_report("Unknown file format '%s'", out_fmt);
2263 ret = -1;
2264 goto out;
2265 }
2266
2267 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2268 if (!proto_drv) {
2269 error_report_err(local_err);
2270 ret = -1;
2271 goto out;
2272 }
2273
Max Reitz2e024cd2015-02-11 09:58:46 -05002274 if (!drv->create_opts) {
2275 error_report("Format driver '%s' does not support image creation",
2276 drv->format_name);
2277 ret = -1;
2278 goto out;
2279 }
Max Reitzf75613c2014-12-02 18:32:46 +01002280
Max Reitz2e024cd2015-02-11 09:58:46 -05002281 if (!proto_drv->create_opts) {
2282 error_report("Protocol driver '%s' does not support image creation",
2283 proto_drv->format_name);
2284 ret = -1;
2285 goto out;
2286 }
Max Reitzf75613c2014-12-02 18:32:46 +01002287
Max Reitz2e024cd2015-02-11 09:58:46 -05002288 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2289 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002290
Max Reitz2e024cd2015-02-11 09:58:46 -05002291 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002292 if (options) {
2293 qemu_opts_do_parse(opts, options, NULL, &local_err);
2294 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002295 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002296 ret = -1;
2297 goto out;
2298 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002299 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002300
Peter Lieven9fd77f92017-04-21 11:11:55 +02002301 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002302 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002303 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2304 if (ret < 0) {
2305 goto out;
2306 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002307 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002308
Kevin Wolfa18953f2010-10-14 15:46:04 +02002309 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002310 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002311 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002312 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002313 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002314 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002315
Max Reitz48758a82017-04-26 15:46:48 +02002316 if (s.src_num > 1 && out_baseimg) {
2317 error_report("Having a backing file for the target makes no sense when "
2318 "concatenating multiple input images");
2319 ret = -1;
2320 goto out;
2321 }
2322
Kevin Wolfefa84d42009-05-18 16:42:12 +02002323 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002324 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002325 bool encryption =
2326 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002327 const char *encryptfmt =
2328 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002329 const char *preallocation =
2330 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002331
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002332 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002333 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002334 ret = -1;
2335 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002336 }
2337
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002338 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002339 error_report("Compression and encryption not supported at "
2340 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002341 ret = -1;
2342 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002343 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002344
Chunyan Liu83d05212014-06-05 17:20:51 +08002345 if (preallocation
2346 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002347 {
2348 error_report("Compression and preallocation not supported at "
2349 "the same time");
2350 ret = -1;
2351 goto out;
2352 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002353 }
2354
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002355 /*
2356 * The later open call will need any decryption secrets, and
2357 * bdrv_create() will purge "opts", so extract them now before
2358 * they are lost.
2359 */
2360 if (!skip_create) {
2361 open_opts = qdict_new();
2362 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2363 }
2364
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002365 if (!skip_create) {
2366 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002367 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002368 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002369 error_reportf_err(local_err, "%s: error while converting %s: ",
2370 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002371 goto out;
bellardea2384d2004-08-01 21:59:26 +00002372 }
2373 }
ths3b46e622007-09-17 08:09:54 +00002374
Peter Lieven9fd77f92017-04-21 11:11:55 +02002375 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002376 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002377 if (ret < 0) {
2378 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002379 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002380 }
2381
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002382 if (skip_create) {
2383 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2384 flags, writethrough, quiet, false);
2385 } else {
2386 /* TODO ultimately we should allow --target-image-opts
2387 * to be used even when -n is not given.
2388 * That has to wait for bdrv_create to be improved
2389 * to allow filenames in option syntax
2390 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002391 s.target = img_open_file(out_filename, open_opts, out_fmt,
2392 flags, writethrough, quiet, false);
2393 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002394 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002395 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002396 ret = -1;
2397 goto out;
2398 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002399 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002400
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002401 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2402 error_report("Compression not supported for this file format");
2403 ret = -1;
2404 goto out;
2405 }
2406
Eric Blake5def6b82016-06-23 16:37:19 -06002407 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002408 * or discard_alignment of the out_bs is greater. Limit to
2409 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2410 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002411 MAX(s.buf_sectors,
2412 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2413 out_bs->bl.pdiscard_alignment >>
2414 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002415
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002416 /* try to align the write requests to the destination to avoid unnecessary
2417 * RMW cycles. */
2418 s.alignment = MAX(pow2floor(s.min_sparse),
2419 DIV_ROUND_UP(out_bs->bl.request_alignment,
2420 BDRV_SECTOR_SIZE));
2421 assert(is_power_of_2(s.alignment));
2422
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002423 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002424 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002425 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002426 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002427 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002428 ret = -1;
2429 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002430 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002431 error_report("output file is smaller than input file");
2432 ret = -1;
2433 goto out;
2434 }
2435 }
2436
Max Reitz351c8ef2018-05-01 18:57:49 +02002437 if (s.target_has_backing) {
2438 /* Errors are treated as "backing length unknown" (which means
2439 * s.target_backing_sectors has to be negative, which it will
2440 * be automatically). The backing file length is used only
2441 * for optimizations, so such a case is not fatal. */
2442 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2443 } else {
2444 s.target_backing_sectors = -1;
2445 }
2446
Peter Lieven24f833c2013-11-27 11:07:07 +01002447 ret = bdrv_get_info(out_bs, &bdi);
2448 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002449 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002450 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002451 goto out;
2452 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002453 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002454 s.compressed = s.compressed || bdi.needs_compressed_writes;
2455 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002456 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002457 }
2458
Peter Lieven9fd77f92017-04-21 11:11:55 +02002459 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002460out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002461 if (!ret) {
2462 qemu_progress_print(100, 0);
2463 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002464 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002465 qemu_opts_del(opts);
2466 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002467 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002468 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002469 blk_unref(s.target);
2470 if (s.src) {
2471 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2472 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002473 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002474 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002475 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002476 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002477fail_getopt:
2478 g_free(options);
2479
Peter Lieven9fd77f92017-04-21 11:11:55 +02002480 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002481}
2482
bellard57d1a2b2004-08-03 21:15:11 +00002483
bellardfaea38e2006-08-05 21:31:00 +00002484static void dump_snapshots(BlockDriverState *bs)
2485{
2486 QEMUSnapshotInfo *sn_tab, *sn;
2487 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002488
2489 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2490 if (nb_sns <= 0)
2491 return;
2492 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002493 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002494 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002495 for(i = 0; i < nb_sns; i++) {
2496 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002497 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002498 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002499 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002500 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002501}
2502
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002503static void dump_json_image_info_list(ImageInfoList *list)
2504{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002505 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002506 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002507 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002508
2509 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2510 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002511 str = qobject_to_json_pretty(obj);
2512 assert(str != NULL);
2513 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002514 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002515 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002516 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002517}
2518
Benoît Canetc054b3f2012-09-05 13:09:02 +02002519static void dump_json_image_info(ImageInfo *info)
2520{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002521 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002522 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002523 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002524
2525 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2526 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002527 str = qobject_to_json_pretty(obj);
2528 assert(str != NULL);
2529 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002530 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002531 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002532 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002533}
2534
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002535static void dump_human_image_info_list(ImageInfoList *list)
2536{
2537 ImageInfoList *elem;
2538 bool delim = false;
2539
2540 for (elem = list; elem; elem = elem->next) {
2541 if (delim) {
2542 printf("\n");
2543 }
2544 delim = true;
2545
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002546 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002547 }
2548}
2549
2550static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2551{
2552 return strcmp(a, b) == 0;
2553}
2554
2555/**
2556 * Open an image file chain and return an ImageInfoList
2557 *
2558 * @filename: topmost image filename
2559 * @fmt: topmost image format (may be NULL to autodetect)
2560 * @chain: true - enumerate entire backing file chain
2561 * false - only topmost image file
2562 *
2563 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2564 * image file. If there was an error a message will have been printed to
2565 * stderr.
2566 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002567static ImageInfoList *collect_image_info_list(bool image_opts,
2568 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002569 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002570 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002571{
2572 ImageInfoList *head = NULL;
2573 ImageInfoList **last = &head;
2574 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002575 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002576
2577 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2578
2579 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002580 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002581 BlockDriverState *bs;
2582 ImageInfo *info;
2583 ImageInfoList *elem;
2584
2585 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2586 error_report("Backing file '%s' creates an infinite loop.",
2587 filename);
2588 goto err;
2589 }
2590 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2591
Max Reitzefaa7c42016-03-16 19:54:38 +01002592 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002593 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2594 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002595 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002596 goto err;
2597 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002598 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002599
Wenchao Xia43526ec2013-06-06 12:27:58 +08002600 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002601 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002602 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002603 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002604 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002605 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002606
2607 elem = g_new0(ImageInfoList, 1);
2608 elem->value = info;
2609 *last = elem;
2610 last = &elem->next;
2611
Markus Armbruster26f54e92014-10-07 13:59:04 +02002612 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002613
2614 filename = fmt = NULL;
2615 if (chain) {
2616 if (info->has_full_backing_filename) {
2617 filename = info->full_backing_filename;
2618 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002619 error_report("Could not determine absolute backing filename,"
2620 " but backing filename '%s' present",
2621 info->backing_filename);
2622 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002623 }
2624 if (info->has_backing_filename_format) {
2625 fmt = info->backing_filename_format;
2626 }
2627 }
2628 }
2629 g_hash_table_destroy(filenames);
2630 return head;
2631
2632err:
2633 qapi_free_ImageInfoList(head);
2634 g_hash_table_destroy(filenames);
2635 return NULL;
2636}
2637
Benoît Canetc054b3f2012-09-05 13:09:02 +02002638static int img_info(int argc, char **argv)
2639{
2640 int c;
2641 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002642 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002643 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002644 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002645 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002646 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002647
bellardea2384d2004-08-01 21:59:26 +00002648 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002649 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002650 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002651 int option_index = 0;
2652 static const struct option long_options[] = {
2653 {"help", no_argument, 0, 'h'},
2654 {"format", required_argument, 0, 'f'},
2655 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002656 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002657 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002658 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002659 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002660 {0, 0, 0, 0}
2661 };
Fam Zheng335e9932017-05-03 00:35:39 +08002662 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002663 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002664 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002665 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002666 }
bellardea2384d2004-08-01 21:59:26 +00002667 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002668 case ':':
2669 missing_argument(argv[optind - 1]);
2670 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002671 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002672 unrecognized_option(argv[optind - 1]);
2673 break;
bellardea2384d2004-08-01 21:59:26 +00002674 case 'h':
2675 help();
2676 break;
2677 case 'f':
2678 fmt = optarg;
2679 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002680 case 'U':
2681 force_share = true;
2682 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002683 case OPTION_OUTPUT:
2684 output = optarg;
2685 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002686 case OPTION_BACKING_CHAIN:
2687 chain = true;
2688 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002689 case OPTION_OBJECT: {
2690 QemuOpts *opts;
2691 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2692 optarg, true);
2693 if (!opts) {
2694 return 1;
2695 }
2696 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002697 case OPTION_IMAGE_OPTS:
2698 image_opts = true;
2699 break;
bellardea2384d2004-08-01 21:59:26 +00002700 }
2701 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002702 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002703 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002704 }
bellardea2384d2004-08-01 21:59:26 +00002705 filename = argv[optind++];
2706
Benoît Canetc054b3f2012-09-05 13:09:02 +02002707 if (output && !strcmp(output, "json")) {
2708 output_format = OFORMAT_JSON;
2709 } else if (output && !strcmp(output, "human")) {
2710 output_format = OFORMAT_HUMAN;
2711 } else if (output) {
2712 error_report("--output must be used with human or json as argument.");
2713 return 1;
2714 }
2715
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002716 if (qemu_opts_foreach(&qemu_object_opts,
2717 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002718 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002719 return 1;
2720 }
2721
Fam Zheng335e9932017-05-03 00:35:39 +08002722 list = collect_image_info_list(image_opts, filename, fmt, chain,
2723 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002724 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002725 return 1;
2726 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002727
Benoît Canetc054b3f2012-09-05 13:09:02 +02002728 switch (output_format) {
2729 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002730 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002731 break;
2732 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002733 if (chain) {
2734 dump_json_image_info_list(list);
2735 } else {
2736 dump_json_image_info(list->value);
2737 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002738 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002739 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002740
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002741 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002742 return 0;
2743}
2744
Eric Blake30065d12019-03-26 13:40:43 -05002745static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2746 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002747{
2748 switch (output_format) {
2749 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002750 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002751 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002752 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002753 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002754 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002755 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002756 e->start, e->length,
2757 e->has_offset ? e->offset : 0,
2758 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002759 }
2760 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2761 * Modify the flags here to allow more coalescing.
2762 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002763 if (next && (!next->data || next->zero)) {
2764 next->data = false;
2765 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002766 }
2767 break;
2768 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002769 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2770 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002771 (e->start == 0 ? "[" : ",\n"),
2772 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002773 e->zero ? "true" : "false",
2774 e->data ? "true" : "false");
2775 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002776 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002777 }
2778 putchar('}');
2779
2780 if (!next) {
2781 printf("]\n");
2782 }
2783 break;
2784 }
Eric Blake30065d12019-03-26 13:40:43 -05002785 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002786}
2787
Eric Blake5e344dd2017-10-11 22:47:02 -05002788static int get_block_status(BlockDriverState *bs, int64_t offset,
2789 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002790{
Eric Blake237d78f2017-10-11 22:47:03 -05002791 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002792 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002793 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002794 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002795 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002796 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002797
2798 /* As an optimization, we could cache the current range of unallocated
2799 * clusters in each file of the chain, and avoid querying the same
2800 * range repeatedly.
2801 */
2802
2803 depth = 0;
2804 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002805 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002806 if (ret < 0) {
2807 return ret;
2808 }
Eric Blake237d78f2017-10-11 22:47:03 -05002809 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002810 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2811 break;
2812 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002813 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002814 if (bs == NULL) {
2815 ret = 0;
2816 break;
2817 }
2818
2819 depth++;
2820 }
2821
John Snow28756452016-02-05 13:12:33 -05002822 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2823
Max Reitzf30c66b2019-02-01 20:29:05 +01002824 if (file && has_offset) {
2825 bdrv_refresh_filename(file);
2826 filename = file->filename;
2827 }
2828
John Snow28756452016-02-05 13:12:33 -05002829 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002830 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002831 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002832 .data = !!(ret & BDRV_BLOCK_DATA),
2833 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002834 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002835 .has_offset = has_offset,
2836 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002837 .has_filename = filename,
2838 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002839 };
2840
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002841 return 0;
2842}
2843
Fam Zheng16b0d552016-01-26 11:59:02 +08002844static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2845{
2846 if (curr->length == 0) {
2847 return false;
2848 }
2849 if (curr->zero != next->zero ||
2850 curr->data != next->data ||
2851 curr->depth != next->depth ||
2852 curr->has_filename != next->has_filename ||
2853 curr->has_offset != next->has_offset) {
2854 return false;
2855 }
2856 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2857 return false;
2858 }
2859 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2860 return false;
2861 }
2862 return true;
2863}
2864
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002865static int img_map(int argc, char **argv)
2866{
2867 int c;
2868 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002869 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002870 BlockDriverState *bs;
2871 const char *filename, *fmt, *output;
2872 int64_t length;
2873 MapEntry curr = { .length = 0 }, next;
2874 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002875 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002876 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002877
2878 fmt = NULL;
2879 output = NULL;
2880 for (;;) {
2881 int option_index = 0;
2882 static const struct option long_options[] = {
2883 {"help", no_argument, 0, 'h'},
2884 {"format", required_argument, 0, 'f'},
2885 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002886 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002887 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002888 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002889 {0, 0, 0, 0}
2890 };
Fam Zheng335e9932017-05-03 00:35:39 +08002891 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002892 long_options, &option_index);
2893 if (c == -1) {
2894 break;
2895 }
2896 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002897 case ':':
2898 missing_argument(argv[optind - 1]);
2899 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002900 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002901 unrecognized_option(argv[optind - 1]);
2902 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002903 case 'h':
2904 help();
2905 break;
2906 case 'f':
2907 fmt = optarg;
2908 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002909 case 'U':
2910 force_share = true;
2911 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002912 case OPTION_OUTPUT:
2913 output = optarg;
2914 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002915 case OPTION_OBJECT: {
2916 QemuOpts *opts;
2917 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2918 optarg, true);
2919 if (!opts) {
2920 return 1;
2921 }
2922 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002923 case OPTION_IMAGE_OPTS:
2924 image_opts = true;
2925 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002926 }
2927 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002928 if (optind != argc - 1) {
2929 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002930 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002931 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002932
2933 if (output && !strcmp(output, "json")) {
2934 output_format = OFORMAT_JSON;
2935 } else if (output && !strcmp(output, "human")) {
2936 output_format = OFORMAT_HUMAN;
2937 } else if (output) {
2938 error_report("--output must be used with human or json as argument.");
2939 return 1;
2940 }
2941
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002942 if (qemu_opts_foreach(&qemu_object_opts,
2943 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002944 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002945 return 1;
2946 }
2947
Fam Zheng335e9932017-05-03 00:35:39 +08002948 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002949 if (!blk) {
2950 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002951 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002952 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002953
2954 if (output_format == OFORMAT_HUMAN) {
2955 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2956 }
2957
Max Reitzf1d3cd72015-02-05 13:58:18 -05002958 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002959 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002960 int64_t offset = curr.start + curr.length;
2961 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002962
2963 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02002964 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002965 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002966
2967 if (ret < 0) {
2968 error_report("Could not read file metadata: %s", strerror(-ret));
2969 goto out;
2970 }
2971
Fam Zheng16b0d552016-01-26 11:59:02 +08002972 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002973 curr.length += next.length;
2974 continue;
2975 }
2976
2977 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05002978 ret = dump_map_entry(output_format, &curr, &next);
2979 if (ret < 0) {
2980 goto out;
2981 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002982 }
2983 curr = next;
2984 }
2985
Eric Blake30065d12019-03-26 13:40:43 -05002986 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002987
2988out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002989 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002990 return ret < 0;
2991}
2992
aliguorif7b4a942009-01-07 17:40:15 +00002993#define SNAPSHOT_LIST 1
2994#define SNAPSHOT_CREATE 2
2995#define SNAPSHOT_APPLY 3
2996#define SNAPSHOT_DELETE 4
2997
Stuart Brady153859b2009-06-07 00:42:17 +01002998static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002999{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003000 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003001 BlockDriverState *bs;
3002 QEMUSnapshotInfo sn;
3003 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003004 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003005 int action = 0;
3006 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003007 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003008 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003009 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003010 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003011
Kevin Wolfce099542016-03-15 13:01:04 +01003012 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003013 /* Parse commandline parameters */
3014 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003015 static const struct option long_options[] = {
3016 {"help", no_argument, 0, 'h'},
3017 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003018 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003019 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003020 {0, 0, 0, 0}
3021 };
Fam Zheng335e9932017-05-03 00:35:39 +08003022 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003023 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003024 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003025 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003026 }
aliguorif7b4a942009-01-07 17:40:15 +00003027 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003028 case ':':
3029 missing_argument(argv[optind - 1]);
3030 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003031 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003032 unrecognized_option(argv[optind - 1]);
3033 break;
aliguorif7b4a942009-01-07 17:40:15 +00003034 case 'h':
3035 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003036 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003037 case 'l':
3038 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003039 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003040 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003041 }
3042 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003043 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003044 break;
3045 case 'a':
3046 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003047 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003048 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003049 }
3050 action = SNAPSHOT_APPLY;
3051 snapshot_name = optarg;
3052 break;
3053 case 'c':
3054 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003055 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003056 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003057 }
3058 action = SNAPSHOT_CREATE;
3059 snapshot_name = optarg;
3060 break;
3061 case 'd':
3062 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003063 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003064 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003065 }
3066 action = SNAPSHOT_DELETE;
3067 snapshot_name = optarg;
3068 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003069 case 'q':
3070 quiet = true;
3071 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003072 case 'U':
3073 force_share = true;
3074 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003075 case OPTION_OBJECT: {
3076 QemuOpts *opts;
3077 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3078 optarg, true);
3079 if (!opts) {
3080 return 1;
3081 }
3082 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003083 case OPTION_IMAGE_OPTS:
3084 image_opts = true;
3085 break;
aliguorif7b4a942009-01-07 17:40:15 +00003086 }
3087 }
3088
Kevin Wolffc11eb22013-08-05 10:53:04 +02003089 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003090 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003091 }
aliguorif7b4a942009-01-07 17:40:15 +00003092 filename = argv[optind++];
3093
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003094 if (qemu_opts_foreach(&qemu_object_opts,
3095 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003096 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003097 return 1;
3098 }
3099
aliguorif7b4a942009-01-07 17:40:15 +00003100 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003101 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3102 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003103 if (!blk) {
3104 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003105 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003106 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003107
3108 /* Perform the requested action */
3109 switch(action) {
3110 case SNAPSHOT_LIST:
3111 dump_snapshots(bs);
3112 break;
3113
3114 case SNAPSHOT_CREATE:
3115 memset(&sn, 0, sizeof(sn));
3116 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3117
3118 qemu_gettimeofday(&tv);
3119 sn.date_sec = tv.tv_sec;
3120 sn.date_nsec = tv.tv_usec * 1000;
3121
3122 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003123 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003124 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003125 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003126 }
aliguorif7b4a942009-01-07 17:40:15 +00003127 break;
3128
3129 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003130 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003131 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003132 error_reportf_err(err, "Could not apply snapshot '%s': ",
3133 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003134 }
aliguorif7b4a942009-01-07 17:40:15 +00003135 break;
3136
3137 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003138 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3139 if (ret < 0) {
3140 error_report("Could not delete snapshot '%s': snapshot not "
3141 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003142 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003143 } else {
3144 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3145 if (ret < 0) {
3146 error_reportf_err(err, "Could not delete snapshot '%s': ",
3147 snapshot_name);
3148 ret = 1;
3149 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003150 }
aliguorif7b4a942009-01-07 17:40:15 +00003151 break;
3152 }
3153
3154 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003155 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003156 if (ret) {
3157 return 1;
3158 }
Stuart Brady153859b2009-06-07 00:42:17 +01003159 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003160}
3161
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003162static int img_rebase(int argc, char **argv)
3163{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003164 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003165 uint8_t *buf_old = NULL;
3166 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003167 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003168 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003169 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3170 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003171 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003172 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003173 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003174 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003175 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003176 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003177 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003178
3179 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003180 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003181 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003182 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003183 out_baseimg = NULL;
3184 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003185 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003186 static const struct option long_options[] = {
3187 {"help", no_argument, 0, 'h'},
3188 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003189 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003190 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003191 {0, 0, 0, 0}
3192 };
Fam Zheng335e9932017-05-03 00:35:39 +08003193 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003194 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003195 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003196 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003197 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003198 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003199 case ':':
3200 missing_argument(argv[optind - 1]);
3201 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003202 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003203 unrecognized_option(argv[optind - 1]);
3204 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003205 case 'h':
3206 help();
3207 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003208 case 'f':
3209 fmt = optarg;
3210 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003211 case 'F':
3212 out_basefmt = optarg;
3213 break;
3214 case 'b':
3215 out_baseimg = optarg;
3216 break;
3217 case 'u':
3218 unsafe = 1;
3219 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003220 case 'p':
3221 progress = 1;
3222 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003223 case 't':
3224 cache = optarg;
3225 break;
Max Reitz40055952014-07-22 22:58:42 +02003226 case 'T':
3227 src_cache = optarg;
3228 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003229 case 'q':
3230 quiet = true;
3231 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003232 case OPTION_OBJECT: {
3233 QemuOpts *opts;
3234 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3235 optarg, true);
3236 if (!opts) {
3237 return 1;
3238 }
3239 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003240 case OPTION_IMAGE_OPTS:
3241 image_opts = true;
3242 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003243 case 'U':
3244 force_share = true;
3245 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003246 }
3247 }
3248
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003249 if (quiet) {
3250 progress = 0;
3251 }
3252
Fam Zhengac1307a2014-04-22 13:36:11 +08003253 if (optind != argc - 1) {
3254 error_exit("Expecting one image file name");
3255 }
3256 if (!unsafe && !out_baseimg) {
3257 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003258 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003259 filename = argv[optind++];
3260
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003261 if (qemu_opts_foreach(&qemu_object_opts,
3262 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003263 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003264 return 1;
3265 }
3266
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003267 qemu_progress_init(progress, 2.0);
3268 qemu_progress_print(0, 100);
3269
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003270 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003271 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003272 if (ret < 0) {
3273 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003274 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003275 }
3276
Kevin Wolfce099542016-03-15 13:01:04 +01003277 src_flags = 0;
3278 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003279 if (ret < 0) {
3280 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003281 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003282 }
3283
Kevin Wolfce099542016-03-15 13:01:04 +01003284 /* The source files are opened read-only, don't care about WCE */
3285 assert((src_flags & BDRV_O_RDWR) == 0);
3286 (void) src_writethrough;
3287
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003288 /*
3289 * Open the images.
3290 *
3291 * Ignore the old backing file for unsafe rebase in case we want to correct
3292 * the reference to a renamed or moved backing file.
3293 */
Fam Zheng335e9932017-05-03 00:35:39 +08003294 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3295 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003296 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003297 ret = -1;
3298 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003299 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003300 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003301
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003302 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003303 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003304 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003305 ret = -1;
3306 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003307 }
3308 }
3309
3310 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003311 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003312 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003313 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003314
Max Reitz35ddd932019-05-09 19:52:35 +02003315 if (bs->backing) {
3316 if (bs->backing_format[0] != '\0') {
Fam Zheng335e9932017-05-03 00:35:39 +08003317 options = qdict_new();
Max Reitz35ddd932019-05-09 19:52:35 +02003318 qdict_put_str(options, "driver", bs->backing_format);
Fam Zheng335e9932017-05-03 00:35:39 +08003319 }
Max Reitz35ddd932019-05-09 19:52:35 +02003320
3321 if (force_share) {
3322 if (!options) {
3323 options = qdict_new();
3324 }
3325 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3326 }
3327 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3328 blk_old_backing = blk_new_open(backing_name, NULL,
3329 options, src_flags, &local_err);
3330 if (!blk_old_backing) {
3331 error_reportf_err(local_err,
3332 "Could not open old backing file '%s': ",
3333 backing_name);
3334 ret = -1;
3335 goto out;
3336 }
3337 } else {
3338 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003339 }
Max Reitz644483d2015-02-05 13:58:17 -05003340
Alex Bligha6166732012-10-16 13:46:18 +01003341 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003342 const char *overlay_filename;
3343 char *out_real_path;
3344
Fam Zheng335e9932017-05-03 00:35:39 +08003345 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003346 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003347 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003348 }
3349 if (force_share) {
3350 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003351 }
3352
Max Reitzf30c66b2019-02-01 20:29:05 +01003353 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003354 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3355 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003356 out_real_path =
3357 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3358 out_baseimg,
3359 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003360 if (local_err) {
3361 error_reportf_err(local_err,
3362 "Could not resolve backing filename: ");
3363 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003364 goto out;
3365 }
3366
3367 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003368 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003369 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003370 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003371 error_reportf_err(local_err,
3372 "Could not open new backing file '%s': ",
3373 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003374 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003375 goto out;
3376 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003377 }
3378 }
3379
3380 /*
3381 * Check each unallocated cluster in the COW file. If it is unallocated,
3382 * accesses go to the backing file. We must therefore compare this cluster
3383 * in the old and new backing file, and if they differ we need to copy it
3384 * from the old backing file into the COW file.
3385 *
3386 * If qemu-img crashes during this step, no harm is done. The content of
3387 * the image is the same as the original one at any time.
3388 */
3389 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003390 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003391 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003392 int64_t new_backing_size = 0;
3393 uint64_t offset;
3394 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003395 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003396
Max Reitzf1d3cd72015-02-05 13:58:18 -05003397 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3398 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003399
Eric Blake41536282017-10-11 22:47:15 -05003400 size = blk_getlength(blk);
3401 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003402 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003403 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003404 ret = -1;
3405 goto out;
3406 }
Max Reitz35ddd932019-05-09 19:52:35 +02003407 if (blk_old_backing) {
3408 old_backing_size = blk_getlength(blk_old_backing);
3409 if (old_backing_size < 0) {
3410 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003411
Max Reitz35ddd932019-05-09 19:52:35 +02003412 bdrv_get_backing_filename(bs, backing_name,
3413 sizeof(backing_name));
3414 error_report("Could not get size of '%s': %s",
3415 backing_name, strerror(-old_backing_size));
3416 ret = -1;
3417 goto out;
3418 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003419 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003420 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003421 new_backing_size = blk_getlength(blk_new_backing);
3422 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003423 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003424 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003425 ret = -1;
3426 goto out;
3427 }
Alex Bligha6166732012-10-16 13:46:18 +01003428 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003429
Eric Blake41536282017-10-11 22:47:15 -05003430 if (size != 0) {
3431 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003432 }
3433
Eric Blake41536282017-10-11 22:47:15 -05003434 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003435 bool buf_old_is_zero = false;
3436
Eric Blake41536282017-10-11 22:47:15 -05003437 /* How many bytes can we handle with the next read? */
3438 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003439
3440 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003441 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003442 if (ret < 0) {
3443 error_report("error while reading image metadata: %s",
3444 strerror(-ret));
3445 goto out;
3446 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003447 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003448 continue;
3449 }
3450
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003451 /*
3452 * Read old and new backing file and take into consideration that
3453 * backing files may be smaller than the COW image.
3454 */
Eric Blake41536282017-10-11 22:47:15 -05003455 if (offset >= old_backing_size) {
3456 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003457 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003458 } else {
Eric Blake41536282017-10-11 22:47:15 -05003459 if (offset + n > old_backing_size) {
3460 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003461 }
3462
Eric Blake41536282017-10-11 22:47:15 -05003463 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003464 if (ret < 0) {
3465 error_report("error while reading from old backing file");
3466 goto out;
3467 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003468 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003469
Eric Blake41536282017-10-11 22:47:15 -05003470 if (offset >= new_backing_size || !blk_new_backing) {
3471 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003472 } else {
Eric Blake41536282017-10-11 22:47:15 -05003473 if (offset + n > new_backing_size) {
3474 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003475 }
3476
Eric Blake41536282017-10-11 22:47:15 -05003477 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003478 if (ret < 0) {
3479 error_report("error while reading from new backing file");
3480 goto out;
3481 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003482 }
3483
3484 /* If they differ, we need to write to the COW file */
3485 uint64_t written = 0;
3486
Eric Blake41536282017-10-11 22:47:15 -05003487 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003488 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003489
Eric Blake41536282017-10-11 22:47:15 -05003490 if (compare_buffers(buf_old + written, buf_new + written,
3491 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003492 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003493 if (buf_old_is_zero) {
3494 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3495 } else {
3496 ret = blk_pwrite(blk, offset + written,
3497 buf_old + written, pnum, 0);
3498 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003499 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003500 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003501 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003502 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003503 }
3504 }
3505
3506 written += pnum;
3507 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003508 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003509 }
3510 }
3511
3512 /*
3513 * Change the backing file. All clusters that are different from the old
3514 * backing file are overwritten in the COW file now, so the visible content
3515 * doesn't change when we switch the backing file.
3516 */
Alex Bligha6166732012-10-16 13:46:18 +01003517 if (out_baseimg && *out_baseimg) {
3518 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3519 } else {
3520 ret = bdrv_change_backing_file(bs, NULL, NULL);
3521 }
3522
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003523 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003524 error_report("Could not change the backing file to '%s': No "
3525 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003526 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003527 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003528 out_baseimg, strerror(-ret));
3529 }
3530
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003531 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003532 /*
3533 * TODO At this point it is possible to check if any clusters that are
3534 * allocated in the COW file are the same in the backing file. If so, they
3535 * could be dropped from the COW file. Don't do this before switching the
3536 * backing file, in case of a crash this would lead to corruption.
3537 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003538out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003539 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003540 /* Cleanup */
3541 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003542 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003543 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003544 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003545 qemu_vfree(buf_old);
3546 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003547
Markus Armbruster26f54e92014-10-07 13:59:04 +02003548 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003549 if (ret) {
3550 return 1;
3551 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003552 return 0;
3553}
3554
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003555static int img_resize(int argc, char **argv)
3556{
Markus Armbruster6750e792015-02-12 17:43:08 +01003557 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003558 int c, ret, relative;
3559 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003560 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003561 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003562 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003563 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003564 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003565
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003566 static QemuOptsList resize_options = {
3567 .name = "resize_options",
3568 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3569 .desc = {
3570 {
3571 .name = BLOCK_OPT_SIZE,
3572 .type = QEMU_OPT_SIZE,
3573 .help = "Virtual disk size"
3574 }, {
3575 /* end of list */
3576 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003577 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003578 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003579 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003580 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003581
Kevin Wolfe80fec72011-04-29 10:58:12 +02003582 /* Remove size from argv manually so that negative numbers are not treated
3583 * as options by getopt. */
3584 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003585 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003586 return 1;
3587 }
3588
3589 size = argv[--argc];
3590
3591 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003592 fmt = NULL;
3593 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003594 static const struct option long_options[] = {
3595 {"help", no_argument, 0, 'h'},
3596 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003597 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003598 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003599 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003600 {0, 0, 0, 0}
3601 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003602 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003603 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003604 if (c == -1) {
3605 break;
3606 }
3607 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003608 case ':':
3609 missing_argument(argv[optind - 1]);
3610 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003611 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003612 unrecognized_option(argv[optind - 1]);
3613 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003614 case 'h':
3615 help();
3616 break;
3617 case 'f':
3618 fmt = optarg;
3619 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003620 case 'q':
3621 quiet = true;
3622 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003623 case OPTION_OBJECT: {
3624 QemuOpts *opts;
3625 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3626 optarg, true);
3627 if (!opts) {
3628 return 1;
3629 }
3630 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003631 case OPTION_IMAGE_OPTS:
3632 image_opts = true;
3633 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003634 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003635 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003636 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003637 if (prealloc == PREALLOC_MODE__MAX) {
3638 error_report("Invalid preallocation mode '%s'", optarg);
3639 return 1;
3640 }
3641 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003642 case OPTION_SHRINK:
3643 shrink = true;
3644 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003645 }
3646 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003647 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003648 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003649 }
3650 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003651
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003652 if (qemu_opts_foreach(&qemu_object_opts,
3653 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003654 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003655 return 1;
3656 }
3657
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003658 /* Choose grow, shrink, or absolute resize mode */
3659 switch (size[0]) {
3660 case '+':
3661 relative = 1;
3662 size++;
3663 break;
3664 case '-':
3665 relative = -1;
3666 size++;
3667 break;
3668 default:
3669 relative = 0;
3670 break;
3671 }
3672
3673 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003674 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003675 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003676 if (err) {
3677 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003678 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003679 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003680 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003681 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003682 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3683 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003684
Max Reitzefaa7c42016-03-16 19:54:38 +01003685 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003686 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3687 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003688 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003689 ret = -1;
3690 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003691 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003692
Max Reitzdc5f6902017-06-13 22:20:55 +02003693 current_size = blk_getlength(blk);
3694 if (current_size < 0) {
3695 error_report("Failed to inquire current image length: %s",
3696 strerror(-current_size));
3697 ret = -1;
3698 goto out;
3699 }
3700
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003701 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003702 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003703 } else {
3704 total_size = n;
3705 }
3706 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003707 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003708 ret = -1;
3709 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003710 }
3711
Max Reitzdc5f6902017-06-13 22:20:55 +02003712 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3713 error_report("Preallocation can only be used for growing images");
3714 ret = -1;
3715 goto out;
3716 }
3717
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003718 if (total_size < current_size && !shrink) {
3719 warn_report("Shrinking an image will delete all data beyond the "
3720 "shrunken image's end. Before performing such an "
3721 "operation, make sure there is no important data there.");
3722
3723 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3724 error_report(
3725 "Use the --shrink option to perform a shrink operation.");
3726 ret = -1;
3727 goto out;
3728 } else {
3729 warn_report("Using the --shrink option will suppress this message. "
3730 "Note that future versions of qemu-img may refuse to "
3731 "shrink images without this option.");
3732 }
3733 }
3734
Max Reitzdc5f6902017-06-13 22:20:55 +02003735 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003736 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003737 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003738 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003739 }
Max Reitz5279b302018-04-21 18:39:57 +02003740
3741 new_size = blk_getlength(blk);
3742 if (new_size < 0) {
3743 error_report("Failed to verify truncated image length: %s",
3744 strerror(-new_size));
3745 ret = -1;
3746 goto out;
3747 }
3748
3749 /* Some block drivers implement a truncation method, but only so
3750 * the user can cause qemu to refresh the image's size from disk.
3751 * The idea is that the user resizes the image outside of qemu and
3752 * then invokes block_resize to inform qemu about it.
3753 * (This includes iscsi and file-posix for device files.)
3754 * Of course, that is not the behavior someone invoking
3755 * qemu-img resize would find useful, so we catch that behavior
3756 * here and tell the user. */
3757 if (new_size != total_size && new_size == current_size) {
3758 error_report("Image was not resized; resizing may not be supported "
3759 "for this image");
3760 ret = -1;
3761 goto out;
3762 }
3763
3764 if (new_size != total_size) {
3765 warn_report("Image should have been resized to %" PRIi64
3766 " bytes, but was resized to %" PRIi64 " bytes",
3767 total_size, new_size);
3768 }
3769
3770 qprintf(quiet, "Image resized.\n");
3771
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003772out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003773 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003774 if (ret) {
3775 return 1;
3776 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003777 return 0;
3778}
3779
Max Reitz76a3a342014-10-27 11:12:51 +01003780static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003781 int64_t offset, int64_t total_work_size,
3782 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003783{
3784 qemu_progress_print(100.f * offset / total_work_size, 0);
3785}
3786
Max Reitz51641352018-05-09 23:00:20 +02003787static int print_amend_option_help(const char *format)
3788{
3789 BlockDriver *drv;
3790
3791 /* Find driver and parse its options */
3792 drv = bdrv_find_format(format);
3793 if (!drv) {
3794 error_report("Unknown file format '%s'", format);
3795 return 1;
3796 }
3797
3798 if (!drv->bdrv_amend_options) {
3799 error_report("Format driver '%s' does not support option amendment",
3800 format);
3801 return 1;
3802 }
3803
3804 /* Every driver supporting amendment must have create_opts */
3805 assert(drv->create_opts);
3806
3807 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003808 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003809 printf("\nNote that not all of these options may be amendable.\n");
3810 return 0;
3811}
3812
Max Reitz6f176b42013-09-03 10:09:50 +02003813static int img_amend(int argc, char **argv)
3814{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003815 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003816 int c, ret = 0;
3817 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003818 QemuOptsList *create_opts = NULL;
3819 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003820 const char *fmt = NULL, *filename, *cache;
3821 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003822 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003823 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003824 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003825 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003826 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003827
Max Reitzbd39e6e2014-07-22 22:58:43 +02003828 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003829 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003830 static const struct option long_options[] = {
3831 {"help", no_argument, 0, 'h'},
3832 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003833 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003834 {0, 0, 0, 0}
3835 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003836 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003837 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003838 if (c == -1) {
3839 break;
3840 }
3841
3842 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003843 case ':':
3844 missing_argument(argv[optind - 1]);
3845 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003846 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003847 unrecognized_option(argv[optind - 1]);
3848 break;
3849 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003850 help();
3851 break;
3852 case 'o':
3853 if (!is_valid_option_list(optarg)) {
3854 error_report("Invalid option list: %s", optarg);
3855 ret = -1;
3856 goto out_no_progress;
3857 }
3858 if (!options) {
3859 options = g_strdup(optarg);
3860 } else {
3861 char *old_options = options;
3862 options = g_strdup_printf("%s,%s", options, optarg);
3863 g_free(old_options);
3864 }
3865 break;
3866 case 'f':
3867 fmt = optarg;
3868 break;
3869 case 't':
3870 cache = optarg;
3871 break;
3872 case 'p':
3873 progress = true;
3874 break;
3875 case 'q':
3876 quiet = true;
3877 break;
3878 case OPTION_OBJECT:
3879 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3880 optarg, true);
3881 if (!opts) {
3882 ret = -1;
3883 goto out_no_progress;
3884 }
3885 break;
3886 case OPTION_IMAGE_OPTS:
3887 image_opts = true;
3888 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003889 }
3890 }
3891
Max Reitz6f176b42013-09-03 10:09:50 +02003892 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003893 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003894 }
3895
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003896 if (qemu_opts_foreach(&qemu_object_opts,
3897 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003898 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003899 ret = -1;
3900 goto out_no_progress;
3901 }
3902
Max Reitz76a3a342014-10-27 11:12:51 +01003903 if (quiet) {
3904 progress = false;
3905 }
3906 qemu_progress_init(progress, 1.0);
3907
Kevin Wolfa283cb62014-02-21 16:24:07 +01003908 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3909 if (fmt && has_help_option(options)) {
3910 /* If a format is explicitly specified (and possibly no filename is
3911 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003912 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003913 goto out;
3914 }
3915
3916 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003917 error_report("Expecting one image file name");
3918 ret = -1;
3919 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003920 }
Max Reitz6f176b42013-09-03 10:09:50 +02003921
Kevin Wolfce099542016-03-15 13:01:04 +01003922 flags = BDRV_O_RDWR;
3923 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003924 if (ret < 0) {
3925 error_report("Invalid cache option: %s", cache);
3926 goto out;
3927 }
3928
Fam Zheng335e9932017-05-03 00:35:39 +08003929 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3930 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003931 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003932 ret = -1;
3933 goto out;
3934 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003935 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003936
3937 fmt = bs->drv->format_name;
3938
Kevin Wolf626f84f2014-02-21 16:24:06 +01003939 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003940 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003941 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003942 goto out;
3943 }
3944
Max Reitz1f996682018-05-09 23:00:17 +02003945 if (!bs->drv->bdrv_amend_options) {
3946 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003947 fmt);
3948 ret = -1;
3949 goto out;
3950 }
3951
Max Reitz1f996682018-05-09 23:00:17 +02003952 /* Every driver supporting amendment must have create_opts */
3953 assert(bs->drv->create_opts);
3954
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003955 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003956 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003957 qemu_opts_do_parse(opts, options, NULL, &err);
3958 if (err) {
3959 error_report_err(err);
3960 ret = -1;
3961 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003962 }
3963
Max Reitz76a3a342014-10-27 11:12:51 +01003964 /* In case the driver does not call amend_status_cb() */
3965 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003966 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003967 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003968 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003969 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003970 goto out;
3971 }
3972
3973out:
Max Reitz76a3a342014-10-27 11:12:51 +01003974 qemu_progress_end();
3975
Max Reitze814dff2015-08-20 16:00:38 -07003976out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003977 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003978 qemu_opts_del(opts);
3979 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003980 g_free(options);
3981
Max Reitz6f176b42013-09-03 10:09:50 +02003982 if (ret) {
3983 return 1;
3984 }
3985 return 0;
3986}
3987
Kevin Wolfb6133b82014-08-05 14:17:13 +02003988typedef struct BenchData {
3989 BlockBackend *blk;
3990 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003991 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003992 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003993 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003994 int nrreq;
3995 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003996 int flush_interval;
3997 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003998 uint8_t *buf;
3999 QEMUIOVector *qiov;
4000
4001 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004002 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004003 uint64_t offset;
4004} BenchData;
4005
Kevin Wolf55d539c2016-06-03 13:59:41 +02004006static void bench_undrained_flush_cb(void *opaque, int ret)
4007{
4008 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004009 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004010 exit(EXIT_FAILURE);
4011 }
4012}
4013
Kevin Wolfb6133b82014-08-05 14:17:13 +02004014static void bench_cb(void *opaque, int ret)
4015{
4016 BenchData *b = opaque;
4017 BlockAIOCB *acb;
4018
4019 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004020 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004021 exit(EXIT_FAILURE);
4022 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004023
4024 if (b->in_flush) {
4025 /* Just finished a flush with drained queue: Start next requests */
4026 assert(b->in_flight == 0);
4027 b->in_flush = false;
4028 } else if (b->in_flight > 0) {
4029 int remaining = b->n - b->in_flight;
4030
Kevin Wolfb6133b82014-08-05 14:17:13 +02004031 b->n--;
4032 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004033
4034 /* Time for flush? Drain queue if requested, then flush */
4035 if (b->flush_interval && remaining % b->flush_interval == 0) {
4036 if (!b->in_flight || !b->drain_on_flush) {
4037 BlockCompletionFunc *cb;
4038
4039 if (b->drain_on_flush) {
4040 b->in_flush = true;
4041 cb = bench_cb;
4042 } else {
4043 cb = bench_undrained_flush_cb;
4044 }
4045
4046 acb = blk_aio_flush(b->blk, cb, b);
4047 if (!acb) {
4048 error_report("Failed to issue flush request");
4049 exit(EXIT_FAILURE);
4050 }
4051 }
4052 if (b->drain_on_flush) {
4053 return;
4054 }
4055 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004056 }
4057
4058 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004059 int64_t offset = b->offset;
4060 /* blk_aio_* might look for completed I/Os and kick bench_cb
4061 * again, so make sure this operation is counted by in_flight
4062 * and b->offset is ready for the next submission.
4063 */
4064 b->in_flight++;
4065 b->offset += b->step;
4066 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004067 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004068 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004069 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004070 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004071 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004072 if (!acb) {
4073 error_report("Failed to issue request");
4074 exit(EXIT_FAILURE);
4075 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004076 }
4077}
4078
4079static int img_bench(int argc, char **argv)
4080{
4081 int c, ret = 0;
4082 const char *fmt = NULL, *filename;
4083 bool quiet = false;
4084 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004085 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004086 int count = 75000;
4087 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004088 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004089 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004090 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004091 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004092 int flush_interval = 0;
4093 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004094 int64_t image_size;
4095 BlockBackend *blk = NULL;
4096 BenchData data = {};
4097 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004098 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004099 struct timeval t1, t2;
4100 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004101 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004102 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004103
4104 for (;;) {
4105 static const struct option long_options[] = {
4106 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004107 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004108 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004109 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004110 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004111 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004112 {0, 0, 0, 0}
4113 };
Fam Zheng335e9932017-05-03 00:35:39 +08004114 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004115 if (c == -1) {
4116 break;
4117 }
4118
4119 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004120 case ':':
4121 missing_argument(argv[optind - 1]);
4122 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004123 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004124 unrecognized_option(argv[optind - 1]);
4125 break;
4126 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004127 help();
4128 break;
4129 case 'c':
4130 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004131 unsigned long res;
4132
4133 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004134 error_report("Invalid request count specified");
4135 return 1;
4136 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004137 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004138 break;
4139 }
4140 case 'd':
4141 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004142 unsigned long res;
4143
4144 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004145 error_report("Invalid queue depth specified");
4146 return 1;
4147 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004148 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004149 break;
4150 }
4151 case 'f':
4152 fmt = optarg;
4153 break;
4154 case 'n':
4155 flags |= BDRV_O_NATIVE_AIO;
4156 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004157 case 'o':
4158 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004159 offset = cvtnum(optarg);
4160 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004161 error_report("Invalid offset specified");
4162 return 1;
4163 }
4164 break;
4165 }
4166 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004167 case 'q':
4168 quiet = true;
4169 break;
4170 case 's':
4171 {
4172 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004173
Markus Armbruster606caa02017-02-21 21:14:04 +01004174 sval = cvtnum(optarg);
4175 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004176 error_report("Invalid buffer size specified");
4177 return 1;
4178 }
4179
4180 bufsize = sval;
4181 break;
4182 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004183 case 'S':
4184 {
4185 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004186
Markus Armbruster606caa02017-02-21 21:14:04 +01004187 sval = cvtnum(optarg);
4188 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004189 error_report("Invalid step size specified");
4190 return 1;
4191 }
4192
4193 step = sval;
4194 break;
4195 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004196 case 't':
4197 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4198 if (ret < 0) {
4199 error_report("Invalid cache mode");
4200 ret = -1;
4201 goto out;
4202 }
4203 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004204 case 'w':
4205 flags |= BDRV_O_RDWR;
4206 is_write = true;
4207 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004208 case 'U':
4209 force_share = true;
4210 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004211 case OPTION_PATTERN:
4212 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004213 unsigned long res;
4214
4215 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004216 error_report("Invalid pattern byte specified");
4217 return 1;
4218 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004219 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004220 break;
4221 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004222 case OPTION_FLUSH_INTERVAL:
4223 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004224 unsigned long res;
4225
4226 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004227 error_report("Invalid flush interval specified");
4228 return 1;
4229 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004230 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004231 break;
4232 }
4233 case OPTION_NO_DRAIN:
4234 drain_on_flush = false;
4235 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004236 case OPTION_IMAGE_OPTS:
4237 image_opts = true;
4238 break;
4239 }
4240 }
4241
4242 if (optind != argc - 1) {
4243 error_exit("Expecting one image file name");
4244 }
4245 filename = argv[argc - 1];
4246
Kevin Wolf55d539c2016-06-03 13:59:41 +02004247 if (!is_write && flush_interval) {
4248 error_report("--flush-interval is only available in write tests");
4249 ret = -1;
4250 goto out;
4251 }
4252 if (flush_interval && flush_interval < depth) {
4253 error_report("Flush interval can't be smaller than depth");
4254 ret = -1;
4255 goto out;
4256 }
4257
Fam Zheng335e9932017-05-03 00:35:39 +08004258 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4259 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004260 if (!blk) {
4261 ret = -1;
4262 goto out;
4263 }
4264
4265 image_size = blk_getlength(blk);
4266 if (image_size < 0) {
4267 ret = image_size;
4268 goto out;
4269 }
4270
4271 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004272 .blk = blk,
4273 .image_size = image_size,
4274 .bufsize = bufsize,
4275 .step = step ?: bufsize,
4276 .nrreq = depth,
4277 .n = count,
4278 .offset = offset,
4279 .write = is_write,
4280 .flush_interval = flush_interval,
4281 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004282 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004283 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004284 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004285 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004286 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004287 if (flush_interval) {
4288 printf("Sending flush every %d requests\n", flush_interval);
4289 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004290
Fam Zheng79d46582018-01-16 14:08:58 +08004291 buf_size = data.nrreq * data.bufsize;
4292 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004293 memset(data.buf, pattern, data.nrreq * data.bufsize);
4294
Fam Zheng79d46582018-01-16 14:08:58 +08004295 blk_register_buf(blk, data.buf, buf_size);
4296
Kevin Wolfb6133b82014-08-05 14:17:13 +02004297 data.qiov = g_new(QEMUIOVector, data.nrreq);
4298 for (i = 0; i < data.nrreq; i++) {
4299 qemu_iovec_init(&data.qiov[i], 1);
4300 qemu_iovec_add(&data.qiov[i],
4301 data.buf + i * data.bufsize, data.bufsize);
4302 }
4303
4304 gettimeofday(&t1, NULL);
4305 bench_cb(&data, 0);
4306
4307 while (data.n > 0) {
4308 main_loop_wait(false);
4309 }
4310 gettimeofday(&t2, NULL);
4311
4312 printf("Run completed in %3.3f seconds.\n",
4313 (t2.tv_sec - t1.tv_sec)
4314 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4315
4316out:
Fam Zheng79d46582018-01-16 14:08:58 +08004317 if (data.buf) {
4318 blk_unregister_buf(blk, data.buf);
4319 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004320 qemu_vfree(data.buf);
4321 blk_unref(blk);
4322
4323 if (ret) {
4324 return 1;
4325 }
4326 return 0;
4327}
4328
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004329#define C_BS 01
4330#define C_COUNT 02
4331#define C_IF 04
4332#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004333#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004334
4335struct DdInfo {
4336 unsigned int flags;
4337 int64_t count;
4338};
4339
4340struct DdIo {
4341 int bsz; /* Block size */
4342 char *filename;
4343 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004344 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004345};
4346
4347struct DdOpts {
4348 const char *name;
4349 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4350 unsigned int flag;
4351};
4352
4353static int img_dd_bs(const char *arg,
4354 struct DdIo *in, struct DdIo *out,
4355 struct DdInfo *dd)
4356{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004357 int64_t res;
4358
Markus Armbruster606caa02017-02-21 21:14:04 +01004359 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004360
Markus Armbruster606caa02017-02-21 21:14:04 +01004361 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004362 error_report("invalid number: '%s'", arg);
4363 return 1;
4364 }
4365 in->bsz = out->bsz = res;
4366
4367 return 0;
4368}
4369
4370static int img_dd_count(const char *arg,
4371 struct DdIo *in, struct DdIo *out,
4372 struct DdInfo *dd)
4373{
Markus Armbruster606caa02017-02-21 21:14:04 +01004374 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004375
Markus Armbruster606caa02017-02-21 21:14:04 +01004376 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004377 error_report("invalid number: '%s'", arg);
4378 return 1;
4379 }
4380
4381 return 0;
4382}
4383
4384static int img_dd_if(const char *arg,
4385 struct DdIo *in, struct DdIo *out,
4386 struct DdInfo *dd)
4387{
4388 in->filename = g_strdup(arg);
4389
4390 return 0;
4391}
4392
4393static int img_dd_of(const char *arg,
4394 struct DdIo *in, struct DdIo *out,
4395 struct DdInfo *dd)
4396{
4397 out->filename = g_strdup(arg);
4398
4399 return 0;
4400}
4401
Reda Sallahif7c15532016-08-10 16:16:09 +02004402static int img_dd_skip(const char *arg,
4403 struct DdIo *in, struct DdIo *out,
4404 struct DdInfo *dd)
4405{
Markus Armbruster606caa02017-02-21 21:14:04 +01004406 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004407
Markus Armbruster606caa02017-02-21 21:14:04 +01004408 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004409 error_report("invalid number: '%s'", arg);
4410 return 1;
4411 }
4412
4413 return 0;
4414}
4415
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004416static int img_dd(int argc, char **argv)
4417{
4418 int ret = 0;
4419 char *arg = NULL;
4420 char *tmp;
4421 BlockDriver *drv = NULL, *proto_drv = NULL;
4422 BlockBackend *blk1 = NULL, *blk2 = NULL;
4423 QemuOpts *opts = NULL;
4424 QemuOptsList *create_opts = NULL;
4425 Error *local_err = NULL;
4426 bool image_opts = false;
4427 int c, i;
4428 const char *out_fmt = "raw";
4429 const char *fmt = NULL;
4430 int64_t size = 0;
4431 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004432 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004433 struct DdInfo dd = {
4434 .flags = 0,
4435 .count = 0,
4436 };
4437 struct DdIo in = {
4438 .bsz = 512, /* Block size is by default 512 bytes */
4439 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004440 .buf = NULL,
4441 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004442 };
4443 struct DdIo out = {
4444 .bsz = 512,
4445 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004446 .buf = NULL,
4447 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004448 };
4449
4450 const struct DdOpts options[] = {
4451 { "bs", img_dd_bs, C_BS },
4452 { "count", img_dd_count, C_COUNT },
4453 { "if", img_dd_if, C_IF },
4454 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004455 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004456 { NULL, NULL, 0 }
4457 };
4458 const struct option long_options[] = {
4459 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004460 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004461 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004462 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004463 { 0, 0, 0, 0 }
4464 };
4465
Fam Zheng335e9932017-05-03 00:35:39 +08004466 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004467 if (c == EOF) {
4468 break;
4469 }
4470 switch (c) {
4471 case 'O':
4472 out_fmt = optarg;
4473 break;
4474 case 'f':
4475 fmt = optarg;
4476 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004477 case ':':
4478 missing_argument(argv[optind - 1]);
4479 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004480 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004481 unrecognized_option(argv[optind - 1]);
4482 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004483 case 'h':
4484 help();
4485 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004486 case 'U':
4487 force_share = true;
4488 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004489 case OPTION_OBJECT:
4490 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004491 ret = -1;
4492 goto out;
4493 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004494 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004495 case OPTION_IMAGE_OPTS:
4496 image_opts = true;
4497 break;
4498 }
4499 }
4500
4501 for (i = optind; i < argc; i++) {
4502 int j;
4503 arg = g_strdup(argv[i]);
4504
4505 tmp = strchr(arg, '=');
4506 if (tmp == NULL) {
4507 error_report("unrecognized operand %s", arg);
4508 ret = -1;
4509 goto out;
4510 }
4511
4512 *tmp++ = '\0';
4513
4514 for (j = 0; options[j].name != NULL; j++) {
4515 if (!strcmp(arg, options[j].name)) {
4516 break;
4517 }
4518 }
4519 if (options[j].name == NULL) {
4520 error_report("unrecognized operand %s", arg);
4521 ret = -1;
4522 goto out;
4523 }
4524
4525 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4526 ret = -1;
4527 goto out;
4528 }
4529 dd.flags |= options[j].flag;
4530 g_free(arg);
4531 arg = NULL;
4532 }
4533
4534 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4535 error_report("Must specify both input and output files");
4536 ret = -1;
4537 goto out;
4538 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004539
4540 if (qemu_opts_foreach(&qemu_object_opts,
4541 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004542 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004543 ret = -1;
4544 goto out;
4545 }
4546
Fam Zheng335e9932017-05-03 00:35:39 +08004547 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4548 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004549
4550 if (!blk1) {
4551 ret = -1;
4552 goto out;
4553 }
4554
4555 drv = bdrv_find_format(out_fmt);
4556 if (!drv) {
4557 error_report("Unknown file format");
4558 ret = -1;
4559 goto out;
4560 }
4561 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4562
4563 if (!proto_drv) {
4564 error_report_err(local_err);
4565 ret = -1;
4566 goto out;
4567 }
4568 if (!drv->create_opts) {
4569 error_report("Format driver '%s' does not support image creation",
4570 drv->format_name);
4571 ret = -1;
4572 goto out;
4573 }
4574 if (!proto_drv->create_opts) {
4575 error_report("Protocol driver '%s' does not support image creation",
4576 proto_drv->format_name);
4577 ret = -1;
4578 goto out;
4579 }
4580 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4581 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4582
4583 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4584
4585 size = blk_getlength(blk1);
4586 if (size < 0) {
4587 error_report("Failed to get size for '%s'", in.filename);
4588 ret = -1;
4589 goto out;
4590 }
4591
4592 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4593 dd.count * in.bsz < size) {
4594 size = dd.count * in.bsz;
4595 }
4596
Reda Sallahif7c15532016-08-10 16:16:09 +02004597 /* Overflow means the specified offset is beyond input image's size */
4598 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4599 size < in.bsz * in.offset)) {
4600 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4601 } else {
4602 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4603 size - in.bsz * in.offset, &error_abort);
4604 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004605
4606 ret = bdrv_create(drv, out.filename, opts, &local_err);
4607 if (ret < 0) {
4608 error_reportf_err(local_err,
4609 "%s: error while creating output image: ",
4610 out.filename);
4611 ret = -1;
4612 goto out;
4613 }
4614
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004615 /* TODO, we can't honour --image-opts for the target,
4616 * since it needs to be given in a format compatible
4617 * with the bdrv_create() call above which does not
4618 * support image-opts style.
4619 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004620 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004621 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004622
4623 if (!blk2) {
4624 ret = -1;
4625 goto out;
4626 }
4627
Reda Sallahif7c15532016-08-10 16:16:09 +02004628 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4629 size < in.offset * in.bsz)) {
4630 /* We give a warning if the skip option is bigger than the input
4631 * size and create an empty output disk image (i.e. like dd(1)).
4632 */
4633 error_report("%s: cannot skip to specified offset", in.filename);
4634 in_pos = size;
4635 } else {
4636 in_pos = in.offset * in.bsz;
4637 }
4638
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004639 in.buf = g_new(uint8_t, in.bsz);
4640
Reda Sallahif7c15532016-08-10 16:16:09 +02004641 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004642 int in_ret, out_ret;
4643
4644 if (in_pos + in.bsz > size) {
4645 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4646 } else {
4647 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4648 }
4649 if (in_ret < 0) {
4650 error_report("error while reading from input image file: %s",
4651 strerror(-in_ret));
4652 ret = -1;
4653 goto out;
4654 }
4655 in_pos += in_ret;
4656
4657 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4658
4659 if (out_ret < 0) {
4660 error_report("error while writing to output image file: %s",
4661 strerror(-out_ret));
4662 ret = -1;
4663 goto out;
4664 }
4665 out_pos += out_ret;
4666 }
4667
4668out:
4669 g_free(arg);
4670 qemu_opts_del(opts);
4671 qemu_opts_free(create_opts);
4672 blk_unref(blk1);
4673 blk_unref(blk2);
4674 g_free(in.filename);
4675 g_free(out.filename);
4676 g_free(in.buf);
4677 g_free(out.buf);
4678
4679 if (ret) {
4680 return 1;
4681 }
4682 return 0;
4683}
4684
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004685static void dump_json_block_measure_info(BlockMeasureInfo *info)
4686{
4687 QString *str;
4688 QObject *obj;
4689 Visitor *v = qobject_output_visitor_new(&obj);
4690
4691 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4692 visit_complete(v, &obj);
4693 str = qobject_to_json_pretty(obj);
4694 assert(str != NULL);
4695 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004696 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004697 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004698 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004699}
4700
4701static int img_measure(int argc, char **argv)
4702{
4703 static const struct option long_options[] = {
4704 {"help", no_argument, 0, 'h'},
4705 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4706 {"object", required_argument, 0, OPTION_OBJECT},
4707 {"output", required_argument, 0, OPTION_OUTPUT},
4708 {"size", required_argument, 0, OPTION_SIZE},
4709 {"force-share", no_argument, 0, 'U'},
4710 {0, 0, 0, 0}
4711 };
4712 OutputFormat output_format = OFORMAT_HUMAN;
4713 BlockBackend *in_blk = NULL;
4714 BlockDriver *drv;
4715 const char *filename = NULL;
4716 const char *fmt = NULL;
4717 const char *out_fmt = "raw";
4718 char *options = NULL;
4719 char *snapshot_name = NULL;
4720 bool force_share = false;
4721 QemuOpts *opts = NULL;
4722 QemuOpts *object_opts = NULL;
4723 QemuOpts *sn_opts = NULL;
4724 QemuOptsList *create_opts = NULL;
4725 bool image_opts = false;
4726 uint64_t img_size = UINT64_MAX;
4727 BlockMeasureInfo *info = NULL;
4728 Error *local_err = NULL;
4729 int ret = 1;
4730 int c;
4731
4732 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4733 long_options, NULL)) != -1) {
4734 switch (c) {
4735 case '?':
4736 case 'h':
4737 help();
4738 break;
4739 case 'f':
4740 fmt = optarg;
4741 break;
4742 case 'O':
4743 out_fmt = optarg;
4744 break;
4745 case 'o':
4746 if (!is_valid_option_list(optarg)) {
4747 error_report("Invalid option list: %s", optarg);
4748 goto out;
4749 }
4750 if (!options) {
4751 options = g_strdup(optarg);
4752 } else {
4753 char *old_options = options;
4754 options = g_strdup_printf("%s,%s", options, optarg);
4755 g_free(old_options);
4756 }
4757 break;
4758 case 'l':
4759 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4760 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4761 optarg, false);
4762 if (!sn_opts) {
4763 error_report("Failed in parsing snapshot param '%s'",
4764 optarg);
4765 goto out;
4766 }
4767 } else {
4768 snapshot_name = optarg;
4769 }
4770 break;
4771 case 'U':
4772 force_share = true;
4773 break;
4774 case OPTION_OBJECT:
4775 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4776 optarg, true);
4777 if (!object_opts) {
4778 goto out;
4779 }
4780 break;
4781 case OPTION_IMAGE_OPTS:
4782 image_opts = true;
4783 break;
4784 case OPTION_OUTPUT:
4785 if (!strcmp(optarg, "json")) {
4786 output_format = OFORMAT_JSON;
4787 } else if (!strcmp(optarg, "human")) {
4788 output_format = OFORMAT_HUMAN;
4789 } else {
4790 error_report("--output must be used with human or json "
4791 "as argument.");
4792 goto out;
4793 }
4794 break;
4795 case OPTION_SIZE:
4796 {
4797 int64_t sval;
4798
4799 sval = cvtnum(optarg);
4800 if (sval < 0) {
4801 if (sval == -ERANGE) {
4802 error_report("Image size must be less than 8 EiB!");
4803 } else {
4804 error_report("Invalid image size specified! You may use "
4805 "k, M, G, T, P or E suffixes for ");
4806 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4807 "petabytes and exabytes.");
4808 }
4809 goto out;
4810 }
4811 img_size = (uint64_t)sval;
4812 }
4813 break;
4814 }
4815 }
4816
4817 if (qemu_opts_foreach(&qemu_object_opts,
4818 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004819 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004820 goto out;
4821 }
4822
4823 if (argc - optind > 1) {
4824 error_report("At most one filename argument is allowed.");
4825 goto out;
4826 } else if (argc - optind == 1) {
4827 filename = argv[optind];
4828 }
4829
4830 if (!filename &&
4831 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4832 error_report("--object, --image-opts, -f, and -l "
4833 "require a filename argument.");
4834 goto out;
4835 }
4836 if (filename && img_size != UINT64_MAX) {
4837 error_report("--size N cannot be used together with a filename.");
4838 goto out;
4839 }
4840 if (!filename && img_size == UINT64_MAX) {
4841 error_report("Either --size N or one filename must be specified.");
4842 goto out;
4843 }
4844
4845 if (filename) {
4846 in_blk = img_open(image_opts, filename, fmt, 0,
4847 false, false, force_share);
4848 if (!in_blk) {
4849 goto out;
4850 }
4851
4852 if (sn_opts) {
4853 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4854 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4855 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4856 &local_err);
4857 } else if (snapshot_name != NULL) {
4858 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4859 snapshot_name, &local_err);
4860 }
4861 if (local_err) {
4862 error_reportf_err(local_err, "Failed to load snapshot: ");
4863 goto out;
4864 }
4865 }
4866
4867 drv = bdrv_find_format(out_fmt);
4868 if (!drv) {
4869 error_report("Unknown file format '%s'", out_fmt);
4870 goto out;
4871 }
4872 if (!drv->create_opts) {
4873 error_report("Format driver '%s' does not support image creation",
4874 drv->format_name);
4875 goto out;
4876 }
4877
4878 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4879 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4880 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4881 if (options) {
4882 qemu_opts_do_parse(opts, options, NULL, &local_err);
4883 if (local_err) {
4884 error_report_err(local_err);
4885 error_report("Invalid options for file format '%s'", out_fmt);
4886 goto out;
4887 }
4888 }
4889 if (img_size != UINT64_MAX) {
4890 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4891 }
4892
4893 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4894 if (local_err) {
4895 error_report_err(local_err);
4896 goto out;
4897 }
4898
4899 if (output_format == OFORMAT_HUMAN) {
4900 printf("required size: %" PRIu64 "\n", info->required);
4901 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4902 } else {
4903 dump_json_block_measure_info(info);
4904 }
4905
4906 ret = 0;
4907
4908out:
4909 qapi_free_BlockMeasureInfo(info);
4910 qemu_opts_del(object_opts);
4911 qemu_opts_del(opts);
4912 qemu_opts_del(sn_opts);
4913 qemu_opts_free(create_opts);
4914 g_free(options);
4915 blk_unref(in_blk);
4916 return ret;
4917}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004918
Anthony Liguoric227f092009-10-01 16:12:16 -05004919static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004920#define DEF(option, callback, arg_string) \
4921 { option, callback },
4922#include "qemu-img-cmds.h"
4923#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004924 { NULL, NULL, },
4925};
4926
bellardea2384d2004-08-01 21:59:26 +00004927int main(int argc, char **argv)
4928{
Anthony Liguoric227f092009-10-01 16:12:16 -05004929 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004930 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004931 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004932 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004933 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004934 static const struct option long_options[] = {
4935 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004936 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004937 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004938 {0, 0, 0, 0}
4939 };
bellardea2384d2004-08-01 21:59:26 +00004940
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004941#ifdef CONFIG_POSIX
4942 signal(SIGPIPE, SIG_IGN);
4943#endif
4944
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01004945 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004946 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004947 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004948
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004949 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004950 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004951 exit(EXIT_FAILURE);
4952 }
4953
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004954 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004955
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004956 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004957 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004958 if (argc < 2) {
4959 error_exit("Not enough arguments");
4960 }
Stuart Brady153859b2009-06-07 00:42:17 +01004961
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004962 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004963 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004964 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004965
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004966 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004967 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004968 case ':':
4969 missing_argument(argv[optind - 1]);
4970 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004971 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004972 unrecognized_option(argv[optind - 1]);
4973 return 0;
4974 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004975 help();
4976 return 0;
4977 case 'V':
4978 printf(QEMU_IMG_VERSION);
4979 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004980 case 'T':
4981 g_free(trace_file);
4982 trace_file = trace_opt_parse(optarg);
4983 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004984 }
bellardea2384d2004-08-01 21:59:26 +00004985 }
Stuart Brady153859b2009-06-07 00:42:17 +01004986
Denis V. Lunev10985132016-06-17 17:44:13 +03004987 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004988
Denis V. Lunev10985132016-06-17 17:44:13 +03004989 /* reset getopt_long scanning */
4990 argc -= optind;
4991 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004992 return 0;
4993 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004994 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00004995 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03004996
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004997 if (!trace_init_backends()) {
4998 exit(1);
4999 }
5000 trace_init_file(trace_file);
5001 qemu_set_log(LOG_TRACE);
5002
Denis V. Lunev10985132016-06-17 17:44:13 +03005003 /* find the command */
5004 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5005 if (!strcmp(cmdname, cmd->name)) {
5006 return cmd->handler(argc, argv);
5007 }
5008 }
Jeff Cody7db16892014-04-25 17:02:32 -04005009
Stuart Brady153859b2009-06-07 00:42:17 +01005010 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005011 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005012}