blob: 9b7506b8aec982fd3702f353520de7f65e25650d [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
348static BlockBackend *img_open_new_file(const char *filename,
349 QemuOpts *create_opts,
350 const char *fmt, int flags,
351 bool writethrough, bool quiet,
352 bool force_share)
353{
354 QDict *options = NULL;
355
356 options = qdict_new();
357 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
358
359 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
360 force_share);
361}
362
363
Max Reitzefaa7c42016-03-16 19:54:38 +0100364static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000365 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100366 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800367 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000368{
369 BlockBackend *blk;
370 if (image_opts) {
371 QemuOpts *opts;
372 if (fmt) {
373 error_report("--image-opts and --format are mutually exclusive");
374 return NULL;
375 }
376 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
377 filename, true);
378 if (!opts) {
379 return NULL;
380 }
Fam Zheng335e9932017-05-03 00:35:39 +0800381 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
382 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000383 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100384 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800385 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000386 }
387 return blk;
388}
389
390
Chunyan Liu83d05212014-06-05 17:20:51 +0800391static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100392 const char *base_filename,
393 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200394{
Markus Armbruster6750e792015-02-12 17:43:08 +0100395 Error *err = NULL;
396
Kevin Wolfefa84d42009-05-18 16:42:12 +0200397 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100398 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100399 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100400 error_report("Backing file not supported for file format '%s'",
401 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100402 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900403 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200404 }
405 }
406 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100407 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100408 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100409 error_report("Backing file format not supported for file "
410 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100411 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900412 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200413 }
414 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900415 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200416}
417
Markus Armbruster606caa02017-02-21 21:14:04 +0100418static int64_t cvtnum(const char *s)
419{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100420 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100421 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100422
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100423 err = qemu_strtosz(s, NULL, &value);
424 if (err < 0) {
425 return err;
426 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100427 if (value > INT64_MAX) {
428 return -ERANGE;
429 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100430 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100431}
432
bellardea2384d2004-08-01 21:59:26 +0000433static int img_create(int argc, char **argv)
434{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200435 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100436 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000437 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000438 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000439 const char *filename;
440 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200441 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200442 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100443 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400444 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000445
bellardea2384d2004-08-01 21:59:26 +0000446 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000447 static const struct option long_options[] = {
448 {"help", no_argument, 0, 'h'},
449 {"object", required_argument, 0, OPTION_OBJECT},
450 {0, 0, 0, 0}
451 };
John Snow6e6e55f2017-07-17 20:34:22 -0400452 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000453 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100454 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000455 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100456 }
bellardea2384d2004-08-01 21:59:26 +0000457 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800458 case ':':
459 missing_argument(argv[optind - 1]);
460 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100461 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800462 unrecognized_option(argv[optind - 1]);
463 break;
bellardea2384d2004-08-01 21:59:26 +0000464 case 'h':
465 help();
466 break;
aliguori9230eaf2009-03-28 17:55:19 +0000467 case 'F':
468 base_fmt = optarg;
469 break;
bellardea2384d2004-08-01 21:59:26 +0000470 case 'b':
471 base_filename = optarg;
472 break;
473 case 'f':
474 fmt = optarg;
475 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200476 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100477 if (!is_valid_option_list(optarg)) {
478 error_report("Invalid option list: %s", optarg);
479 goto fail;
480 }
481 if (!options) {
482 options = g_strdup(optarg);
483 } else {
484 char *old_options = options;
485 options = g_strdup_printf("%s,%s", options, optarg);
486 g_free(old_options);
487 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200488 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100489 case 'q':
490 quiet = true;
491 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400492 case 'u':
493 flags |= BDRV_O_NO_BACKING;
494 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000495 case OPTION_OBJECT: {
496 QemuOpts *opts;
497 opts = qemu_opts_parse_noisily(&qemu_object_opts,
498 optarg, true);
499 if (!opts) {
500 goto fail;
501 }
502 } break;
bellardea2384d2004-08-01 21:59:26 +0000503 }
504 }
aliguori9230eaf2009-03-28 17:55:19 +0000505
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900506 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100507 filename = (optind < argc) ? argv[optind] : NULL;
508 if (options && has_help_option(options)) {
509 g_free(options);
510 return print_block_option_help(filename, fmt);
511 }
512
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100513 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800514 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100515 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100516 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900517
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000518 if (qemu_opts_foreach(&qemu_object_opts,
519 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200520 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000521 goto fail;
522 }
523
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100524 /* Get image size, if specified */
525 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100526 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100527
528 sval = cvtnum(argv[optind++]);
529 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800530 if (sval == -ERANGE) {
531 error_report("Image size must be less than 8 EiB!");
532 } else {
533 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200534 "G, T, P or E suffixes for ");
535 error_report("kilobytes, megabytes, gigabytes, terabytes, "
536 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800537 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100538 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100539 }
540 img_size = (uint64_t)sval;
541 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200542 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800543 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200544 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100545
Luiz Capitulino9b375252012-11-30 10:52:05 -0200546 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400547 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100548 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100549 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100550 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900551 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200552
Kevin Wolf77386bf2014-02-21 16:24:04 +0100553 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000554 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100555
556fail:
557 g_free(options);
558 return 1;
bellardea2384d2004-08-01 21:59:26 +0000559}
560
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100561static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500562{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500563 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500564 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100565 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600566
567 visit_type_ImageCheck(v, NULL, &check, &error_abort);
568 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500569 str = qobject_to_json_pretty(obj);
570 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100571 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200572 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600573 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200574 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500575}
576
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100577static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500578{
579 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100580 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500581 } else {
582 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100583 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
584 "Data may be corrupted, or further writes to the image "
585 "may corrupt it.\n",
586 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500587 }
588
589 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100590 qprintf(quiet,
591 "\n%" PRId64 " leaked clusters were found on the image.\n"
592 "This means waste of disk space, but no harm to data.\n",
593 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500594 }
595
596 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100597 qprintf(quiet,
598 "\n%" PRId64
599 " internal errors have occurred during the check.\n",
600 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500601 }
602 }
603
604 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100605 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
606 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
607 check->allocated_clusters, check->total_clusters,
608 check->allocated_clusters * 100.0 / check->total_clusters,
609 check->fragmented_clusters * 100.0 / check->allocated_clusters,
610 check->compressed_clusters * 100.0 /
611 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500612 }
613
614 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100615 qprintf(quiet,
616 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500617 }
618}
619
620static int collect_image_check(BlockDriverState *bs,
621 ImageCheck *check,
622 const char *filename,
623 const char *fmt,
624 int fix)
625{
626 int ret;
627 BdrvCheckResult result;
628
629 ret = bdrv_check(bs, &result, fix);
630 if (ret < 0) {
631 return ret;
632 }
633
634 check->filename = g_strdup(filename);
635 check->format = g_strdup(bdrv_get_format_name(bs));
636 check->check_errors = result.check_errors;
637 check->corruptions = result.corruptions;
638 check->has_corruptions = result.corruptions != 0;
639 check->leaks = result.leaks;
640 check->has_leaks = result.leaks != 0;
641 check->corruptions_fixed = result.corruptions_fixed;
642 check->has_corruptions_fixed = result.corruptions != 0;
643 check->leaks_fixed = result.leaks_fixed;
644 check->has_leaks_fixed = result.leaks != 0;
645 check->image_end_offset = result.image_end_offset;
646 check->has_image_end_offset = result.image_end_offset != 0;
647 check->total_clusters = result.bfi.total_clusters;
648 check->has_total_clusters = result.bfi.total_clusters != 0;
649 check->allocated_clusters = result.bfi.allocated_clusters;
650 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
651 check->fragmented_clusters = result.bfi.fragmented_clusters;
652 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100653 check->compressed_clusters = result.bfi.compressed_clusters;
654 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500655
656 return 0;
657}
658
Kevin Wolfe076f332010-06-29 11:43:13 +0200659/*
660 * Checks an image for consistency. Exit codes:
661 *
Max Reitzd6635c42014-06-02 22:15:21 +0200662 * 0 - Check completed, image is good
663 * 1 - Check not completed because of internal errors
664 * 2 - Check completed, image is corrupted
665 * 3 - Check completed, image has leaked clusters, but is good otherwise
666 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200667 */
aliguori15859692009-04-21 23:11:53 +0000668static int img_check(int argc, char **argv)
669{
670 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500671 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200672 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200673 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000674 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200675 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100676 int flags = BDRV_O_CHECK;
677 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200678 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100679 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000680 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800681 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000682
683 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200685 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100686
aliguori15859692009-04-21 23:11:53 +0000687 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500688 int option_index = 0;
689 static const struct option long_options[] = {
690 {"help", no_argument, 0, 'h'},
691 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530692 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500693 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000694 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000695 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800696 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500697 {0, 0, 0, 0}
698 };
Fam Zheng335e9932017-05-03 00:35:39 +0800699 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500700 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100701 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000702 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100703 }
aliguori15859692009-04-21 23:11:53 +0000704 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800705 case ':':
706 missing_argument(argv[optind - 1]);
707 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100708 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800709 unrecognized_option(argv[optind - 1]);
710 break;
aliguori15859692009-04-21 23:11:53 +0000711 case 'h':
712 help();
713 break;
714 case 'f':
715 fmt = optarg;
716 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200717 case 'r':
718 flags |= BDRV_O_RDWR;
719
720 if (!strcmp(optarg, "leaks")) {
721 fix = BDRV_FIX_LEAKS;
722 } else if (!strcmp(optarg, "all")) {
723 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
724 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800725 error_exit("Unknown option value for -r "
726 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200727 }
728 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500729 case OPTION_OUTPUT:
730 output = optarg;
731 break;
Max Reitz40055952014-07-22 22:58:42 +0200732 case 'T':
733 cache = optarg;
734 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100735 case 'q':
736 quiet = true;
737 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800738 case 'U':
739 force_share = true;
740 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000741 case OPTION_OBJECT: {
742 QemuOpts *opts;
743 opts = qemu_opts_parse_noisily(&qemu_object_opts,
744 optarg, true);
745 if (!opts) {
746 return 1;
747 }
748 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000749 case OPTION_IMAGE_OPTS:
750 image_opts = true;
751 break;
aliguori15859692009-04-21 23:11:53 +0000752 }
753 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200754 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800755 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100756 }
aliguori15859692009-04-21 23:11:53 +0000757 filename = argv[optind++];
758
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500759 if (output && !strcmp(output, "json")) {
760 output_format = OFORMAT_JSON;
761 } else if (output && !strcmp(output, "human")) {
762 output_format = OFORMAT_HUMAN;
763 } else if (output) {
764 error_report("--output must be used with human or json as argument.");
765 return 1;
766 }
767
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000768 if (qemu_opts_foreach(&qemu_object_opts,
769 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200770 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000771 return 1;
772 }
773
Kevin Wolfce099542016-03-15 13:01:04 +0100774 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200775 if (ret < 0) {
776 error_report("Invalid source cache option: %s", cache);
777 return 1;
778 }
779
Fam Zheng335e9932017-05-03 00:35:39 +0800780 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
781 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200782 if (!blk) {
783 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900784 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200785 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500786
787 check = g_new0(ImageCheck, 1);
788 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200789
790 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200791 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200792 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500793 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200794 }
795
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500796 if (check->corruptions_fixed || check->leaks_fixed) {
797 int corruptions_fixed, leaks_fixed;
798
799 leaks_fixed = check->leaks_fixed;
800 corruptions_fixed = check->corruptions_fixed;
801
802 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100803 qprintf(quiet,
804 "The following inconsistencies were found and repaired:\n\n"
805 " %" PRId64 " leaked clusters\n"
806 " %" PRId64 " corruptions\n\n"
807 "Double checking the fixed image now...\n",
808 check->leaks_fixed,
809 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500810 }
811
812 ret = collect_image_check(bs, check, filename, fmt, 0);
813
814 check->leaks_fixed = leaks_fixed;
815 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200816 }
817
Max Reitz832390a2014-10-23 15:29:12 +0200818 if (!ret) {
819 switch (output_format) {
820 case OFORMAT_HUMAN:
821 dump_human_image_check(check, quiet);
822 break;
823 case OFORMAT_JSON:
824 dump_json_image_check(check, quiet);
825 break;
826 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500827 }
828
829 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200830 if (ret) {
831 error_report("Check failed: %s", strerror(-ret));
832 } else {
833 error_report("Check failed");
834 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500835 ret = 1;
836 goto fail;
837 }
838
839 if (check->corruptions) {
840 ret = 2;
841 } else if (check->leaks) {
842 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200843 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500844 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000845 }
846
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500847fail:
848 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200849 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500850 return ret;
aliguori15859692009-04-21 23:11:53 +0000851}
852
Max Reitzd4a32382014-10-24 15:57:37 +0200853typedef struct CommonBlockJobCBInfo {
854 BlockDriverState *bs;
855 Error **errp;
856} CommonBlockJobCBInfo;
857
858static void common_block_job_cb(void *opaque, int ret)
859{
860 CommonBlockJobCBInfo *cbi = opaque;
861
862 if (ret < 0) {
863 error_setg_errno(cbi->errp, -ret, "Block job failed");
864 }
Max Reitzd4a32382014-10-24 15:57:37 +0200865}
866
867static void run_block_job(BlockJob *job, Error **errp)
868{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200869 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800870 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200871
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200872 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200873 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200874 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200875 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200876 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200877 if (job->job.progress_total) {
878 progress = (float)job->job.progress_current /
879 job->job.progress_total * 100.f;
880 }
881 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200882 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200883
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200884 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200885 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800886 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200887 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800888 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200889 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200890 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200891
sochin.jiang4172a002017-06-15 14:47:33 +0800892 /* publish completion progress only when success */
893 if (!ret) {
894 qemu_progress_print(100.f, 0);
895 }
Max Reitzd4a32382014-10-24 15:57:37 +0200896}
897
bellardea2384d2004-08-01 21:59:26 +0000898static int img_commit(int argc, char **argv)
899{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400900 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200901 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200902 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200903 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100904 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200905 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100906 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200907 Error *local_err = NULL;
908 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000909 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200910 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000911
912 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400913 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200914 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000915 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000916 static const struct option long_options[] = {
917 {"help", no_argument, 0, 'h'},
918 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000919 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000920 {0, 0, 0, 0}
921 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800922 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000923 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100924 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000925 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100926 }
bellardea2384d2004-08-01 21:59:26 +0000927 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800928 case ':':
929 missing_argument(argv[optind - 1]);
930 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100931 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800932 unrecognized_option(argv[optind - 1]);
933 break;
bellardea2384d2004-08-01 21:59:26 +0000934 case 'h':
935 help();
936 break;
937 case 'f':
938 fmt = optarg;
939 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400940 case 't':
941 cache = optarg;
942 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200943 case 'b':
944 base = optarg;
945 /* -b implies -d */
946 drop = true;
947 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200948 case 'd':
949 drop = true;
950 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200951 case 'p':
952 progress = true;
953 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100954 case 'q':
955 quiet = true;
956 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000957 case OPTION_OBJECT: {
958 QemuOpts *opts;
959 opts = qemu_opts_parse_noisily(&qemu_object_opts,
960 optarg, true);
961 if (!opts) {
962 return 1;
963 }
964 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000965 case OPTION_IMAGE_OPTS:
966 image_opts = true;
967 break;
bellardea2384d2004-08-01 21:59:26 +0000968 }
969 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200970
971 /* Progress is not shown in Quiet mode */
972 if (quiet) {
973 progress = false;
974 }
975
Kevin Wolffc11eb22013-08-05 10:53:04 +0200976 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800977 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100978 }
bellardea2384d2004-08-01 21:59:26 +0000979 filename = argv[optind++];
980
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000981 if (qemu_opts_foreach(&qemu_object_opts,
982 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200983 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000984 return 1;
985 }
986
Max Reitz9a86fe42014-10-24 15:57:38 +0200987 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100988 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400989 if (ret < 0) {
990 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100991 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400992 }
993
Fam Zheng335e9932017-05-03 00:35:39 +0800994 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
995 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200996 if (!blk) {
997 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900998 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200999 bs = blk_bs(blk);
1000
Max Reitz687fa1d2014-10-24 15:57:39 +02001001 qemu_progress_init(progress, 1.f);
1002 qemu_progress_print(0.f, 100);
1003
Max Reitz1b22bff2014-10-24 15:57:40 +02001004 if (base) {
1005 base_bs = bdrv_find_backing_image(bs, base);
1006 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001007 error_setg(&local_err,
1008 "Did not find '%s' in the backing chain of '%s'",
1009 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001010 goto done;
1011 }
1012 } else {
1013 /* This is different from QMP, which by default uses the deepest file in
1014 * the backing chain (i.e., the very base); however, the traditional
1015 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001016 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001017 if (!base_bs) {
1018 error_setg(&local_err, "Image does not have a backing file");
1019 goto done;
1020 }
bellardea2384d2004-08-01 21:59:26 +00001021 }
1022
Max Reitzd4a32382014-10-24 15:57:37 +02001023 cbi = (CommonBlockJobCBInfo){
1024 .errp = &local_err,
1025 .bs = bs,
1026 };
1027
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001028 aio_context = bdrv_get_aio_context(bs);
1029 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001030 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001031 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001032 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001033 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001034 if (local_err) {
1035 goto done;
1036 }
1037
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001038 /* When the block job completes, the BlockBackend reference will point to
1039 * the old backing file. In order to avoid that the top image is already
1040 * deleted, so we can still empty it afterwards, increment the reference
1041 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001042 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001043 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001044 }
1045
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001046 job = block_job_get("commit");
1047 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001048 if (local_err) {
1049 goto unref_backing;
1050 }
1051
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001052 if (!drop && bs->drv->bdrv_make_empty) {
1053 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001054 if (ret) {
1055 error_setg_errno(&local_err, -ret, "Could not empty %s",
1056 filename);
1057 goto unref_backing;
1058 }
1059 }
1060
1061unref_backing:
1062 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001063 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001064 }
Max Reitzd4a32382014-10-24 15:57:37 +02001065
1066done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001067 qemu_progress_end();
1068
Markus Armbruster26f54e92014-10-07 13:59:04 +02001069 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001070
1071 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001072 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001073 return 1;
1074 }
Max Reitzd4a32382014-10-24 15:57:37 +02001075
1076 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001077 return 0;
1078}
1079
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001080/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001081 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1082 * of the first sector boundary within buf where the sector contains a
1083 * non-zero byte. This function is robust to a buffer that is not
1084 * sector-aligned.
1085 */
1086static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1087{
1088 int64_t i;
1089 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1090
1091 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1092 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1093 return i;
1094 }
1095 }
1096 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1097 return i;
1098 }
1099 return -1;
1100}
1101
1102/*
thsf58c7b32008-06-05 21:53:49 +00001103 * Returns true iff the first sector pointed to by 'buf' contains at least
1104 * a non-NUL byte.
1105 *
1106 * 'pnum' is set to the number of sectors (including and immediately following
1107 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001108 * The function will try to align the end offset to alignment boundaries so
1109 * that the request will at least end aligned and consequtive requests will
1110 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001111 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001112static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1113 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001114{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001115 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001116 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001117
1118 if (n <= 0) {
1119 *pnum = 0;
1120 return 0;
1121 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001122 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001123 for(i = 1; i < n; i++) {
1124 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001125 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001126 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001127 }
bellardea2384d2004-08-01 21:59:26 +00001128 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001129
1130 tail = (sector_num + i) & (alignment - 1);
1131 if (tail) {
1132 if (is_zero && i <= tail) {
1133 /* treat unallocated areas which only consist
1134 * of a small tail as allocated. */
1135 is_zero = false;
1136 }
1137 if (!is_zero) {
1138 /* align up end offset of allocated areas. */
1139 i += alignment - tail;
1140 i = MIN(i, n);
1141 } else {
1142 /* align down end offset of zero areas. */
1143 i -= tail;
1144 }
1145 }
bellardea2384d2004-08-01 21:59:26 +00001146 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001147 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001148}
1149
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001150/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001151 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1152 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1153 * breaking up write requests for only small sparse areas.
1154 */
1155static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001156 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001157{
1158 int ret;
1159 int num_checked, num_used;
1160
1161 if (n < min) {
1162 min = n;
1163 }
1164
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001165 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001166 if (!ret) {
1167 return ret;
1168 }
1169
1170 num_used = *pnum;
1171 buf += BDRV_SECTOR_SIZE * *pnum;
1172 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001173 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001174 num_checked = num_used;
1175
1176 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001177 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001178
1179 buf += BDRV_SECTOR_SIZE * *pnum;
1180 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001181 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001182 num_checked += *pnum;
1183 if (ret) {
1184 num_used = num_checked;
1185 } else if (*pnum >= min) {
1186 break;
1187 }
1188 }
1189
1190 *pnum = num_used;
1191 return 1;
1192}
1193
1194/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001195 * Compares two buffers sector by sector. Returns 0 if the first
1196 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001197 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001198 * pnum is set to the sector-aligned size of the buffer prefix that
1199 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001200 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001201static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1202 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001203{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001204 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001205 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001206
Eric Blakedc61cd32017-10-11 22:47:14 -05001207 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001208
Eric Blakedc61cd32017-10-11 22:47:14 -05001209 res = !!memcmp(buf1, buf2, i);
1210 while (i < bytes) {
1211 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001212
Eric Blakedc61cd32017-10-11 22:47:14 -05001213 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001214 break;
1215 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001216 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001217 }
1218
1219 *pnum = i;
1220 return res;
1221}
1222
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001223#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001224
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001225/*
1226 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1227 *
Eric Blake0608e402017-10-11 22:47:12 -05001228 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1229 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1230 * failure), and 4 on error (the exit status for read errors), after emitting
1231 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001232 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001233 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001234 * @param offset: Starting offset to check
1235 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001236 * @param filename: Name of disk file we are checking (logging purpose)
1237 * @param buffer: Allocated buffer for storing read data
1238 * @param quiet: Flag for quiet mode
1239 */
Eric Blakec41508e2017-10-11 22:47:13 -05001240static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1241 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001242 uint8_t *buffer, bool quiet)
1243{
Eric Blakedebb38a2017-10-11 22:47:11 -05001244 int ret = 0;
1245 int64_t idx;
1246
Eric Blakec41508e2017-10-11 22:47:13 -05001247 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001248 if (ret < 0) {
1249 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001250 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001251 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001252 }
Eric Blakec41508e2017-10-11 22:47:13 -05001253 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001254 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001255 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001256 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001257 return 1;
1258 }
1259
1260 return 0;
1261}
1262
1263/*
1264 * Compares two images. Exit codes:
1265 *
1266 * 0 - Images are identical
1267 * 1 - Images differ
1268 * >1 - Error occurred
1269 */
1270static int img_compare(int argc, char **argv)
1271{
Max Reitz40055952014-07-22 22:58:42 +02001272 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001273 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001274 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001275 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001276 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001277 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001278 int allocated1, allocated2;
1279 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1280 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001281 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001282 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001283 int64_t total_size;
1284 int64_t offset = 0;
1285 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001286 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001288 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001289 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001290
Max Reitz40055952014-07-22 22:58:42 +02001291 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001292 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001293 static const struct option long_options[] = {
1294 {"help", no_argument, 0, 'h'},
1295 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001296 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001297 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001298 {0, 0, 0, 0}
1299 };
Fam Zheng335e9932017-05-03 00:35:39 +08001300 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001301 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001302 if (c == -1) {
1303 break;
1304 }
1305 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001306 case ':':
1307 missing_argument(argv[optind - 1]);
1308 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001309 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001310 unrecognized_option(argv[optind - 1]);
1311 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001312 case 'h':
1313 help();
1314 break;
1315 case 'f':
1316 fmt1 = optarg;
1317 break;
1318 case 'F':
1319 fmt2 = optarg;
1320 break;
Max Reitz40055952014-07-22 22:58:42 +02001321 case 'T':
1322 cache = optarg;
1323 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001324 case 'p':
1325 progress = true;
1326 break;
1327 case 'q':
1328 quiet = true;
1329 break;
1330 case 's':
1331 strict = true;
1332 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001333 case 'U':
1334 force_share = true;
1335 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001336 case OPTION_OBJECT: {
1337 QemuOpts *opts;
1338 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1339 optarg, true);
1340 if (!opts) {
1341 ret = 2;
1342 goto out4;
1343 }
1344 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001345 case OPTION_IMAGE_OPTS:
1346 image_opts = true;
1347 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001348 }
1349 }
1350
1351 /* Progress is not shown in Quiet mode */
1352 if (quiet) {
1353 progress = false;
1354 }
1355
1356
Kevin Wolffc11eb22013-08-05 10:53:04 +02001357 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001358 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001359 }
1360 filename1 = argv[optind++];
1361 filename2 = argv[optind++];
1362
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001363 if (qemu_opts_foreach(&qemu_object_opts,
1364 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001365 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001366 ret = 2;
1367 goto out4;
1368 }
1369
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001370 /* Initialize before goto out */
1371 qemu_progress_init(progress, 2.0);
1372
Kevin Wolfce099542016-03-15 13:01:04 +01001373 flags = 0;
1374 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001375 if (ret < 0) {
1376 error_report("Invalid source cache option: %s", cache);
1377 ret = 2;
1378 goto out3;
1379 }
1380
Fam Zheng335e9932017-05-03 00:35:39 +08001381 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1382 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001383 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001384 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001385 goto out3;
1386 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001387
Fam Zheng335e9932017-05-03 00:35:39 +08001388 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1389 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001390 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001391 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001392 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001393 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001394 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001395 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001396
Max Reitzf1d3cd72015-02-05 13:58:18 -05001397 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1398 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001399 total_size1 = blk_getlength(blk1);
1400 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001401 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001402 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001403 ret = 4;
1404 goto out;
1405 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001406 total_size2 = blk_getlength(blk2);
1407 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001408 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001409 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001410 ret = 4;
1411 goto out;
1412 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001413 total_size = MIN(total_size1, total_size2);
1414 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415
1416 qemu_progress_print(0, 100);
1417
Eric Blake033d9fc2017-10-11 22:47:16 -05001418 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001419 ret = 1;
1420 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1421 goto out;
1422 }
1423
Eric Blake033d9fc2017-10-11 22:47:16 -05001424 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001425 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001426
Eric Blake033d9fc2017-10-11 22:47:16 -05001427 status1 = bdrv_block_status_above(bs1, NULL, offset,
1428 total_size1 - offset, &pnum1, NULL,
1429 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001430 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001431 ret = 3;
1432 error_report("Sector allocation test failed for %s", filename1);
1433 goto out;
1434 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001435 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001436
Eric Blake033d9fc2017-10-11 22:47:16 -05001437 status2 = bdrv_block_status_above(bs2, NULL, offset,
1438 total_size2 - offset, &pnum2, NULL,
1439 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001440 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001441 ret = 3;
1442 error_report("Sector allocation test failed for %s", filename2);
1443 goto out;
1444 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001445 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001446
1447 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001448 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001449
Fam Zheng25ad8e62016-01-13 16:37:41 +08001450 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001451 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001452 ret = 1;
1453 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001454 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001455 goto out;
1456 }
1457 }
1458 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001459 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001460 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001461 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001462 int64_t pnum;
1463
Eric Blake033d9fc2017-10-11 22:47:16 -05001464 chunk = MIN(chunk, IO_BUF_SIZE);
1465 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001466 if (ret < 0) {
1467 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001468 " of %s: %s",
1469 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001470 ret = 4;
1471 goto out;
1472 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001473 ret = blk_pread(blk2, offset, buf2, chunk);
1474 if (ret < 0) {
1475 error_report("Error while reading offset %" PRId64
1476 " of %s: %s",
1477 offset, filename2, strerror(-ret));
1478 ret = 4;
1479 goto out;
1480 }
1481 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1482 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001483 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001484 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001485 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001486 goto out;
1487 }
1488 }
1489 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001490 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001493 filename1, buf1, quiet);
1494 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001495 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001496 filename2, buf1, quiet);
1497 }
1498 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 goto out;
1500 }
1501 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001502 offset += chunk;
1503 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001504 }
1505
Eric Blake033d9fc2017-10-11 22:47:16 -05001506 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001507 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001508 const char *filename_over;
1509
1510 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001511 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001512 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001513 filename_over = filename1;
1514 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001515 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001516 filename_over = filename2;
1517 }
1518
Eric Blake033d9fc2017-10-11 22:47:16 -05001519 while (offset < progress_base) {
1520 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1521 progress_base - offset, &chunk,
1522 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001523 if (ret < 0) {
1524 ret = 3;
1525 error_report("Sector allocation test failed for %s",
1526 filename_over);
1527 goto out;
1528
1529 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001530 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001531 chunk = MIN(chunk, IO_BUF_SIZE);
1532 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001533 filename_over, buf1, quiet);
1534 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001535 goto out;
1536 }
1537 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001538 offset += chunk;
1539 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001540 }
1541 }
1542
1543 qprintf(quiet, "Images are identical.\n");
1544 ret = 0;
1545
1546out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001547 qemu_vfree(buf1);
1548 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001549 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001550out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001551 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001552out3:
1553 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001554out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001555 return ret;
1556}
1557
Kevin Wolf690c7302015-03-19 13:33:32 +01001558enum ImgConvertBlockStatus {
1559 BLK_DATA,
1560 BLK_ZERO,
1561 BLK_BACKING_FILE,
1562};
1563
Peter Lieven2d9187b2017-02-28 13:40:07 +01001564#define MAX_COROUTINES 16
1565
Kevin Wolf690c7302015-03-19 13:33:32 +01001566typedef struct ImgConvertState {
1567 BlockBackend **src;
1568 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001569 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001570 int64_t total_sectors;
1571 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001572 int64_t allocated_done;
1573 int64_t sector_num;
1574 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001575 enum ImgConvertBlockStatus status;
1576 int64_t sector_next_status;
1577 BlockBackend *target;
1578 bool has_zero_init;
1579 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001580 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001581 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001582 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001583 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001584 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001585 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001586 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001587 size_t cluster_sectors;
1588 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001589 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001590 int running_coroutines;
1591 Coroutine *co[MAX_COROUTINES];
1592 int64_t wait_sector_num[MAX_COROUTINES];
1593 CoMutex lock;
1594 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001595} ImgConvertState;
1596
Peter Lieven2d9187b2017-02-28 13:40:07 +01001597static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1598 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001599{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001600 *src_cur = 0;
1601 *src_cur_offset = 0;
1602 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1603 *src_cur_offset += s->src_sectors[*src_cur];
1604 (*src_cur)++;
1605 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001606 }
1607}
1608
1609static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1610{
Eric Blake31826642017-10-11 22:47:08 -05001611 int64_t src_cur_offset;
1612 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001613 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001614
Peter Lieven2d9187b2017-02-28 13:40:07 +01001615 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001616
1617 assert(s->total_sectors > sector_num);
1618 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1619
Max Reitz351c8ef2018-05-01 18:57:49 +02001620 if (s->target_backing_sectors >= 0) {
1621 if (sector_num >= s->target_backing_sectors) {
1622 post_backing_zero = s->unallocated_blocks_are_zero;
1623 } else if (sector_num + n > s->target_backing_sectors) {
1624 /* Split requests around target_backing_sectors (because
1625 * starting from there, zeros are handled differently) */
1626 n = s->target_backing_sectors - sector_num;
1627 }
1628 }
1629
Kevin Wolf690c7302015-03-19 13:33:32 +01001630 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001631 int64_t count = n * BDRV_SECTOR_SIZE;
1632
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001633 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001634
1635 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1636 (sector_num - src_cur_offset) *
1637 BDRV_SECTOR_SIZE,
1638 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001639 } else {
Eric Blake31826642017-10-11 22:47:08 -05001640 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1641 (sector_num - src_cur_offset) *
1642 BDRV_SECTOR_SIZE,
1643 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001644 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001645 if (ret < 0) {
1646 return ret;
1647 }
Eric Blake31826642017-10-11 22:47:08 -05001648 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001649
1650 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001651 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001652 } else if (ret & BDRV_BLOCK_DATA) {
1653 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001654 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001655 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001656 }
1657
1658 s->sector_next_status = sector_num + n;
1659 }
1660
1661 n = MIN(n, s->sector_next_status - sector_num);
1662 if (s->status == BLK_DATA) {
1663 n = MIN(n, s->buf_sectors);
1664 }
1665
1666 /* We need to write complete clusters for compressed images, so if an
1667 * unallocated area is shorter than that, we must consider the whole
1668 * cluster allocated. */
1669 if (s->compressed) {
1670 if (n < s->cluster_sectors) {
1671 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1672 s->status = BLK_DATA;
1673 } else {
1674 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1675 }
1676 }
1677
1678 return n;
1679}
1680
Peter Lieven2d9187b2017-02-28 13:40:07 +01001681static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1682 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001683{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001684 int n, ret;
1685 QEMUIOVector qiov;
1686 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001687
Kevin Wolf690c7302015-03-19 13:33:32 +01001688 assert(nb_sectors <= s->buf_sectors);
1689 while (nb_sectors > 0) {
1690 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001691 int src_cur;
1692 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001693
1694 /* In the case of compression with multiple source files, we can get a
1695 * nb_sectors that spreads into the next part. So we must be able to
1696 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001697 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1698 blk = s->src[src_cur];
1699 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001700
Peter Lieven2d9187b2017-02-28 13:40:07 +01001701 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1702 iov.iov_base = buf;
1703 iov.iov_len = n << BDRV_SECTOR_BITS;
1704 qemu_iovec_init_external(&qiov, &iov, 1);
1705
1706 ret = blk_co_preadv(
1707 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1708 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001709 if (ret < 0) {
1710 return ret;
1711 }
1712
1713 sector_num += n;
1714 nb_sectors -= n;
1715 buf += n * BDRV_SECTOR_SIZE;
1716 }
1717
1718 return 0;
1719}
1720
Peter Lieven2d9187b2017-02-28 13:40:07 +01001721
1722static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1723 int nb_sectors, uint8_t *buf,
1724 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001725{
1726 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001727 QEMUIOVector qiov;
1728 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001729
1730 while (nb_sectors > 0) {
1731 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001732 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1733
Peter Lieven2d9187b2017-02-28 13:40:07 +01001734 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001735 case BLK_BACKING_FILE:
1736 /* If we have a backing file, leave clusters unallocated that are
1737 * unallocated in the source image, so that the backing file is
1738 * visible at the respective offset. */
1739 assert(s->target_has_backing);
1740 break;
1741
1742 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001743 /* If we're told to keep the target fully allocated (-S 0) or there
1744 * is real non-zero data, we must write it. Otherwise we can treat
1745 * it as zero sectors.
1746 * Compressed clusters need to be written as a whole, so in that
1747 * case we can only save the write if the buffer is completely
1748 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001749 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001750 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001751 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1752 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001753 (s->compressed &&
1754 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001755 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001756 iov.iov_base = buf;
1757 iov.iov_len = n << BDRV_SECTOR_BITS;
1758 qemu_iovec_init_external(&qiov, &iov, 1);
1759
1760 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001761 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001762 if (ret < 0) {
1763 return ret;
1764 }
1765 break;
1766 }
1767 /* fall-through */
1768
1769 case BLK_ZERO:
1770 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001771 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001772 break;
1773 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001774 ret = blk_co_pwrite_zeroes(s->target,
1775 sector_num << BDRV_SECTOR_BITS,
1776 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001777 if (ret < 0) {
1778 return ret;
1779 }
1780 break;
1781 }
1782
1783 sector_num += n;
1784 nb_sectors -= n;
1785 buf += n * BDRV_SECTOR_SIZE;
1786 }
1787
1788 return 0;
1789}
1790
Fam Zhengee5306d2018-06-01 17:26:48 +08001791static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1792 int nb_sectors)
1793{
1794 int n, ret;
1795
1796 while (nb_sectors > 0) {
1797 BlockBackend *blk;
1798 int src_cur;
1799 int64_t bs_sectors, src_cur_offset;
1800 int64_t offset;
1801
1802 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1803 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1804 blk = s->src[src_cur];
1805 bs_sectors = s->src_sectors[src_cur];
1806
1807 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1808
1809 ret = blk_co_copy_range(blk, offset, s->target,
1810 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001811 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001812 if (ret < 0) {
1813 return ret;
1814 }
1815
1816 sector_num += n;
1817 nb_sectors -= n;
1818 }
1819 return 0;
1820}
1821
Peter Lieven2d9187b2017-02-28 13:40:07 +01001822static void coroutine_fn convert_co_do_copy(void *opaque)
1823{
1824 ImgConvertState *s = opaque;
1825 uint8_t *buf = NULL;
1826 int ret, i;
1827 int index = -1;
1828
1829 for (i = 0; i < s->num_coroutines; i++) {
1830 if (s->co[i] == qemu_coroutine_self()) {
1831 index = i;
1832 break;
1833 }
1834 }
1835 assert(index >= 0);
1836
1837 s->running_coroutines++;
1838 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1839
1840 while (1) {
1841 int n;
1842 int64_t sector_num;
1843 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001844 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001845
1846 qemu_co_mutex_lock(&s->lock);
1847 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1848 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001849 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001850 }
1851 n = convert_iteration_sectors(s, s->sector_num);
1852 if (n < 0) {
1853 qemu_co_mutex_unlock(&s->lock);
1854 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001855 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001856 }
1857 /* save current sector and allocation status to local variables */
1858 sector_num = s->sector_num;
1859 status = s->status;
1860 if (!s->min_sparse && s->status == BLK_ZERO) {
1861 n = MIN(n, s->buf_sectors);
1862 }
1863 /* increment global sector counter so that other coroutines can
1864 * already continue reading beyond this request */
1865 s->sector_num += n;
1866 qemu_co_mutex_unlock(&s->lock);
1867
1868 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1869 s->allocated_done += n;
1870 qemu_progress_print(100.0 * s->allocated_done /
1871 s->allocated_sectors, 0);
1872 }
1873
Fam Zhengee5306d2018-06-01 17:26:48 +08001874retry:
1875 copy_range = s->copy_range && s->status == BLK_DATA;
1876 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001877 ret = convert_co_read(s, sector_num, n, buf);
1878 if (ret < 0) {
1879 error_report("error while reading sector %" PRId64
1880 ": %s", sector_num, strerror(-ret));
1881 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001882 }
1883 } else if (!s->min_sparse && status == BLK_ZERO) {
1884 status = BLK_DATA;
1885 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1886 }
1887
1888 if (s->wr_in_order) {
1889 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001890 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001891 s->wait_sector_num[index] = sector_num;
1892 qemu_coroutine_yield();
1893 }
1894 s->wait_sector_num[index] = -1;
1895 }
1896
Anton Nefedovb91127e2017-04-26 11:33:15 +03001897 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001898 if (copy_range) {
1899 ret = convert_co_copy_range(s, sector_num, n);
1900 if (ret) {
1901 s->copy_range = false;
1902 goto retry;
1903 }
1904 } else {
1905 ret = convert_co_write(s, sector_num, n, buf, status);
1906 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001907 if (ret < 0) {
1908 error_report("error while writing sector %" PRId64
1909 ": %s", sector_num, strerror(-ret));
1910 s->ret = ret;
1911 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001912 }
1913
1914 if (s->wr_in_order) {
1915 /* reenter the coroutine that might have waited
1916 * for this write to complete */
1917 s->wr_offs = sector_num + n;
1918 for (i = 0; i < s->num_coroutines; i++) {
1919 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1920 /*
1921 * A -> B -> A cannot occur because A has
1922 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1923 * B will never enter A during this time window.
1924 */
1925 qemu_coroutine_enter(s->co[i]);
1926 break;
1927 }
1928 }
1929 }
1930 }
1931
Peter Lieven2d9187b2017-02-28 13:40:07 +01001932 qemu_vfree(buf);
1933 s->co[index] = NULL;
1934 s->running_coroutines--;
1935 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1936 /* the convert job finished successfully */
1937 s->ret = 0;
1938 }
1939}
1940
Kevin Wolf690c7302015-03-19 13:33:32 +01001941static int convert_do_copy(ImgConvertState *s)
1942{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001943 int ret, i, n;
1944 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001945
1946 /* Check whether we have zero initialisation or can get it efficiently */
1947 s->has_zero_init = s->min_sparse && !s->target_has_backing
1948 ? bdrv_has_zero_init(blk_bs(s->target))
1949 : false;
1950
1951 if (!s->has_zero_init && !s->target_has_backing &&
1952 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1953 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001954 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001955 if (ret == 0) {
1956 s->has_zero_init = true;
1957 }
1958 }
1959
1960 /* Allocate buffer for copied data. For compressed images, only one cluster
1961 * can be copied at a time. */
1962 if (s->compressed) {
1963 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1964 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001965 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001966 }
1967 s->buf_sectors = s->cluster_sectors;
1968 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001969
Kevin Wolf690c7302015-03-19 13:33:32 +01001970 while (sector_num < s->total_sectors) {
1971 n = convert_iteration_sectors(s, sector_num);
1972 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001973 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001974 }
Max Reitzaad15de2016-03-24 23:33:57 +01001975 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1976 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001977 s->allocated_sectors += n;
1978 }
1979 sector_num += n;
1980 }
1981
1982 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001983 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001984 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001985
Peter Lieven2d9187b2017-02-28 13:40:07 +01001986 qemu_co_mutex_init(&s->lock);
1987 for (i = 0; i < s->num_coroutines; i++) {
1988 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1989 s->wait_sector_num[i] = -1;
1990 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001991 }
1992
Anton Nefedovb91127e2017-04-26 11:33:15 +03001993 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001994 main_loop_wait(false);
1995 }
1996
1997 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001998 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001999 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002000 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002001 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002002 }
2003 }
2004
Peter Lieven2d9187b2017-02-28 13:40:07 +01002005 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002006}
2007
Peter Lieven6360ab22018-07-13 09:15:39 +02002008#define MAX_BUF_SECTORS 32768
2009
bellardea2384d2004-08-01 21:59:26 +00002010static int img_convert(int argc, char **argv)
2011{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002012 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002013 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002014 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2015 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002016 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002017 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002018 BlockDriverState *out_bs;
2019 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002020 QemuOptsList *create_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002021 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002022 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002023 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002024 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002025 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002026 bool force_share = false;
bellardea2384d2004-08-01 21:59:26 +00002027
Peter Lieven9fd77f92017-04-21 11:11:55 +02002028 ImgConvertState s = (ImgConvertState) {
2029 /* Need at least 4k of zeros for sparse detection */
2030 .min_sparse = 8,
Fam Zhengee5306d2018-06-01 17:26:48 +08002031 .copy_range = true,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002032 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2033 .wr_in_order = true,
2034 .num_coroutines = 8,
2035 };
2036
bellardea2384d2004-08-01 21:59:26 +00002037 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002038 static const struct option long_options[] = {
2039 {"help", no_argument, 0, 'h'},
2040 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002041 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002042 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002043 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002044 {0, 0, 0, 0}
2045 };
Thomas Huth46e8d272018-06-06 14:35:51 +02002046 c = getopt_long(argc, argv, ":hf:O:B:co:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002047 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002048 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002049 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002050 }
bellardea2384d2004-08-01 21:59:26 +00002051 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002052 case ':':
2053 missing_argument(argv[optind - 1]);
2054 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002055 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002056 unrecognized_option(argv[optind - 1]);
2057 break;
bellardea2384d2004-08-01 21:59:26 +00002058 case 'h':
2059 help();
2060 break;
2061 case 'f':
2062 fmt = optarg;
2063 break;
2064 case 'O':
2065 out_fmt = optarg;
2066 break;
thsf58c7b32008-06-05 21:53:49 +00002067 case 'B':
2068 out_baseimg = optarg;
2069 break;
bellardea2384d2004-08-01 21:59:26 +00002070 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002071 s.compressed = true;
Fam Zhengee5306d2018-06-01 17:26:48 +08002072 s.copy_range = false;
bellardea2384d2004-08-01 21:59:26 +00002073 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002074 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002075 if (!is_valid_option_list(optarg)) {
2076 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002077 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002078 }
2079 if (!options) {
2080 options = g_strdup(optarg);
2081 } else {
2082 char *old_options = options;
2083 options = g_strdup_printf("%s,%s", options, optarg);
2084 g_free(old_options);
2085 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002086 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002087 case 'l':
2088 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002089 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2090 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002091 if (!sn_opts) {
2092 error_report("Failed in parsing snapshot param '%s'",
2093 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002094 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002095 }
2096 } else {
2097 snapshot_name = optarg;
2098 }
2099 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002100 case 'S':
2101 {
2102 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002103
2104 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002105 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2106 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2107 error_report("Invalid buffer size for sparse output specified. "
2108 "Valid sizes are multiples of %llu up to %llu. Select "
2109 "0 to disable sparse detection (fully allocates output).",
2110 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002111 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002112 }
2113
Peter Lieven9fd77f92017-04-21 11:11:55 +02002114 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhengee5306d2018-06-01 17:26:48 +08002115 s.copy_range = false;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002116 break;
2117 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002118 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002119 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002120 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002121 case 't':
2122 cache = optarg;
2123 break;
Max Reitz40055952014-07-22 22:58:42 +02002124 case 'T':
2125 src_cache = optarg;
2126 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002127 case 'q':
2128 quiet = true;
2129 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002130 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002131 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002132 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002133 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002134 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2135 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002136 error_report("Invalid number of coroutines. Allowed number of"
2137 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002138 goto fail_getopt;
2139 }
2140 break;
2141 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002142 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002143 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002144 case 'U':
2145 force_share = true;
2146 break;
Max Reitz3258b912017-04-26 15:46:47 +02002147 case OPTION_OBJECT: {
2148 QemuOpts *object_opts;
2149 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2150 optarg, true);
2151 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002152 goto fail_getopt;
2153 }
2154 break;
Max Reitz3258b912017-04-26 15:46:47 +02002155 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002156 case OPTION_IMAGE_OPTS:
2157 image_opts = true;
2158 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002159 case OPTION_TARGET_IMAGE_OPTS:
2160 tgt_image_opts = true;
2161 break;
bellardea2384d2004-08-01 21:59:26 +00002162 }
2163 }
ths3b46e622007-09-17 08:09:54 +00002164
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002165 if (!out_fmt && !tgt_image_opts) {
2166 out_fmt = "raw";
2167 }
2168
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002169 if (qemu_opts_foreach(&qemu_object_opts,
2170 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002171 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002172 goto fail_getopt;
2173 }
2174
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002175 if (tgt_image_opts && !skip_create) {
2176 error_report("--target-image-opts requires use of -n flag");
2177 goto fail_getopt;
2178 }
2179
Peter Lieven9fd77f92017-04-21 11:11:55 +02002180 s.src_num = argc - optind - 1;
2181 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2182
2183 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002184 if (out_fmt) {
2185 ret = print_block_option_help(out_filename, out_fmt);
2186 goto fail_getopt;
2187 } else {
2188 error_report("Option help requires a format be specified");
2189 goto fail_getopt;
2190 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002191 }
2192
2193 if (s.src_num < 1) {
2194 error_report("Must specify image file name");
2195 goto fail_getopt;
2196 }
2197
2198
Peter Lieven9fd77f92017-04-21 11:11:55 +02002199 /* ret is still -EINVAL until here */
2200 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2201 if (ret < 0) {
2202 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002203 goto fail_getopt;
2204 }
2205
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002206 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002207 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002208 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002209 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002210 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002211 qemu_progress_print(0, 100);
2212
Peter Lieven9fd77f92017-04-21 11:11:55 +02002213 s.src = g_new0(BlockBackend *, s.src_num);
2214 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002215
Peter Lieven9fd77f92017-04-21 11:11:55 +02002216 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2217 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002218 fmt, src_flags, src_writethrough, quiet,
2219 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002220 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002221 ret = -1;
2222 goto out;
2223 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002224 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2225 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002226 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002227 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002228 ret = -1;
2229 goto out;
2230 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002231 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002232 }
bellardea2384d2004-08-01 21:59:26 +00002233
Wenchao Xiaef806542013-12-04 17:10:57 +08002234 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002235 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002236 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2237 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2238 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002239 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002240 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002241 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002242 ret = -1;
2243 goto out;
2244 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002245
Peter Lieven9fd77f92017-04-21 11:11:55 +02002246 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2247 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002248 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002249 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002250 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002251 ret = -1;
2252 goto out;
edison51ef6722010-09-21 19:58:41 -07002253 }
2254
Max Reitz2e024cd2015-02-11 09:58:46 -05002255 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002256 /* Find driver and parse its options */
2257 drv = bdrv_find_format(out_fmt);
2258 if (!drv) {
2259 error_report("Unknown file format '%s'", out_fmt);
2260 ret = -1;
2261 goto out;
2262 }
2263
2264 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2265 if (!proto_drv) {
2266 error_report_err(local_err);
2267 ret = -1;
2268 goto out;
2269 }
2270
Max Reitz2e024cd2015-02-11 09:58:46 -05002271 if (!drv->create_opts) {
2272 error_report("Format driver '%s' does not support image creation",
2273 drv->format_name);
2274 ret = -1;
2275 goto out;
2276 }
Max Reitzf75613c2014-12-02 18:32:46 +01002277
Max Reitz2e024cd2015-02-11 09:58:46 -05002278 if (!proto_drv->create_opts) {
2279 error_report("Protocol driver '%s' does not support image creation",
2280 proto_drv->format_name);
2281 ret = -1;
2282 goto out;
2283 }
Max Reitzf75613c2014-12-02 18:32:46 +01002284
Max Reitz2e024cd2015-02-11 09:58:46 -05002285 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2286 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002287
Max Reitz2e024cd2015-02-11 09:58:46 -05002288 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002289 if (options) {
2290 qemu_opts_do_parse(opts, options, NULL, &local_err);
2291 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002292 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002293 ret = -1;
2294 goto out;
2295 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002296 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002297
Peter Lieven9fd77f92017-04-21 11:11:55 +02002298 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002299 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002300 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2301 if (ret < 0) {
2302 goto out;
2303 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002304 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002305
Kevin Wolfa18953f2010-10-14 15:46:04 +02002306 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002307 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002308 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002309 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002310 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002311 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002312
Max Reitz48758a82017-04-26 15:46:48 +02002313 if (s.src_num > 1 && out_baseimg) {
2314 error_report("Having a backing file for the target makes no sense when "
2315 "concatenating multiple input images");
2316 ret = -1;
2317 goto out;
2318 }
2319
Kevin Wolfefa84d42009-05-18 16:42:12 +02002320 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002321 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002322 bool encryption =
2323 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002324 const char *encryptfmt =
2325 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002326 const char *preallocation =
2327 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002328
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002329 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002330 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002331 ret = -1;
2332 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002333 }
2334
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002335 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002336 error_report("Compression and encryption not supported at "
2337 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002338 ret = -1;
2339 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002340 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002341
Chunyan Liu83d05212014-06-05 17:20:51 +08002342 if (preallocation
2343 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002344 {
2345 error_report("Compression and preallocation not supported at "
2346 "the same time");
2347 ret = -1;
2348 goto out;
2349 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002350 }
2351
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002352 if (!skip_create) {
2353 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002354 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002355 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002356 error_reportf_err(local_err, "%s: error while converting %s: ",
2357 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002358 goto out;
bellardea2384d2004-08-01 21:59:26 +00002359 }
2360 }
ths3b46e622007-09-17 08:09:54 +00002361
Peter Lieven9fd77f92017-04-21 11:11:55 +02002362 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002363 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002364 if (ret < 0) {
2365 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002366 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002367 }
2368
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002369 if (skip_create) {
2370 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2371 flags, writethrough, quiet, false);
2372 } else {
2373 /* TODO ultimately we should allow --target-image-opts
2374 * to be used even when -n is not given.
2375 * That has to wait for bdrv_create to be improved
2376 * to allow filenames in option syntax
2377 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01002378 s.target = img_open_new_file(out_filename, opts, out_fmt,
2379 flags, writethrough, quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002380 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002381 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002382 ret = -1;
2383 goto out;
2384 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002385 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002386
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002387 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2388 error_report("Compression not supported for this file format");
2389 ret = -1;
2390 goto out;
2391 }
2392
Eric Blake5def6b82016-06-23 16:37:19 -06002393 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002394 * or discard_alignment of the out_bs is greater. Limit to
2395 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2396 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002397 MAX(s.buf_sectors,
2398 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2399 out_bs->bl.pdiscard_alignment >>
2400 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002401
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002402 /* try to align the write requests to the destination to avoid unnecessary
2403 * RMW cycles. */
2404 s.alignment = MAX(pow2floor(s.min_sparse),
2405 DIV_ROUND_UP(out_bs->bl.request_alignment,
2406 BDRV_SECTOR_SIZE));
2407 assert(is_power_of_2(s.alignment));
2408
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002409 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002410 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002411 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002412 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002413 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002414 ret = -1;
2415 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002416 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002417 error_report("output file is smaller than input file");
2418 ret = -1;
2419 goto out;
2420 }
2421 }
2422
Max Reitz351c8ef2018-05-01 18:57:49 +02002423 if (s.target_has_backing) {
2424 /* Errors are treated as "backing length unknown" (which means
2425 * s.target_backing_sectors has to be negative, which it will
2426 * be automatically). The backing file length is used only
2427 * for optimizations, so such a case is not fatal. */
2428 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2429 } else {
2430 s.target_backing_sectors = -1;
2431 }
2432
Peter Lieven24f833c2013-11-27 11:07:07 +01002433 ret = bdrv_get_info(out_bs, &bdi);
2434 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002435 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002436 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002437 goto out;
2438 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002439 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002440 s.compressed = s.compressed || bdi.needs_compressed_writes;
2441 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002442 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002443 }
2444
Peter Lieven9fd77f92017-04-21 11:11:55 +02002445 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002446out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002447 if (!ret) {
2448 qemu_progress_print(100, 0);
2449 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002450 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002451 qemu_opts_del(opts);
2452 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002453 qemu_opts_del(sn_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002454 blk_unref(s.target);
2455 if (s.src) {
2456 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2457 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002458 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002459 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002460 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002461 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002462fail_getopt:
2463 g_free(options);
2464
Peter Lieven9fd77f92017-04-21 11:11:55 +02002465 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002466}
2467
bellard57d1a2b2004-08-03 21:15:11 +00002468
bellardfaea38e2006-08-05 21:31:00 +00002469static void dump_snapshots(BlockDriverState *bs)
2470{
2471 QEMUSnapshotInfo *sn_tab, *sn;
2472 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002473
2474 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2475 if (nb_sns <= 0)
2476 return;
2477 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002478 bdrv_snapshot_dump(fprintf, stdout, NULL);
2479 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002480 for(i = 0; i < nb_sns; i++) {
2481 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002482 bdrv_snapshot_dump(fprintf, stdout, sn);
2483 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002484 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002485 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002486}
2487
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002488static void dump_json_image_info_list(ImageInfoList *list)
2489{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002490 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002491 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002492 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002493
2494 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2495 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002496 str = qobject_to_json_pretty(obj);
2497 assert(str != NULL);
2498 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002499 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002500 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002501 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002502}
2503
Benoît Canetc054b3f2012-09-05 13:09:02 +02002504static void dump_json_image_info(ImageInfo *info)
2505{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002506 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002507 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002508 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002509
2510 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2511 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002512 str = qobject_to_json_pretty(obj);
2513 assert(str != NULL);
2514 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002515 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002516 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002517 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002518}
2519
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002520static void dump_human_image_info_list(ImageInfoList *list)
2521{
2522 ImageInfoList *elem;
2523 bool delim = false;
2524
2525 for (elem = list; elem; elem = elem->next) {
2526 if (delim) {
2527 printf("\n");
2528 }
2529 delim = true;
2530
Wenchao Xia5b917042013-05-25 11:09:45 +08002531 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002532 }
2533}
2534
2535static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2536{
2537 return strcmp(a, b) == 0;
2538}
2539
2540/**
2541 * Open an image file chain and return an ImageInfoList
2542 *
2543 * @filename: topmost image filename
2544 * @fmt: topmost image format (may be NULL to autodetect)
2545 * @chain: true - enumerate entire backing file chain
2546 * false - only topmost image file
2547 *
2548 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2549 * image file. If there was an error a message will have been printed to
2550 * stderr.
2551 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002552static ImageInfoList *collect_image_info_list(bool image_opts,
2553 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002554 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002555 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002556{
2557 ImageInfoList *head = NULL;
2558 ImageInfoList **last = &head;
2559 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002560 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002561
2562 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2563
2564 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002565 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002566 BlockDriverState *bs;
2567 ImageInfo *info;
2568 ImageInfoList *elem;
2569
2570 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2571 error_report("Backing file '%s' creates an infinite loop.",
2572 filename);
2573 goto err;
2574 }
2575 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2576
Max Reitzefaa7c42016-03-16 19:54:38 +01002577 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002578 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2579 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002580 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002581 goto err;
2582 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002583 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002584
Wenchao Xia43526ec2013-06-06 12:27:58 +08002585 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002586 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002587 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002588 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002589 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002590 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002591
2592 elem = g_new0(ImageInfoList, 1);
2593 elem->value = info;
2594 *last = elem;
2595 last = &elem->next;
2596
Markus Armbruster26f54e92014-10-07 13:59:04 +02002597 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002598
2599 filename = fmt = NULL;
2600 if (chain) {
2601 if (info->has_full_backing_filename) {
2602 filename = info->full_backing_filename;
2603 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002604 error_report("Could not determine absolute backing filename,"
2605 " but backing filename '%s' present",
2606 info->backing_filename);
2607 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002608 }
2609 if (info->has_backing_filename_format) {
2610 fmt = info->backing_filename_format;
2611 }
2612 }
2613 }
2614 g_hash_table_destroy(filenames);
2615 return head;
2616
2617err:
2618 qapi_free_ImageInfoList(head);
2619 g_hash_table_destroy(filenames);
2620 return NULL;
2621}
2622
Benoît Canetc054b3f2012-09-05 13:09:02 +02002623static int img_info(int argc, char **argv)
2624{
2625 int c;
2626 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002627 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002628 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002629 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002630 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002631 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002632
bellardea2384d2004-08-01 21:59:26 +00002633 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002634 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002635 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002636 int option_index = 0;
2637 static const struct option long_options[] = {
2638 {"help", no_argument, 0, 'h'},
2639 {"format", required_argument, 0, 'f'},
2640 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002641 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002642 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002643 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002644 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002645 {0, 0, 0, 0}
2646 };
Fam Zheng335e9932017-05-03 00:35:39 +08002647 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002648 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002649 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002650 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002651 }
bellardea2384d2004-08-01 21:59:26 +00002652 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002653 case ':':
2654 missing_argument(argv[optind - 1]);
2655 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002656 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002657 unrecognized_option(argv[optind - 1]);
2658 break;
bellardea2384d2004-08-01 21:59:26 +00002659 case 'h':
2660 help();
2661 break;
2662 case 'f':
2663 fmt = optarg;
2664 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002665 case 'U':
2666 force_share = true;
2667 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002668 case OPTION_OUTPUT:
2669 output = optarg;
2670 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002671 case OPTION_BACKING_CHAIN:
2672 chain = true;
2673 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002674 case OPTION_OBJECT: {
2675 QemuOpts *opts;
2676 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2677 optarg, true);
2678 if (!opts) {
2679 return 1;
2680 }
2681 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002682 case OPTION_IMAGE_OPTS:
2683 image_opts = true;
2684 break;
bellardea2384d2004-08-01 21:59:26 +00002685 }
2686 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002687 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002688 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002689 }
bellardea2384d2004-08-01 21:59:26 +00002690 filename = argv[optind++];
2691
Benoît Canetc054b3f2012-09-05 13:09:02 +02002692 if (output && !strcmp(output, "json")) {
2693 output_format = OFORMAT_JSON;
2694 } else if (output && !strcmp(output, "human")) {
2695 output_format = OFORMAT_HUMAN;
2696 } else if (output) {
2697 error_report("--output must be used with human or json as argument.");
2698 return 1;
2699 }
2700
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002701 if (qemu_opts_foreach(&qemu_object_opts,
2702 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002703 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002704 return 1;
2705 }
2706
Fam Zheng335e9932017-05-03 00:35:39 +08002707 list = collect_image_info_list(image_opts, filename, fmt, chain,
2708 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002709 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002710 return 1;
2711 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002712
Benoît Canetc054b3f2012-09-05 13:09:02 +02002713 switch (output_format) {
2714 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002715 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002716 break;
2717 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002718 if (chain) {
2719 dump_json_image_info_list(list);
2720 } else {
2721 dump_json_image_info(list->value);
2722 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002723 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002724 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002725
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002726 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002727 return 0;
2728}
2729
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002730static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2731 MapEntry *next)
2732{
2733 switch (output_format) {
2734 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002735 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002736 error_report("File contains external, encrypted or compressed clusters.");
2737 exit(1);
2738 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002739 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002740 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002741 e->start, e->length,
2742 e->has_offset ? e->offset : 0,
2743 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002744 }
2745 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2746 * Modify the flags here to allow more coalescing.
2747 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002748 if (next && (!next->data || next->zero)) {
2749 next->data = false;
2750 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002751 }
2752 break;
2753 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002754 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2755 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002756 (e->start == 0 ? "[" : ",\n"),
2757 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002758 e->zero ? "true" : "false",
2759 e->data ? "true" : "false");
2760 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002761 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002762 }
2763 putchar('}');
2764
2765 if (!next) {
2766 printf("]\n");
2767 }
2768 break;
2769 }
2770}
2771
Eric Blake5e344dd2017-10-11 22:47:02 -05002772static int get_block_status(BlockDriverState *bs, int64_t offset,
2773 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002774{
Eric Blake237d78f2017-10-11 22:47:03 -05002775 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002776 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002777 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002778 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002779 int64_t map;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002780
2781 /* As an optimization, we could cache the current range of unallocated
2782 * clusters in each file of the chain, and avoid querying the same
2783 * range repeatedly.
2784 */
2785
2786 depth = 0;
2787 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002788 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002789 if (ret < 0) {
2790 return ret;
2791 }
Eric Blake237d78f2017-10-11 22:47:03 -05002792 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002793 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2794 break;
2795 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002796 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002797 if (bs == NULL) {
2798 ret = 0;
2799 break;
2800 }
2801
2802 depth++;
2803 }
2804
John Snow28756452016-02-05 13:12:33 -05002805 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2806
2807 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002808 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002809 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002810 .data = !!(ret & BDRV_BLOCK_DATA),
2811 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002812 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002813 .has_offset = has_offset,
2814 .depth = depth,
2815 .has_filename = file && has_offset,
2816 .filename = file && has_offset ? file->filename : NULL,
2817 };
2818
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002819 return 0;
2820}
2821
Fam Zheng16b0d552016-01-26 11:59:02 +08002822static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2823{
2824 if (curr->length == 0) {
2825 return false;
2826 }
2827 if (curr->zero != next->zero ||
2828 curr->data != next->data ||
2829 curr->depth != next->depth ||
2830 curr->has_filename != next->has_filename ||
2831 curr->has_offset != next->has_offset) {
2832 return false;
2833 }
2834 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2835 return false;
2836 }
2837 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2838 return false;
2839 }
2840 return true;
2841}
2842
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002843static int img_map(int argc, char **argv)
2844{
2845 int c;
2846 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002847 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002848 BlockDriverState *bs;
2849 const char *filename, *fmt, *output;
2850 int64_t length;
2851 MapEntry curr = { .length = 0 }, next;
2852 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002853 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002854 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002855
2856 fmt = NULL;
2857 output = NULL;
2858 for (;;) {
2859 int option_index = 0;
2860 static const struct option long_options[] = {
2861 {"help", no_argument, 0, 'h'},
2862 {"format", required_argument, 0, 'f'},
2863 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002864 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002865 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002866 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002867 {0, 0, 0, 0}
2868 };
Fam Zheng335e9932017-05-03 00:35:39 +08002869 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002870 long_options, &option_index);
2871 if (c == -1) {
2872 break;
2873 }
2874 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002875 case ':':
2876 missing_argument(argv[optind - 1]);
2877 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002878 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002879 unrecognized_option(argv[optind - 1]);
2880 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002881 case 'h':
2882 help();
2883 break;
2884 case 'f':
2885 fmt = optarg;
2886 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002887 case 'U':
2888 force_share = true;
2889 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002890 case OPTION_OUTPUT:
2891 output = optarg;
2892 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002893 case OPTION_OBJECT: {
2894 QemuOpts *opts;
2895 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2896 optarg, true);
2897 if (!opts) {
2898 return 1;
2899 }
2900 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002901 case OPTION_IMAGE_OPTS:
2902 image_opts = true;
2903 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002904 }
2905 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002906 if (optind != argc - 1) {
2907 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002908 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002909 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002910
2911 if (output && !strcmp(output, "json")) {
2912 output_format = OFORMAT_JSON;
2913 } else if (output && !strcmp(output, "human")) {
2914 output_format = OFORMAT_HUMAN;
2915 } else if (output) {
2916 error_report("--output must be used with human or json as argument.");
2917 return 1;
2918 }
2919
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002920 if (qemu_opts_foreach(&qemu_object_opts,
2921 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002922 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002923 return 1;
2924 }
2925
Fam Zheng335e9932017-05-03 00:35:39 +08002926 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002927 if (!blk) {
2928 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002929 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002930 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002931
2932 if (output_format == OFORMAT_HUMAN) {
2933 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2934 }
2935
Max Reitzf1d3cd72015-02-05 13:58:18 -05002936 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002937 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002938 int64_t offset = curr.start + curr.length;
2939 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002940
2941 /* Probe up to 1 GiB at a time. */
Eric Blakee0b371e2018-06-11 16:39:26 -05002942 n = MIN(1 << 30, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002943 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002944
2945 if (ret < 0) {
2946 error_report("Could not read file metadata: %s", strerror(-ret));
2947 goto out;
2948 }
2949
Fam Zheng16b0d552016-01-26 11:59:02 +08002950 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002951 curr.length += next.length;
2952 continue;
2953 }
2954
2955 if (curr.length > 0) {
2956 dump_map_entry(output_format, &curr, &next);
2957 }
2958 curr = next;
2959 }
2960
2961 dump_map_entry(output_format, &curr, NULL);
2962
2963out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002964 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002965 return ret < 0;
2966}
2967
aliguorif7b4a942009-01-07 17:40:15 +00002968#define SNAPSHOT_LIST 1
2969#define SNAPSHOT_CREATE 2
2970#define SNAPSHOT_APPLY 3
2971#define SNAPSHOT_DELETE 4
2972
Stuart Brady153859b2009-06-07 00:42:17 +01002973static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002974{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002975 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002976 BlockDriverState *bs;
2977 QEMUSnapshotInfo sn;
2978 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002979 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002980 int action = 0;
2981 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002982 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002983 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002984 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002985 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002986
Kevin Wolfce099542016-03-15 13:01:04 +01002987 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002988 /* Parse commandline parameters */
2989 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002990 static const struct option long_options[] = {
2991 {"help", no_argument, 0, 'h'},
2992 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002993 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002994 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002995 {0, 0, 0, 0}
2996 };
Fam Zheng335e9932017-05-03 00:35:39 +08002997 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002998 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002999 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003000 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003001 }
aliguorif7b4a942009-01-07 17:40:15 +00003002 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003003 case ':':
3004 missing_argument(argv[optind - 1]);
3005 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003006 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003007 unrecognized_option(argv[optind - 1]);
3008 break;
aliguorif7b4a942009-01-07 17:40:15 +00003009 case 'h':
3010 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003011 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003012 case 'l':
3013 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003014 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003015 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003016 }
3017 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003018 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003019 break;
3020 case 'a':
3021 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003022 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003023 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003024 }
3025 action = SNAPSHOT_APPLY;
3026 snapshot_name = optarg;
3027 break;
3028 case 'c':
3029 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003030 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003031 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003032 }
3033 action = SNAPSHOT_CREATE;
3034 snapshot_name = optarg;
3035 break;
3036 case 'd':
3037 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003038 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003039 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003040 }
3041 action = SNAPSHOT_DELETE;
3042 snapshot_name = optarg;
3043 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003044 case 'q':
3045 quiet = true;
3046 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003047 case 'U':
3048 force_share = true;
3049 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003050 case OPTION_OBJECT: {
3051 QemuOpts *opts;
3052 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3053 optarg, true);
3054 if (!opts) {
3055 return 1;
3056 }
3057 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003058 case OPTION_IMAGE_OPTS:
3059 image_opts = true;
3060 break;
aliguorif7b4a942009-01-07 17:40:15 +00003061 }
3062 }
3063
Kevin Wolffc11eb22013-08-05 10:53:04 +02003064 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003065 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003066 }
aliguorif7b4a942009-01-07 17:40:15 +00003067 filename = argv[optind++];
3068
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003069 if (qemu_opts_foreach(&qemu_object_opts,
3070 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003071 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003072 return 1;
3073 }
3074
aliguorif7b4a942009-01-07 17:40:15 +00003075 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003076 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3077 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003078 if (!blk) {
3079 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003080 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003081 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003082
3083 /* Perform the requested action */
3084 switch(action) {
3085 case SNAPSHOT_LIST:
3086 dump_snapshots(bs);
3087 break;
3088
3089 case SNAPSHOT_CREATE:
3090 memset(&sn, 0, sizeof(sn));
3091 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3092
3093 qemu_gettimeofday(&tv);
3094 sn.date_sec = tv.tv_sec;
3095 sn.date_nsec = tv.tv_usec * 1000;
3096
3097 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003098 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003099 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003100 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003101 }
aliguorif7b4a942009-01-07 17:40:15 +00003102 break;
3103
3104 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003105 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003106 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003107 error_reportf_err(err, "Could not apply snapshot '%s': ",
3108 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003109 }
aliguorif7b4a942009-01-07 17:40:15 +00003110 break;
3111
3112 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003113 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003114 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003115 error_reportf_err(err, "Could not delete snapshot '%s': ",
3116 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003117 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003118 }
aliguorif7b4a942009-01-07 17:40:15 +00003119 break;
3120 }
3121
3122 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003123 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003124 if (ret) {
3125 return 1;
3126 }
Stuart Brady153859b2009-06-07 00:42:17 +01003127 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003128}
3129
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003130static int img_rebase(int argc, char **argv)
3131{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003132 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003133 uint8_t *buf_old = NULL;
3134 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003135 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003136 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003137 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3138 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003139 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003140 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003141 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003142 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003143 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003144 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003145 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003146
3147 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003148 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003149 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003150 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003151 out_baseimg = NULL;
3152 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003153 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003154 static const struct option long_options[] = {
3155 {"help", no_argument, 0, 'h'},
3156 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003157 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003158 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003159 {0, 0, 0, 0}
3160 };
Fam Zheng335e9932017-05-03 00:35:39 +08003161 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003162 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003163 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003164 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003165 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003166 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003167 case ':':
3168 missing_argument(argv[optind - 1]);
3169 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003170 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003171 unrecognized_option(argv[optind - 1]);
3172 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003173 case 'h':
3174 help();
3175 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003176 case 'f':
3177 fmt = optarg;
3178 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003179 case 'F':
3180 out_basefmt = optarg;
3181 break;
3182 case 'b':
3183 out_baseimg = optarg;
3184 break;
3185 case 'u':
3186 unsafe = 1;
3187 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003188 case 'p':
3189 progress = 1;
3190 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003191 case 't':
3192 cache = optarg;
3193 break;
Max Reitz40055952014-07-22 22:58:42 +02003194 case 'T':
3195 src_cache = optarg;
3196 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003197 case 'q':
3198 quiet = true;
3199 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003200 case OPTION_OBJECT: {
3201 QemuOpts *opts;
3202 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3203 optarg, true);
3204 if (!opts) {
3205 return 1;
3206 }
3207 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003208 case OPTION_IMAGE_OPTS:
3209 image_opts = true;
3210 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003211 case 'U':
3212 force_share = true;
3213 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003214 }
3215 }
3216
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003217 if (quiet) {
3218 progress = 0;
3219 }
3220
Fam Zhengac1307a2014-04-22 13:36:11 +08003221 if (optind != argc - 1) {
3222 error_exit("Expecting one image file name");
3223 }
3224 if (!unsafe && !out_baseimg) {
3225 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003226 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003227 filename = argv[optind++];
3228
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003229 if (qemu_opts_foreach(&qemu_object_opts,
3230 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003231 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003232 return 1;
3233 }
3234
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003235 qemu_progress_init(progress, 2.0);
3236 qemu_progress_print(0, 100);
3237
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003238 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003239 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003240 if (ret < 0) {
3241 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003242 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003243 }
3244
Kevin Wolfce099542016-03-15 13:01:04 +01003245 src_flags = 0;
3246 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003247 if (ret < 0) {
3248 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003249 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003250 }
3251
Kevin Wolfce099542016-03-15 13:01:04 +01003252 /* The source files are opened read-only, don't care about WCE */
3253 assert((src_flags & BDRV_O_RDWR) == 0);
3254 (void) src_writethrough;
3255
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003256 /*
3257 * Open the images.
3258 *
3259 * Ignore the old backing file for unsafe rebase in case we want to correct
3260 * the reference to a renamed or moved backing file.
3261 */
Fam Zheng335e9932017-05-03 00:35:39 +08003262 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3263 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003264 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003265 ret = -1;
3266 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003267 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003268 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003269
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003270 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003271 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003272 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003273 ret = -1;
3274 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003275 }
3276 }
3277
3278 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003279 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003280 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003281 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003282
Max Reitz644483d2015-02-05 13:58:17 -05003283 if (bs->backing_format[0] != '\0') {
3284 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003285 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003286 }
3287
Fam Zheng335e9932017-05-03 00:35:39 +08003288 if (force_share) {
3289 if (!options) {
3290 options = qdict_new();
3291 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003292 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003293 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003294 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003295 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003296 options, src_flags, &local_err);
3297 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003298 error_reportf_err(local_err,
3299 "Could not open old backing file '%s': ",
3300 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003301 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003302 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003303 }
Max Reitz644483d2015-02-05 13:58:17 -05003304
Alex Bligha6166732012-10-16 13:46:18 +01003305 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003306 const char *overlay_filename;
3307 char *out_real_path;
3308
Fam Zheng335e9932017-05-03 00:35:39 +08003309 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003310 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003311 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003312 }
3313 if (force_share) {
3314 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003315 }
3316
Max Reitzd16699b2018-05-09 20:20:01 +02003317 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3318 : bs->filename;
3319 out_real_path = g_malloc(PATH_MAX);
3320
3321 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3322 out_baseimg,
3323 out_real_path,
3324 PATH_MAX,
3325 &local_err);
3326 if (local_err) {
3327 error_reportf_err(local_err,
3328 "Could not resolve backing filename: ");
3329 ret = -1;
3330 g_free(out_real_path);
3331 goto out;
3332 }
3333
3334 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003335 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003336 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003337 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003338 error_reportf_err(local_err,
3339 "Could not open new backing file '%s': ",
3340 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003341 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003342 goto out;
3343 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003344 }
3345 }
3346
3347 /*
3348 * Check each unallocated cluster in the COW file. If it is unallocated,
3349 * accesses go to the backing file. We must therefore compare this cluster
3350 * in the old and new backing file, and if they differ we need to copy it
3351 * from the old backing file into the COW file.
3352 *
3353 * If qemu-img crashes during this step, no harm is done. The content of
3354 * the image is the same as the original one at any time.
3355 */
3356 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003357 int64_t size;
3358 int64_t old_backing_size;
3359 int64_t new_backing_size = 0;
3360 uint64_t offset;
3361 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003362 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003363
Max Reitzf1d3cd72015-02-05 13:58:18 -05003364 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3365 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003366
Eric Blake41536282017-10-11 22:47:15 -05003367 size = blk_getlength(blk);
3368 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003369 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003370 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003371 ret = -1;
3372 goto out;
3373 }
Eric Blake41536282017-10-11 22:47:15 -05003374 old_backing_size = blk_getlength(blk_old_backing);
3375 if (old_backing_size < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003376 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003377
3378 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3379 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003380 backing_name, strerror(-old_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003381 ret = -1;
3382 goto out;
3383 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003384 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003385 new_backing_size = blk_getlength(blk_new_backing);
3386 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003387 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003388 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003389 ret = -1;
3390 goto out;
3391 }
Alex Bligha6166732012-10-16 13:46:18 +01003392 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003393
Eric Blake41536282017-10-11 22:47:15 -05003394 if (size != 0) {
3395 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003396 }
3397
Eric Blake41536282017-10-11 22:47:15 -05003398 for (offset = 0; offset < size; offset += n) {
3399 /* How many bytes can we handle with the next read? */
3400 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003401
3402 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003403 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003404 if (ret < 0) {
3405 error_report("error while reading image metadata: %s",
3406 strerror(-ret));
3407 goto out;
3408 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003409 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003410 continue;
3411 }
3412
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003413 /*
3414 * Read old and new backing file and take into consideration that
3415 * backing files may be smaller than the COW image.
3416 */
Eric Blake41536282017-10-11 22:47:15 -05003417 if (offset >= old_backing_size) {
3418 memset(buf_old, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003419 } else {
Eric Blake41536282017-10-11 22:47:15 -05003420 if (offset + n > old_backing_size) {
3421 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003422 }
3423
Eric Blake41536282017-10-11 22:47:15 -05003424 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003425 if (ret < 0) {
3426 error_report("error while reading from old backing file");
3427 goto out;
3428 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003429 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003430
Eric Blake41536282017-10-11 22:47:15 -05003431 if (offset >= new_backing_size || !blk_new_backing) {
3432 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003433 } else {
Eric Blake41536282017-10-11 22:47:15 -05003434 if (offset + n > new_backing_size) {
3435 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003436 }
3437
Eric Blake41536282017-10-11 22:47:15 -05003438 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003439 if (ret < 0) {
3440 error_report("error while reading from new backing file");
3441 goto out;
3442 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003443 }
3444
3445 /* If they differ, we need to write to the COW file */
3446 uint64_t written = 0;
3447
Eric Blake41536282017-10-11 22:47:15 -05003448 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003449 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003450
Eric Blake41536282017-10-11 22:47:15 -05003451 if (compare_buffers(buf_old + written, buf_new + written,
3452 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003453 {
Eric Blake41536282017-10-11 22:47:15 -05003454 ret = blk_pwrite(blk, offset + written,
Eric Blakedc61cd32017-10-11 22:47:14 -05003455 buf_old + written, pnum, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003456 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003457 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003458 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003459 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003460 }
3461 }
3462
3463 written += pnum;
3464 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003465 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003466 }
3467 }
3468
3469 /*
3470 * Change the backing file. All clusters that are different from the old
3471 * backing file are overwritten in the COW file now, so the visible content
3472 * doesn't change when we switch the backing file.
3473 */
Alex Bligha6166732012-10-16 13:46:18 +01003474 if (out_baseimg && *out_baseimg) {
3475 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3476 } else {
3477 ret = bdrv_change_backing_file(bs, NULL, NULL);
3478 }
3479
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003480 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003481 error_report("Could not change the backing file to '%s': No "
3482 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003483 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003484 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003485 out_baseimg, strerror(-ret));
3486 }
3487
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003488 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003489 /*
3490 * TODO At this point it is possible to check if any clusters that are
3491 * allocated in the COW file are the same in the backing file. If so, they
3492 * could be dropped from the COW file. Don't do this before switching the
3493 * backing file, in case of a crash this would lead to corruption.
3494 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003495out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003496 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003497 /* Cleanup */
3498 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003499 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003500 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003501 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003502 qemu_vfree(buf_old);
3503 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003504
Markus Armbruster26f54e92014-10-07 13:59:04 +02003505 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003506 if (ret) {
3507 return 1;
3508 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003509 return 0;
3510}
3511
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003512static int img_resize(int argc, char **argv)
3513{
Markus Armbruster6750e792015-02-12 17:43:08 +01003514 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003515 int c, ret, relative;
3516 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003517 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003518 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003519 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003520 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003521 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003522
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003523 static QemuOptsList resize_options = {
3524 .name = "resize_options",
3525 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3526 .desc = {
3527 {
3528 .name = BLOCK_OPT_SIZE,
3529 .type = QEMU_OPT_SIZE,
3530 .help = "Virtual disk size"
3531 }, {
3532 /* end of list */
3533 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003534 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003535 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003536 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003537 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003538
Kevin Wolfe80fec72011-04-29 10:58:12 +02003539 /* Remove size from argv manually so that negative numbers are not treated
3540 * as options by getopt. */
3541 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003542 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003543 return 1;
3544 }
3545
3546 size = argv[--argc];
3547
3548 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003549 fmt = NULL;
3550 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003551 static const struct option long_options[] = {
3552 {"help", no_argument, 0, 'h'},
3553 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003554 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003555 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003556 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003557 {0, 0, 0, 0}
3558 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003559 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003560 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003561 if (c == -1) {
3562 break;
3563 }
3564 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003565 case ':':
3566 missing_argument(argv[optind - 1]);
3567 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003568 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003569 unrecognized_option(argv[optind - 1]);
3570 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003571 case 'h':
3572 help();
3573 break;
3574 case 'f':
3575 fmt = optarg;
3576 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003577 case 'q':
3578 quiet = true;
3579 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003580 case OPTION_OBJECT: {
3581 QemuOpts *opts;
3582 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3583 optarg, true);
3584 if (!opts) {
3585 return 1;
3586 }
3587 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003588 case OPTION_IMAGE_OPTS:
3589 image_opts = true;
3590 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003591 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003592 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003593 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003594 if (prealloc == PREALLOC_MODE__MAX) {
3595 error_report("Invalid preallocation mode '%s'", optarg);
3596 return 1;
3597 }
3598 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003599 case OPTION_SHRINK:
3600 shrink = true;
3601 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003602 }
3603 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003604 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003605 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003606 }
3607 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003608
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003609 if (qemu_opts_foreach(&qemu_object_opts,
3610 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003611 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003612 return 1;
3613 }
3614
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003615 /* Choose grow, shrink, or absolute resize mode */
3616 switch (size[0]) {
3617 case '+':
3618 relative = 1;
3619 size++;
3620 break;
3621 case '-':
3622 relative = -1;
3623 size++;
3624 break;
3625 default:
3626 relative = 0;
3627 break;
3628 }
3629
3630 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003631 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003632 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003633 if (err) {
3634 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003635 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003636 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003637 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003638 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003639 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3640 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003641
Max Reitzefaa7c42016-03-16 19:54:38 +01003642 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003643 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3644 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003645 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003646 ret = -1;
3647 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003648 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003649
Max Reitzdc5f6902017-06-13 22:20:55 +02003650 current_size = blk_getlength(blk);
3651 if (current_size < 0) {
3652 error_report("Failed to inquire current image length: %s",
3653 strerror(-current_size));
3654 ret = -1;
3655 goto out;
3656 }
3657
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003658 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003659 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003660 } else {
3661 total_size = n;
3662 }
3663 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003664 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003665 ret = -1;
3666 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003667 }
3668
Max Reitzdc5f6902017-06-13 22:20:55 +02003669 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3670 error_report("Preallocation can only be used for growing images");
3671 ret = -1;
3672 goto out;
3673 }
3674
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003675 if (total_size < current_size && !shrink) {
3676 warn_report("Shrinking an image will delete all data beyond the "
3677 "shrunken image's end. Before performing such an "
3678 "operation, make sure there is no important data there.");
3679
3680 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3681 error_report(
3682 "Use the --shrink option to perform a shrink operation.");
3683 ret = -1;
3684 goto out;
3685 } else {
3686 warn_report("Using the --shrink option will suppress this message. "
3687 "Note that future versions of qemu-img may refuse to "
3688 "shrink images without this option.");
3689 }
3690 }
3691
Max Reitzdc5f6902017-06-13 22:20:55 +02003692 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003693 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003694 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003695 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003696 }
Max Reitz5279b302018-04-21 18:39:57 +02003697
3698 new_size = blk_getlength(blk);
3699 if (new_size < 0) {
3700 error_report("Failed to verify truncated image length: %s",
3701 strerror(-new_size));
3702 ret = -1;
3703 goto out;
3704 }
3705
3706 /* Some block drivers implement a truncation method, but only so
3707 * the user can cause qemu to refresh the image's size from disk.
3708 * The idea is that the user resizes the image outside of qemu and
3709 * then invokes block_resize to inform qemu about it.
3710 * (This includes iscsi and file-posix for device files.)
3711 * Of course, that is not the behavior someone invoking
3712 * qemu-img resize would find useful, so we catch that behavior
3713 * here and tell the user. */
3714 if (new_size != total_size && new_size == current_size) {
3715 error_report("Image was not resized; resizing may not be supported "
3716 "for this image");
3717 ret = -1;
3718 goto out;
3719 }
3720
3721 if (new_size != total_size) {
3722 warn_report("Image should have been resized to %" PRIi64
3723 " bytes, but was resized to %" PRIi64 " bytes",
3724 total_size, new_size);
3725 }
3726
3727 qprintf(quiet, "Image resized.\n");
3728
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003729out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003730 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003731 if (ret) {
3732 return 1;
3733 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003734 return 0;
3735}
3736
Max Reitz76a3a342014-10-27 11:12:51 +01003737static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003738 int64_t offset, int64_t total_work_size,
3739 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003740{
3741 qemu_progress_print(100.f * offset / total_work_size, 0);
3742}
3743
Max Reitz51641352018-05-09 23:00:20 +02003744static int print_amend_option_help(const char *format)
3745{
3746 BlockDriver *drv;
3747
3748 /* Find driver and parse its options */
3749 drv = bdrv_find_format(format);
3750 if (!drv) {
3751 error_report("Unknown file format '%s'", format);
3752 return 1;
3753 }
3754
3755 if (!drv->bdrv_amend_options) {
3756 error_report("Format driver '%s' does not support option amendment",
3757 format);
3758 return 1;
3759 }
3760
3761 /* Every driver supporting amendment must have create_opts */
3762 assert(drv->create_opts);
3763
3764 printf("Creation options for '%s':\n", format);
3765 qemu_opts_print_help(drv->create_opts);
3766 printf("\nNote that not all of these options may be amendable.\n");
3767 return 0;
3768}
3769
Max Reitz6f176b42013-09-03 10:09:50 +02003770static int img_amend(int argc, char **argv)
3771{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003772 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003773 int c, ret = 0;
3774 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003775 QemuOptsList *create_opts = NULL;
3776 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003777 const char *fmt = NULL, *filename, *cache;
3778 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003779 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003780 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003781 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003782 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003783 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003784
Max Reitzbd39e6e2014-07-22 22:58:43 +02003785 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003786 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003787 static const struct option long_options[] = {
3788 {"help", no_argument, 0, 'h'},
3789 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003790 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003791 {0, 0, 0, 0}
3792 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003793 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003794 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003795 if (c == -1) {
3796 break;
3797 }
3798
3799 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003800 case ':':
3801 missing_argument(argv[optind - 1]);
3802 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003803 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003804 unrecognized_option(argv[optind - 1]);
3805 break;
3806 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003807 help();
3808 break;
3809 case 'o':
3810 if (!is_valid_option_list(optarg)) {
3811 error_report("Invalid option list: %s", optarg);
3812 ret = -1;
3813 goto out_no_progress;
3814 }
3815 if (!options) {
3816 options = g_strdup(optarg);
3817 } else {
3818 char *old_options = options;
3819 options = g_strdup_printf("%s,%s", options, optarg);
3820 g_free(old_options);
3821 }
3822 break;
3823 case 'f':
3824 fmt = optarg;
3825 break;
3826 case 't':
3827 cache = optarg;
3828 break;
3829 case 'p':
3830 progress = true;
3831 break;
3832 case 'q':
3833 quiet = true;
3834 break;
3835 case OPTION_OBJECT:
3836 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3837 optarg, true);
3838 if (!opts) {
3839 ret = -1;
3840 goto out_no_progress;
3841 }
3842 break;
3843 case OPTION_IMAGE_OPTS:
3844 image_opts = true;
3845 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003846 }
3847 }
3848
Max Reitz6f176b42013-09-03 10:09:50 +02003849 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003850 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003851 }
3852
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003853 if (qemu_opts_foreach(&qemu_object_opts,
3854 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003855 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003856 ret = -1;
3857 goto out_no_progress;
3858 }
3859
Max Reitz76a3a342014-10-27 11:12:51 +01003860 if (quiet) {
3861 progress = false;
3862 }
3863 qemu_progress_init(progress, 1.0);
3864
Kevin Wolfa283cb62014-02-21 16:24:07 +01003865 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3866 if (fmt && has_help_option(options)) {
3867 /* If a format is explicitly specified (and possibly no filename is
3868 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003869 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003870 goto out;
3871 }
3872
3873 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003874 error_report("Expecting one image file name");
3875 ret = -1;
3876 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003877 }
Max Reitz6f176b42013-09-03 10:09:50 +02003878
Kevin Wolfce099542016-03-15 13:01:04 +01003879 flags = BDRV_O_RDWR;
3880 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003881 if (ret < 0) {
3882 error_report("Invalid cache option: %s", cache);
3883 goto out;
3884 }
3885
Fam Zheng335e9932017-05-03 00:35:39 +08003886 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3887 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003888 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003889 ret = -1;
3890 goto out;
3891 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003892 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003893
3894 fmt = bs->drv->format_name;
3895
Kevin Wolf626f84f2014-02-21 16:24:06 +01003896 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003897 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003898 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003899 goto out;
3900 }
3901
Max Reitz1f996682018-05-09 23:00:17 +02003902 if (!bs->drv->bdrv_amend_options) {
3903 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003904 fmt);
3905 ret = -1;
3906 goto out;
3907 }
3908
Max Reitz1f996682018-05-09 23:00:17 +02003909 /* Every driver supporting amendment must have create_opts */
3910 assert(bs->drv->create_opts);
3911
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003912 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003913 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003914 qemu_opts_do_parse(opts, options, NULL, &err);
3915 if (err) {
3916 error_report_err(err);
3917 ret = -1;
3918 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003919 }
3920
Max Reitz76a3a342014-10-27 11:12:51 +01003921 /* In case the driver does not call amend_status_cb() */
3922 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003923 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003924 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003925 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003926 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003927 goto out;
3928 }
3929
3930out:
Max Reitz76a3a342014-10-27 11:12:51 +01003931 qemu_progress_end();
3932
Max Reitze814dff2015-08-20 16:00:38 -07003933out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003934 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003935 qemu_opts_del(opts);
3936 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003937 g_free(options);
3938
Max Reitz6f176b42013-09-03 10:09:50 +02003939 if (ret) {
3940 return 1;
3941 }
3942 return 0;
3943}
3944
Kevin Wolfb6133b82014-08-05 14:17:13 +02003945typedef struct BenchData {
3946 BlockBackend *blk;
3947 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003948 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003949 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003950 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003951 int nrreq;
3952 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003953 int flush_interval;
3954 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003955 uint8_t *buf;
3956 QEMUIOVector *qiov;
3957
3958 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003959 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003960 uint64_t offset;
3961} BenchData;
3962
Kevin Wolf55d539c2016-06-03 13:59:41 +02003963static void bench_undrained_flush_cb(void *opaque, int ret)
3964{
3965 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003966 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003967 exit(EXIT_FAILURE);
3968 }
3969}
3970
Kevin Wolfb6133b82014-08-05 14:17:13 +02003971static void bench_cb(void *opaque, int ret)
3972{
3973 BenchData *b = opaque;
3974 BlockAIOCB *acb;
3975
3976 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003977 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003978 exit(EXIT_FAILURE);
3979 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003980
3981 if (b->in_flush) {
3982 /* Just finished a flush with drained queue: Start next requests */
3983 assert(b->in_flight == 0);
3984 b->in_flush = false;
3985 } else if (b->in_flight > 0) {
3986 int remaining = b->n - b->in_flight;
3987
Kevin Wolfb6133b82014-08-05 14:17:13 +02003988 b->n--;
3989 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003990
3991 /* Time for flush? Drain queue if requested, then flush */
3992 if (b->flush_interval && remaining % b->flush_interval == 0) {
3993 if (!b->in_flight || !b->drain_on_flush) {
3994 BlockCompletionFunc *cb;
3995
3996 if (b->drain_on_flush) {
3997 b->in_flush = true;
3998 cb = bench_cb;
3999 } else {
4000 cb = bench_undrained_flush_cb;
4001 }
4002
4003 acb = blk_aio_flush(b->blk, cb, b);
4004 if (!acb) {
4005 error_report("Failed to issue flush request");
4006 exit(EXIT_FAILURE);
4007 }
4008 }
4009 if (b->drain_on_flush) {
4010 return;
4011 }
4012 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004013 }
4014
4015 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004016 int64_t offset = b->offset;
4017 /* blk_aio_* might look for completed I/Os and kick bench_cb
4018 * again, so make sure this operation is counted by in_flight
4019 * and b->offset is ready for the next submission.
4020 */
4021 b->in_flight++;
4022 b->offset += b->step;
4023 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004024 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004025 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004026 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004027 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004028 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004029 if (!acb) {
4030 error_report("Failed to issue request");
4031 exit(EXIT_FAILURE);
4032 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004033 }
4034}
4035
4036static int img_bench(int argc, char **argv)
4037{
4038 int c, ret = 0;
4039 const char *fmt = NULL, *filename;
4040 bool quiet = false;
4041 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004042 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004043 int count = 75000;
4044 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004045 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004046 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004047 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004048 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004049 int flush_interval = 0;
4050 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004051 int64_t image_size;
4052 BlockBackend *blk = NULL;
4053 BenchData data = {};
4054 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004055 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004056 struct timeval t1, t2;
4057 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004058 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004059 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004060
4061 for (;;) {
4062 static const struct option long_options[] = {
4063 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004064 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004065 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004066 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004067 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004068 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004069 {0, 0, 0, 0}
4070 };
Fam Zheng335e9932017-05-03 00:35:39 +08004071 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004072 if (c == -1) {
4073 break;
4074 }
4075
4076 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004077 case ':':
4078 missing_argument(argv[optind - 1]);
4079 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004080 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004081 unrecognized_option(argv[optind - 1]);
4082 break;
4083 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004084 help();
4085 break;
4086 case 'c':
4087 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004088 unsigned long res;
4089
4090 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004091 error_report("Invalid request count specified");
4092 return 1;
4093 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004094 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004095 break;
4096 }
4097 case 'd':
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 queue depth specified");
4103 return 1;
4104 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004105 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004106 break;
4107 }
4108 case 'f':
4109 fmt = optarg;
4110 break;
4111 case 'n':
4112 flags |= BDRV_O_NATIVE_AIO;
4113 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004114 case 'o':
4115 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004116 offset = cvtnum(optarg);
4117 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004118 error_report("Invalid offset specified");
4119 return 1;
4120 }
4121 break;
4122 }
4123 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004124 case 'q':
4125 quiet = true;
4126 break;
4127 case 's':
4128 {
4129 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004130
Markus Armbruster606caa02017-02-21 21:14:04 +01004131 sval = cvtnum(optarg);
4132 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004133 error_report("Invalid buffer size specified");
4134 return 1;
4135 }
4136
4137 bufsize = sval;
4138 break;
4139 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004140 case 'S':
4141 {
4142 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004143
Markus Armbruster606caa02017-02-21 21:14:04 +01004144 sval = cvtnum(optarg);
4145 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004146 error_report("Invalid step size specified");
4147 return 1;
4148 }
4149
4150 step = sval;
4151 break;
4152 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004153 case 't':
4154 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4155 if (ret < 0) {
4156 error_report("Invalid cache mode");
4157 ret = -1;
4158 goto out;
4159 }
4160 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004161 case 'w':
4162 flags |= BDRV_O_RDWR;
4163 is_write = true;
4164 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004165 case 'U':
4166 force_share = true;
4167 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004168 case OPTION_PATTERN:
4169 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004170 unsigned long res;
4171
4172 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004173 error_report("Invalid pattern byte specified");
4174 return 1;
4175 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004176 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004177 break;
4178 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004179 case OPTION_FLUSH_INTERVAL:
4180 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004181 unsigned long res;
4182
4183 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004184 error_report("Invalid flush interval specified");
4185 return 1;
4186 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004187 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004188 break;
4189 }
4190 case OPTION_NO_DRAIN:
4191 drain_on_flush = false;
4192 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004193 case OPTION_IMAGE_OPTS:
4194 image_opts = true;
4195 break;
4196 }
4197 }
4198
4199 if (optind != argc - 1) {
4200 error_exit("Expecting one image file name");
4201 }
4202 filename = argv[argc - 1];
4203
Kevin Wolf55d539c2016-06-03 13:59:41 +02004204 if (!is_write && flush_interval) {
4205 error_report("--flush-interval is only available in write tests");
4206 ret = -1;
4207 goto out;
4208 }
4209 if (flush_interval && flush_interval < depth) {
4210 error_report("Flush interval can't be smaller than depth");
4211 ret = -1;
4212 goto out;
4213 }
4214
Fam Zheng335e9932017-05-03 00:35:39 +08004215 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4216 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004217 if (!blk) {
4218 ret = -1;
4219 goto out;
4220 }
4221
4222 image_size = blk_getlength(blk);
4223 if (image_size < 0) {
4224 ret = image_size;
4225 goto out;
4226 }
4227
4228 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004229 .blk = blk,
4230 .image_size = image_size,
4231 .bufsize = bufsize,
4232 .step = step ?: bufsize,
4233 .nrreq = depth,
4234 .n = count,
4235 .offset = offset,
4236 .write = is_write,
4237 .flush_interval = flush_interval,
4238 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004239 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004240 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004241 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004242 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004243 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004244 if (flush_interval) {
4245 printf("Sending flush every %d requests\n", flush_interval);
4246 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004247
Fam Zheng79d46582018-01-16 14:08:58 +08004248 buf_size = data.nrreq * data.bufsize;
4249 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004250 memset(data.buf, pattern, data.nrreq * data.bufsize);
4251
Fam Zheng79d46582018-01-16 14:08:58 +08004252 blk_register_buf(blk, data.buf, buf_size);
4253
Kevin Wolfb6133b82014-08-05 14:17:13 +02004254 data.qiov = g_new(QEMUIOVector, data.nrreq);
4255 for (i = 0; i < data.nrreq; i++) {
4256 qemu_iovec_init(&data.qiov[i], 1);
4257 qemu_iovec_add(&data.qiov[i],
4258 data.buf + i * data.bufsize, data.bufsize);
4259 }
4260
4261 gettimeofday(&t1, NULL);
4262 bench_cb(&data, 0);
4263
4264 while (data.n > 0) {
4265 main_loop_wait(false);
4266 }
4267 gettimeofday(&t2, NULL);
4268
4269 printf("Run completed in %3.3f seconds.\n",
4270 (t2.tv_sec - t1.tv_sec)
4271 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4272
4273out:
Fam Zheng79d46582018-01-16 14:08:58 +08004274 if (data.buf) {
4275 blk_unregister_buf(blk, data.buf);
4276 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004277 qemu_vfree(data.buf);
4278 blk_unref(blk);
4279
4280 if (ret) {
4281 return 1;
4282 }
4283 return 0;
4284}
4285
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004286#define C_BS 01
4287#define C_COUNT 02
4288#define C_IF 04
4289#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004290#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004291
4292struct DdInfo {
4293 unsigned int flags;
4294 int64_t count;
4295};
4296
4297struct DdIo {
4298 int bsz; /* Block size */
4299 char *filename;
4300 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004301 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004302};
4303
4304struct DdOpts {
4305 const char *name;
4306 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4307 unsigned int flag;
4308};
4309
4310static int img_dd_bs(const char *arg,
4311 struct DdIo *in, struct DdIo *out,
4312 struct DdInfo *dd)
4313{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004314 int64_t res;
4315
Markus Armbruster606caa02017-02-21 21:14:04 +01004316 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004317
Markus Armbruster606caa02017-02-21 21:14:04 +01004318 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004319 error_report("invalid number: '%s'", arg);
4320 return 1;
4321 }
4322 in->bsz = out->bsz = res;
4323
4324 return 0;
4325}
4326
4327static int img_dd_count(const char *arg,
4328 struct DdIo *in, struct DdIo *out,
4329 struct DdInfo *dd)
4330{
Markus Armbruster606caa02017-02-21 21:14:04 +01004331 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004332
Markus Armbruster606caa02017-02-21 21:14:04 +01004333 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004334 error_report("invalid number: '%s'", arg);
4335 return 1;
4336 }
4337
4338 return 0;
4339}
4340
4341static int img_dd_if(const char *arg,
4342 struct DdIo *in, struct DdIo *out,
4343 struct DdInfo *dd)
4344{
4345 in->filename = g_strdup(arg);
4346
4347 return 0;
4348}
4349
4350static int img_dd_of(const char *arg,
4351 struct DdIo *in, struct DdIo *out,
4352 struct DdInfo *dd)
4353{
4354 out->filename = g_strdup(arg);
4355
4356 return 0;
4357}
4358
Reda Sallahif7c15532016-08-10 16:16:09 +02004359static int img_dd_skip(const char *arg,
4360 struct DdIo *in, struct DdIo *out,
4361 struct DdInfo *dd)
4362{
Markus Armbruster606caa02017-02-21 21:14:04 +01004363 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004364
Markus Armbruster606caa02017-02-21 21:14:04 +01004365 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004366 error_report("invalid number: '%s'", arg);
4367 return 1;
4368 }
4369
4370 return 0;
4371}
4372
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004373static int img_dd(int argc, char **argv)
4374{
4375 int ret = 0;
4376 char *arg = NULL;
4377 char *tmp;
4378 BlockDriver *drv = NULL, *proto_drv = NULL;
4379 BlockBackend *blk1 = NULL, *blk2 = NULL;
4380 QemuOpts *opts = NULL;
4381 QemuOptsList *create_opts = NULL;
4382 Error *local_err = NULL;
4383 bool image_opts = false;
4384 int c, i;
4385 const char *out_fmt = "raw";
4386 const char *fmt = NULL;
4387 int64_t size = 0;
4388 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004389 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004390 struct DdInfo dd = {
4391 .flags = 0,
4392 .count = 0,
4393 };
4394 struct DdIo in = {
4395 .bsz = 512, /* Block size is by default 512 bytes */
4396 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004397 .buf = NULL,
4398 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004399 };
4400 struct DdIo out = {
4401 .bsz = 512,
4402 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004403 .buf = NULL,
4404 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004405 };
4406
4407 const struct DdOpts options[] = {
4408 { "bs", img_dd_bs, C_BS },
4409 { "count", img_dd_count, C_COUNT },
4410 { "if", img_dd_if, C_IF },
4411 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004412 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004413 { NULL, NULL, 0 }
4414 };
4415 const struct option long_options[] = {
4416 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004417 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004418 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004419 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004420 { 0, 0, 0, 0 }
4421 };
4422
Fam Zheng335e9932017-05-03 00:35:39 +08004423 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004424 if (c == EOF) {
4425 break;
4426 }
4427 switch (c) {
4428 case 'O':
4429 out_fmt = optarg;
4430 break;
4431 case 'f':
4432 fmt = optarg;
4433 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004434 case ':':
4435 missing_argument(argv[optind - 1]);
4436 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004437 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004438 unrecognized_option(argv[optind - 1]);
4439 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004440 case 'h':
4441 help();
4442 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004443 case 'U':
4444 force_share = true;
4445 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004446 case OPTION_OBJECT:
4447 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004448 ret = -1;
4449 goto out;
4450 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004451 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004452 case OPTION_IMAGE_OPTS:
4453 image_opts = true;
4454 break;
4455 }
4456 }
4457
4458 for (i = optind; i < argc; i++) {
4459 int j;
4460 arg = g_strdup(argv[i]);
4461
4462 tmp = strchr(arg, '=');
4463 if (tmp == NULL) {
4464 error_report("unrecognized operand %s", arg);
4465 ret = -1;
4466 goto out;
4467 }
4468
4469 *tmp++ = '\0';
4470
4471 for (j = 0; options[j].name != NULL; j++) {
4472 if (!strcmp(arg, options[j].name)) {
4473 break;
4474 }
4475 }
4476 if (options[j].name == NULL) {
4477 error_report("unrecognized operand %s", arg);
4478 ret = -1;
4479 goto out;
4480 }
4481
4482 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4483 ret = -1;
4484 goto out;
4485 }
4486 dd.flags |= options[j].flag;
4487 g_free(arg);
4488 arg = NULL;
4489 }
4490
4491 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4492 error_report("Must specify both input and output files");
4493 ret = -1;
4494 goto out;
4495 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004496
4497 if (qemu_opts_foreach(&qemu_object_opts,
4498 user_creatable_add_opts_foreach,
4499 NULL, NULL)) {
4500 ret = -1;
4501 goto out;
4502 }
4503
Fam Zheng335e9932017-05-03 00:35:39 +08004504 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4505 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004506
4507 if (!blk1) {
4508 ret = -1;
4509 goto out;
4510 }
4511
4512 drv = bdrv_find_format(out_fmt);
4513 if (!drv) {
4514 error_report("Unknown file format");
4515 ret = -1;
4516 goto out;
4517 }
4518 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4519
4520 if (!proto_drv) {
4521 error_report_err(local_err);
4522 ret = -1;
4523 goto out;
4524 }
4525 if (!drv->create_opts) {
4526 error_report("Format driver '%s' does not support image creation",
4527 drv->format_name);
4528 ret = -1;
4529 goto out;
4530 }
4531 if (!proto_drv->create_opts) {
4532 error_report("Protocol driver '%s' does not support image creation",
4533 proto_drv->format_name);
4534 ret = -1;
4535 goto out;
4536 }
4537 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4538 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4539
4540 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4541
4542 size = blk_getlength(blk1);
4543 if (size < 0) {
4544 error_report("Failed to get size for '%s'", in.filename);
4545 ret = -1;
4546 goto out;
4547 }
4548
4549 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4550 dd.count * in.bsz < size) {
4551 size = dd.count * in.bsz;
4552 }
4553
Reda Sallahif7c15532016-08-10 16:16:09 +02004554 /* Overflow means the specified offset is beyond input image's size */
4555 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4556 size < in.bsz * in.offset)) {
4557 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4558 } else {
4559 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4560 size - in.bsz * in.offset, &error_abort);
4561 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004562
4563 ret = bdrv_create(drv, out.filename, opts, &local_err);
4564 if (ret < 0) {
4565 error_reportf_err(local_err,
4566 "%s: error while creating output image: ",
4567 out.filename);
4568 ret = -1;
4569 goto out;
4570 }
4571
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004572 /* TODO, we can't honour --image-opts for the target,
4573 * since it needs to be given in a format compatible
4574 * with the bdrv_create() call above which does not
4575 * support image-opts style.
4576 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004577 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004578 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004579
4580 if (!blk2) {
4581 ret = -1;
4582 goto out;
4583 }
4584
Reda Sallahif7c15532016-08-10 16:16:09 +02004585 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4586 size < in.offset * in.bsz)) {
4587 /* We give a warning if the skip option is bigger than the input
4588 * size and create an empty output disk image (i.e. like dd(1)).
4589 */
4590 error_report("%s: cannot skip to specified offset", in.filename);
4591 in_pos = size;
4592 } else {
4593 in_pos = in.offset * in.bsz;
4594 }
4595
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004596 in.buf = g_new(uint8_t, in.bsz);
4597
Reda Sallahif7c15532016-08-10 16:16:09 +02004598 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004599 int in_ret, out_ret;
4600
4601 if (in_pos + in.bsz > size) {
4602 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4603 } else {
4604 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4605 }
4606 if (in_ret < 0) {
4607 error_report("error while reading from input image file: %s",
4608 strerror(-in_ret));
4609 ret = -1;
4610 goto out;
4611 }
4612 in_pos += in_ret;
4613
4614 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4615
4616 if (out_ret < 0) {
4617 error_report("error while writing to output image file: %s",
4618 strerror(-out_ret));
4619 ret = -1;
4620 goto out;
4621 }
4622 out_pos += out_ret;
4623 }
4624
4625out:
4626 g_free(arg);
4627 qemu_opts_del(opts);
4628 qemu_opts_free(create_opts);
4629 blk_unref(blk1);
4630 blk_unref(blk2);
4631 g_free(in.filename);
4632 g_free(out.filename);
4633 g_free(in.buf);
4634 g_free(out.buf);
4635
4636 if (ret) {
4637 return 1;
4638 }
4639 return 0;
4640}
4641
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004642static void dump_json_block_measure_info(BlockMeasureInfo *info)
4643{
4644 QString *str;
4645 QObject *obj;
4646 Visitor *v = qobject_output_visitor_new(&obj);
4647
4648 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4649 visit_complete(v, &obj);
4650 str = qobject_to_json_pretty(obj);
4651 assert(str != NULL);
4652 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004653 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004654 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004655 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004656}
4657
4658static int img_measure(int argc, char **argv)
4659{
4660 static const struct option long_options[] = {
4661 {"help", no_argument, 0, 'h'},
4662 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4663 {"object", required_argument, 0, OPTION_OBJECT},
4664 {"output", required_argument, 0, OPTION_OUTPUT},
4665 {"size", required_argument, 0, OPTION_SIZE},
4666 {"force-share", no_argument, 0, 'U'},
4667 {0, 0, 0, 0}
4668 };
4669 OutputFormat output_format = OFORMAT_HUMAN;
4670 BlockBackend *in_blk = NULL;
4671 BlockDriver *drv;
4672 const char *filename = NULL;
4673 const char *fmt = NULL;
4674 const char *out_fmt = "raw";
4675 char *options = NULL;
4676 char *snapshot_name = NULL;
4677 bool force_share = false;
4678 QemuOpts *opts = NULL;
4679 QemuOpts *object_opts = NULL;
4680 QemuOpts *sn_opts = NULL;
4681 QemuOptsList *create_opts = NULL;
4682 bool image_opts = false;
4683 uint64_t img_size = UINT64_MAX;
4684 BlockMeasureInfo *info = NULL;
4685 Error *local_err = NULL;
4686 int ret = 1;
4687 int c;
4688
4689 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4690 long_options, NULL)) != -1) {
4691 switch (c) {
4692 case '?':
4693 case 'h':
4694 help();
4695 break;
4696 case 'f':
4697 fmt = optarg;
4698 break;
4699 case 'O':
4700 out_fmt = optarg;
4701 break;
4702 case 'o':
4703 if (!is_valid_option_list(optarg)) {
4704 error_report("Invalid option list: %s", optarg);
4705 goto out;
4706 }
4707 if (!options) {
4708 options = g_strdup(optarg);
4709 } else {
4710 char *old_options = options;
4711 options = g_strdup_printf("%s,%s", options, optarg);
4712 g_free(old_options);
4713 }
4714 break;
4715 case 'l':
4716 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4717 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4718 optarg, false);
4719 if (!sn_opts) {
4720 error_report("Failed in parsing snapshot param '%s'",
4721 optarg);
4722 goto out;
4723 }
4724 } else {
4725 snapshot_name = optarg;
4726 }
4727 break;
4728 case 'U':
4729 force_share = true;
4730 break;
4731 case OPTION_OBJECT:
4732 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4733 optarg, true);
4734 if (!object_opts) {
4735 goto out;
4736 }
4737 break;
4738 case OPTION_IMAGE_OPTS:
4739 image_opts = true;
4740 break;
4741 case OPTION_OUTPUT:
4742 if (!strcmp(optarg, "json")) {
4743 output_format = OFORMAT_JSON;
4744 } else if (!strcmp(optarg, "human")) {
4745 output_format = OFORMAT_HUMAN;
4746 } else {
4747 error_report("--output must be used with human or json "
4748 "as argument.");
4749 goto out;
4750 }
4751 break;
4752 case OPTION_SIZE:
4753 {
4754 int64_t sval;
4755
4756 sval = cvtnum(optarg);
4757 if (sval < 0) {
4758 if (sval == -ERANGE) {
4759 error_report("Image size must be less than 8 EiB!");
4760 } else {
4761 error_report("Invalid image size specified! You may use "
4762 "k, M, G, T, P or E suffixes for ");
4763 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4764 "petabytes and exabytes.");
4765 }
4766 goto out;
4767 }
4768 img_size = (uint64_t)sval;
4769 }
4770 break;
4771 }
4772 }
4773
4774 if (qemu_opts_foreach(&qemu_object_opts,
4775 user_creatable_add_opts_foreach,
4776 NULL, NULL)) {
4777 goto out;
4778 }
4779
4780 if (argc - optind > 1) {
4781 error_report("At most one filename argument is allowed.");
4782 goto out;
4783 } else if (argc - optind == 1) {
4784 filename = argv[optind];
4785 }
4786
4787 if (!filename &&
4788 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4789 error_report("--object, --image-opts, -f, and -l "
4790 "require a filename argument.");
4791 goto out;
4792 }
4793 if (filename && img_size != UINT64_MAX) {
4794 error_report("--size N cannot be used together with a filename.");
4795 goto out;
4796 }
4797 if (!filename && img_size == UINT64_MAX) {
4798 error_report("Either --size N or one filename must be specified.");
4799 goto out;
4800 }
4801
4802 if (filename) {
4803 in_blk = img_open(image_opts, filename, fmt, 0,
4804 false, false, force_share);
4805 if (!in_blk) {
4806 goto out;
4807 }
4808
4809 if (sn_opts) {
4810 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4811 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4812 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4813 &local_err);
4814 } else if (snapshot_name != NULL) {
4815 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4816 snapshot_name, &local_err);
4817 }
4818 if (local_err) {
4819 error_reportf_err(local_err, "Failed to load snapshot: ");
4820 goto out;
4821 }
4822 }
4823
4824 drv = bdrv_find_format(out_fmt);
4825 if (!drv) {
4826 error_report("Unknown file format '%s'", out_fmt);
4827 goto out;
4828 }
4829 if (!drv->create_opts) {
4830 error_report("Format driver '%s' does not support image creation",
4831 drv->format_name);
4832 goto out;
4833 }
4834
4835 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4836 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4837 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4838 if (options) {
4839 qemu_opts_do_parse(opts, options, NULL, &local_err);
4840 if (local_err) {
4841 error_report_err(local_err);
4842 error_report("Invalid options for file format '%s'", out_fmt);
4843 goto out;
4844 }
4845 }
4846 if (img_size != UINT64_MAX) {
4847 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4848 }
4849
4850 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4851 if (local_err) {
4852 error_report_err(local_err);
4853 goto out;
4854 }
4855
4856 if (output_format == OFORMAT_HUMAN) {
4857 printf("required size: %" PRIu64 "\n", info->required);
4858 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4859 } else {
4860 dump_json_block_measure_info(info);
4861 }
4862
4863 ret = 0;
4864
4865out:
4866 qapi_free_BlockMeasureInfo(info);
4867 qemu_opts_del(object_opts);
4868 qemu_opts_del(opts);
4869 qemu_opts_del(sn_opts);
4870 qemu_opts_free(create_opts);
4871 g_free(options);
4872 blk_unref(in_blk);
4873 return ret;
4874}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004875
Anthony Liguoric227f092009-10-01 16:12:16 -05004876static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004877#define DEF(option, callback, arg_string) \
4878 { option, callback },
4879#include "qemu-img-cmds.h"
4880#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004881 { NULL, NULL, },
4882};
4883
bellardea2384d2004-08-01 21:59:26 +00004884int main(int argc, char **argv)
4885{
Anthony Liguoric227f092009-10-01 16:12:16 -05004886 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004887 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004888 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004889 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004890 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004891 static const struct option long_options[] = {
4892 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004893 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004894 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004895 {0, 0, 0, 0}
4896 };
bellardea2384d2004-08-01 21:59:26 +00004897
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004898#ifdef CONFIG_POSIX
4899 signal(SIGPIPE, SIG_IGN);
4900#endif
4901
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004902 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004903 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004904 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004905
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004906 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004907 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004908 exit(EXIT_FAILURE);
4909 }
4910
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004911 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004912
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004913 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004914 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004915 if (argc < 2) {
4916 error_exit("Not enough arguments");
4917 }
Stuart Brady153859b2009-06-07 00:42:17 +01004918
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004919 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004920 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004921 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004922
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004923 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004924 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004925 case ':':
4926 missing_argument(argv[optind - 1]);
4927 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004928 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004929 unrecognized_option(argv[optind - 1]);
4930 return 0;
4931 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004932 help();
4933 return 0;
4934 case 'V':
4935 printf(QEMU_IMG_VERSION);
4936 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004937 case 'T':
4938 g_free(trace_file);
4939 trace_file = trace_opt_parse(optarg);
4940 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004941 }
bellardea2384d2004-08-01 21:59:26 +00004942 }
Stuart Brady153859b2009-06-07 00:42:17 +01004943
Denis V. Lunev10985132016-06-17 17:44:13 +03004944 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004945
Denis V. Lunev10985132016-06-17 17:44:13 +03004946 /* reset getopt_long scanning */
4947 argc -= optind;
4948 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004949 return 0;
4950 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004951 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004952 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004953
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004954 if (!trace_init_backends()) {
4955 exit(1);
4956 }
4957 trace_init_file(trace_file);
4958 qemu_set_log(LOG_TRACE);
4959
Denis V. Lunev10985132016-06-17 17:44:13 +03004960 /* find the command */
4961 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4962 if (!strcmp(cmdname, cmd->name)) {
4963 return cmd->handler(argc, argv);
4964 }
4965 }
Jeff Cody7db16892014-04-25 17:02:32 -04004966
Stuart Brady153859b2009-06-07 00:42:17 +01004967 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004968 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004969}