blob: b12f4cd19b0a938dba9f5d8b3bfde5d52ab7bfae [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Fam Zheng67a1de02016-06-01 17:44:21 +080028#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010029#include "qapi/error.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010030#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010031#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010032#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010033#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010034#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020035#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000036#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010037#include "qemu/option.h"
38#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030039#include "qemu/log.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000040#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010041#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020042#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010043#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020044#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080045#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010046#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030047#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000048
Thomas Huth7e563bf2018-02-15 12:06:47 +010049#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020050 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040051
Anthony Liguoric227f092009-10-01 16:12:16 -050052typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010053 const char *name;
54 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050055} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010056
Federico Simoncelli8599ea42013-01-28 06:59:47 -050057enum {
58 OPTION_OUTPUT = 256,
59 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000060 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000061 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020062 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020063 OPTION_FLUSH_INTERVAL = 261,
64 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010065 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010066 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020067 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030068 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050069};
70
71typedef enum OutputFormat {
72 OFORMAT_JSON,
73 OFORMAT_HUMAN,
74} OutputFormat;
75
Kevin Wolfe6996142016-03-15 13:03:11 +010076/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040077#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000078
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010079static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000080{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010081 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000082}
83
Fam Zhengac1307a2014-04-22 13:36:11 +080084static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
85{
86 va_list ap;
87
88 error_printf("qemu-img: ");
89
90 va_start(ap, fmt);
91 error_vprintf(fmt, ap);
92 va_end(ap);
93
94 error_printf("\nTry 'qemu-img --help' for more information\n");
95 exit(EXIT_FAILURE);
96}
97
Stefan Hajnoczic9192972017-03-17 18:45:41 +080098static void QEMU_NORETURN missing_argument(const char *option)
99{
100 error_exit("missing argument for option '%s'", option);
101}
102
103static void QEMU_NORETURN unrecognized_option(const char *option)
104{
105 error_exit("unrecognized option '%s'", option);
106}
107
blueswir1d2c639d2009-01-24 18:19:25 +0000108/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800109static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000110{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100111 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400112 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300113 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300114 "QEMU disk image utility\n"
115 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300120 "\n"
malc3f020d72010-02-08 12:04:56 +0300121 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100122#define DEF(option, callback, arg_string) \
123 " " arg_string "\n"
124#include "qemu-img-cmds.h"
125#undef DEF
malc3f020d72010-02-08 12:04:56 +0300126 "\n"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300139 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300151 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400152 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
153 " new backing file match exactly. The image doesn't need a working\n"
154 " backing file before rebasing in this case (useful for renaming the\n"
155 " backing file). For image creation, allow creating without attempting\n"
156 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300157 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200158 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100159 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200160 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
161 " contain only zeros for qemu-img to create a sparse image during\n"
162 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
163 " unallocated or zero sectors, and the destination image will always be\n"
164 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200165 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100166 " '-n' skips the target volume creation (useful if the volume is created\n"
167 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300168 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200169 "Parameters to check subcommand:\n"
170 " '-r' tries to repair any inconsistencies that are found during the check.\n"
171 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
172 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200173 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200174 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100175 "Parameters to convert subcommand:\n"
176 " '-m' specifies how many coroutines work in parallel during the convert\n"
177 " process (defaults to 8)\n"
178 " '-W' allow to write to the target out of order rather than sequential\n"
179 "\n"
malc3f020d72010-02-08 12:04:56 +0300180 "Parameters to snapshot subcommand:\n"
181 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
182 " '-a' applies a snapshot (revert disk to saved state)\n"
183 " '-c' creates a snapshot\n"
184 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100185 " '-l' lists all snapshots in the given image\n"
186 "\n"
187 "Parameters to compare subcommand:\n"
188 " '-f' first image format\n"
189 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200190 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
191 "\n"
192 "Parameters to dd subcommand:\n"
193 " 'bs=BYTES' read and write up to BYTES bytes at a time "
194 "(default: 512)\n"
195 " 'count=N' copy only N input blocks\n"
196 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200197 " 'of=FILE' write to FILE\n"
198 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100199
200 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100201 bdrv_iterate_format(format_print, NULL);
Eric Blakef5048cb2017-08-03 11:33:53 -0500202 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800203 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000204}
205
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000206static QemuOptsList qemu_object_opts = {
207 .name = "object",
208 .implied_opt_name = "qom-type",
209 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
210 .desc = {
211 { }
212 },
213};
214
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000215static QemuOptsList qemu_source_opts = {
216 .name = "source",
217 .implied_opt_name = "file",
218 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
219 .desc = {
220 { }
221 },
222};
223
Stefan Weil7c30f652013-06-16 17:01:05 +0200224static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100225{
226 int ret = 0;
227 if (!quiet) {
228 va_list args;
229 va_start(args, fmt);
230 ret = vprintf(fmt, args);
231 va_end(args);
232 }
233 return ret;
234}
235
bellardea2384d2004-08-01 21:59:26 +0000236
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100237static int print_block_option_help(const char *filename, const char *fmt)
238{
239 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800240 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500241 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100242
243 /* Find driver and parse its options */
244 drv = bdrv_find_format(fmt);
245 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100246 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100247 return 1;
248 }
249
Max Reitzd402b6a2018-05-09 23:00:21 +0200250 if (!drv->create_opts) {
251 error_report("Format driver '%s' does not support image creation", fmt);
252 return 1;
253 }
254
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800255 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100256 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500257 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100258 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100259 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800260 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100261 return 1;
262 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200263 if (!proto_drv->create_opts) {
264 error_report("Protocal driver '%s' does not support image creation",
265 proto_drv->format_name);
266 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 Reitz7f3fb002018-05-09 23:00:19 +0200271 printf("Supported options:\n");
Chunyan Liu83d05212014-06-05 17:20:51 +0800272 qemu_opts_print_help(create_opts);
273 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100274 return 0;
275}
276
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000277
Max Reitzefaa7c42016-03-16 19:54:38 +0100278static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100279 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800280 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000281{
282 QDict *options;
283 Error *local_err = NULL;
284 BlockBackend *blk;
285 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800286 if (force_share) {
287 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200288 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800289 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200290 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800291 return NULL;
292 }
Max Reitz4615f872018-05-02 22:20:50 +0200293 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800294 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100295 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000296 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100297 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000298 return NULL;
299 }
Kevin Wolfce099542016-03-15 13:01:04 +0100300 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000301
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000302 return blk;
303}
304
Max Reitzefaa7c42016-03-16 19:54:38 +0100305static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100306 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000307 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800308 bool writethrough, bool quiet,
309 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000310{
311 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200312 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100313
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100314 if (!options) {
315 options = qdict_new();
316 }
bellard75c23802004-08-27 21:28:58 +0000317 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500318 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000319 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100320
Fam Zheng335e9932017-05-03 00:35:39 +0800321 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500322 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800323 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100324 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500325 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100326 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000327 return NULL;
bellard75c23802004-08-27 21:28:58 +0000328 }
Kevin Wolfce099542016-03-15 13:01:04 +0100329 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100330
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200331 return blk;
bellard75c23802004-08-27 21:28:58 +0000332}
333
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000334
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100335static int img_add_key_secrets(void *opaque,
336 const char *name, const char *value,
337 Error **errp)
338{
339 QDict *options = opaque;
340
341 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600342 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100343 }
344
345 return 0;
346}
347
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100348
Max Reitzefaa7c42016-03-16 19:54:38 +0100349static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000350 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100351 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800352 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000353{
354 BlockBackend *blk;
355 if (image_opts) {
356 QemuOpts *opts;
357 if (fmt) {
358 error_report("--image-opts and --format are mutually exclusive");
359 return NULL;
360 }
361 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
362 filename, true);
363 if (!opts) {
364 return NULL;
365 }
Fam Zheng335e9932017-05-03 00:35:39 +0800366 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
367 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000368 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100369 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800370 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000371 }
372 return blk;
373}
374
375
Chunyan Liu83d05212014-06-05 17:20:51 +0800376static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100377 const char *base_filename,
378 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200379{
Markus Armbruster6750e792015-02-12 17:43:08 +0100380 Error *err = NULL;
381
Kevin Wolfefa84d42009-05-18 16:42:12 +0200382 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100383 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100384 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100385 error_report("Backing file not supported for file format '%s'",
386 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100387 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900388 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200389 }
390 }
391 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100392 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100393 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100394 error_report("Backing file format not supported for file "
395 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100396 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900397 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200398 }
399 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900400 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200401}
402
Markus Armbruster606caa02017-02-21 21:14:04 +0100403static int64_t cvtnum(const char *s)
404{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100405 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100406 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100407
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100408 err = qemu_strtosz(s, NULL, &value);
409 if (err < 0) {
410 return err;
411 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100412 if (value > INT64_MAX) {
413 return -ERANGE;
414 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100415 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100416}
417
bellardea2384d2004-08-01 21:59:26 +0000418static int img_create(int argc, char **argv)
419{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200420 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100421 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000422 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000423 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000424 const char *filename;
425 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200426 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200427 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100428 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400429 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000430
bellardea2384d2004-08-01 21:59:26 +0000431 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000432 static const struct option long_options[] = {
433 {"help", no_argument, 0, 'h'},
434 {"object", required_argument, 0, OPTION_OBJECT},
435 {0, 0, 0, 0}
436 };
John Snow6e6e55f2017-07-17 20:34:22 -0400437 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000438 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100439 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000440 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100441 }
bellardea2384d2004-08-01 21:59:26 +0000442 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800443 case ':':
444 missing_argument(argv[optind - 1]);
445 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100446 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800447 unrecognized_option(argv[optind - 1]);
448 break;
bellardea2384d2004-08-01 21:59:26 +0000449 case 'h':
450 help();
451 break;
aliguori9230eaf2009-03-28 17:55:19 +0000452 case 'F':
453 base_fmt = optarg;
454 break;
bellardea2384d2004-08-01 21:59:26 +0000455 case 'b':
456 base_filename = optarg;
457 break;
458 case 'f':
459 fmt = optarg;
460 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200461 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100462 if (!is_valid_option_list(optarg)) {
463 error_report("Invalid option list: %s", optarg);
464 goto fail;
465 }
466 if (!options) {
467 options = g_strdup(optarg);
468 } else {
469 char *old_options = options;
470 options = g_strdup_printf("%s,%s", options, optarg);
471 g_free(old_options);
472 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200473 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100474 case 'q':
475 quiet = true;
476 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400477 case 'u':
478 flags |= BDRV_O_NO_BACKING;
479 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000480 case OPTION_OBJECT: {
481 QemuOpts *opts;
482 opts = qemu_opts_parse_noisily(&qemu_object_opts,
483 optarg, true);
484 if (!opts) {
485 goto fail;
486 }
487 } break;
bellardea2384d2004-08-01 21:59:26 +0000488 }
489 }
aliguori9230eaf2009-03-28 17:55:19 +0000490
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900491 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100492 filename = (optind < argc) ? argv[optind] : NULL;
493 if (options && has_help_option(options)) {
494 g_free(options);
495 return print_block_option_help(filename, fmt);
496 }
497
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100498 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800499 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100500 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100501 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900502
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000503 if (qemu_opts_foreach(&qemu_object_opts,
504 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200505 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000506 goto fail;
507 }
508
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100509 /* Get image size, if specified */
510 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100511 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100512
513 sval = cvtnum(argv[optind++]);
514 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800515 if (sval == -ERANGE) {
516 error_report("Image size must be less than 8 EiB!");
517 } else {
518 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200519 "G, T, P or E suffixes for ");
520 error_report("kilobytes, megabytes, gigabytes, terabytes, "
521 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800522 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100523 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100524 }
525 img_size = (uint64_t)sval;
526 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200527 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800528 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200529 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100530
Luiz Capitulino9b375252012-11-30 10:52:05 -0200531 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400532 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100533 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100534 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100535 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900536 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200537
Kevin Wolf77386bf2014-02-21 16:24:04 +0100538 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000539 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100540
541fail:
542 g_free(options);
543 return 1;
bellardea2384d2004-08-01 21:59:26 +0000544}
545
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100546static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500547{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500548 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500549 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100550 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600551
552 visit_type_ImageCheck(v, NULL, &check, &error_abort);
553 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500554 str = qobject_to_json_pretty(obj);
555 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100556 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200557 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600558 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200559 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560}
561
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100562static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500563{
564 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100565 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500566 } else {
567 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100568 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
569 "Data may be corrupted, or further writes to the image "
570 "may corrupt it.\n",
571 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500572 }
573
574 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100575 qprintf(quiet,
576 "\n%" PRId64 " leaked clusters were found on the image.\n"
577 "This means waste of disk space, but no harm to data.\n",
578 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500579 }
580
581 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100582 qprintf(quiet,
583 "\n%" PRId64
584 " internal errors have occurred during the check.\n",
585 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500586 }
587 }
588
589 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100590 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
591 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
592 check->allocated_clusters, check->total_clusters,
593 check->allocated_clusters * 100.0 / check->total_clusters,
594 check->fragmented_clusters * 100.0 / check->allocated_clusters,
595 check->compressed_clusters * 100.0 /
596 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500597 }
598
599 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100600 qprintf(quiet,
601 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500602 }
603}
604
605static int collect_image_check(BlockDriverState *bs,
606 ImageCheck *check,
607 const char *filename,
608 const char *fmt,
609 int fix)
610{
611 int ret;
612 BdrvCheckResult result;
613
614 ret = bdrv_check(bs, &result, fix);
615 if (ret < 0) {
616 return ret;
617 }
618
619 check->filename = g_strdup(filename);
620 check->format = g_strdup(bdrv_get_format_name(bs));
621 check->check_errors = result.check_errors;
622 check->corruptions = result.corruptions;
623 check->has_corruptions = result.corruptions != 0;
624 check->leaks = result.leaks;
625 check->has_leaks = result.leaks != 0;
626 check->corruptions_fixed = result.corruptions_fixed;
627 check->has_corruptions_fixed = result.corruptions != 0;
628 check->leaks_fixed = result.leaks_fixed;
629 check->has_leaks_fixed = result.leaks != 0;
630 check->image_end_offset = result.image_end_offset;
631 check->has_image_end_offset = result.image_end_offset != 0;
632 check->total_clusters = result.bfi.total_clusters;
633 check->has_total_clusters = result.bfi.total_clusters != 0;
634 check->allocated_clusters = result.bfi.allocated_clusters;
635 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
636 check->fragmented_clusters = result.bfi.fragmented_clusters;
637 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100638 check->compressed_clusters = result.bfi.compressed_clusters;
639 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500640
641 return 0;
642}
643
Kevin Wolfe076f332010-06-29 11:43:13 +0200644/*
645 * Checks an image for consistency. Exit codes:
646 *
Max Reitzd6635c42014-06-02 22:15:21 +0200647 * 0 - Check completed, image is good
648 * 1 - Check not completed because of internal errors
649 * 2 - Check completed, image is corrupted
650 * 3 - Check completed, image has leaked clusters, but is good otherwise
651 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200652 */
aliguori15859692009-04-21 23:11:53 +0000653static int img_check(int argc, char **argv)
654{
655 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500656 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200657 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200658 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000659 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200660 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100661 int flags = BDRV_O_CHECK;
662 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200663 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100664 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000665 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800666 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000667
668 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500669 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200670 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100671
aliguori15859692009-04-21 23:11:53 +0000672 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500673 int option_index = 0;
674 static const struct option long_options[] = {
675 {"help", no_argument, 0, 'h'},
676 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530677 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500678 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000679 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000680 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800681 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500682 {0, 0, 0, 0}
683 };
Fam Zheng335e9932017-05-03 00:35:39 +0800684 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500685 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100686 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000687 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100688 }
aliguori15859692009-04-21 23:11:53 +0000689 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800690 case ':':
691 missing_argument(argv[optind - 1]);
692 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100693 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800694 unrecognized_option(argv[optind - 1]);
695 break;
aliguori15859692009-04-21 23:11:53 +0000696 case 'h':
697 help();
698 break;
699 case 'f':
700 fmt = optarg;
701 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200702 case 'r':
703 flags |= BDRV_O_RDWR;
704
705 if (!strcmp(optarg, "leaks")) {
706 fix = BDRV_FIX_LEAKS;
707 } else if (!strcmp(optarg, "all")) {
708 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
709 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800710 error_exit("Unknown option value for -r "
711 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200712 }
713 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500714 case OPTION_OUTPUT:
715 output = optarg;
716 break;
Max Reitz40055952014-07-22 22:58:42 +0200717 case 'T':
718 cache = optarg;
719 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100720 case 'q':
721 quiet = true;
722 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800723 case 'U':
724 force_share = true;
725 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000726 case OPTION_OBJECT: {
727 QemuOpts *opts;
728 opts = qemu_opts_parse_noisily(&qemu_object_opts,
729 optarg, true);
730 if (!opts) {
731 return 1;
732 }
733 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000734 case OPTION_IMAGE_OPTS:
735 image_opts = true;
736 break;
aliguori15859692009-04-21 23:11:53 +0000737 }
738 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200739 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800740 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100741 }
aliguori15859692009-04-21 23:11:53 +0000742 filename = argv[optind++];
743
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500744 if (output && !strcmp(output, "json")) {
745 output_format = OFORMAT_JSON;
746 } else if (output && !strcmp(output, "human")) {
747 output_format = OFORMAT_HUMAN;
748 } else if (output) {
749 error_report("--output must be used with human or json as argument.");
750 return 1;
751 }
752
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000753 if (qemu_opts_foreach(&qemu_object_opts,
754 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200755 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000756 return 1;
757 }
758
Kevin Wolfce099542016-03-15 13:01:04 +0100759 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200760 if (ret < 0) {
761 error_report("Invalid source cache option: %s", cache);
762 return 1;
763 }
764
Fam Zheng335e9932017-05-03 00:35:39 +0800765 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
766 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200767 if (!blk) {
768 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900769 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200770 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500771
772 check = g_new0(ImageCheck, 1);
773 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200774
775 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200776 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200777 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500778 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200779 }
780
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500781 if (check->corruptions_fixed || check->leaks_fixed) {
782 int corruptions_fixed, leaks_fixed;
783
784 leaks_fixed = check->leaks_fixed;
785 corruptions_fixed = check->corruptions_fixed;
786
787 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100788 qprintf(quiet,
789 "The following inconsistencies were found and repaired:\n\n"
790 " %" PRId64 " leaked clusters\n"
791 " %" PRId64 " corruptions\n\n"
792 "Double checking the fixed image now...\n",
793 check->leaks_fixed,
794 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500795 }
796
797 ret = collect_image_check(bs, check, filename, fmt, 0);
798
799 check->leaks_fixed = leaks_fixed;
800 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200801 }
802
Max Reitz832390a2014-10-23 15:29:12 +0200803 if (!ret) {
804 switch (output_format) {
805 case OFORMAT_HUMAN:
806 dump_human_image_check(check, quiet);
807 break;
808 case OFORMAT_JSON:
809 dump_json_image_check(check, quiet);
810 break;
811 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500812 }
813
814 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200815 if (ret) {
816 error_report("Check failed: %s", strerror(-ret));
817 } else {
818 error_report("Check failed");
819 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500820 ret = 1;
821 goto fail;
822 }
823
824 if (check->corruptions) {
825 ret = 2;
826 } else if (check->leaks) {
827 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200828 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500829 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000830 }
831
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500832fail:
833 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200834 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500835 return ret;
aliguori15859692009-04-21 23:11:53 +0000836}
837
Max Reitzd4a32382014-10-24 15:57:37 +0200838typedef struct CommonBlockJobCBInfo {
839 BlockDriverState *bs;
840 Error **errp;
841} CommonBlockJobCBInfo;
842
843static void common_block_job_cb(void *opaque, int ret)
844{
845 CommonBlockJobCBInfo *cbi = opaque;
846
847 if (ret < 0) {
848 error_setg_errno(cbi->errp, -ret, "Block job failed");
849 }
Max Reitzd4a32382014-10-24 15:57:37 +0200850}
851
852static void run_block_job(BlockJob *job, Error **errp)
853{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200854 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800855 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200856
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200857 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200858 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200859 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200860 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200861 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200862 if (job->job.progress_total) {
863 progress = (float)job->job.progress_current /
864 job->job.progress_total * 100.f;
865 }
866 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200867 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200868
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200869 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200870 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800871 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200872 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800873 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200874 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200875 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200876
sochin.jiang4172a002017-06-15 14:47:33 +0800877 /* publish completion progress only when success */
878 if (!ret) {
879 qemu_progress_print(100.f, 0);
880 }
Max Reitzd4a32382014-10-24 15:57:37 +0200881}
882
bellardea2384d2004-08-01 21:59:26 +0000883static int img_commit(int argc, char **argv)
884{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400885 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200886 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200887 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200888 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100889 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200890 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100891 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200892 Error *local_err = NULL;
893 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000894 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200895 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000896
897 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400898 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200899 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000900 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000901 static const struct option long_options[] = {
902 {"help", no_argument, 0, 'h'},
903 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000904 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000905 {0, 0, 0, 0}
906 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800907 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000908 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100909 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000910 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100911 }
bellardea2384d2004-08-01 21:59:26 +0000912 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800913 case ':':
914 missing_argument(argv[optind - 1]);
915 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100916 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800917 unrecognized_option(argv[optind - 1]);
918 break;
bellardea2384d2004-08-01 21:59:26 +0000919 case 'h':
920 help();
921 break;
922 case 'f':
923 fmt = optarg;
924 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400925 case 't':
926 cache = optarg;
927 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200928 case 'b':
929 base = optarg;
930 /* -b implies -d */
931 drop = true;
932 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200933 case 'd':
934 drop = true;
935 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200936 case 'p':
937 progress = true;
938 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100939 case 'q':
940 quiet = true;
941 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000942 case OPTION_OBJECT: {
943 QemuOpts *opts;
944 opts = qemu_opts_parse_noisily(&qemu_object_opts,
945 optarg, true);
946 if (!opts) {
947 return 1;
948 }
949 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000950 case OPTION_IMAGE_OPTS:
951 image_opts = true;
952 break;
bellardea2384d2004-08-01 21:59:26 +0000953 }
954 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200955
956 /* Progress is not shown in Quiet mode */
957 if (quiet) {
958 progress = false;
959 }
960
Kevin Wolffc11eb22013-08-05 10:53:04 +0200961 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800962 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100963 }
bellardea2384d2004-08-01 21:59:26 +0000964 filename = argv[optind++];
965
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000966 if (qemu_opts_foreach(&qemu_object_opts,
967 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200968 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000969 return 1;
970 }
971
Max Reitz9a86fe42014-10-24 15:57:38 +0200972 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100973 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400974 if (ret < 0) {
975 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100976 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400977 }
978
Fam Zheng335e9932017-05-03 00:35:39 +0800979 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
980 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200981 if (!blk) {
982 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900983 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200984 bs = blk_bs(blk);
985
Max Reitz687fa1d2014-10-24 15:57:39 +0200986 qemu_progress_init(progress, 1.f);
987 qemu_progress_print(0.f, 100);
988
Max Reitz1b22bff2014-10-24 15:57:40 +0200989 if (base) {
990 base_bs = bdrv_find_backing_image(bs, base);
991 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100992 error_setg(&local_err,
993 "Did not find '%s' in the backing chain of '%s'",
994 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200995 goto done;
996 }
997 } else {
998 /* This is different from QMP, which by default uses the deepest file in
999 * the backing chain (i.e., the very base); however, the traditional
1000 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001001 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001002 if (!base_bs) {
1003 error_setg(&local_err, "Image does not have a backing file");
1004 goto done;
1005 }
bellardea2384d2004-08-01 21:59:26 +00001006 }
1007
Max Reitzd4a32382014-10-24 15:57:37 +02001008 cbi = (CommonBlockJobCBInfo){
1009 .errp = &local_err,
1010 .bs = bs,
1011 };
1012
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001013 aio_context = bdrv_get_aio_context(bs);
1014 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001015 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001016 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001017 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001018 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001019 if (local_err) {
1020 goto done;
1021 }
1022
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001023 /* When the block job completes, the BlockBackend reference will point to
1024 * the old backing file. In order to avoid that the top image is already
1025 * deleted, so we can still empty it afterwards, increment the reference
1026 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001027 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001028 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001029 }
1030
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001031 job = block_job_get("commit");
1032 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001033 if (local_err) {
1034 goto unref_backing;
1035 }
1036
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001037 if (!drop && bs->drv->bdrv_make_empty) {
1038 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001039 if (ret) {
1040 error_setg_errno(&local_err, -ret, "Could not empty %s",
1041 filename);
1042 goto unref_backing;
1043 }
1044 }
1045
1046unref_backing:
1047 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001048 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001049 }
Max Reitzd4a32382014-10-24 15:57:37 +02001050
1051done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001052 qemu_progress_end();
1053
Markus Armbruster26f54e92014-10-07 13:59:04 +02001054 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001055
1056 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001057 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001058 return 1;
1059 }
Max Reitzd4a32382014-10-24 15:57:37 +02001060
1061 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001062 return 0;
1063}
1064
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001065/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001066 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1067 * of the first sector boundary within buf where the sector contains a
1068 * non-zero byte. This function is robust to a buffer that is not
1069 * sector-aligned.
1070 */
1071static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1072{
1073 int64_t i;
1074 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1075
1076 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1077 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1078 return i;
1079 }
1080 }
1081 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1082 return i;
1083 }
1084 return -1;
1085}
1086
1087/*
thsf58c7b32008-06-05 21:53:49 +00001088 * Returns true iff the first sector pointed to by 'buf' contains at least
1089 * a non-NUL byte.
1090 *
1091 * 'pnum' is set to the number of sectors (including and immediately following
1092 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001093 * The function will try to align the end offset to alignment boundaries so
1094 * that the request will at least end aligned and consequtive requests will
1095 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001096 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001097static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1098 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001099{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001100 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001101 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001102
1103 if (n <= 0) {
1104 *pnum = 0;
1105 return 0;
1106 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001107 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001108 for(i = 1; i < n; i++) {
1109 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001110 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001111 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001112 }
bellardea2384d2004-08-01 21:59:26 +00001113 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001114
1115 tail = (sector_num + i) & (alignment - 1);
1116 if (tail) {
1117 if (is_zero && i <= tail) {
1118 /* treat unallocated areas which only consist
1119 * of a small tail as allocated. */
1120 is_zero = false;
1121 }
1122 if (!is_zero) {
1123 /* align up end offset of allocated areas. */
1124 i += alignment - tail;
1125 i = MIN(i, n);
1126 } else {
1127 /* align down end offset of zero areas. */
1128 i -= tail;
1129 }
1130 }
bellardea2384d2004-08-01 21:59:26 +00001131 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001132 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001133}
1134
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001135/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001136 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1137 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1138 * breaking up write requests for only small sparse areas.
1139 */
1140static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001141 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001142{
1143 int ret;
1144 int num_checked, num_used;
1145
1146 if (n < min) {
1147 min = n;
1148 }
1149
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001150 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001151 if (!ret) {
1152 return ret;
1153 }
1154
1155 num_used = *pnum;
1156 buf += BDRV_SECTOR_SIZE * *pnum;
1157 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001158 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001159 num_checked = num_used;
1160
1161 while (n > 0) {
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
1164 buf += BDRV_SECTOR_SIZE * *pnum;
1165 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001166 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001167 num_checked += *pnum;
1168 if (ret) {
1169 num_used = num_checked;
1170 } else if (*pnum >= min) {
1171 break;
1172 }
1173 }
1174
1175 *pnum = num_used;
1176 return 1;
1177}
1178
1179/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001180 * Compares two buffers sector by sector. Returns 0 if the first
1181 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001182 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001183 * pnum is set to the sector-aligned size of the buffer prefix that
1184 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001185 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001186static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1187 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001188{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001189 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001190 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001191
Eric Blakedc61cd32017-10-11 22:47:14 -05001192 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001193
Eric Blakedc61cd32017-10-11 22:47:14 -05001194 res = !!memcmp(buf1, buf2, i);
1195 while (i < bytes) {
1196 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001197
Eric Blakedc61cd32017-10-11 22:47:14 -05001198 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001199 break;
1200 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001201 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001202 }
1203
1204 *pnum = i;
1205 return res;
1206}
1207
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001208#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001209
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001210/*
1211 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1212 *
Eric Blake0608e402017-10-11 22:47:12 -05001213 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1214 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1215 * failure), and 4 on error (the exit status for read errors), after emitting
1216 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001217 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001218 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001219 * @param offset: Starting offset to check
1220 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001221 * @param filename: Name of disk file we are checking (logging purpose)
1222 * @param buffer: Allocated buffer for storing read data
1223 * @param quiet: Flag for quiet mode
1224 */
Eric Blakec41508e2017-10-11 22:47:13 -05001225static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1226 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001227 uint8_t *buffer, bool quiet)
1228{
Eric Blakedebb38a2017-10-11 22:47:11 -05001229 int ret = 0;
1230 int64_t idx;
1231
Eric Blakec41508e2017-10-11 22:47:13 -05001232 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001233 if (ret < 0) {
1234 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001235 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001236 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001237 }
Eric Blakec41508e2017-10-11 22:47:13 -05001238 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001239 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001240 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001241 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001242 return 1;
1243 }
1244
1245 return 0;
1246}
1247
1248/*
1249 * Compares two images. Exit codes:
1250 *
1251 * 0 - Images are identical
1252 * 1 - Images differ
1253 * >1 - Error occurred
1254 */
1255static int img_compare(int argc, char **argv)
1256{
Max Reitz40055952014-07-22 22:58:42 +02001257 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001258 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001259 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001260 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001261 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001262 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001263 int allocated1, allocated2;
1264 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1265 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001266 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001267 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001268 int64_t total_size;
1269 int64_t offset = 0;
1270 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001271 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001272 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001273 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001274 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001275
Max Reitz40055952014-07-22 22:58:42 +02001276 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001277 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001278 static const struct option long_options[] = {
1279 {"help", no_argument, 0, 'h'},
1280 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001281 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001282 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001283 {0, 0, 0, 0}
1284 };
Fam Zheng335e9932017-05-03 00:35:39 +08001285 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001286 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287 if (c == -1) {
1288 break;
1289 }
1290 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001291 case ':':
1292 missing_argument(argv[optind - 1]);
1293 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001294 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001295 unrecognized_option(argv[optind - 1]);
1296 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001297 case 'h':
1298 help();
1299 break;
1300 case 'f':
1301 fmt1 = optarg;
1302 break;
1303 case 'F':
1304 fmt2 = optarg;
1305 break;
Max Reitz40055952014-07-22 22:58:42 +02001306 case 'T':
1307 cache = optarg;
1308 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001309 case 'p':
1310 progress = true;
1311 break;
1312 case 'q':
1313 quiet = true;
1314 break;
1315 case 's':
1316 strict = true;
1317 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001318 case 'U':
1319 force_share = true;
1320 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001321 case OPTION_OBJECT: {
1322 QemuOpts *opts;
1323 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1324 optarg, true);
1325 if (!opts) {
1326 ret = 2;
1327 goto out4;
1328 }
1329 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001330 case OPTION_IMAGE_OPTS:
1331 image_opts = true;
1332 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001333 }
1334 }
1335
1336 /* Progress is not shown in Quiet mode */
1337 if (quiet) {
1338 progress = false;
1339 }
1340
1341
Kevin Wolffc11eb22013-08-05 10:53:04 +02001342 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001343 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001344 }
1345 filename1 = argv[optind++];
1346 filename2 = argv[optind++];
1347
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001348 if (qemu_opts_foreach(&qemu_object_opts,
1349 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001350 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001351 ret = 2;
1352 goto out4;
1353 }
1354
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001355 /* Initialize before goto out */
1356 qemu_progress_init(progress, 2.0);
1357
Kevin Wolfce099542016-03-15 13:01:04 +01001358 flags = 0;
1359 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001360 if (ret < 0) {
1361 error_report("Invalid source cache option: %s", cache);
1362 ret = 2;
1363 goto out3;
1364 }
1365
Fam Zheng335e9932017-05-03 00:35:39 +08001366 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1367 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001368 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001369 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001370 goto out3;
1371 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001372
Fam Zheng335e9932017-05-03 00:35:39 +08001373 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1374 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001375 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001376 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001377 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001378 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001379 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001380 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001381
Max Reitzf1d3cd72015-02-05 13:58:18 -05001382 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1383 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001384 total_size1 = blk_getlength(blk1);
1385 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001386 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001387 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001388 ret = 4;
1389 goto out;
1390 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001391 total_size2 = blk_getlength(blk2);
1392 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001393 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001394 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001395 ret = 4;
1396 goto out;
1397 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001398 total_size = MIN(total_size1, total_size2);
1399 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001400
1401 qemu_progress_print(0, 100);
1402
Eric Blake033d9fc2017-10-11 22:47:16 -05001403 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001404 ret = 1;
1405 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1406 goto out;
1407 }
1408
Eric Blake033d9fc2017-10-11 22:47:16 -05001409 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001410 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001411
Eric Blake033d9fc2017-10-11 22:47:16 -05001412 status1 = bdrv_block_status_above(bs1, NULL, offset,
1413 total_size1 - offset, &pnum1, NULL,
1414 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001415 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001416 ret = 3;
1417 error_report("Sector allocation test failed for %s", filename1);
1418 goto out;
1419 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001420 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001421
Eric Blake033d9fc2017-10-11 22:47:16 -05001422 status2 = bdrv_block_status_above(bs2, NULL, offset,
1423 total_size2 - offset, &pnum2, NULL,
1424 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001425 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001426 ret = 3;
1427 error_report("Sector allocation test failed for %s", filename2);
1428 goto out;
1429 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001430 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001431
1432 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001433 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001434
Fam Zheng25ad8e62016-01-13 16:37:41 +08001435 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001436 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001437 ret = 1;
1438 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001439 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001440 goto out;
1441 }
1442 }
1443 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001444 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001445 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001446 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001447 int64_t pnum;
1448
Eric Blake033d9fc2017-10-11 22:47:16 -05001449 chunk = MIN(chunk, IO_BUF_SIZE);
1450 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001451 if (ret < 0) {
1452 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001453 " of %s: %s",
1454 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001455 ret = 4;
1456 goto out;
1457 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001458 ret = blk_pread(blk2, offset, buf2, chunk);
1459 if (ret < 0) {
1460 error_report("Error while reading offset %" PRId64
1461 " of %s: %s",
1462 offset, filename2, strerror(-ret));
1463 ret = 4;
1464 goto out;
1465 }
1466 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1467 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001468 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001469 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001470 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001471 goto out;
1472 }
1473 }
1474 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001475 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001476 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001477 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001478 filename1, buf1, quiet);
1479 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001480 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001481 filename2, buf1, quiet);
1482 }
1483 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001484 goto out;
1485 }
1486 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001487 offset += chunk;
1488 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001489 }
1490
Eric Blake033d9fc2017-10-11 22:47:16 -05001491 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001492 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001493 const char *filename_over;
1494
1495 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001496 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001497 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001498 filename_over = filename1;
1499 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001500 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001501 filename_over = filename2;
1502 }
1503
Eric Blake033d9fc2017-10-11 22:47:16 -05001504 while (offset < progress_base) {
1505 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1506 progress_base - offset, &chunk,
1507 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001508 if (ret < 0) {
1509 ret = 3;
1510 error_report("Sector allocation test failed for %s",
1511 filename_over);
1512 goto out;
1513
1514 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001515 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001516 chunk = MIN(chunk, IO_BUF_SIZE);
1517 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001518 filename_over, buf1, quiet);
1519 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001520 goto out;
1521 }
1522 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001523 offset += chunk;
1524 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001525 }
1526 }
1527
1528 qprintf(quiet, "Images are identical.\n");
1529 ret = 0;
1530
1531out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 qemu_vfree(buf1);
1533 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001534 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001535out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001536 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001537out3:
1538 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001539out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001540 return ret;
1541}
1542
Kevin Wolf690c7302015-03-19 13:33:32 +01001543enum ImgConvertBlockStatus {
1544 BLK_DATA,
1545 BLK_ZERO,
1546 BLK_BACKING_FILE,
1547};
1548
Peter Lieven2d9187b2017-02-28 13:40:07 +01001549#define MAX_COROUTINES 16
1550
Kevin Wolf690c7302015-03-19 13:33:32 +01001551typedef struct ImgConvertState {
1552 BlockBackend **src;
1553 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001554 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001555 int64_t total_sectors;
1556 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001557 int64_t allocated_done;
1558 int64_t sector_num;
1559 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001560 enum ImgConvertBlockStatus status;
1561 int64_t sector_next_status;
1562 BlockBackend *target;
1563 bool has_zero_init;
1564 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001565 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001566 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001567 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001568 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001569 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001570 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001571 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001572 size_t cluster_sectors;
1573 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001574 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001575 int running_coroutines;
1576 Coroutine *co[MAX_COROUTINES];
1577 int64_t wait_sector_num[MAX_COROUTINES];
1578 CoMutex lock;
1579 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001580} ImgConvertState;
1581
Peter Lieven2d9187b2017-02-28 13:40:07 +01001582static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1583 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001584{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001585 *src_cur = 0;
1586 *src_cur_offset = 0;
1587 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1588 *src_cur_offset += s->src_sectors[*src_cur];
1589 (*src_cur)++;
1590 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001591 }
1592}
1593
1594static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1595{
Eric Blake31826642017-10-11 22:47:08 -05001596 int64_t src_cur_offset;
1597 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001598 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001599
Peter Lieven2d9187b2017-02-28 13:40:07 +01001600 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001601
1602 assert(s->total_sectors > sector_num);
1603 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1604
Max Reitz351c8ef2018-05-01 18:57:49 +02001605 if (s->target_backing_sectors >= 0) {
1606 if (sector_num >= s->target_backing_sectors) {
1607 post_backing_zero = s->unallocated_blocks_are_zero;
1608 } else if (sector_num + n > s->target_backing_sectors) {
1609 /* Split requests around target_backing_sectors (because
1610 * starting from there, zeros are handled differently) */
1611 n = s->target_backing_sectors - sector_num;
1612 }
1613 }
1614
Kevin Wolf690c7302015-03-19 13:33:32 +01001615 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001616 int64_t count = n * BDRV_SECTOR_SIZE;
1617
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001618 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001619
1620 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1621 (sector_num - src_cur_offset) *
1622 BDRV_SECTOR_SIZE,
1623 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001624 } else {
Eric Blake31826642017-10-11 22:47:08 -05001625 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1626 (sector_num - src_cur_offset) *
1627 BDRV_SECTOR_SIZE,
1628 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001629 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001630 if (ret < 0) {
1631 return ret;
1632 }
Eric Blake31826642017-10-11 22:47:08 -05001633 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001634
1635 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001636 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001637 } else if (ret & BDRV_BLOCK_DATA) {
1638 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001639 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001640 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001641 }
1642
1643 s->sector_next_status = sector_num + n;
1644 }
1645
1646 n = MIN(n, s->sector_next_status - sector_num);
1647 if (s->status == BLK_DATA) {
1648 n = MIN(n, s->buf_sectors);
1649 }
1650
1651 /* We need to write complete clusters for compressed images, so if an
1652 * unallocated area is shorter than that, we must consider the whole
1653 * cluster allocated. */
1654 if (s->compressed) {
1655 if (n < s->cluster_sectors) {
1656 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1657 s->status = BLK_DATA;
1658 } else {
1659 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1660 }
1661 }
1662
1663 return n;
1664}
1665
Peter Lieven2d9187b2017-02-28 13:40:07 +01001666static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1667 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001668{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001669 int n, ret;
1670 QEMUIOVector qiov;
1671 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001672
Kevin Wolf690c7302015-03-19 13:33:32 +01001673 assert(nb_sectors <= s->buf_sectors);
1674 while (nb_sectors > 0) {
1675 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001676 int src_cur;
1677 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001678
1679 /* In the case of compression with multiple source files, we can get a
1680 * nb_sectors that spreads into the next part. So we must be able to
1681 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001682 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1683 blk = s->src[src_cur];
1684 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001685
Peter Lieven2d9187b2017-02-28 13:40:07 +01001686 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1687 iov.iov_base = buf;
1688 iov.iov_len = n << BDRV_SECTOR_BITS;
1689 qemu_iovec_init_external(&qiov, &iov, 1);
1690
1691 ret = blk_co_preadv(
1692 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1693 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001694 if (ret < 0) {
1695 return ret;
1696 }
1697
1698 sector_num += n;
1699 nb_sectors -= n;
1700 buf += n * BDRV_SECTOR_SIZE;
1701 }
1702
1703 return 0;
1704}
1705
Peter Lieven2d9187b2017-02-28 13:40:07 +01001706
1707static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1708 int nb_sectors, uint8_t *buf,
1709 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001710{
1711 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001712 QEMUIOVector qiov;
1713 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001714
1715 while (nb_sectors > 0) {
1716 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001717 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1718
Peter Lieven2d9187b2017-02-28 13:40:07 +01001719 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001720 case BLK_BACKING_FILE:
1721 /* If we have a backing file, leave clusters unallocated that are
1722 * unallocated in the source image, so that the backing file is
1723 * visible at the respective offset. */
1724 assert(s->target_has_backing);
1725 break;
1726
1727 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001728 /* If we're told to keep the target fully allocated (-S 0) or there
1729 * is real non-zero data, we must write it. Otherwise we can treat
1730 * it as zero sectors.
1731 * Compressed clusters need to be written as a whole, so in that
1732 * case we can only save the write if the buffer is completely
1733 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001734 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001735 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001736 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1737 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001738 (s->compressed &&
1739 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001740 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001741 iov.iov_base = buf;
1742 iov.iov_len = n << BDRV_SECTOR_BITS;
1743 qemu_iovec_init_external(&qiov, &iov, 1);
1744
1745 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001746 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001747 if (ret < 0) {
1748 return ret;
1749 }
1750 break;
1751 }
1752 /* fall-through */
1753
1754 case BLK_ZERO:
1755 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001756 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001757 break;
1758 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001759 ret = blk_co_pwrite_zeroes(s->target,
1760 sector_num << BDRV_SECTOR_BITS,
1761 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001762 if (ret < 0) {
1763 return ret;
1764 }
1765 break;
1766 }
1767
1768 sector_num += n;
1769 nb_sectors -= n;
1770 buf += n * BDRV_SECTOR_SIZE;
1771 }
1772
1773 return 0;
1774}
1775
Fam Zhengee5306d2018-06-01 17:26:48 +08001776static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1777 int nb_sectors)
1778{
1779 int n, ret;
1780
1781 while (nb_sectors > 0) {
1782 BlockBackend *blk;
1783 int src_cur;
1784 int64_t bs_sectors, src_cur_offset;
1785 int64_t offset;
1786
1787 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1788 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1789 blk = s->src[src_cur];
1790 bs_sectors = s->src_sectors[src_cur];
1791
1792 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1793
1794 ret = blk_co_copy_range(blk, offset, s->target,
1795 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001796 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001797 if (ret < 0) {
1798 return ret;
1799 }
1800
1801 sector_num += n;
1802 nb_sectors -= n;
1803 }
1804 return 0;
1805}
1806
Peter Lieven2d9187b2017-02-28 13:40:07 +01001807static void coroutine_fn convert_co_do_copy(void *opaque)
1808{
1809 ImgConvertState *s = opaque;
1810 uint8_t *buf = NULL;
1811 int ret, i;
1812 int index = -1;
1813
1814 for (i = 0; i < s->num_coroutines; i++) {
1815 if (s->co[i] == qemu_coroutine_self()) {
1816 index = i;
1817 break;
1818 }
1819 }
1820 assert(index >= 0);
1821
1822 s->running_coroutines++;
1823 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1824
1825 while (1) {
1826 int n;
1827 int64_t sector_num;
1828 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001829 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001830
1831 qemu_co_mutex_lock(&s->lock);
1832 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1833 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001834 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001835 }
1836 n = convert_iteration_sectors(s, s->sector_num);
1837 if (n < 0) {
1838 qemu_co_mutex_unlock(&s->lock);
1839 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001840 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001841 }
1842 /* save current sector and allocation status to local variables */
1843 sector_num = s->sector_num;
1844 status = s->status;
1845 if (!s->min_sparse && s->status == BLK_ZERO) {
1846 n = MIN(n, s->buf_sectors);
1847 }
1848 /* increment global sector counter so that other coroutines can
1849 * already continue reading beyond this request */
1850 s->sector_num += n;
1851 qemu_co_mutex_unlock(&s->lock);
1852
1853 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1854 s->allocated_done += n;
1855 qemu_progress_print(100.0 * s->allocated_done /
1856 s->allocated_sectors, 0);
1857 }
1858
Fam Zhengee5306d2018-06-01 17:26:48 +08001859retry:
1860 copy_range = s->copy_range && s->status == BLK_DATA;
1861 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001862 ret = convert_co_read(s, sector_num, n, buf);
1863 if (ret < 0) {
1864 error_report("error while reading sector %" PRId64
1865 ": %s", sector_num, strerror(-ret));
1866 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001867 }
1868 } else if (!s->min_sparse && status == BLK_ZERO) {
1869 status = BLK_DATA;
1870 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1871 }
1872
1873 if (s->wr_in_order) {
1874 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001875 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001876 s->wait_sector_num[index] = sector_num;
1877 qemu_coroutine_yield();
1878 }
1879 s->wait_sector_num[index] = -1;
1880 }
1881
Anton Nefedovb91127e2017-04-26 11:33:15 +03001882 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001883 if (copy_range) {
1884 ret = convert_co_copy_range(s, sector_num, n);
1885 if (ret) {
1886 s->copy_range = false;
1887 goto retry;
1888 }
1889 } else {
1890 ret = convert_co_write(s, sector_num, n, buf, status);
1891 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001892 if (ret < 0) {
1893 error_report("error while writing sector %" PRId64
1894 ": %s", sector_num, strerror(-ret));
1895 s->ret = ret;
1896 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001897 }
1898
1899 if (s->wr_in_order) {
1900 /* reenter the coroutine that might have waited
1901 * for this write to complete */
1902 s->wr_offs = sector_num + n;
1903 for (i = 0; i < s->num_coroutines; i++) {
1904 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1905 /*
1906 * A -> B -> A cannot occur because A has
1907 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1908 * B will never enter A during this time window.
1909 */
1910 qemu_coroutine_enter(s->co[i]);
1911 break;
1912 }
1913 }
1914 }
1915 }
1916
Peter Lieven2d9187b2017-02-28 13:40:07 +01001917 qemu_vfree(buf);
1918 s->co[index] = NULL;
1919 s->running_coroutines--;
1920 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1921 /* the convert job finished successfully */
1922 s->ret = 0;
1923 }
1924}
1925
Kevin Wolf690c7302015-03-19 13:33:32 +01001926static int convert_do_copy(ImgConvertState *s)
1927{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001928 int ret, i, n;
1929 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001930
1931 /* Check whether we have zero initialisation or can get it efficiently */
1932 s->has_zero_init = s->min_sparse && !s->target_has_backing
1933 ? bdrv_has_zero_init(blk_bs(s->target))
1934 : false;
1935
1936 if (!s->has_zero_init && !s->target_has_backing &&
1937 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1938 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001939 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001940 if (ret == 0) {
1941 s->has_zero_init = true;
1942 }
1943 }
1944
1945 /* Allocate buffer for copied data. For compressed images, only one cluster
1946 * can be copied at a time. */
1947 if (s->compressed) {
1948 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1949 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001950 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001951 }
1952 s->buf_sectors = s->cluster_sectors;
1953 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001954
Kevin Wolf690c7302015-03-19 13:33:32 +01001955 while (sector_num < s->total_sectors) {
1956 n = convert_iteration_sectors(s, sector_num);
1957 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001958 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001959 }
Max Reitzaad15de2016-03-24 23:33:57 +01001960 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1961 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001962 s->allocated_sectors += n;
1963 }
1964 sector_num += n;
1965 }
1966
1967 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001968 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001969 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001970
Peter Lieven2d9187b2017-02-28 13:40:07 +01001971 qemu_co_mutex_init(&s->lock);
1972 for (i = 0; i < s->num_coroutines; i++) {
1973 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1974 s->wait_sector_num[i] = -1;
1975 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001976 }
1977
Anton Nefedovb91127e2017-04-26 11:33:15 +03001978 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001979 main_loop_wait(false);
1980 }
1981
1982 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001983 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001984 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001985 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001986 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001987 }
1988 }
1989
Peter Lieven2d9187b2017-02-28 13:40:07 +01001990 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001991}
1992
Peter Lieven6360ab22018-07-13 09:15:39 +02001993#define MAX_BUF_SECTORS 32768
1994
bellardea2384d2004-08-01 21:59:26 +00001995static int img_convert(int argc, char **argv)
1996{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001997 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001998 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001999 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2000 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002001 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002002 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002003 BlockDriverState *out_bs;
2004 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002005 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002006 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002007 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002008 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002009 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002010 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002011 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002012 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002013 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002014
Peter Lieven9fd77f92017-04-21 11:11:55 +02002015 ImgConvertState s = (ImgConvertState) {
2016 /* Need at least 4k of zeros for sparse detection */
2017 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002018 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002019 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2020 .wr_in_order = true,
2021 .num_coroutines = 8,
2022 };
2023
bellardea2384d2004-08-01 21:59:26 +00002024 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002025 static const struct option long_options[] = {
2026 {"help", no_argument, 0, 'h'},
2027 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002028 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002029 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002030 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002031 {0, 0, 0, 0}
2032 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002033 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002034 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002035 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002036 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002037 }
bellardea2384d2004-08-01 21:59:26 +00002038 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002039 case ':':
2040 missing_argument(argv[optind - 1]);
2041 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002042 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002043 unrecognized_option(argv[optind - 1]);
2044 break;
bellardea2384d2004-08-01 21:59:26 +00002045 case 'h':
2046 help();
2047 break;
2048 case 'f':
2049 fmt = optarg;
2050 break;
2051 case 'O':
2052 out_fmt = optarg;
2053 break;
thsf58c7b32008-06-05 21:53:49 +00002054 case 'B':
2055 out_baseimg = optarg;
2056 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002057 case 'C':
2058 s.copy_range = true;
2059 break;
bellardea2384d2004-08-01 21:59:26 +00002060 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002061 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002062 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002063 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002064 if (!is_valid_option_list(optarg)) {
2065 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002066 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002067 }
2068 if (!options) {
2069 options = g_strdup(optarg);
2070 } else {
2071 char *old_options = options;
2072 options = g_strdup_printf("%s,%s", options, optarg);
2073 g_free(old_options);
2074 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002075 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002076 case 'l':
2077 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002078 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2079 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002080 if (!sn_opts) {
2081 error_report("Failed in parsing snapshot param '%s'",
2082 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002083 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002084 }
2085 } else {
2086 snapshot_name = optarg;
2087 }
2088 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002089 case 'S':
2090 {
2091 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002092
2093 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002094 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2095 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2096 error_report("Invalid buffer size for sparse output specified. "
2097 "Valid sizes are multiples of %llu up to %llu. Select "
2098 "0 to disable sparse detection (fully allocates output).",
2099 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002100 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002101 }
2102
Peter Lieven9fd77f92017-04-21 11:11:55 +02002103 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002104 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002105 break;
2106 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002107 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002108 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002109 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002110 case 't':
2111 cache = optarg;
2112 break;
Max Reitz40055952014-07-22 22:58:42 +02002113 case 'T':
2114 src_cache = optarg;
2115 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002116 case 'q':
2117 quiet = true;
2118 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002119 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002120 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002121 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002122 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002123 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2124 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002125 error_report("Invalid number of coroutines. Allowed number of"
2126 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002127 goto fail_getopt;
2128 }
2129 break;
2130 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002131 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002132 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002133 case 'U':
2134 force_share = true;
2135 break;
Max Reitz3258b912017-04-26 15:46:47 +02002136 case OPTION_OBJECT: {
2137 QemuOpts *object_opts;
2138 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2139 optarg, true);
2140 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002141 goto fail_getopt;
2142 }
2143 break;
Max Reitz3258b912017-04-26 15:46:47 +02002144 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002145 case OPTION_IMAGE_OPTS:
2146 image_opts = true;
2147 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002148 case OPTION_TARGET_IMAGE_OPTS:
2149 tgt_image_opts = true;
2150 break;
bellardea2384d2004-08-01 21:59:26 +00002151 }
2152 }
ths3b46e622007-09-17 08:09:54 +00002153
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002154 if (!out_fmt && !tgt_image_opts) {
2155 out_fmt = "raw";
2156 }
2157
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002158 if (qemu_opts_foreach(&qemu_object_opts,
2159 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002160 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002161 goto fail_getopt;
2162 }
2163
Fam Zhenge11ce122018-07-27 11:34:01 +08002164 if (s.compressed && s.copy_range) {
2165 error_report("Cannot enable copy offloading when -c is used");
2166 goto fail_getopt;
2167 }
2168
2169 if (explict_min_sparse && s.copy_range) {
2170 error_report("Cannot enable copy offloading when -S is used");
2171 goto fail_getopt;
2172 }
2173
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002174 if (tgt_image_opts && !skip_create) {
2175 error_report("--target-image-opts requires use of -n flag");
2176 goto fail_getopt;
2177 }
2178
Peter Lieven9fd77f92017-04-21 11:11:55 +02002179 s.src_num = argc - optind - 1;
2180 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2181
2182 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002183 if (out_fmt) {
2184 ret = print_block_option_help(out_filename, out_fmt);
2185 goto fail_getopt;
2186 } else {
2187 error_report("Option help requires a format be specified");
2188 goto fail_getopt;
2189 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002190 }
2191
2192 if (s.src_num < 1) {
2193 error_report("Must specify image file name");
2194 goto fail_getopt;
2195 }
2196
2197
Peter Lieven9fd77f92017-04-21 11:11:55 +02002198 /* ret is still -EINVAL until here */
2199 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2200 if (ret < 0) {
2201 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002202 goto fail_getopt;
2203 }
2204
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002205 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002206 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002207 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002208 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002209 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002210 qemu_progress_print(0, 100);
2211
Peter Lieven9fd77f92017-04-21 11:11:55 +02002212 s.src = g_new0(BlockBackend *, s.src_num);
2213 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002214
Peter Lieven9fd77f92017-04-21 11:11:55 +02002215 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2216 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002217 fmt, src_flags, src_writethrough, quiet,
2218 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002219 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002220 ret = -1;
2221 goto out;
2222 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002223 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2224 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002225 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002226 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002227 ret = -1;
2228 goto out;
2229 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002230 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002231 }
bellardea2384d2004-08-01 21:59:26 +00002232
Wenchao Xiaef806542013-12-04 17:10:57 +08002233 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002234 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002235 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2236 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2237 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002238 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002239 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002240 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002241 ret = -1;
2242 goto out;
2243 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002244
Peter Lieven9fd77f92017-04-21 11:11:55 +02002245 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2246 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002247 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002248 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002249 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002250 ret = -1;
2251 goto out;
edison51ef6722010-09-21 19:58:41 -07002252 }
2253
Max Reitz2e024cd2015-02-11 09:58:46 -05002254 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002255 /* Find driver and parse its options */
2256 drv = bdrv_find_format(out_fmt);
2257 if (!drv) {
2258 error_report("Unknown file format '%s'", out_fmt);
2259 ret = -1;
2260 goto out;
2261 }
2262
2263 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2264 if (!proto_drv) {
2265 error_report_err(local_err);
2266 ret = -1;
2267 goto out;
2268 }
2269
Max Reitz2e024cd2015-02-11 09:58:46 -05002270 if (!drv->create_opts) {
2271 error_report("Format driver '%s' does not support image creation",
2272 drv->format_name);
2273 ret = -1;
2274 goto out;
2275 }
Max Reitzf75613c2014-12-02 18:32:46 +01002276
Max Reitz2e024cd2015-02-11 09:58:46 -05002277 if (!proto_drv->create_opts) {
2278 error_report("Protocol driver '%s' does not support image creation",
2279 proto_drv->format_name);
2280 ret = -1;
2281 goto out;
2282 }
Max Reitzf75613c2014-12-02 18:32:46 +01002283
Max Reitz2e024cd2015-02-11 09:58:46 -05002284 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2285 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002286
Max Reitz2e024cd2015-02-11 09:58:46 -05002287 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002288 if (options) {
2289 qemu_opts_do_parse(opts, options, NULL, &local_err);
2290 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002291 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002292 ret = -1;
2293 goto out;
2294 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002295 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002296
Peter Lieven9fd77f92017-04-21 11:11:55 +02002297 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002298 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002299 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2300 if (ret < 0) {
2301 goto out;
2302 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002303 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002304
Kevin Wolfa18953f2010-10-14 15:46:04 +02002305 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002306 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002307 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002308 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002309 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002310 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002311
Max Reitz48758a82017-04-26 15:46:48 +02002312 if (s.src_num > 1 && out_baseimg) {
2313 error_report("Having a backing file for the target makes no sense when "
2314 "concatenating multiple input images");
2315 ret = -1;
2316 goto out;
2317 }
2318
Kevin Wolfefa84d42009-05-18 16:42:12 +02002319 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002320 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002321 bool encryption =
2322 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002323 const char *encryptfmt =
2324 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002325 const char *preallocation =
2326 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002327
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002328 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002329 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002330 ret = -1;
2331 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002332 }
2333
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002334 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002335 error_report("Compression and encryption not supported at "
2336 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002337 ret = -1;
2338 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002339 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002340
Chunyan Liu83d05212014-06-05 17:20:51 +08002341 if (preallocation
2342 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002343 {
2344 error_report("Compression and preallocation not supported at "
2345 "the same time");
2346 ret = -1;
2347 goto out;
2348 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002349 }
2350
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002351 /*
2352 * The later open call will need any decryption secrets, and
2353 * bdrv_create() will purge "opts", so extract them now before
2354 * they are lost.
2355 */
2356 if (!skip_create) {
2357 open_opts = qdict_new();
2358 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2359 }
2360
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002361 if (!skip_create) {
2362 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002363 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002364 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002365 error_reportf_err(local_err, "%s: error while converting %s: ",
2366 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002367 goto out;
bellardea2384d2004-08-01 21:59:26 +00002368 }
2369 }
ths3b46e622007-09-17 08:09:54 +00002370
Peter Lieven9fd77f92017-04-21 11:11:55 +02002371 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002372 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002373 if (ret < 0) {
2374 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002375 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002376 }
2377
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002378 if (skip_create) {
2379 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2380 flags, writethrough, quiet, false);
2381 } else {
2382 /* TODO ultimately we should allow --target-image-opts
2383 * to be used even when -n is not given.
2384 * That has to wait for bdrv_create to be improved
2385 * to allow filenames in option syntax
2386 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002387 s.target = img_open_file(out_filename, open_opts, out_fmt,
2388 flags, writethrough, quiet, false);
2389 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002390 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002391 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002392 ret = -1;
2393 goto out;
2394 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002395 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002396
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002397 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2398 error_report("Compression not supported for this file format");
2399 ret = -1;
2400 goto out;
2401 }
2402
Eric Blake5def6b82016-06-23 16:37:19 -06002403 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002404 * or discard_alignment of the out_bs is greater. Limit to
2405 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2406 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002407 MAX(s.buf_sectors,
2408 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2409 out_bs->bl.pdiscard_alignment >>
2410 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002411
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002412 /* try to align the write requests to the destination to avoid unnecessary
2413 * RMW cycles. */
2414 s.alignment = MAX(pow2floor(s.min_sparse),
2415 DIV_ROUND_UP(out_bs->bl.request_alignment,
2416 BDRV_SECTOR_SIZE));
2417 assert(is_power_of_2(s.alignment));
2418
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002419 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002420 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002421 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002422 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002423 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002424 ret = -1;
2425 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002426 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002427 error_report("output file is smaller than input file");
2428 ret = -1;
2429 goto out;
2430 }
2431 }
2432
Max Reitz351c8ef2018-05-01 18:57:49 +02002433 if (s.target_has_backing) {
2434 /* Errors are treated as "backing length unknown" (which means
2435 * s.target_backing_sectors has to be negative, which it will
2436 * be automatically). The backing file length is used only
2437 * for optimizations, so such a case is not fatal. */
2438 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2439 } else {
2440 s.target_backing_sectors = -1;
2441 }
2442
Peter Lieven24f833c2013-11-27 11:07:07 +01002443 ret = bdrv_get_info(out_bs, &bdi);
2444 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002445 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002446 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002447 goto out;
2448 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002449 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002450 s.compressed = s.compressed || bdi.needs_compressed_writes;
2451 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002452 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002453 }
2454
Peter Lieven9fd77f92017-04-21 11:11:55 +02002455 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002456out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002457 if (!ret) {
2458 qemu_progress_print(100, 0);
2459 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002460 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002461 qemu_opts_del(opts);
2462 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002463 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002464 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002465 blk_unref(s.target);
2466 if (s.src) {
2467 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2468 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002469 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002470 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002471 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002472 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002473fail_getopt:
2474 g_free(options);
2475
Peter Lieven9fd77f92017-04-21 11:11:55 +02002476 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002477}
2478
bellard57d1a2b2004-08-03 21:15:11 +00002479
bellardfaea38e2006-08-05 21:31:00 +00002480static void dump_snapshots(BlockDriverState *bs)
2481{
2482 QEMUSnapshotInfo *sn_tab, *sn;
2483 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002484
2485 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2486 if (nb_sns <= 0)
2487 return;
2488 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002489 bdrv_snapshot_dump(fprintf, stdout, NULL);
2490 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002491 for(i = 0; i < nb_sns; i++) {
2492 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002493 bdrv_snapshot_dump(fprintf, stdout, sn);
2494 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002495 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002496 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002497}
2498
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002499static void dump_json_image_info_list(ImageInfoList *list)
2500{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002501 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002502 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002503 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002504
2505 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2506 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002507 str = qobject_to_json_pretty(obj);
2508 assert(str != NULL);
2509 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002510 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002511 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002512 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002513}
2514
Benoît Canetc054b3f2012-09-05 13:09:02 +02002515static void dump_json_image_info(ImageInfo *info)
2516{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002517 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002518 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002519 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002520
2521 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2522 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002523 str = qobject_to_json_pretty(obj);
2524 assert(str != NULL);
2525 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002526 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002527 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002528 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002529}
2530
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002531static void dump_human_image_info_list(ImageInfoList *list)
2532{
2533 ImageInfoList *elem;
2534 bool delim = false;
2535
2536 for (elem = list; elem; elem = elem->next) {
2537 if (delim) {
2538 printf("\n");
2539 }
2540 delim = true;
2541
Wenchao Xia5b917042013-05-25 11:09:45 +08002542 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002543 }
2544}
2545
2546static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2547{
2548 return strcmp(a, b) == 0;
2549}
2550
2551/**
2552 * Open an image file chain and return an ImageInfoList
2553 *
2554 * @filename: topmost image filename
2555 * @fmt: topmost image format (may be NULL to autodetect)
2556 * @chain: true - enumerate entire backing file chain
2557 * false - only topmost image file
2558 *
2559 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2560 * image file. If there was an error a message will have been printed to
2561 * stderr.
2562 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002563static ImageInfoList *collect_image_info_list(bool image_opts,
2564 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002565 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002566 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002567{
2568 ImageInfoList *head = NULL;
2569 ImageInfoList **last = &head;
2570 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002571 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002572
2573 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2574
2575 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002576 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002577 BlockDriverState *bs;
2578 ImageInfo *info;
2579 ImageInfoList *elem;
2580
2581 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2582 error_report("Backing file '%s' creates an infinite loop.",
2583 filename);
2584 goto err;
2585 }
2586 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2587
Max Reitzefaa7c42016-03-16 19:54:38 +01002588 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002589 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2590 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002591 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002592 goto err;
2593 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002594 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002595
Wenchao Xia43526ec2013-06-06 12:27:58 +08002596 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002597 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002598 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002599 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002600 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002601 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002602
2603 elem = g_new0(ImageInfoList, 1);
2604 elem->value = info;
2605 *last = elem;
2606 last = &elem->next;
2607
Markus Armbruster26f54e92014-10-07 13:59:04 +02002608 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002609
2610 filename = fmt = NULL;
2611 if (chain) {
2612 if (info->has_full_backing_filename) {
2613 filename = info->full_backing_filename;
2614 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002615 error_report("Could not determine absolute backing filename,"
2616 " but backing filename '%s' present",
2617 info->backing_filename);
2618 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002619 }
2620 if (info->has_backing_filename_format) {
2621 fmt = info->backing_filename_format;
2622 }
2623 }
2624 }
2625 g_hash_table_destroy(filenames);
2626 return head;
2627
2628err:
2629 qapi_free_ImageInfoList(head);
2630 g_hash_table_destroy(filenames);
2631 return NULL;
2632}
2633
Benoît Canetc054b3f2012-09-05 13:09:02 +02002634static int img_info(int argc, char **argv)
2635{
2636 int c;
2637 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002638 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002639 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002640 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002641 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002642 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002643
bellardea2384d2004-08-01 21:59:26 +00002644 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002645 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002646 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002647 int option_index = 0;
2648 static const struct option long_options[] = {
2649 {"help", no_argument, 0, 'h'},
2650 {"format", required_argument, 0, 'f'},
2651 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002652 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002653 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002654 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002655 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002656 {0, 0, 0, 0}
2657 };
Fam Zheng335e9932017-05-03 00:35:39 +08002658 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002659 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002660 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002661 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002662 }
bellardea2384d2004-08-01 21:59:26 +00002663 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002664 case ':':
2665 missing_argument(argv[optind - 1]);
2666 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002667 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002668 unrecognized_option(argv[optind - 1]);
2669 break;
bellardea2384d2004-08-01 21:59:26 +00002670 case 'h':
2671 help();
2672 break;
2673 case 'f':
2674 fmt = optarg;
2675 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002676 case 'U':
2677 force_share = true;
2678 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002679 case OPTION_OUTPUT:
2680 output = optarg;
2681 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002682 case OPTION_BACKING_CHAIN:
2683 chain = true;
2684 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002685 case OPTION_OBJECT: {
2686 QemuOpts *opts;
2687 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2688 optarg, true);
2689 if (!opts) {
2690 return 1;
2691 }
2692 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002693 case OPTION_IMAGE_OPTS:
2694 image_opts = true;
2695 break;
bellardea2384d2004-08-01 21:59:26 +00002696 }
2697 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002698 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002699 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002700 }
bellardea2384d2004-08-01 21:59:26 +00002701 filename = argv[optind++];
2702
Benoît Canetc054b3f2012-09-05 13:09:02 +02002703 if (output && !strcmp(output, "json")) {
2704 output_format = OFORMAT_JSON;
2705 } else if (output && !strcmp(output, "human")) {
2706 output_format = OFORMAT_HUMAN;
2707 } else if (output) {
2708 error_report("--output must be used with human or json as argument.");
2709 return 1;
2710 }
2711
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002712 if (qemu_opts_foreach(&qemu_object_opts,
2713 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002714 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002715 return 1;
2716 }
2717
Fam Zheng335e9932017-05-03 00:35:39 +08002718 list = collect_image_info_list(image_opts, filename, fmt, chain,
2719 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002720 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002721 return 1;
2722 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002723
Benoît Canetc054b3f2012-09-05 13:09:02 +02002724 switch (output_format) {
2725 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002726 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002727 break;
2728 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002729 if (chain) {
2730 dump_json_image_info_list(list);
2731 } else {
2732 dump_json_image_info(list->value);
2733 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002734 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002735 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002736
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002737 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002738 return 0;
2739}
2740
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002741static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2742 MapEntry *next)
2743{
2744 switch (output_format) {
2745 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002746 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002747 error_report("File contains external, encrypted or compressed clusters.");
2748 exit(1);
2749 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002750 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002751 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002752 e->start, e->length,
2753 e->has_offset ? e->offset : 0,
2754 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002755 }
2756 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2757 * Modify the flags here to allow more coalescing.
2758 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002759 if (next && (!next->data || next->zero)) {
2760 next->data = false;
2761 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002762 }
2763 break;
2764 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002765 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2766 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002767 (e->start == 0 ? "[" : ",\n"),
2768 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002769 e->zero ? "true" : "false",
2770 e->data ? "true" : "false");
2771 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002772 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002773 }
2774 putchar('}');
2775
2776 if (!next) {
2777 printf("]\n");
2778 }
2779 break;
2780 }
2781}
2782
Eric Blake5e344dd2017-10-11 22:47:02 -05002783static int get_block_status(BlockDriverState *bs, int64_t offset,
2784 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002785{
Eric Blake237d78f2017-10-11 22:47:03 -05002786 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002787 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002788 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002789 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002790 int64_t map;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002791
2792 /* As an optimization, we could cache the current range of unallocated
2793 * clusters in each file of the chain, and avoid querying the same
2794 * range repeatedly.
2795 */
2796
2797 depth = 0;
2798 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002799 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002800 if (ret < 0) {
2801 return ret;
2802 }
Eric Blake237d78f2017-10-11 22:47:03 -05002803 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002804 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2805 break;
2806 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002807 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002808 if (bs == NULL) {
2809 ret = 0;
2810 break;
2811 }
2812
2813 depth++;
2814 }
2815
John Snow28756452016-02-05 13:12:33 -05002816 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2817
2818 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002819 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002820 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002821 .data = !!(ret & BDRV_BLOCK_DATA),
2822 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002823 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002824 .has_offset = has_offset,
2825 .depth = depth,
2826 .has_filename = file && has_offset,
2827 .filename = file && has_offset ? file->filename : NULL,
2828 };
2829
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002830 return 0;
2831}
2832
Fam Zheng16b0d552016-01-26 11:59:02 +08002833static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2834{
2835 if (curr->length == 0) {
2836 return false;
2837 }
2838 if (curr->zero != next->zero ||
2839 curr->data != next->data ||
2840 curr->depth != next->depth ||
2841 curr->has_filename != next->has_filename ||
2842 curr->has_offset != next->has_offset) {
2843 return false;
2844 }
2845 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2846 return false;
2847 }
2848 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2849 return false;
2850 }
2851 return true;
2852}
2853
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002854static int img_map(int argc, char **argv)
2855{
2856 int c;
2857 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002858 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002859 BlockDriverState *bs;
2860 const char *filename, *fmt, *output;
2861 int64_t length;
2862 MapEntry curr = { .length = 0 }, next;
2863 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002864 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002865 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002866
2867 fmt = NULL;
2868 output = NULL;
2869 for (;;) {
2870 int option_index = 0;
2871 static const struct option long_options[] = {
2872 {"help", no_argument, 0, 'h'},
2873 {"format", required_argument, 0, 'f'},
2874 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002875 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002876 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002877 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002878 {0, 0, 0, 0}
2879 };
Fam Zheng335e9932017-05-03 00:35:39 +08002880 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002881 long_options, &option_index);
2882 if (c == -1) {
2883 break;
2884 }
2885 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002886 case ':':
2887 missing_argument(argv[optind - 1]);
2888 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002889 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002890 unrecognized_option(argv[optind - 1]);
2891 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002892 case 'h':
2893 help();
2894 break;
2895 case 'f':
2896 fmt = optarg;
2897 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002898 case 'U':
2899 force_share = true;
2900 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002901 case OPTION_OUTPUT:
2902 output = optarg;
2903 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002904 case OPTION_OBJECT: {
2905 QemuOpts *opts;
2906 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2907 optarg, true);
2908 if (!opts) {
2909 return 1;
2910 }
2911 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002912 case OPTION_IMAGE_OPTS:
2913 image_opts = true;
2914 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002915 }
2916 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002917 if (optind != argc - 1) {
2918 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002919 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002920 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002921
2922 if (output && !strcmp(output, "json")) {
2923 output_format = OFORMAT_JSON;
2924 } else if (output && !strcmp(output, "human")) {
2925 output_format = OFORMAT_HUMAN;
2926 } else if (output) {
2927 error_report("--output must be used with human or json as argument.");
2928 return 1;
2929 }
2930
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002931 if (qemu_opts_foreach(&qemu_object_opts,
2932 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002933 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002934 return 1;
2935 }
2936
Fam Zheng335e9932017-05-03 00:35:39 +08002937 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002938 if (!blk) {
2939 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002940 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002941 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002942
2943 if (output_format == OFORMAT_HUMAN) {
2944 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2945 }
2946
Max Reitzf1d3cd72015-02-05 13:58:18 -05002947 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002948 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002949 int64_t offset = curr.start + curr.length;
2950 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002951
2952 /* Probe up to 1 GiB at a time. */
Eric Blakee0b371e2018-06-11 16:39:26 -05002953 n = MIN(1 << 30, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002954 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002955
2956 if (ret < 0) {
2957 error_report("Could not read file metadata: %s", strerror(-ret));
2958 goto out;
2959 }
2960
Fam Zheng16b0d552016-01-26 11:59:02 +08002961 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002962 curr.length += next.length;
2963 continue;
2964 }
2965
2966 if (curr.length > 0) {
2967 dump_map_entry(output_format, &curr, &next);
2968 }
2969 curr = next;
2970 }
2971
2972 dump_map_entry(output_format, &curr, NULL);
2973
2974out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002975 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002976 return ret < 0;
2977}
2978
aliguorif7b4a942009-01-07 17:40:15 +00002979#define SNAPSHOT_LIST 1
2980#define SNAPSHOT_CREATE 2
2981#define SNAPSHOT_APPLY 3
2982#define SNAPSHOT_DELETE 4
2983
Stuart Brady153859b2009-06-07 00:42:17 +01002984static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002985{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002986 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002987 BlockDriverState *bs;
2988 QEMUSnapshotInfo sn;
2989 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002990 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002991 int action = 0;
2992 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002993 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002994 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002995 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002996 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002997
Kevin Wolfce099542016-03-15 13:01:04 +01002998 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002999 /* Parse commandline parameters */
3000 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003001 static const struct option long_options[] = {
3002 {"help", no_argument, 0, 'h'},
3003 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003004 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003005 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003006 {0, 0, 0, 0}
3007 };
Fam Zheng335e9932017-05-03 00:35:39 +08003008 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003009 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003010 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003011 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003012 }
aliguorif7b4a942009-01-07 17:40:15 +00003013 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003014 case ':':
3015 missing_argument(argv[optind - 1]);
3016 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003017 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003018 unrecognized_option(argv[optind - 1]);
3019 break;
aliguorif7b4a942009-01-07 17:40:15 +00003020 case 'h':
3021 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003022 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003023 case 'l':
3024 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003025 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003026 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003027 }
3028 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003029 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003030 break;
3031 case 'a':
3032 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003033 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003034 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003035 }
3036 action = SNAPSHOT_APPLY;
3037 snapshot_name = optarg;
3038 break;
3039 case 'c':
3040 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003041 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003042 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003043 }
3044 action = SNAPSHOT_CREATE;
3045 snapshot_name = optarg;
3046 break;
3047 case 'd':
3048 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003049 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003050 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003051 }
3052 action = SNAPSHOT_DELETE;
3053 snapshot_name = optarg;
3054 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003055 case 'q':
3056 quiet = true;
3057 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003058 case 'U':
3059 force_share = true;
3060 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003061 case OPTION_OBJECT: {
3062 QemuOpts *opts;
3063 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3064 optarg, true);
3065 if (!opts) {
3066 return 1;
3067 }
3068 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003069 case OPTION_IMAGE_OPTS:
3070 image_opts = true;
3071 break;
aliguorif7b4a942009-01-07 17:40:15 +00003072 }
3073 }
3074
Kevin Wolffc11eb22013-08-05 10:53:04 +02003075 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003076 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003077 }
aliguorif7b4a942009-01-07 17:40:15 +00003078 filename = argv[optind++];
3079
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003080 if (qemu_opts_foreach(&qemu_object_opts,
3081 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003082 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003083 return 1;
3084 }
3085
aliguorif7b4a942009-01-07 17:40:15 +00003086 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003087 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3088 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003089 if (!blk) {
3090 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003091 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003092 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003093
3094 /* Perform the requested action */
3095 switch(action) {
3096 case SNAPSHOT_LIST:
3097 dump_snapshots(bs);
3098 break;
3099
3100 case SNAPSHOT_CREATE:
3101 memset(&sn, 0, sizeof(sn));
3102 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3103
3104 qemu_gettimeofday(&tv);
3105 sn.date_sec = tv.tv_sec;
3106 sn.date_nsec = tv.tv_usec * 1000;
3107
3108 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003109 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003110 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003111 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003112 }
aliguorif7b4a942009-01-07 17:40:15 +00003113 break;
3114
3115 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003116 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003117 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003118 error_reportf_err(err, "Could not apply snapshot '%s': ",
3119 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003120 }
aliguorif7b4a942009-01-07 17:40:15 +00003121 break;
3122
3123 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003124 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003125 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003126 error_reportf_err(err, "Could not delete snapshot '%s': ",
3127 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003128 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003129 }
aliguorif7b4a942009-01-07 17:40:15 +00003130 break;
3131 }
3132
3133 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003134 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003135 if (ret) {
3136 return 1;
3137 }
Stuart Brady153859b2009-06-07 00:42:17 +01003138 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003139}
3140
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003141static int img_rebase(int argc, char **argv)
3142{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003143 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003144 uint8_t *buf_old = NULL;
3145 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003146 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003147 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003148 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3149 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003150 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003151 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003152 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003153 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003154 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003155 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003156 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003157
3158 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003159 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003160 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003161 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003162 out_baseimg = NULL;
3163 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003164 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003165 static const struct option long_options[] = {
3166 {"help", no_argument, 0, 'h'},
3167 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003168 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003169 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003170 {0, 0, 0, 0}
3171 };
Fam Zheng335e9932017-05-03 00:35:39 +08003172 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003173 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003174 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003175 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003176 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003177 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003178 case ':':
3179 missing_argument(argv[optind - 1]);
3180 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003181 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003182 unrecognized_option(argv[optind - 1]);
3183 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003184 case 'h':
3185 help();
3186 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003187 case 'f':
3188 fmt = optarg;
3189 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003190 case 'F':
3191 out_basefmt = optarg;
3192 break;
3193 case 'b':
3194 out_baseimg = optarg;
3195 break;
3196 case 'u':
3197 unsafe = 1;
3198 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003199 case 'p':
3200 progress = 1;
3201 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003202 case 't':
3203 cache = optarg;
3204 break;
Max Reitz40055952014-07-22 22:58:42 +02003205 case 'T':
3206 src_cache = optarg;
3207 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003208 case 'q':
3209 quiet = true;
3210 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003211 case OPTION_OBJECT: {
3212 QemuOpts *opts;
3213 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3214 optarg, true);
3215 if (!opts) {
3216 return 1;
3217 }
3218 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003219 case OPTION_IMAGE_OPTS:
3220 image_opts = true;
3221 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003222 case 'U':
3223 force_share = true;
3224 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003225 }
3226 }
3227
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003228 if (quiet) {
3229 progress = 0;
3230 }
3231
Fam Zhengac1307a2014-04-22 13:36:11 +08003232 if (optind != argc - 1) {
3233 error_exit("Expecting one image file name");
3234 }
3235 if (!unsafe && !out_baseimg) {
3236 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003237 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003238 filename = argv[optind++];
3239
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003240 if (qemu_opts_foreach(&qemu_object_opts,
3241 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003242 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003243 return 1;
3244 }
3245
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003246 qemu_progress_init(progress, 2.0);
3247 qemu_progress_print(0, 100);
3248
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003249 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003250 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003251 if (ret < 0) {
3252 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003253 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003254 }
3255
Kevin Wolfce099542016-03-15 13:01:04 +01003256 src_flags = 0;
3257 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003258 if (ret < 0) {
3259 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003260 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003261 }
3262
Kevin Wolfce099542016-03-15 13:01:04 +01003263 /* The source files are opened read-only, don't care about WCE */
3264 assert((src_flags & BDRV_O_RDWR) == 0);
3265 (void) src_writethrough;
3266
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003267 /*
3268 * Open the images.
3269 *
3270 * Ignore the old backing file for unsafe rebase in case we want to correct
3271 * the reference to a renamed or moved backing file.
3272 */
Fam Zheng335e9932017-05-03 00:35:39 +08003273 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3274 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003275 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003276 ret = -1;
3277 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003278 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003279 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003280
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003281 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003282 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003283 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003284 ret = -1;
3285 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003286 }
3287 }
3288
3289 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003290 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003291 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003292 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003293
Max Reitz644483d2015-02-05 13:58:17 -05003294 if (bs->backing_format[0] != '\0') {
3295 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003296 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003297 }
3298
Fam Zheng335e9932017-05-03 00:35:39 +08003299 if (force_share) {
3300 if (!options) {
3301 options = qdict_new();
3302 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003303 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003304 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003305 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003306 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003307 options, src_flags, &local_err);
3308 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003309 error_reportf_err(local_err,
3310 "Could not open old backing file '%s': ",
3311 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003312 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003313 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003314 }
Max Reitz644483d2015-02-05 13:58:17 -05003315
Alex Bligha6166732012-10-16 13:46:18 +01003316 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003317 const char *overlay_filename;
3318 char *out_real_path;
3319
Fam Zheng335e9932017-05-03 00:35:39 +08003320 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003321 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003322 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003323 }
3324 if (force_share) {
3325 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003326 }
3327
Max Reitzd16699b2018-05-09 20:20:01 +02003328 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3329 : bs->filename;
3330 out_real_path = g_malloc(PATH_MAX);
3331
3332 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3333 out_baseimg,
3334 out_real_path,
3335 PATH_MAX,
3336 &local_err);
3337 if (local_err) {
3338 error_reportf_err(local_err,
3339 "Could not resolve backing filename: ");
3340 ret = -1;
3341 g_free(out_real_path);
3342 goto out;
3343 }
3344
3345 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003346 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003347 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003348 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003349 error_reportf_err(local_err,
3350 "Could not open new backing file '%s': ",
3351 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003352 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003353 goto out;
3354 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003355 }
3356 }
3357
3358 /*
3359 * Check each unallocated cluster in the COW file. If it is unallocated,
3360 * accesses go to the backing file. We must therefore compare this cluster
3361 * in the old and new backing file, and if they differ we need to copy it
3362 * from the old backing file into the COW file.
3363 *
3364 * If qemu-img crashes during this step, no harm is done. The content of
3365 * the image is the same as the original one at any time.
3366 */
3367 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003368 int64_t size;
3369 int64_t old_backing_size;
3370 int64_t new_backing_size = 0;
3371 uint64_t offset;
3372 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003373 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003374
Max Reitzf1d3cd72015-02-05 13:58:18 -05003375 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3376 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003377
Eric Blake41536282017-10-11 22:47:15 -05003378 size = blk_getlength(blk);
3379 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003380 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003381 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003382 ret = -1;
3383 goto out;
3384 }
Eric Blake41536282017-10-11 22:47:15 -05003385 old_backing_size = blk_getlength(blk_old_backing);
3386 if (old_backing_size < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003387 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003388
3389 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3390 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003391 backing_name, strerror(-old_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003392 ret = -1;
3393 goto out;
3394 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003395 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003396 new_backing_size = blk_getlength(blk_new_backing);
3397 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003398 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003399 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003400 ret = -1;
3401 goto out;
3402 }
Alex Bligha6166732012-10-16 13:46:18 +01003403 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003404
Eric Blake41536282017-10-11 22:47:15 -05003405 if (size != 0) {
3406 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003407 }
3408
Eric Blake41536282017-10-11 22:47:15 -05003409 for (offset = 0; offset < size; offset += n) {
3410 /* How many bytes can we handle with the next read? */
3411 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003412
3413 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003414 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003415 if (ret < 0) {
3416 error_report("error while reading image metadata: %s",
3417 strerror(-ret));
3418 goto out;
3419 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003420 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003421 continue;
3422 }
3423
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003424 /*
3425 * Read old and new backing file and take into consideration that
3426 * backing files may be smaller than the COW image.
3427 */
Eric Blake41536282017-10-11 22:47:15 -05003428 if (offset >= old_backing_size) {
3429 memset(buf_old, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003430 } else {
Eric Blake41536282017-10-11 22:47:15 -05003431 if (offset + n > old_backing_size) {
3432 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003433 }
3434
Eric Blake41536282017-10-11 22:47:15 -05003435 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003436 if (ret < 0) {
3437 error_report("error while reading from old backing file");
3438 goto out;
3439 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003440 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003441
Eric Blake41536282017-10-11 22:47:15 -05003442 if (offset >= new_backing_size || !blk_new_backing) {
3443 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003444 } else {
Eric Blake41536282017-10-11 22:47:15 -05003445 if (offset + n > new_backing_size) {
3446 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003447 }
3448
Eric Blake41536282017-10-11 22:47:15 -05003449 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003450 if (ret < 0) {
3451 error_report("error while reading from new backing file");
3452 goto out;
3453 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003454 }
3455
3456 /* If they differ, we need to write to the COW file */
3457 uint64_t written = 0;
3458
Eric Blake41536282017-10-11 22:47:15 -05003459 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003460 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003461
Eric Blake41536282017-10-11 22:47:15 -05003462 if (compare_buffers(buf_old + written, buf_new + written,
3463 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003464 {
Eric Blake41536282017-10-11 22:47:15 -05003465 ret = blk_pwrite(blk, offset + written,
Eric Blakedc61cd32017-10-11 22:47:14 -05003466 buf_old + written, pnum, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003467 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003468 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003469 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003470 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003471 }
3472 }
3473
3474 written += pnum;
3475 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003476 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003477 }
3478 }
3479
3480 /*
3481 * Change the backing file. All clusters that are different from the old
3482 * backing file are overwritten in the COW file now, so the visible content
3483 * doesn't change when we switch the backing file.
3484 */
Alex Bligha6166732012-10-16 13:46:18 +01003485 if (out_baseimg && *out_baseimg) {
3486 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3487 } else {
3488 ret = bdrv_change_backing_file(bs, NULL, NULL);
3489 }
3490
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003491 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003492 error_report("Could not change the backing file to '%s': No "
3493 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003494 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003495 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003496 out_baseimg, strerror(-ret));
3497 }
3498
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003499 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003500 /*
3501 * TODO At this point it is possible to check if any clusters that are
3502 * allocated in the COW file are the same in the backing file. If so, they
3503 * could be dropped from the COW file. Don't do this before switching the
3504 * backing file, in case of a crash this would lead to corruption.
3505 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003506out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003507 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003508 /* Cleanup */
3509 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003510 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003511 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003512 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003513 qemu_vfree(buf_old);
3514 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003515
Markus Armbruster26f54e92014-10-07 13:59:04 +02003516 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003517 if (ret) {
3518 return 1;
3519 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003520 return 0;
3521}
3522
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003523static int img_resize(int argc, char **argv)
3524{
Markus Armbruster6750e792015-02-12 17:43:08 +01003525 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003526 int c, ret, relative;
3527 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003528 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003529 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003530 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003531 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003532 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003533
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003534 static QemuOptsList resize_options = {
3535 .name = "resize_options",
3536 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3537 .desc = {
3538 {
3539 .name = BLOCK_OPT_SIZE,
3540 .type = QEMU_OPT_SIZE,
3541 .help = "Virtual disk size"
3542 }, {
3543 /* end of list */
3544 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003545 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003546 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003547 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003548 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003549
Kevin Wolfe80fec72011-04-29 10:58:12 +02003550 /* Remove size from argv manually so that negative numbers are not treated
3551 * as options by getopt. */
3552 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003553 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003554 return 1;
3555 }
3556
3557 size = argv[--argc];
3558
3559 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003560 fmt = NULL;
3561 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003562 static const struct option long_options[] = {
3563 {"help", no_argument, 0, 'h'},
3564 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003565 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003566 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003567 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003568 {0, 0, 0, 0}
3569 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003570 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003571 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003572 if (c == -1) {
3573 break;
3574 }
3575 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003576 case ':':
3577 missing_argument(argv[optind - 1]);
3578 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003579 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003580 unrecognized_option(argv[optind - 1]);
3581 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003582 case 'h':
3583 help();
3584 break;
3585 case 'f':
3586 fmt = optarg;
3587 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003588 case 'q':
3589 quiet = true;
3590 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003591 case OPTION_OBJECT: {
3592 QemuOpts *opts;
3593 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3594 optarg, true);
3595 if (!opts) {
3596 return 1;
3597 }
3598 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003599 case OPTION_IMAGE_OPTS:
3600 image_opts = true;
3601 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003602 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003603 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003604 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003605 if (prealloc == PREALLOC_MODE__MAX) {
3606 error_report("Invalid preallocation mode '%s'", optarg);
3607 return 1;
3608 }
3609 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003610 case OPTION_SHRINK:
3611 shrink = true;
3612 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003613 }
3614 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003615 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003616 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003617 }
3618 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003619
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003620 if (qemu_opts_foreach(&qemu_object_opts,
3621 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003622 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003623 return 1;
3624 }
3625
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003626 /* Choose grow, shrink, or absolute resize mode */
3627 switch (size[0]) {
3628 case '+':
3629 relative = 1;
3630 size++;
3631 break;
3632 case '-':
3633 relative = -1;
3634 size++;
3635 break;
3636 default:
3637 relative = 0;
3638 break;
3639 }
3640
3641 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003642 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003643 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003644 if (err) {
3645 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003646 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003647 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003648 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003649 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003650 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3651 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003652
Max Reitzefaa7c42016-03-16 19:54:38 +01003653 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003654 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3655 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003656 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003657 ret = -1;
3658 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003659 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003660
Max Reitzdc5f6902017-06-13 22:20:55 +02003661 current_size = blk_getlength(blk);
3662 if (current_size < 0) {
3663 error_report("Failed to inquire current image length: %s",
3664 strerror(-current_size));
3665 ret = -1;
3666 goto out;
3667 }
3668
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003669 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003670 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003671 } else {
3672 total_size = n;
3673 }
3674 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003675 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003676 ret = -1;
3677 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003678 }
3679
Max Reitzdc5f6902017-06-13 22:20:55 +02003680 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3681 error_report("Preallocation can only be used for growing images");
3682 ret = -1;
3683 goto out;
3684 }
3685
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003686 if (total_size < current_size && !shrink) {
3687 warn_report("Shrinking an image will delete all data beyond the "
3688 "shrunken image's end. Before performing such an "
3689 "operation, make sure there is no important data there.");
3690
3691 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3692 error_report(
3693 "Use the --shrink option to perform a shrink operation.");
3694 ret = -1;
3695 goto out;
3696 } else {
3697 warn_report("Using the --shrink option will suppress this message. "
3698 "Note that future versions of qemu-img may refuse to "
3699 "shrink images without this option.");
3700 }
3701 }
3702
Max Reitzdc5f6902017-06-13 22:20:55 +02003703 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003704 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003705 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003706 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003707 }
Max Reitz5279b302018-04-21 18:39:57 +02003708
3709 new_size = blk_getlength(blk);
3710 if (new_size < 0) {
3711 error_report("Failed to verify truncated image length: %s",
3712 strerror(-new_size));
3713 ret = -1;
3714 goto out;
3715 }
3716
3717 /* Some block drivers implement a truncation method, but only so
3718 * the user can cause qemu to refresh the image's size from disk.
3719 * The idea is that the user resizes the image outside of qemu and
3720 * then invokes block_resize to inform qemu about it.
3721 * (This includes iscsi and file-posix for device files.)
3722 * Of course, that is not the behavior someone invoking
3723 * qemu-img resize would find useful, so we catch that behavior
3724 * here and tell the user. */
3725 if (new_size != total_size && new_size == current_size) {
3726 error_report("Image was not resized; resizing may not be supported "
3727 "for this image");
3728 ret = -1;
3729 goto out;
3730 }
3731
3732 if (new_size != total_size) {
3733 warn_report("Image should have been resized to %" PRIi64
3734 " bytes, but was resized to %" PRIi64 " bytes",
3735 total_size, new_size);
3736 }
3737
3738 qprintf(quiet, "Image resized.\n");
3739
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003740out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003741 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003742 if (ret) {
3743 return 1;
3744 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003745 return 0;
3746}
3747
Max Reitz76a3a342014-10-27 11:12:51 +01003748static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003749 int64_t offset, int64_t total_work_size,
3750 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003751{
3752 qemu_progress_print(100.f * offset / total_work_size, 0);
3753}
3754
Max Reitz51641352018-05-09 23:00:20 +02003755static int print_amend_option_help(const char *format)
3756{
3757 BlockDriver *drv;
3758
3759 /* Find driver and parse its options */
3760 drv = bdrv_find_format(format);
3761 if (!drv) {
3762 error_report("Unknown file format '%s'", format);
3763 return 1;
3764 }
3765
3766 if (!drv->bdrv_amend_options) {
3767 error_report("Format driver '%s' does not support option amendment",
3768 format);
3769 return 1;
3770 }
3771
3772 /* Every driver supporting amendment must have create_opts */
3773 assert(drv->create_opts);
3774
3775 printf("Creation options for '%s':\n", format);
3776 qemu_opts_print_help(drv->create_opts);
3777 printf("\nNote that not all of these options may be amendable.\n");
3778 return 0;
3779}
3780
Max Reitz6f176b42013-09-03 10:09:50 +02003781static int img_amend(int argc, char **argv)
3782{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003783 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003784 int c, ret = 0;
3785 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003786 QemuOptsList *create_opts = NULL;
3787 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003788 const char *fmt = NULL, *filename, *cache;
3789 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003790 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003791 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003792 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003793 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003794 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003795
Max Reitzbd39e6e2014-07-22 22:58:43 +02003796 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003797 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003798 static const struct option long_options[] = {
3799 {"help", no_argument, 0, 'h'},
3800 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003801 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003802 {0, 0, 0, 0}
3803 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003804 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003805 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003806 if (c == -1) {
3807 break;
3808 }
3809
3810 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003811 case ':':
3812 missing_argument(argv[optind - 1]);
3813 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003814 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003815 unrecognized_option(argv[optind - 1]);
3816 break;
3817 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003818 help();
3819 break;
3820 case 'o':
3821 if (!is_valid_option_list(optarg)) {
3822 error_report("Invalid option list: %s", optarg);
3823 ret = -1;
3824 goto out_no_progress;
3825 }
3826 if (!options) {
3827 options = g_strdup(optarg);
3828 } else {
3829 char *old_options = options;
3830 options = g_strdup_printf("%s,%s", options, optarg);
3831 g_free(old_options);
3832 }
3833 break;
3834 case 'f':
3835 fmt = optarg;
3836 break;
3837 case 't':
3838 cache = optarg;
3839 break;
3840 case 'p':
3841 progress = true;
3842 break;
3843 case 'q':
3844 quiet = true;
3845 break;
3846 case OPTION_OBJECT:
3847 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3848 optarg, true);
3849 if (!opts) {
3850 ret = -1;
3851 goto out_no_progress;
3852 }
3853 break;
3854 case OPTION_IMAGE_OPTS:
3855 image_opts = true;
3856 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003857 }
3858 }
3859
Max Reitz6f176b42013-09-03 10:09:50 +02003860 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003861 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003862 }
3863
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003864 if (qemu_opts_foreach(&qemu_object_opts,
3865 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003866 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003867 ret = -1;
3868 goto out_no_progress;
3869 }
3870
Max Reitz76a3a342014-10-27 11:12:51 +01003871 if (quiet) {
3872 progress = false;
3873 }
3874 qemu_progress_init(progress, 1.0);
3875
Kevin Wolfa283cb62014-02-21 16:24:07 +01003876 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3877 if (fmt && has_help_option(options)) {
3878 /* If a format is explicitly specified (and possibly no filename is
3879 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003880 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003881 goto out;
3882 }
3883
3884 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003885 error_report("Expecting one image file name");
3886 ret = -1;
3887 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003888 }
Max Reitz6f176b42013-09-03 10:09:50 +02003889
Kevin Wolfce099542016-03-15 13:01:04 +01003890 flags = BDRV_O_RDWR;
3891 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003892 if (ret < 0) {
3893 error_report("Invalid cache option: %s", cache);
3894 goto out;
3895 }
3896
Fam Zheng335e9932017-05-03 00:35:39 +08003897 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3898 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003899 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003900 ret = -1;
3901 goto out;
3902 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003903 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003904
3905 fmt = bs->drv->format_name;
3906
Kevin Wolf626f84f2014-02-21 16:24:06 +01003907 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003908 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003909 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003910 goto out;
3911 }
3912
Max Reitz1f996682018-05-09 23:00:17 +02003913 if (!bs->drv->bdrv_amend_options) {
3914 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003915 fmt);
3916 ret = -1;
3917 goto out;
3918 }
3919
Max Reitz1f996682018-05-09 23:00:17 +02003920 /* Every driver supporting amendment must have create_opts */
3921 assert(bs->drv->create_opts);
3922
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003923 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003924 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003925 qemu_opts_do_parse(opts, options, NULL, &err);
3926 if (err) {
3927 error_report_err(err);
3928 ret = -1;
3929 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003930 }
3931
Max Reitz76a3a342014-10-27 11:12:51 +01003932 /* In case the driver does not call amend_status_cb() */
3933 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003934 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003935 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003936 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003937 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003938 goto out;
3939 }
3940
3941out:
Max Reitz76a3a342014-10-27 11:12:51 +01003942 qemu_progress_end();
3943
Max Reitze814dff2015-08-20 16:00:38 -07003944out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003945 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003946 qemu_opts_del(opts);
3947 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003948 g_free(options);
3949
Max Reitz6f176b42013-09-03 10:09:50 +02003950 if (ret) {
3951 return 1;
3952 }
3953 return 0;
3954}
3955
Kevin Wolfb6133b82014-08-05 14:17:13 +02003956typedef struct BenchData {
3957 BlockBackend *blk;
3958 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003959 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003960 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003961 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003962 int nrreq;
3963 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003964 int flush_interval;
3965 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003966 uint8_t *buf;
3967 QEMUIOVector *qiov;
3968
3969 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003970 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003971 uint64_t offset;
3972} BenchData;
3973
Kevin Wolf55d539c2016-06-03 13:59:41 +02003974static void bench_undrained_flush_cb(void *opaque, int ret)
3975{
3976 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003977 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003978 exit(EXIT_FAILURE);
3979 }
3980}
3981
Kevin Wolfb6133b82014-08-05 14:17:13 +02003982static void bench_cb(void *opaque, int ret)
3983{
3984 BenchData *b = opaque;
3985 BlockAIOCB *acb;
3986
3987 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003988 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003989 exit(EXIT_FAILURE);
3990 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003991
3992 if (b->in_flush) {
3993 /* Just finished a flush with drained queue: Start next requests */
3994 assert(b->in_flight == 0);
3995 b->in_flush = false;
3996 } else if (b->in_flight > 0) {
3997 int remaining = b->n - b->in_flight;
3998
Kevin Wolfb6133b82014-08-05 14:17:13 +02003999 b->n--;
4000 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004001
4002 /* Time for flush? Drain queue if requested, then flush */
4003 if (b->flush_interval && remaining % b->flush_interval == 0) {
4004 if (!b->in_flight || !b->drain_on_flush) {
4005 BlockCompletionFunc *cb;
4006
4007 if (b->drain_on_flush) {
4008 b->in_flush = true;
4009 cb = bench_cb;
4010 } else {
4011 cb = bench_undrained_flush_cb;
4012 }
4013
4014 acb = blk_aio_flush(b->blk, cb, b);
4015 if (!acb) {
4016 error_report("Failed to issue flush request");
4017 exit(EXIT_FAILURE);
4018 }
4019 }
4020 if (b->drain_on_flush) {
4021 return;
4022 }
4023 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004024 }
4025
4026 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004027 int64_t offset = b->offset;
4028 /* blk_aio_* might look for completed I/Os and kick bench_cb
4029 * again, so make sure this operation is counted by in_flight
4030 * and b->offset is ready for the next submission.
4031 */
4032 b->in_flight++;
4033 b->offset += b->step;
4034 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004035 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004036 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004037 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004038 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004039 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004040 if (!acb) {
4041 error_report("Failed to issue request");
4042 exit(EXIT_FAILURE);
4043 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004044 }
4045}
4046
4047static int img_bench(int argc, char **argv)
4048{
4049 int c, ret = 0;
4050 const char *fmt = NULL, *filename;
4051 bool quiet = false;
4052 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004053 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004054 int count = 75000;
4055 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004056 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004057 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004058 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004059 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004060 int flush_interval = 0;
4061 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004062 int64_t image_size;
4063 BlockBackend *blk = NULL;
4064 BenchData data = {};
4065 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004066 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004067 struct timeval t1, t2;
4068 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004069 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004070 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004071
4072 for (;;) {
4073 static const struct option long_options[] = {
4074 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004075 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004076 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004077 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004078 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004079 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004080 {0, 0, 0, 0}
4081 };
Fam Zheng335e9932017-05-03 00:35:39 +08004082 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004083 if (c == -1) {
4084 break;
4085 }
4086
4087 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004088 case ':':
4089 missing_argument(argv[optind - 1]);
4090 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004091 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004092 unrecognized_option(argv[optind - 1]);
4093 break;
4094 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004095 help();
4096 break;
4097 case 'c':
4098 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004099 unsigned long res;
4100
4101 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004102 error_report("Invalid request count specified");
4103 return 1;
4104 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004105 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004106 break;
4107 }
4108 case 'd':
4109 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004110 unsigned long res;
4111
4112 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004113 error_report("Invalid queue depth specified");
4114 return 1;
4115 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004116 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004117 break;
4118 }
4119 case 'f':
4120 fmt = optarg;
4121 break;
4122 case 'n':
4123 flags |= BDRV_O_NATIVE_AIO;
4124 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004125 case 'o':
4126 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004127 offset = cvtnum(optarg);
4128 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004129 error_report("Invalid offset specified");
4130 return 1;
4131 }
4132 break;
4133 }
4134 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004135 case 'q':
4136 quiet = true;
4137 break;
4138 case 's':
4139 {
4140 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004141
Markus Armbruster606caa02017-02-21 21:14:04 +01004142 sval = cvtnum(optarg);
4143 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004144 error_report("Invalid buffer size specified");
4145 return 1;
4146 }
4147
4148 bufsize = sval;
4149 break;
4150 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004151 case 'S':
4152 {
4153 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004154
Markus Armbruster606caa02017-02-21 21:14:04 +01004155 sval = cvtnum(optarg);
4156 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004157 error_report("Invalid step size specified");
4158 return 1;
4159 }
4160
4161 step = sval;
4162 break;
4163 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004164 case 't':
4165 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4166 if (ret < 0) {
4167 error_report("Invalid cache mode");
4168 ret = -1;
4169 goto out;
4170 }
4171 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004172 case 'w':
4173 flags |= BDRV_O_RDWR;
4174 is_write = true;
4175 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004176 case 'U':
4177 force_share = true;
4178 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004179 case OPTION_PATTERN:
4180 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004181 unsigned long res;
4182
4183 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004184 error_report("Invalid pattern byte specified");
4185 return 1;
4186 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004187 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004188 break;
4189 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004190 case OPTION_FLUSH_INTERVAL:
4191 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004192 unsigned long res;
4193
4194 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004195 error_report("Invalid flush interval specified");
4196 return 1;
4197 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004198 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004199 break;
4200 }
4201 case OPTION_NO_DRAIN:
4202 drain_on_flush = false;
4203 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004204 case OPTION_IMAGE_OPTS:
4205 image_opts = true;
4206 break;
4207 }
4208 }
4209
4210 if (optind != argc - 1) {
4211 error_exit("Expecting one image file name");
4212 }
4213 filename = argv[argc - 1];
4214
Kevin Wolf55d539c2016-06-03 13:59:41 +02004215 if (!is_write && flush_interval) {
4216 error_report("--flush-interval is only available in write tests");
4217 ret = -1;
4218 goto out;
4219 }
4220 if (flush_interval && flush_interval < depth) {
4221 error_report("Flush interval can't be smaller than depth");
4222 ret = -1;
4223 goto out;
4224 }
4225
Fam Zheng335e9932017-05-03 00:35:39 +08004226 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4227 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004228 if (!blk) {
4229 ret = -1;
4230 goto out;
4231 }
4232
4233 image_size = blk_getlength(blk);
4234 if (image_size < 0) {
4235 ret = image_size;
4236 goto out;
4237 }
4238
4239 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004240 .blk = blk,
4241 .image_size = image_size,
4242 .bufsize = bufsize,
4243 .step = step ?: bufsize,
4244 .nrreq = depth,
4245 .n = count,
4246 .offset = offset,
4247 .write = is_write,
4248 .flush_interval = flush_interval,
4249 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004250 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004251 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004252 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004253 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004254 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004255 if (flush_interval) {
4256 printf("Sending flush every %d requests\n", flush_interval);
4257 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004258
Fam Zheng79d46582018-01-16 14:08:58 +08004259 buf_size = data.nrreq * data.bufsize;
4260 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004261 memset(data.buf, pattern, data.nrreq * data.bufsize);
4262
Fam Zheng79d46582018-01-16 14:08:58 +08004263 blk_register_buf(blk, data.buf, buf_size);
4264
Kevin Wolfb6133b82014-08-05 14:17:13 +02004265 data.qiov = g_new(QEMUIOVector, data.nrreq);
4266 for (i = 0; i < data.nrreq; i++) {
4267 qemu_iovec_init(&data.qiov[i], 1);
4268 qemu_iovec_add(&data.qiov[i],
4269 data.buf + i * data.bufsize, data.bufsize);
4270 }
4271
4272 gettimeofday(&t1, NULL);
4273 bench_cb(&data, 0);
4274
4275 while (data.n > 0) {
4276 main_loop_wait(false);
4277 }
4278 gettimeofday(&t2, NULL);
4279
4280 printf("Run completed in %3.3f seconds.\n",
4281 (t2.tv_sec - t1.tv_sec)
4282 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4283
4284out:
Fam Zheng79d46582018-01-16 14:08:58 +08004285 if (data.buf) {
4286 blk_unregister_buf(blk, data.buf);
4287 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004288 qemu_vfree(data.buf);
4289 blk_unref(blk);
4290
4291 if (ret) {
4292 return 1;
4293 }
4294 return 0;
4295}
4296
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004297#define C_BS 01
4298#define C_COUNT 02
4299#define C_IF 04
4300#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004301#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004302
4303struct DdInfo {
4304 unsigned int flags;
4305 int64_t count;
4306};
4307
4308struct DdIo {
4309 int bsz; /* Block size */
4310 char *filename;
4311 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004312 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004313};
4314
4315struct DdOpts {
4316 const char *name;
4317 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4318 unsigned int flag;
4319};
4320
4321static int img_dd_bs(const char *arg,
4322 struct DdIo *in, struct DdIo *out,
4323 struct DdInfo *dd)
4324{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004325 int64_t res;
4326
Markus Armbruster606caa02017-02-21 21:14:04 +01004327 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004328
Markus Armbruster606caa02017-02-21 21:14:04 +01004329 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004330 error_report("invalid number: '%s'", arg);
4331 return 1;
4332 }
4333 in->bsz = out->bsz = res;
4334
4335 return 0;
4336}
4337
4338static int img_dd_count(const char *arg,
4339 struct DdIo *in, struct DdIo *out,
4340 struct DdInfo *dd)
4341{
Markus Armbruster606caa02017-02-21 21:14:04 +01004342 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004343
Markus Armbruster606caa02017-02-21 21:14:04 +01004344 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004345 error_report("invalid number: '%s'", arg);
4346 return 1;
4347 }
4348
4349 return 0;
4350}
4351
4352static int img_dd_if(const char *arg,
4353 struct DdIo *in, struct DdIo *out,
4354 struct DdInfo *dd)
4355{
4356 in->filename = g_strdup(arg);
4357
4358 return 0;
4359}
4360
4361static int img_dd_of(const char *arg,
4362 struct DdIo *in, struct DdIo *out,
4363 struct DdInfo *dd)
4364{
4365 out->filename = g_strdup(arg);
4366
4367 return 0;
4368}
4369
Reda Sallahif7c15532016-08-10 16:16:09 +02004370static int img_dd_skip(const char *arg,
4371 struct DdIo *in, struct DdIo *out,
4372 struct DdInfo *dd)
4373{
Markus Armbruster606caa02017-02-21 21:14:04 +01004374 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004375
Markus Armbruster606caa02017-02-21 21:14:04 +01004376 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004377 error_report("invalid number: '%s'", arg);
4378 return 1;
4379 }
4380
4381 return 0;
4382}
4383
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004384static int img_dd(int argc, char **argv)
4385{
4386 int ret = 0;
4387 char *arg = NULL;
4388 char *tmp;
4389 BlockDriver *drv = NULL, *proto_drv = NULL;
4390 BlockBackend *blk1 = NULL, *blk2 = NULL;
4391 QemuOpts *opts = NULL;
4392 QemuOptsList *create_opts = NULL;
4393 Error *local_err = NULL;
4394 bool image_opts = false;
4395 int c, i;
4396 const char *out_fmt = "raw";
4397 const char *fmt = NULL;
4398 int64_t size = 0;
4399 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004400 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004401 struct DdInfo dd = {
4402 .flags = 0,
4403 .count = 0,
4404 };
4405 struct DdIo in = {
4406 .bsz = 512, /* Block size is by default 512 bytes */
4407 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004408 .buf = NULL,
4409 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004410 };
4411 struct DdIo out = {
4412 .bsz = 512,
4413 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004414 .buf = NULL,
4415 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004416 };
4417
4418 const struct DdOpts options[] = {
4419 { "bs", img_dd_bs, C_BS },
4420 { "count", img_dd_count, C_COUNT },
4421 { "if", img_dd_if, C_IF },
4422 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004423 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004424 { NULL, NULL, 0 }
4425 };
4426 const struct option long_options[] = {
4427 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004428 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004429 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004430 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004431 { 0, 0, 0, 0 }
4432 };
4433
Fam Zheng335e9932017-05-03 00:35:39 +08004434 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004435 if (c == EOF) {
4436 break;
4437 }
4438 switch (c) {
4439 case 'O':
4440 out_fmt = optarg;
4441 break;
4442 case 'f':
4443 fmt = optarg;
4444 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004445 case ':':
4446 missing_argument(argv[optind - 1]);
4447 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004448 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004449 unrecognized_option(argv[optind - 1]);
4450 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004451 case 'h':
4452 help();
4453 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004454 case 'U':
4455 force_share = true;
4456 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004457 case OPTION_OBJECT:
4458 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004459 ret = -1;
4460 goto out;
4461 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004462 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004463 case OPTION_IMAGE_OPTS:
4464 image_opts = true;
4465 break;
4466 }
4467 }
4468
4469 for (i = optind; i < argc; i++) {
4470 int j;
4471 arg = g_strdup(argv[i]);
4472
4473 tmp = strchr(arg, '=');
4474 if (tmp == NULL) {
4475 error_report("unrecognized operand %s", arg);
4476 ret = -1;
4477 goto out;
4478 }
4479
4480 *tmp++ = '\0';
4481
4482 for (j = 0; options[j].name != NULL; j++) {
4483 if (!strcmp(arg, options[j].name)) {
4484 break;
4485 }
4486 }
4487 if (options[j].name == NULL) {
4488 error_report("unrecognized operand %s", arg);
4489 ret = -1;
4490 goto out;
4491 }
4492
4493 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4494 ret = -1;
4495 goto out;
4496 }
4497 dd.flags |= options[j].flag;
4498 g_free(arg);
4499 arg = NULL;
4500 }
4501
4502 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4503 error_report("Must specify both input and output files");
4504 ret = -1;
4505 goto out;
4506 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004507
4508 if (qemu_opts_foreach(&qemu_object_opts,
4509 user_creatable_add_opts_foreach,
4510 NULL, NULL)) {
4511 ret = -1;
4512 goto out;
4513 }
4514
Fam Zheng335e9932017-05-03 00:35:39 +08004515 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4516 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004517
4518 if (!blk1) {
4519 ret = -1;
4520 goto out;
4521 }
4522
4523 drv = bdrv_find_format(out_fmt);
4524 if (!drv) {
4525 error_report("Unknown file format");
4526 ret = -1;
4527 goto out;
4528 }
4529 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4530
4531 if (!proto_drv) {
4532 error_report_err(local_err);
4533 ret = -1;
4534 goto out;
4535 }
4536 if (!drv->create_opts) {
4537 error_report("Format driver '%s' does not support image creation",
4538 drv->format_name);
4539 ret = -1;
4540 goto out;
4541 }
4542 if (!proto_drv->create_opts) {
4543 error_report("Protocol driver '%s' does not support image creation",
4544 proto_drv->format_name);
4545 ret = -1;
4546 goto out;
4547 }
4548 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4549 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4550
4551 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4552
4553 size = blk_getlength(blk1);
4554 if (size < 0) {
4555 error_report("Failed to get size for '%s'", in.filename);
4556 ret = -1;
4557 goto out;
4558 }
4559
4560 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4561 dd.count * in.bsz < size) {
4562 size = dd.count * in.bsz;
4563 }
4564
Reda Sallahif7c15532016-08-10 16:16:09 +02004565 /* Overflow means the specified offset is beyond input image's size */
4566 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4567 size < in.bsz * in.offset)) {
4568 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4569 } else {
4570 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4571 size - in.bsz * in.offset, &error_abort);
4572 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004573
4574 ret = bdrv_create(drv, out.filename, opts, &local_err);
4575 if (ret < 0) {
4576 error_reportf_err(local_err,
4577 "%s: error while creating output image: ",
4578 out.filename);
4579 ret = -1;
4580 goto out;
4581 }
4582
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004583 /* TODO, we can't honour --image-opts for the target,
4584 * since it needs to be given in a format compatible
4585 * with the bdrv_create() call above which does not
4586 * support image-opts style.
4587 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004588 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004589 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004590
4591 if (!blk2) {
4592 ret = -1;
4593 goto out;
4594 }
4595
Reda Sallahif7c15532016-08-10 16:16:09 +02004596 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4597 size < in.offset * in.bsz)) {
4598 /* We give a warning if the skip option is bigger than the input
4599 * size and create an empty output disk image (i.e. like dd(1)).
4600 */
4601 error_report("%s: cannot skip to specified offset", in.filename);
4602 in_pos = size;
4603 } else {
4604 in_pos = in.offset * in.bsz;
4605 }
4606
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004607 in.buf = g_new(uint8_t, in.bsz);
4608
Reda Sallahif7c15532016-08-10 16:16:09 +02004609 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004610 int in_ret, out_ret;
4611
4612 if (in_pos + in.bsz > size) {
4613 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4614 } else {
4615 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4616 }
4617 if (in_ret < 0) {
4618 error_report("error while reading from input image file: %s",
4619 strerror(-in_ret));
4620 ret = -1;
4621 goto out;
4622 }
4623 in_pos += in_ret;
4624
4625 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4626
4627 if (out_ret < 0) {
4628 error_report("error while writing to output image file: %s",
4629 strerror(-out_ret));
4630 ret = -1;
4631 goto out;
4632 }
4633 out_pos += out_ret;
4634 }
4635
4636out:
4637 g_free(arg);
4638 qemu_opts_del(opts);
4639 qemu_opts_free(create_opts);
4640 blk_unref(blk1);
4641 blk_unref(blk2);
4642 g_free(in.filename);
4643 g_free(out.filename);
4644 g_free(in.buf);
4645 g_free(out.buf);
4646
4647 if (ret) {
4648 return 1;
4649 }
4650 return 0;
4651}
4652
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004653static void dump_json_block_measure_info(BlockMeasureInfo *info)
4654{
4655 QString *str;
4656 QObject *obj;
4657 Visitor *v = qobject_output_visitor_new(&obj);
4658
4659 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4660 visit_complete(v, &obj);
4661 str = qobject_to_json_pretty(obj);
4662 assert(str != NULL);
4663 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004664 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004665 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004666 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004667}
4668
4669static int img_measure(int argc, char **argv)
4670{
4671 static const struct option long_options[] = {
4672 {"help", no_argument, 0, 'h'},
4673 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4674 {"object", required_argument, 0, OPTION_OBJECT},
4675 {"output", required_argument, 0, OPTION_OUTPUT},
4676 {"size", required_argument, 0, OPTION_SIZE},
4677 {"force-share", no_argument, 0, 'U'},
4678 {0, 0, 0, 0}
4679 };
4680 OutputFormat output_format = OFORMAT_HUMAN;
4681 BlockBackend *in_blk = NULL;
4682 BlockDriver *drv;
4683 const char *filename = NULL;
4684 const char *fmt = NULL;
4685 const char *out_fmt = "raw";
4686 char *options = NULL;
4687 char *snapshot_name = NULL;
4688 bool force_share = false;
4689 QemuOpts *opts = NULL;
4690 QemuOpts *object_opts = NULL;
4691 QemuOpts *sn_opts = NULL;
4692 QemuOptsList *create_opts = NULL;
4693 bool image_opts = false;
4694 uint64_t img_size = UINT64_MAX;
4695 BlockMeasureInfo *info = NULL;
4696 Error *local_err = NULL;
4697 int ret = 1;
4698 int c;
4699
4700 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4701 long_options, NULL)) != -1) {
4702 switch (c) {
4703 case '?':
4704 case 'h':
4705 help();
4706 break;
4707 case 'f':
4708 fmt = optarg;
4709 break;
4710 case 'O':
4711 out_fmt = optarg;
4712 break;
4713 case 'o':
4714 if (!is_valid_option_list(optarg)) {
4715 error_report("Invalid option list: %s", optarg);
4716 goto out;
4717 }
4718 if (!options) {
4719 options = g_strdup(optarg);
4720 } else {
4721 char *old_options = options;
4722 options = g_strdup_printf("%s,%s", options, optarg);
4723 g_free(old_options);
4724 }
4725 break;
4726 case 'l':
4727 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4728 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4729 optarg, false);
4730 if (!sn_opts) {
4731 error_report("Failed in parsing snapshot param '%s'",
4732 optarg);
4733 goto out;
4734 }
4735 } else {
4736 snapshot_name = optarg;
4737 }
4738 break;
4739 case 'U':
4740 force_share = true;
4741 break;
4742 case OPTION_OBJECT:
4743 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4744 optarg, true);
4745 if (!object_opts) {
4746 goto out;
4747 }
4748 break;
4749 case OPTION_IMAGE_OPTS:
4750 image_opts = true;
4751 break;
4752 case OPTION_OUTPUT:
4753 if (!strcmp(optarg, "json")) {
4754 output_format = OFORMAT_JSON;
4755 } else if (!strcmp(optarg, "human")) {
4756 output_format = OFORMAT_HUMAN;
4757 } else {
4758 error_report("--output must be used with human or json "
4759 "as argument.");
4760 goto out;
4761 }
4762 break;
4763 case OPTION_SIZE:
4764 {
4765 int64_t sval;
4766
4767 sval = cvtnum(optarg);
4768 if (sval < 0) {
4769 if (sval == -ERANGE) {
4770 error_report("Image size must be less than 8 EiB!");
4771 } else {
4772 error_report("Invalid image size specified! You may use "
4773 "k, M, G, T, P or E suffixes for ");
4774 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4775 "petabytes and exabytes.");
4776 }
4777 goto out;
4778 }
4779 img_size = (uint64_t)sval;
4780 }
4781 break;
4782 }
4783 }
4784
4785 if (qemu_opts_foreach(&qemu_object_opts,
4786 user_creatable_add_opts_foreach,
4787 NULL, NULL)) {
4788 goto out;
4789 }
4790
4791 if (argc - optind > 1) {
4792 error_report("At most one filename argument is allowed.");
4793 goto out;
4794 } else if (argc - optind == 1) {
4795 filename = argv[optind];
4796 }
4797
4798 if (!filename &&
4799 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4800 error_report("--object, --image-opts, -f, and -l "
4801 "require a filename argument.");
4802 goto out;
4803 }
4804 if (filename && img_size != UINT64_MAX) {
4805 error_report("--size N cannot be used together with a filename.");
4806 goto out;
4807 }
4808 if (!filename && img_size == UINT64_MAX) {
4809 error_report("Either --size N or one filename must be specified.");
4810 goto out;
4811 }
4812
4813 if (filename) {
4814 in_blk = img_open(image_opts, filename, fmt, 0,
4815 false, false, force_share);
4816 if (!in_blk) {
4817 goto out;
4818 }
4819
4820 if (sn_opts) {
4821 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4822 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4823 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4824 &local_err);
4825 } else if (snapshot_name != NULL) {
4826 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4827 snapshot_name, &local_err);
4828 }
4829 if (local_err) {
4830 error_reportf_err(local_err, "Failed to load snapshot: ");
4831 goto out;
4832 }
4833 }
4834
4835 drv = bdrv_find_format(out_fmt);
4836 if (!drv) {
4837 error_report("Unknown file format '%s'", out_fmt);
4838 goto out;
4839 }
4840 if (!drv->create_opts) {
4841 error_report("Format driver '%s' does not support image creation",
4842 drv->format_name);
4843 goto out;
4844 }
4845
4846 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4847 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4848 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4849 if (options) {
4850 qemu_opts_do_parse(opts, options, NULL, &local_err);
4851 if (local_err) {
4852 error_report_err(local_err);
4853 error_report("Invalid options for file format '%s'", out_fmt);
4854 goto out;
4855 }
4856 }
4857 if (img_size != UINT64_MAX) {
4858 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4859 }
4860
4861 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4862 if (local_err) {
4863 error_report_err(local_err);
4864 goto out;
4865 }
4866
4867 if (output_format == OFORMAT_HUMAN) {
4868 printf("required size: %" PRIu64 "\n", info->required);
4869 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4870 } else {
4871 dump_json_block_measure_info(info);
4872 }
4873
4874 ret = 0;
4875
4876out:
4877 qapi_free_BlockMeasureInfo(info);
4878 qemu_opts_del(object_opts);
4879 qemu_opts_del(opts);
4880 qemu_opts_del(sn_opts);
4881 qemu_opts_free(create_opts);
4882 g_free(options);
4883 blk_unref(in_blk);
4884 return ret;
4885}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004886
Anthony Liguoric227f092009-10-01 16:12:16 -05004887static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004888#define DEF(option, callback, arg_string) \
4889 { option, callback },
4890#include "qemu-img-cmds.h"
4891#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004892 { NULL, NULL, },
4893};
4894
bellardea2384d2004-08-01 21:59:26 +00004895int main(int argc, char **argv)
4896{
Anthony Liguoric227f092009-10-01 16:12:16 -05004897 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004898 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004899 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004900 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004901 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004902 static const struct option long_options[] = {
4903 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004904 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004905 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004906 {0, 0, 0, 0}
4907 };
bellardea2384d2004-08-01 21:59:26 +00004908
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004909#ifdef CONFIG_POSIX
4910 signal(SIGPIPE, SIG_IGN);
4911#endif
4912
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004913 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004914 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004915 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004916
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004917 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004918 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004919 exit(EXIT_FAILURE);
4920 }
4921
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004922 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004923
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004924 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004925 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004926 if (argc < 2) {
4927 error_exit("Not enough arguments");
4928 }
Stuart Brady153859b2009-06-07 00:42:17 +01004929
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004930 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004931 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004932 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004933
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004934 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004935 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004936 case ':':
4937 missing_argument(argv[optind - 1]);
4938 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004939 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004940 unrecognized_option(argv[optind - 1]);
4941 return 0;
4942 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004943 help();
4944 return 0;
4945 case 'V':
4946 printf(QEMU_IMG_VERSION);
4947 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004948 case 'T':
4949 g_free(trace_file);
4950 trace_file = trace_opt_parse(optarg);
4951 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004952 }
bellardea2384d2004-08-01 21:59:26 +00004953 }
Stuart Brady153859b2009-06-07 00:42:17 +01004954
Denis V. Lunev10985132016-06-17 17:44:13 +03004955 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004956
Denis V. Lunev10985132016-06-17 17:44:13 +03004957 /* reset getopt_long scanning */
4958 argc -= optind;
4959 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004960 return 0;
4961 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004962 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004963 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004964
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004965 if (!trace_init_backends()) {
4966 exit(1);
4967 }
4968 trace_init_file(trace_file);
4969 qemu_set_log(LOG_TRACE);
4970
Denis V. Lunev10985132016-06-17 17:44:13 +03004971 /* find the command */
4972 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4973 if (!strcmp(cmdname, cmd->name)) {
4974 return cmd->handler(argc, argv);
4975 }
4976 }
Jeff Cody7db16892014-04-25 17:02:32 -04004977
Stuart Brady153859b2009-06-07 00:42:17 +01004978 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004979 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004980}