blob: 13a6ca31b402ea50f036cb5db57bd8412a8caee2 [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");
Max Reitz63898712018-10-19 18:49:25 +0200272 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800273 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100274 return 0;
275}
276
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000277
Max Reitzefaa7c42016-03-16 19:54:38 +0100278static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100279 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800280 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000281{
282 QDict *options;
283 Error *local_err = NULL;
284 BlockBackend *blk;
285 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800286 if (force_share) {
287 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200288 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800289 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200290 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800291 return NULL;
292 }
Max Reitz4615f872018-05-02 22:20:50 +0200293 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800294 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100295 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000296 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100297 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000298 return NULL;
299 }
Kevin Wolfce099542016-03-15 13:01:04 +0100300 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000301
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000302 return blk;
303}
304
Max Reitzefaa7c42016-03-16 19:54:38 +0100305static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100306 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000307 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800308 bool writethrough, bool quiet,
309 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000310{
311 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200312 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100313
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100314 if (!options) {
315 options = qdict_new();
316 }
bellard75c23802004-08-27 21:28:58 +0000317 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500318 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000319 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100320
Fam Zheng335e9932017-05-03 00:35:39 +0800321 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500322 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800323 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100324 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500325 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100326 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000327 return NULL;
bellard75c23802004-08-27 21:28:58 +0000328 }
Kevin Wolfce099542016-03-15 13:01:04 +0100329 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100330
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200331 return blk;
bellard75c23802004-08-27 21:28:58 +0000332}
333
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000334
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100335static int img_add_key_secrets(void *opaque,
336 const char *name, const char *value,
337 Error **errp)
338{
339 QDict *options = opaque;
340
341 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600342 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100343 }
344
345 return 0;
346}
347
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100348
Max Reitzefaa7c42016-03-16 19:54:38 +0100349static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000350 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100351 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800352 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000353{
354 BlockBackend *blk;
355 if (image_opts) {
356 QemuOpts *opts;
357 if (fmt) {
358 error_report("--image-opts and --format are mutually exclusive");
359 return NULL;
360 }
361 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
362 filename, true);
363 if (!opts) {
364 return NULL;
365 }
Fam Zheng335e9932017-05-03 00:35:39 +0800366 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
367 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000368 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100369 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800370 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000371 }
372 return blk;
373}
374
375
Chunyan Liu83d05212014-06-05 17:20:51 +0800376static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100377 const char *base_filename,
378 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200379{
Markus Armbruster6750e792015-02-12 17:43:08 +0100380 Error *err = NULL;
381
Kevin Wolfefa84d42009-05-18 16:42:12 +0200382 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100383 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100384 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100385 error_report("Backing file not supported for file format '%s'",
386 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100387 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900388 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200389 }
390 }
391 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100392 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100393 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100394 error_report("Backing file format not supported for file "
395 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100396 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900397 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200398 }
399 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900400 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200401}
402
Markus Armbruster606caa02017-02-21 21:14:04 +0100403static int64_t cvtnum(const char *s)
404{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100405 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100406 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100407
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100408 err = qemu_strtosz(s, NULL, &value);
409 if (err < 0) {
410 return err;
411 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100412 if (value > INT64_MAX) {
413 return -ERANGE;
414 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100415 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100416}
417
bellardea2384d2004-08-01 21:59:26 +0000418static int img_create(int argc, char **argv)
419{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200420 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100421 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000422 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000423 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000424 const char *filename;
425 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200426 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200427 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100428 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400429 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000430
bellardea2384d2004-08-01 21:59:26 +0000431 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000432 static const struct option long_options[] = {
433 {"help", no_argument, 0, 'h'},
434 {"object", required_argument, 0, OPTION_OBJECT},
435 {0, 0, 0, 0}
436 };
John Snow6e6e55f2017-07-17 20:34:22 -0400437 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000438 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100439 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000440 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100441 }
bellardea2384d2004-08-01 21:59:26 +0000442 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800443 case ':':
444 missing_argument(argv[optind - 1]);
445 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100446 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800447 unrecognized_option(argv[optind - 1]);
448 break;
bellardea2384d2004-08-01 21:59:26 +0000449 case 'h':
450 help();
451 break;
aliguori9230eaf2009-03-28 17:55:19 +0000452 case 'F':
453 base_fmt = optarg;
454 break;
bellardea2384d2004-08-01 21:59:26 +0000455 case 'b':
456 base_filename = optarg;
457 break;
458 case 'f':
459 fmt = optarg;
460 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200461 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100462 if (!is_valid_option_list(optarg)) {
463 error_report("Invalid option list: %s", optarg);
464 goto fail;
465 }
466 if (!options) {
467 options = g_strdup(optarg);
468 } else {
469 char *old_options = options;
470 options = g_strdup_printf("%s,%s", options, optarg);
471 g_free(old_options);
472 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200473 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100474 case 'q':
475 quiet = true;
476 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400477 case 'u':
478 flags |= BDRV_O_NO_BACKING;
479 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000480 case OPTION_OBJECT: {
481 QemuOpts *opts;
482 opts = qemu_opts_parse_noisily(&qemu_object_opts,
483 optarg, true);
484 if (!opts) {
485 goto fail;
486 }
487 } break;
bellardea2384d2004-08-01 21:59:26 +0000488 }
489 }
aliguori9230eaf2009-03-28 17:55:19 +0000490
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900491 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100492 filename = (optind < argc) ? argv[optind] : NULL;
493 if (options && has_help_option(options)) {
494 g_free(options);
495 return print_block_option_help(filename, fmt);
496 }
497
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100498 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800499 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100500 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100501 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900502
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000503 if (qemu_opts_foreach(&qemu_object_opts,
504 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200505 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000506 goto fail;
507 }
508
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100509 /* Get image size, if specified */
510 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100511 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100512
513 sval = cvtnum(argv[optind++]);
514 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800515 if (sval == -ERANGE) {
516 error_report("Image size must be less than 8 EiB!");
517 } else {
518 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200519 "G, T, P or E suffixes for ");
520 error_report("kilobytes, megabytes, gigabytes, terabytes, "
521 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800522 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100523 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100524 }
525 img_size = (uint64_t)sval;
526 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200527 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800528 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200529 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100530
Luiz Capitulino9b375252012-11-30 10:52:05 -0200531 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400532 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100533 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100534 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100535 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900536 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200537
Kevin Wolf77386bf2014-02-21 16:24:04 +0100538 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000539 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100540
541fail:
542 g_free(options);
543 return 1;
bellardea2384d2004-08-01 21:59:26 +0000544}
545
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100546static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500547{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500548 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500549 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100550 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600551
552 visit_type_ImageCheck(v, NULL, &check, &error_abort);
553 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500554 str = qobject_to_json_pretty(obj);
555 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100556 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200557 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600558 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200559 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560}
561
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100562static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500563{
564 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100565 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500566 } else {
567 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100568 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
569 "Data may be corrupted, or further writes to the image "
570 "may corrupt it.\n",
571 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500572 }
573
574 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100575 qprintf(quiet,
576 "\n%" PRId64 " leaked clusters were found on the image.\n"
577 "This means waste of disk space, but no harm to data.\n",
578 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500579 }
580
581 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100582 qprintf(quiet,
583 "\n%" PRId64
584 " internal errors have occurred during the check.\n",
585 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500586 }
587 }
588
589 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100590 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
591 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
592 check->allocated_clusters, check->total_clusters,
593 check->allocated_clusters * 100.0 / check->total_clusters,
594 check->fragmented_clusters * 100.0 / check->allocated_clusters,
595 check->compressed_clusters * 100.0 /
596 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500597 }
598
599 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100600 qprintf(quiet,
601 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500602 }
603}
604
605static int collect_image_check(BlockDriverState *bs,
606 ImageCheck *check,
607 const char *filename,
608 const char *fmt,
609 int fix)
610{
611 int ret;
612 BdrvCheckResult result;
613
614 ret = bdrv_check(bs, &result, fix);
615 if (ret < 0) {
616 return ret;
617 }
618
619 check->filename = g_strdup(filename);
620 check->format = g_strdup(bdrv_get_format_name(bs));
621 check->check_errors = result.check_errors;
622 check->corruptions = result.corruptions;
623 check->has_corruptions = result.corruptions != 0;
624 check->leaks = result.leaks;
625 check->has_leaks = result.leaks != 0;
626 check->corruptions_fixed = result.corruptions_fixed;
627 check->has_corruptions_fixed = result.corruptions != 0;
628 check->leaks_fixed = result.leaks_fixed;
629 check->has_leaks_fixed = result.leaks != 0;
630 check->image_end_offset = result.image_end_offset;
631 check->has_image_end_offset = result.image_end_offset != 0;
632 check->total_clusters = result.bfi.total_clusters;
633 check->has_total_clusters = result.bfi.total_clusters != 0;
634 check->allocated_clusters = result.bfi.allocated_clusters;
635 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
636 check->fragmented_clusters = result.bfi.fragmented_clusters;
637 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100638 check->compressed_clusters = result.bfi.compressed_clusters;
639 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500640
641 return 0;
642}
643
Kevin Wolfe076f332010-06-29 11:43:13 +0200644/*
645 * Checks an image for consistency. Exit codes:
646 *
Max Reitzd6635c42014-06-02 22:15:21 +0200647 * 0 - Check completed, image is good
648 * 1 - Check not completed because of internal errors
649 * 2 - Check completed, image is corrupted
650 * 3 - Check completed, image has leaked clusters, but is good otherwise
651 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200652 */
aliguori15859692009-04-21 23:11:53 +0000653static int img_check(int argc, char **argv)
654{
655 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500656 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200657 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200658 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000659 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200660 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100661 int flags = BDRV_O_CHECK;
662 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200663 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100664 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000665 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800666 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000667
668 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500669 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200670 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100671
aliguori15859692009-04-21 23:11:53 +0000672 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500673 int option_index = 0;
674 static const struct option long_options[] = {
675 {"help", no_argument, 0, 'h'},
676 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530677 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500678 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000679 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000680 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800681 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500682 {0, 0, 0, 0}
683 };
Fam Zheng335e9932017-05-03 00:35:39 +0800684 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500685 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100686 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000687 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100688 }
aliguori15859692009-04-21 23:11:53 +0000689 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800690 case ':':
691 missing_argument(argv[optind - 1]);
692 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100693 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800694 unrecognized_option(argv[optind - 1]);
695 break;
aliguori15859692009-04-21 23:11:53 +0000696 case 'h':
697 help();
698 break;
699 case 'f':
700 fmt = optarg;
701 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200702 case 'r':
703 flags |= BDRV_O_RDWR;
704
705 if (!strcmp(optarg, "leaks")) {
706 fix = BDRV_FIX_LEAKS;
707 } else if (!strcmp(optarg, "all")) {
708 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
709 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800710 error_exit("Unknown option value for -r "
711 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200712 }
713 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500714 case OPTION_OUTPUT:
715 output = optarg;
716 break;
Max Reitz40055952014-07-22 22:58:42 +0200717 case 'T':
718 cache = optarg;
719 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100720 case 'q':
721 quiet = true;
722 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800723 case 'U':
724 force_share = true;
725 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000726 case OPTION_OBJECT: {
727 QemuOpts *opts;
728 opts = qemu_opts_parse_noisily(&qemu_object_opts,
729 optarg, true);
730 if (!opts) {
731 return 1;
732 }
733 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000734 case OPTION_IMAGE_OPTS:
735 image_opts = true;
736 break;
aliguori15859692009-04-21 23:11:53 +0000737 }
738 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200739 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800740 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100741 }
aliguori15859692009-04-21 23:11:53 +0000742 filename = argv[optind++];
743
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500744 if (output && !strcmp(output, "json")) {
745 output_format = OFORMAT_JSON;
746 } else if (output && !strcmp(output, "human")) {
747 output_format = OFORMAT_HUMAN;
748 } else if (output) {
749 error_report("--output must be used with human or json as argument.");
750 return 1;
751 }
752
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000753 if (qemu_opts_foreach(&qemu_object_opts,
754 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200755 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000756 return 1;
757 }
758
Kevin Wolfce099542016-03-15 13:01:04 +0100759 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200760 if (ret < 0) {
761 error_report("Invalid source cache option: %s", cache);
762 return 1;
763 }
764
Fam Zheng335e9932017-05-03 00:35:39 +0800765 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
766 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200767 if (!blk) {
768 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900769 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200770 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500771
772 check = g_new0(ImageCheck, 1);
773 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200774
775 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200776 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200777 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500778 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200779 }
780
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500781 if (check->corruptions_fixed || check->leaks_fixed) {
782 int corruptions_fixed, leaks_fixed;
783
784 leaks_fixed = check->leaks_fixed;
785 corruptions_fixed = check->corruptions_fixed;
786
787 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100788 qprintf(quiet,
789 "The following inconsistencies were found and repaired:\n\n"
790 " %" PRId64 " leaked clusters\n"
791 " %" PRId64 " corruptions\n\n"
792 "Double checking the fixed image now...\n",
793 check->leaks_fixed,
794 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500795 }
796
797 ret = collect_image_check(bs, check, filename, fmt, 0);
798
799 check->leaks_fixed = leaks_fixed;
800 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200801 }
802
Max Reitz832390a2014-10-23 15:29:12 +0200803 if (!ret) {
804 switch (output_format) {
805 case OFORMAT_HUMAN:
806 dump_human_image_check(check, quiet);
807 break;
808 case OFORMAT_JSON:
809 dump_json_image_check(check, quiet);
810 break;
811 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500812 }
813
814 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200815 if (ret) {
816 error_report("Check failed: %s", strerror(-ret));
817 } else {
818 error_report("Check failed");
819 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500820 ret = 1;
821 goto fail;
822 }
823
824 if (check->corruptions) {
825 ret = 2;
826 } else if (check->leaks) {
827 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200828 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500829 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000830 }
831
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500832fail:
833 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200834 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500835 return ret;
aliguori15859692009-04-21 23:11:53 +0000836}
837
Max Reitzd4a32382014-10-24 15:57:37 +0200838typedef struct CommonBlockJobCBInfo {
839 BlockDriverState *bs;
840 Error **errp;
841} CommonBlockJobCBInfo;
842
843static void common_block_job_cb(void *opaque, int ret)
844{
845 CommonBlockJobCBInfo *cbi = opaque;
846
847 if (ret < 0) {
848 error_setg_errno(cbi->errp, -ret, "Block job failed");
849 }
Max Reitzd4a32382014-10-24 15:57:37 +0200850}
851
852static void run_block_job(BlockJob *job, Error **errp)
853{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200854 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800855 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200856
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200857 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200858 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200859 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200860 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200861 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200862 if (job->job.progress_total) {
863 progress = (float)job->job.progress_current /
864 job->job.progress_total * 100.f;
865 }
866 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200867 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200868
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200869 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200870 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800871 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200872 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800873 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200874 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200875 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200876
sochin.jiang4172a002017-06-15 14:47:33 +0800877 /* publish completion progress only when success */
878 if (!ret) {
879 qemu_progress_print(100.f, 0);
880 }
Max Reitzd4a32382014-10-24 15:57:37 +0200881}
882
bellardea2384d2004-08-01 21:59:26 +0000883static int img_commit(int argc, char **argv)
884{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400885 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200886 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200887 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200888 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100889 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200890 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100891 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200892 Error *local_err = NULL;
893 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000894 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200895 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000896
897 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400898 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200899 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000900 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000901 static const struct option long_options[] = {
902 {"help", no_argument, 0, 'h'},
903 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000904 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000905 {0, 0, 0, 0}
906 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800907 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000908 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100909 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000910 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100911 }
bellardea2384d2004-08-01 21:59:26 +0000912 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800913 case ':':
914 missing_argument(argv[optind - 1]);
915 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100916 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800917 unrecognized_option(argv[optind - 1]);
918 break;
bellardea2384d2004-08-01 21:59:26 +0000919 case 'h':
920 help();
921 break;
922 case 'f':
923 fmt = optarg;
924 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400925 case 't':
926 cache = optarg;
927 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200928 case 'b':
929 base = optarg;
930 /* -b implies -d */
931 drop = true;
932 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200933 case 'd':
934 drop = true;
935 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200936 case 'p':
937 progress = true;
938 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100939 case 'q':
940 quiet = true;
941 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000942 case OPTION_OBJECT: {
943 QemuOpts *opts;
944 opts = qemu_opts_parse_noisily(&qemu_object_opts,
945 optarg, true);
946 if (!opts) {
947 return 1;
948 }
949 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000950 case OPTION_IMAGE_OPTS:
951 image_opts = true;
952 break;
bellardea2384d2004-08-01 21:59:26 +0000953 }
954 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200955
956 /* Progress is not shown in Quiet mode */
957 if (quiet) {
958 progress = false;
959 }
960
Kevin Wolffc11eb22013-08-05 10:53:04 +0200961 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800962 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100963 }
bellardea2384d2004-08-01 21:59:26 +0000964 filename = argv[optind++];
965
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000966 if (qemu_opts_foreach(&qemu_object_opts,
967 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200968 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000969 return 1;
970 }
971
Max Reitz9a86fe42014-10-24 15:57:38 +0200972 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100973 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400974 if (ret < 0) {
975 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100976 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400977 }
978
Fam Zheng335e9932017-05-03 00:35:39 +0800979 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
980 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200981 if (!blk) {
982 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900983 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200984 bs = blk_bs(blk);
985
Max Reitz687fa1d2014-10-24 15:57:39 +0200986 qemu_progress_init(progress, 1.f);
987 qemu_progress_print(0.f, 100);
988
Max Reitz1b22bff2014-10-24 15:57:40 +0200989 if (base) {
990 base_bs = bdrv_find_backing_image(bs, base);
991 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100992 error_setg(&local_err,
993 "Did not find '%s' in the backing chain of '%s'",
994 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200995 goto done;
996 }
997 } else {
998 /* This is different from QMP, which by default uses the deepest file in
999 * the backing chain (i.e., the very base); however, the traditional
1000 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001001 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001002 if (!base_bs) {
1003 error_setg(&local_err, "Image does not have a backing file");
1004 goto done;
1005 }
bellardea2384d2004-08-01 21:59:26 +00001006 }
1007
Max Reitzd4a32382014-10-24 15:57:37 +02001008 cbi = (CommonBlockJobCBInfo){
1009 .errp = &local_err,
1010 .bs = bs,
1011 };
1012
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001013 aio_context = bdrv_get_aio_context(bs);
1014 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001015 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001016 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001017 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001018 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001019 if (local_err) {
1020 goto done;
1021 }
1022
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001023 /* When the block job completes, the BlockBackend reference will point to
1024 * the old backing file. In order to avoid that the top image is already
1025 * deleted, so we can still empty it afterwards, increment the reference
1026 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001027 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001028 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001029 }
1030
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001031 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001032 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001033 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001034 if (local_err) {
1035 goto unref_backing;
1036 }
1037
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001038 if (!drop && bs->drv->bdrv_make_empty) {
1039 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001040 if (ret) {
1041 error_setg_errno(&local_err, -ret, "Could not empty %s",
1042 filename);
1043 goto unref_backing;
1044 }
1045 }
1046
1047unref_backing:
1048 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001049 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001050 }
Max Reitzd4a32382014-10-24 15:57:37 +02001051
1052done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001053 qemu_progress_end();
1054
Markus Armbruster26f54e92014-10-07 13:59:04 +02001055 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001056
1057 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001058 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001059 return 1;
1060 }
Max Reitzd4a32382014-10-24 15:57:37 +02001061
1062 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001063 return 0;
1064}
1065
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001066/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001067 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1068 * of the first sector boundary within buf where the sector contains a
1069 * non-zero byte. This function is robust to a buffer that is not
1070 * sector-aligned.
1071 */
1072static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1073{
1074 int64_t i;
1075 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1076
1077 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1078 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1079 return i;
1080 }
1081 }
1082 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1083 return i;
1084 }
1085 return -1;
1086}
1087
1088/*
thsf58c7b32008-06-05 21:53:49 +00001089 * Returns true iff the first sector pointed to by 'buf' contains at least
1090 * a non-NUL byte.
1091 *
1092 * 'pnum' is set to the number of sectors (including and immediately following
1093 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001094 * The function will try to align the end offset to alignment boundaries so
1095 * that the request will at least end aligned and consequtive requests will
1096 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001097 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001098static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1099 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001100{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001101 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001102 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001103
1104 if (n <= 0) {
1105 *pnum = 0;
1106 return 0;
1107 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001108 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001109 for(i = 1; i < n; i++) {
1110 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001111 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001112 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001113 }
bellardea2384d2004-08-01 21:59:26 +00001114 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001115
1116 tail = (sector_num + i) & (alignment - 1);
1117 if (tail) {
1118 if (is_zero && i <= tail) {
1119 /* treat unallocated areas which only consist
1120 * of a small tail as allocated. */
1121 is_zero = false;
1122 }
1123 if (!is_zero) {
1124 /* align up end offset of allocated areas. */
1125 i += alignment - tail;
1126 i = MIN(i, n);
1127 } else {
1128 /* align down end offset of zero areas. */
1129 i -= tail;
1130 }
1131 }
bellardea2384d2004-08-01 21:59:26 +00001132 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001133 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001134}
1135
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001136/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001137 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1138 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1139 * breaking up write requests for only small sparse areas.
1140 */
1141static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001142 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001143{
1144 int ret;
1145 int num_checked, num_used;
1146
1147 if (n < min) {
1148 min = n;
1149 }
1150
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001151 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001152 if (!ret) {
1153 return ret;
1154 }
1155
1156 num_used = *pnum;
1157 buf += BDRV_SECTOR_SIZE * *pnum;
1158 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001159 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001160 num_checked = num_used;
1161
1162 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001163 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001164
1165 buf += BDRV_SECTOR_SIZE * *pnum;
1166 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001167 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001168 num_checked += *pnum;
1169 if (ret) {
1170 num_used = num_checked;
1171 } else if (*pnum >= min) {
1172 break;
1173 }
1174 }
1175
1176 *pnum = num_used;
1177 return 1;
1178}
1179
1180/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001181 * Compares two buffers sector by sector. Returns 0 if the first
1182 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001183 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001184 * pnum is set to the sector-aligned size of the buffer prefix that
1185 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001186 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001187static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1188 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001189{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001190 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001191 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001192
Eric Blakedc61cd32017-10-11 22:47:14 -05001193 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001194
Eric Blakedc61cd32017-10-11 22:47:14 -05001195 res = !!memcmp(buf1, buf2, i);
1196 while (i < bytes) {
1197 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001198
Eric Blakedc61cd32017-10-11 22:47:14 -05001199 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001200 break;
1201 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001202 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001203 }
1204
1205 *pnum = i;
1206 return res;
1207}
1208
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001209#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001210
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001211/*
1212 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1213 *
Eric Blake0608e402017-10-11 22:47:12 -05001214 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1215 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1216 * failure), and 4 on error (the exit status for read errors), after emitting
1217 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001218 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001219 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001220 * @param offset: Starting offset to check
1221 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001222 * @param filename: Name of disk file we are checking (logging purpose)
1223 * @param buffer: Allocated buffer for storing read data
1224 * @param quiet: Flag for quiet mode
1225 */
Eric Blakec41508e2017-10-11 22:47:13 -05001226static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1227 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001228 uint8_t *buffer, bool quiet)
1229{
Eric Blakedebb38a2017-10-11 22:47:11 -05001230 int ret = 0;
1231 int64_t idx;
1232
Eric Blakec41508e2017-10-11 22:47:13 -05001233 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001234 if (ret < 0) {
1235 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001236 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001237 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001238 }
Eric Blakec41508e2017-10-11 22:47:13 -05001239 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001240 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001241 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001242 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001243 return 1;
1244 }
1245
1246 return 0;
1247}
1248
1249/*
1250 * Compares two images. Exit codes:
1251 *
1252 * 0 - Images are identical
1253 * 1 - Images differ
1254 * >1 - Error occurred
1255 */
1256static int img_compare(int argc, char **argv)
1257{
Max Reitz40055952014-07-22 22:58:42 +02001258 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001259 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001260 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001261 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001262 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001263 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001264 int allocated1, allocated2;
1265 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1266 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001267 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001268 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001269 int64_t total_size;
1270 int64_t offset = 0;
1271 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001272 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001273 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001274 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001275 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001276
Max Reitz40055952014-07-22 22:58:42 +02001277 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001278 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001279 static const struct option long_options[] = {
1280 {"help", no_argument, 0, 'h'},
1281 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001282 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001283 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001284 {0, 0, 0, 0}
1285 };
Fam Zheng335e9932017-05-03 00:35:39 +08001286 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001287 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001288 if (c == -1) {
1289 break;
1290 }
1291 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001292 case ':':
1293 missing_argument(argv[optind - 1]);
1294 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001295 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001296 unrecognized_option(argv[optind - 1]);
1297 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001298 case 'h':
1299 help();
1300 break;
1301 case 'f':
1302 fmt1 = optarg;
1303 break;
1304 case 'F':
1305 fmt2 = optarg;
1306 break;
Max Reitz40055952014-07-22 22:58:42 +02001307 case 'T':
1308 cache = optarg;
1309 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001310 case 'p':
1311 progress = true;
1312 break;
1313 case 'q':
1314 quiet = true;
1315 break;
1316 case 's':
1317 strict = true;
1318 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001319 case 'U':
1320 force_share = true;
1321 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001322 case OPTION_OBJECT: {
1323 QemuOpts *opts;
1324 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1325 optarg, true);
1326 if (!opts) {
1327 ret = 2;
1328 goto out4;
1329 }
1330 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001331 case OPTION_IMAGE_OPTS:
1332 image_opts = true;
1333 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001334 }
1335 }
1336
1337 /* Progress is not shown in Quiet mode */
1338 if (quiet) {
1339 progress = false;
1340 }
1341
1342
Kevin Wolffc11eb22013-08-05 10:53:04 +02001343 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001344 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001345 }
1346 filename1 = argv[optind++];
1347 filename2 = argv[optind++];
1348
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001349 if (qemu_opts_foreach(&qemu_object_opts,
1350 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001351 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001352 ret = 2;
1353 goto out4;
1354 }
1355
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001356 /* Initialize before goto out */
1357 qemu_progress_init(progress, 2.0);
1358
Kevin Wolfce099542016-03-15 13:01:04 +01001359 flags = 0;
1360 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001361 if (ret < 0) {
1362 error_report("Invalid source cache option: %s", cache);
1363 ret = 2;
1364 goto out3;
1365 }
1366
Fam Zheng335e9932017-05-03 00:35:39 +08001367 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1368 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001369 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001370 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001371 goto out3;
1372 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001373
Fam Zheng335e9932017-05-03 00:35:39 +08001374 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1375 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001376 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001377 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001378 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001379 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001380 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001381 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001382
Max Reitzf1d3cd72015-02-05 13:58:18 -05001383 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1384 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001385 total_size1 = blk_getlength(blk1);
1386 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001387 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001388 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001389 ret = 4;
1390 goto out;
1391 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001392 total_size2 = blk_getlength(blk2);
1393 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001394 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001395 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001396 ret = 4;
1397 goto out;
1398 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001399 total_size = MIN(total_size1, total_size2);
1400 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001401
1402 qemu_progress_print(0, 100);
1403
Eric Blake033d9fc2017-10-11 22:47:16 -05001404 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001405 ret = 1;
1406 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1407 goto out;
1408 }
1409
Eric Blake033d9fc2017-10-11 22:47:16 -05001410 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001411 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001412
Eric Blake033d9fc2017-10-11 22:47:16 -05001413 status1 = bdrv_block_status_above(bs1, NULL, offset,
1414 total_size1 - offset, &pnum1, NULL,
1415 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001416 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001417 ret = 3;
1418 error_report("Sector allocation test failed for %s", filename1);
1419 goto out;
1420 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001421 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001422
Eric Blake033d9fc2017-10-11 22:47:16 -05001423 status2 = bdrv_block_status_above(bs2, NULL, offset,
1424 total_size2 - offset, &pnum2, NULL,
1425 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001426 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001427 ret = 3;
1428 error_report("Sector allocation test failed for %s", filename2);
1429 goto out;
1430 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001431 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001432
1433 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001434 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001435
Fam Zheng25ad8e62016-01-13 16:37:41 +08001436 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001437 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001438 ret = 1;
1439 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001440 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001441 goto out;
1442 }
1443 }
1444 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001445 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001446 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001447 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001448 int64_t pnum;
1449
Eric Blake033d9fc2017-10-11 22:47:16 -05001450 chunk = MIN(chunk, IO_BUF_SIZE);
1451 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001452 if (ret < 0) {
1453 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001454 " of %s: %s",
1455 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001456 ret = 4;
1457 goto out;
1458 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001459 ret = blk_pread(blk2, offset, buf2, chunk);
1460 if (ret < 0) {
1461 error_report("Error while reading offset %" PRId64
1462 " of %s: %s",
1463 offset, filename2, strerror(-ret));
1464 ret = 4;
1465 goto out;
1466 }
1467 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1468 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001469 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001470 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001471 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001472 goto out;
1473 }
1474 }
1475 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001476 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001477 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001478 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001479 filename1, buf1, quiet);
1480 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001481 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001482 filename2, buf1, quiet);
1483 }
1484 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001485 goto out;
1486 }
1487 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001488 offset += chunk;
1489 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001490 }
1491
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001493 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001494 const char *filename_over;
1495
1496 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001497 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001498 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 filename_over = filename1;
1500 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001501 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001502 filename_over = filename2;
1503 }
1504
Eric Blake033d9fc2017-10-11 22:47:16 -05001505 while (offset < progress_base) {
1506 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1507 progress_base - offset, &chunk,
1508 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001509 if (ret < 0) {
1510 ret = 3;
1511 error_report("Sector allocation test failed for %s",
1512 filename_over);
1513 goto out;
1514
1515 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001516 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001517 chunk = MIN(chunk, IO_BUF_SIZE);
1518 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519 filename_over, buf1, quiet);
1520 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001521 goto out;
1522 }
1523 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001524 offset += chunk;
1525 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001526 }
1527 }
1528
1529 qprintf(quiet, "Images are identical.\n");
1530 ret = 0;
1531
1532out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001533 qemu_vfree(buf1);
1534 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001535 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001536out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001537 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001538out3:
1539 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001540out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001541 return ret;
1542}
1543
Kevin Wolf690c7302015-03-19 13:33:32 +01001544enum ImgConvertBlockStatus {
1545 BLK_DATA,
1546 BLK_ZERO,
1547 BLK_BACKING_FILE,
1548};
1549
Peter Lieven2d9187b2017-02-28 13:40:07 +01001550#define MAX_COROUTINES 16
1551
Kevin Wolf690c7302015-03-19 13:33:32 +01001552typedef struct ImgConvertState {
1553 BlockBackend **src;
1554 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001555 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001556 int64_t total_sectors;
1557 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001558 int64_t allocated_done;
1559 int64_t sector_num;
1560 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001561 enum ImgConvertBlockStatus status;
1562 int64_t sector_next_status;
1563 BlockBackend *target;
1564 bool has_zero_init;
1565 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001566 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001567 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001568 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001569 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001570 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001571 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001572 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001573 size_t cluster_sectors;
1574 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001575 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001576 int running_coroutines;
1577 Coroutine *co[MAX_COROUTINES];
1578 int64_t wait_sector_num[MAX_COROUTINES];
1579 CoMutex lock;
1580 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001581} ImgConvertState;
1582
Peter Lieven2d9187b2017-02-28 13:40:07 +01001583static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1584 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001585{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001586 *src_cur = 0;
1587 *src_cur_offset = 0;
1588 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1589 *src_cur_offset += s->src_sectors[*src_cur];
1590 (*src_cur)++;
1591 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001592 }
1593}
1594
1595static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1596{
Eric Blake31826642017-10-11 22:47:08 -05001597 int64_t src_cur_offset;
1598 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001599 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001600
Peter Lieven2d9187b2017-02-28 13:40:07 +01001601 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001602
1603 assert(s->total_sectors > sector_num);
1604 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1605
Max Reitz351c8ef2018-05-01 18:57:49 +02001606 if (s->target_backing_sectors >= 0) {
1607 if (sector_num >= s->target_backing_sectors) {
1608 post_backing_zero = s->unallocated_blocks_are_zero;
1609 } else if (sector_num + n > s->target_backing_sectors) {
1610 /* Split requests around target_backing_sectors (because
1611 * starting from there, zeros are handled differently) */
1612 n = s->target_backing_sectors - sector_num;
1613 }
1614 }
1615
Kevin Wolf690c7302015-03-19 13:33:32 +01001616 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001617 int64_t count = n * BDRV_SECTOR_SIZE;
1618
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001619 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001620
1621 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1622 (sector_num - src_cur_offset) *
1623 BDRV_SECTOR_SIZE,
1624 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001625 } else {
Eric Blake31826642017-10-11 22:47:08 -05001626 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1627 (sector_num - src_cur_offset) *
1628 BDRV_SECTOR_SIZE,
1629 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001630 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001631 if (ret < 0) {
1632 return ret;
1633 }
Eric Blake31826642017-10-11 22:47:08 -05001634 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001635
1636 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001637 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001638 } else if (ret & BDRV_BLOCK_DATA) {
1639 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001640 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001641 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001642 }
1643
1644 s->sector_next_status = sector_num + n;
1645 }
1646
1647 n = MIN(n, s->sector_next_status - sector_num);
1648 if (s->status == BLK_DATA) {
1649 n = MIN(n, s->buf_sectors);
1650 }
1651
1652 /* We need to write complete clusters for compressed images, so if an
1653 * unallocated area is shorter than that, we must consider the whole
1654 * cluster allocated. */
1655 if (s->compressed) {
1656 if (n < s->cluster_sectors) {
1657 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1658 s->status = BLK_DATA;
1659 } else {
1660 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1661 }
1662 }
1663
1664 return n;
1665}
1666
Peter Lieven2d9187b2017-02-28 13:40:07 +01001667static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1668 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001669{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001670 int n, ret;
1671 QEMUIOVector qiov;
1672 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001673
Kevin Wolf690c7302015-03-19 13:33:32 +01001674 assert(nb_sectors <= s->buf_sectors);
1675 while (nb_sectors > 0) {
1676 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001677 int src_cur;
1678 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001679
1680 /* In the case of compression with multiple source files, we can get a
1681 * nb_sectors that spreads into the next part. So we must be able to
1682 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001683 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1684 blk = s->src[src_cur];
1685 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001686
Peter Lieven2d9187b2017-02-28 13:40:07 +01001687 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1688 iov.iov_base = buf;
1689 iov.iov_len = n << BDRV_SECTOR_BITS;
1690 qemu_iovec_init_external(&qiov, &iov, 1);
1691
1692 ret = blk_co_preadv(
1693 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1694 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001695 if (ret < 0) {
1696 return ret;
1697 }
1698
1699 sector_num += n;
1700 nb_sectors -= n;
1701 buf += n * BDRV_SECTOR_SIZE;
1702 }
1703
1704 return 0;
1705}
1706
Peter Lieven2d9187b2017-02-28 13:40:07 +01001707
1708static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1709 int nb_sectors, uint8_t *buf,
1710 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001711{
1712 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001713 QEMUIOVector qiov;
1714 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001715
1716 while (nb_sectors > 0) {
1717 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001718 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1719
Peter Lieven2d9187b2017-02-28 13:40:07 +01001720 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001721 case BLK_BACKING_FILE:
1722 /* If we have a backing file, leave clusters unallocated that are
1723 * unallocated in the source image, so that the backing file is
1724 * visible at the respective offset. */
1725 assert(s->target_has_backing);
1726 break;
1727
1728 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001729 /* If we're told to keep the target fully allocated (-S 0) or there
1730 * is real non-zero data, we must write it. Otherwise we can treat
1731 * it as zero sectors.
1732 * Compressed clusters need to be written as a whole, so in that
1733 * case we can only save the write if the buffer is completely
1734 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001735 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001736 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001737 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1738 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001739 (s->compressed &&
1740 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001741 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001742 iov.iov_base = buf;
1743 iov.iov_len = n << BDRV_SECTOR_BITS;
1744 qemu_iovec_init_external(&qiov, &iov, 1);
1745
1746 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001747 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001748 if (ret < 0) {
1749 return ret;
1750 }
1751 break;
1752 }
1753 /* fall-through */
1754
1755 case BLK_ZERO:
1756 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001757 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001758 break;
1759 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001760 ret = blk_co_pwrite_zeroes(s->target,
1761 sector_num << BDRV_SECTOR_BITS,
1762 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001763 if (ret < 0) {
1764 return ret;
1765 }
1766 break;
1767 }
1768
1769 sector_num += n;
1770 nb_sectors -= n;
1771 buf += n * BDRV_SECTOR_SIZE;
1772 }
1773
1774 return 0;
1775}
1776
Fam Zhengee5306d2018-06-01 17:26:48 +08001777static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1778 int nb_sectors)
1779{
1780 int n, ret;
1781
1782 while (nb_sectors > 0) {
1783 BlockBackend *blk;
1784 int src_cur;
1785 int64_t bs_sectors, src_cur_offset;
1786 int64_t offset;
1787
1788 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1789 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1790 blk = s->src[src_cur];
1791 bs_sectors = s->src_sectors[src_cur];
1792
1793 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1794
1795 ret = blk_co_copy_range(blk, offset, s->target,
1796 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001797 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001798 if (ret < 0) {
1799 return ret;
1800 }
1801
1802 sector_num += n;
1803 nb_sectors -= n;
1804 }
1805 return 0;
1806}
1807
Peter Lieven2d9187b2017-02-28 13:40:07 +01001808static void coroutine_fn convert_co_do_copy(void *opaque)
1809{
1810 ImgConvertState *s = opaque;
1811 uint8_t *buf = NULL;
1812 int ret, i;
1813 int index = -1;
1814
1815 for (i = 0; i < s->num_coroutines; i++) {
1816 if (s->co[i] == qemu_coroutine_self()) {
1817 index = i;
1818 break;
1819 }
1820 }
1821 assert(index >= 0);
1822
1823 s->running_coroutines++;
1824 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1825
1826 while (1) {
1827 int n;
1828 int64_t sector_num;
1829 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001830 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001831
1832 qemu_co_mutex_lock(&s->lock);
1833 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1834 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001835 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001836 }
1837 n = convert_iteration_sectors(s, s->sector_num);
1838 if (n < 0) {
1839 qemu_co_mutex_unlock(&s->lock);
1840 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001841 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001842 }
1843 /* save current sector and allocation status to local variables */
1844 sector_num = s->sector_num;
1845 status = s->status;
1846 if (!s->min_sparse && s->status == BLK_ZERO) {
1847 n = MIN(n, s->buf_sectors);
1848 }
1849 /* increment global sector counter so that other coroutines can
1850 * already continue reading beyond this request */
1851 s->sector_num += n;
1852 qemu_co_mutex_unlock(&s->lock);
1853
1854 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1855 s->allocated_done += n;
1856 qemu_progress_print(100.0 * s->allocated_done /
1857 s->allocated_sectors, 0);
1858 }
1859
Fam Zhengee5306d2018-06-01 17:26:48 +08001860retry:
1861 copy_range = s->copy_range && s->status == BLK_DATA;
1862 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001863 ret = convert_co_read(s, sector_num, n, buf);
1864 if (ret < 0) {
1865 error_report("error while reading sector %" PRId64
1866 ": %s", sector_num, strerror(-ret));
1867 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001868 }
1869 } else if (!s->min_sparse && status == BLK_ZERO) {
1870 status = BLK_DATA;
1871 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1872 }
1873
1874 if (s->wr_in_order) {
1875 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001876 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001877 s->wait_sector_num[index] = sector_num;
1878 qemu_coroutine_yield();
1879 }
1880 s->wait_sector_num[index] = -1;
1881 }
1882
Anton Nefedovb91127e2017-04-26 11:33:15 +03001883 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001884 if (copy_range) {
1885 ret = convert_co_copy_range(s, sector_num, n);
1886 if (ret) {
1887 s->copy_range = false;
1888 goto retry;
1889 }
1890 } else {
1891 ret = convert_co_write(s, sector_num, n, buf, status);
1892 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001893 if (ret < 0) {
1894 error_report("error while writing sector %" PRId64
1895 ": %s", sector_num, strerror(-ret));
1896 s->ret = ret;
1897 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001898 }
1899
1900 if (s->wr_in_order) {
1901 /* reenter the coroutine that might have waited
1902 * for this write to complete */
1903 s->wr_offs = sector_num + n;
1904 for (i = 0; i < s->num_coroutines; i++) {
1905 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1906 /*
1907 * A -> B -> A cannot occur because A has
1908 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1909 * B will never enter A during this time window.
1910 */
1911 qemu_coroutine_enter(s->co[i]);
1912 break;
1913 }
1914 }
1915 }
1916 }
1917
Peter Lieven2d9187b2017-02-28 13:40:07 +01001918 qemu_vfree(buf);
1919 s->co[index] = NULL;
1920 s->running_coroutines--;
1921 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1922 /* the convert job finished successfully */
1923 s->ret = 0;
1924 }
1925}
1926
Kevin Wolf690c7302015-03-19 13:33:32 +01001927static int convert_do_copy(ImgConvertState *s)
1928{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001929 int ret, i, n;
1930 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001931
1932 /* Check whether we have zero initialisation or can get it efficiently */
1933 s->has_zero_init = s->min_sparse && !s->target_has_backing
1934 ? bdrv_has_zero_init(blk_bs(s->target))
1935 : false;
1936
1937 if (!s->has_zero_init && !s->target_has_backing &&
1938 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1939 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001940 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001941 if (ret == 0) {
1942 s->has_zero_init = true;
1943 }
1944 }
1945
1946 /* Allocate buffer for copied data. For compressed images, only one cluster
1947 * can be copied at a time. */
1948 if (s->compressed) {
1949 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1950 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001951 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001952 }
1953 s->buf_sectors = s->cluster_sectors;
1954 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001955
Kevin Wolf690c7302015-03-19 13:33:32 +01001956 while (sector_num < s->total_sectors) {
1957 n = convert_iteration_sectors(s, sector_num);
1958 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001959 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001960 }
Max Reitzaad15de2016-03-24 23:33:57 +01001961 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1962 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001963 s->allocated_sectors += n;
1964 }
1965 sector_num += n;
1966 }
1967
1968 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001969 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001970 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001971
Peter Lieven2d9187b2017-02-28 13:40:07 +01001972 qemu_co_mutex_init(&s->lock);
1973 for (i = 0; i < s->num_coroutines; i++) {
1974 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1975 s->wait_sector_num[i] = -1;
1976 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001977 }
1978
Anton Nefedovb91127e2017-04-26 11:33:15 +03001979 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001980 main_loop_wait(false);
1981 }
1982
1983 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001984 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001985 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001986 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001987 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001988 }
1989 }
1990
Peter Lieven2d9187b2017-02-28 13:40:07 +01001991 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001992}
1993
Peter Lieven6360ab22018-07-13 09:15:39 +02001994#define MAX_BUF_SECTORS 32768
1995
bellardea2384d2004-08-01 21:59:26 +00001996static int img_convert(int argc, char **argv)
1997{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001998 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001999 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002000 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2001 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002002 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002003 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002004 BlockDriverState *out_bs;
2005 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002006 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002007 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002008 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002009 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002010 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002011 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002012 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002013 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002014 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002015
Peter Lieven9fd77f92017-04-21 11:11:55 +02002016 ImgConvertState s = (ImgConvertState) {
2017 /* Need at least 4k of zeros for sparse detection */
2018 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002019 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002020 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2021 .wr_in_order = true,
2022 .num_coroutines = 8,
2023 };
2024
bellardea2384d2004-08-01 21:59:26 +00002025 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002026 static const struct option long_options[] = {
2027 {"help", no_argument, 0, 'h'},
2028 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002029 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002030 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002031 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002032 {0, 0, 0, 0}
2033 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002034 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002035 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002036 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002037 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002038 }
bellardea2384d2004-08-01 21:59:26 +00002039 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002040 case ':':
2041 missing_argument(argv[optind - 1]);
2042 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002043 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002044 unrecognized_option(argv[optind - 1]);
2045 break;
bellardea2384d2004-08-01 21:59:26 +00002046 case 'h':
2047 help();
2048 break;
2049 case 'f':
2050 fmt = optarg;
2051 break;
2052 case 'O':
2053 out_fmt = optarg;
2054 break;
thsf58c7b32008-06-05 21:53:49 +00002055 case 'B':
2056 out_baseimg = optarg;
2057 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002058 case 'C':
2059 s.copy_range = true;
2060 break;
bellardea2384d2004-08-01 21:59:26 +00002061 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002062 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002063 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002064 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002065 if (!is_valid_option_list(optarg)) {
2066 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002067 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002068 }
2069 if (!options) {
2070 options = g_strdup(optarg);
2071 } else {
2072 char *old_options = options;
2073 options = g_strdup_printf("%s,%s", options, optarg);
2074 g_free(old_options);
2075 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002076 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002077 case 'l':
2078 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002079 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2080 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002081 if (!sn_opts) {
2082 error_report("Failed in parsing snapshot param '%s'",
2083 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002084 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002085 }
2086 } else {
2087 snapshot_name = optarg;
2088 }
2089 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002090 case 'S':
2091 {
2092 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002093
2094 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002095 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2096 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2097 error_report("Invalid buffer size for sparse output specified. "
2098 "Valid sizes are multiples of %llu up to %llu. Select "
2099 "0 to disable sparse detection (fully allocates output).",
2100 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002101 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002102 }
2103
Peter Lieven9fd77f92017-04-21 11:11:55 +02002104 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002105 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002106 break;
2107 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002108 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002109 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002110 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002111 case 't':
2112 cache = optarg;
2113 break;
Max Reitz40055952014-07-22 22:58:42 +02002114 case 'T':
2115 src_cache = optarg;
2116 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002117 case 'q':
2118 quiet = true;
2119 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002120 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002121 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002122 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002123 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002124 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2125 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002126 error_report("Invalid number of coroutines. Allowed number of"
2127 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002128 goto fail_getopt;
2129 }
2130 break;
2131 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002132 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002133 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002134 case 'U':
2135 force_share = true;
2136 break;
Max Reitz3258b912017-04-26 15:46:47 +02002137 case OPTION_OBJECT: {
2138 QemuOpts *object_opts;
2139 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2140 optarg, true);
2141 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002142 goto fail_getopt;
2143 }
2144 break;
Max Reitz3258b912017-04-26 15:46:47 +02002145 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002146 case OPTION_IMAGE_OPTS:
2147 image_opts = true;
2148 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002149 case OPTION_TARGET_IMAGE_OPTS:
2150 tgt_image_opts = true;
2151 break;
bellardea2384d2004-08-01 21:59:26 +00002152 }
2153 }
ths3b46e622007-09-17 08:09:54 +00002154
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002155 if (!out_fmt && !tgt_image_opts) {
2156 out_fmt = "raw";
2157 }
2158
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002159 if (qemu_opts_foreach(&qemu_object_opts,
2160 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002161 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002162 goto fail_getopt;
2163 }
2164
Fam Zhenge11ce122018-07-27 11:34:01 +08002165 if (s.compressed && s.copy_range) {
2166 error_report("Cannot enable copy offloading when -c is used");
2167 goto fail_getopt;
2168 }
2169
2170 if (explict_min_sparse && s.copy_range) {
2171 error_report("Cannot enable copy offloading when -S is used");
2172 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
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002352 /*
2353 * The later open call will need any decryption secrets, and
2354 * bdrv_create() will purge "opts", so extract them now before
2355 * they are lost.
2356 */
2357 if (!skip_create) {
2358 open_opts = qdict_new();
2359 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2360 }
2361
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002362 if (!skip_create) {
2363 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002364 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002365 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002366 error_reportf_err(local_err, "%s: error while converting %s: ",
2367 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002368 goto out;
bellardea2384d2004-08-01 21:59:26 +00002369 }
2370 }
ths3b46e622007-09-17 08:09:54 +00002371
Peter Lieven9fd77f92017-04-21 11:11:55 +02002372 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002373 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002374 if (ret < 0) {
2375 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002376 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002377 }
2378
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002379 if (skip_create) {
2380 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2381 flags, writethrough, quiet, false);
2382 } else {
2383 /* TODO ultimately we should allow --target-image-opts
2384 * to be used even when -n is not given.
2385 * That has to wait for bdrv_create to be improved
2386 * to allow filenames in option syntax
2387 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002388 s.target = img_open_file(out_filename, open_opts, out_fmt,
2389 flags, writethrough, quiet, false);
2390 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002391 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002392 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002393 ret = -1;
2394 goto out;
2395 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002396 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002397
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002398 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2399 error_report("Compression not supported for this file format");
2400 ret = -1;
2401 goto out;
2402 }
2403
Eric Blake5def6b82016-06-23 16:37:19 -06002404 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002405 * or discard_alignment of the out_bs is greater. Limit to
2406 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2407 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002408 MAX(s.buf_sectors,
2409 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2410 out_bs->bl.pdiscard_alignment >>
2411 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002412
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002413 /* try to align the write requests to the destination to avoid unnecessary
2414 * RMW cycles. */
2415 s.alignment = MAX(pow2floor(s.min_sparse),
2416 DIV_ROUND_UP(out_bs->bl.request_alignment,
2417 BDRV_SECTOR_SIZE));
2418 assert(is_power_of_2(s.alignment));
2419
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002420 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002421 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002422 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002423 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002424 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002425 ret = -1;
2426 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002427 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002428 error_report("output file is smaller than input file");
2429 ret = -1;
2430 goto out;
2431 }
2432 }
2433
Max Reitz351c8ef2018-05-01 18:57:49 +02002434 if (s.target_has_backing) {
2435 /* Errors are treated as "backing length unknown" (which means
2436 * s.target_backing_sectors has to be negative, which it will
2437 * be automatically). The backing file length is used only
2438 * for optimizations, so such a case is not fatal. */
2439 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2440 } else {
2441 s.target_backing_sectors = -1;
2442 }
2443
Peter Lieven24f833c2013-11-27 11:07:07 +01002444 ret = bdrv_get_info(out_bs, &bdi);
2445 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002446 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002447 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002448 goto out;
2449 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002450 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002451 s.compressed = s.compressed || bdi.needs_compressed_writes;
2452 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002453 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002454 }
2455
Peter Lieven9fd77f92017-04-21 11:11:55 +02002456 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002457out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002458 if (!ret) {
2459 qemu_progress_print(100, 0);
2460 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002461 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002462 qemu_opts_del(opts);
2463 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002464 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002465 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002466 blk_unref(s.target);
2467 if (s.src) {
2468 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2469 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002470 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002471 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002472 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002473 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002474fail_getopt:
2475 g_free(options);
2476
Peter Lieven9fd77f92017-04-21 11:11:55 +02002477 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002478}
2479
bellard57d1a2b2004-08-03 21:15:11 +00002480
bellardfaea38e2006-08-05 21:31:00 +00002481static void dump_snapshots(BlockDriverState *bs)
2482{
2483 QEMUSnapshotInfo *sn_tab, *sn;
2484 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002485
2486 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2487 if (nb_sns <= 0)
2488 return;
2489 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002490 bdrv_snapshot_dump(fprintf, stdout, NULL);
2491 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002492 for(i = 0; i < nb_sns; i++) {
2493 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002494 bdrv_snapshot_dump(fprintf, stdout, sn);
2495 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002496 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002497 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002498}
2499
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002500static void dump_json_image_info_list(ImageInfoList *list)
2501{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002502 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002503 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002504 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002505
2506 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2507 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002508 str = qobject_to_json_pretty(obj);
2509 assert(str != NULL);
2510 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002511 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002512 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002513 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002514}
2515
Benoît Canetc054b3f2012-09-05 13:09:02 +02002516static void dump_json_image_info(ImageInfo *info)
2517{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002518 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002519 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002520 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002521
2522 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2523 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002524 str = qobject_to_json_pretty(obj);
2525 assert(str != NULL);
2526 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002527 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002528 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002529 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002530}
2531
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002532static void dump_human_image_info_list(ImageInfoList *list)
2533{
2534 ImageInfoList *elem;
2535 bool delim = false;
2536
2537 for (elem = list; elem; elem = elem->next) {
2538 if (delim) {
2539 printf("\n");
2540 }
2541 delim = true;
2542
Wenchao Xia5b917042013-05-25 11:09:45 +08002543 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002544 }
2545}
2546
2547static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2548{
2549 return strcmp(a, b) == 0;
2550}
2551
2552/**
2553 * Open an image file chain and return an ImageInfoList
2554 *
2555 * @filename: topmost image filename
2556 * @fmt: topmost image format (may be NULL to autodetect)
2557 * @chain: true - enumerate entire backing file chain
2558 * false - only topmost image file
2559 *
2560 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2561 * image file. If there was an error a message will have been printed to
2562 * stderr.
2563 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002564static ImageInfoList *collect_image_info_list(bool image_opts,
2565 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002566 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002567 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002568{
2569 ImageInfoList *head = NULL;
2570 ImageInfoList **last = &head;
2571 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002572 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002573
2574 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2575
2576 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002577 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002578 BlockDriverState *bs;
2579 ImageInfo *info;
2580 ImageInfoList *elem;
2581
2582 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2583 error_report("Backing file '%s' creates an infinite loop.",
2584 filename);
2585 goto err;
2586 }
2587 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2588
Max Reitzefaa7c42016-03-16 19:54:38 +01002589 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002590 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2591 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002592 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002593 goto err;
2594 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002595 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002596
Wenchao Xia43526ec2013-06-06 12:27:58 +08002597 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002598 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002599 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002600 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002601 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002602 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002603
2604 elem = g_new0(ImageInfoList, 1);
2605 elem->value = info;
2606 *last = elem;
2607 last = &elem->next;
2608
Markus Armbruster26f54e92014-10-07 13:59:04 +02002609 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002610
2611 filename = fmt = NULL;
2612 if (chain) {
2613 if (info->has_full_backing_filename) {
2614 filename = info->full_backing_filename;
2615 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002616 error_report("Could not determine absolute backing filename,"
2617 " but backing filename '%s' present",
2618 info->backing_filename);
2619 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002620 }
2621 if (info->has_backing_filename_format) {
2622 fmt = info->backing_filename_format;
2623 }
2624 }
2625 }
2626 g_hash_table_destroy(filenames);
2627 return head;
2628
2629err:
2630 qapi_free_ImageInfoList(head);
2631 g_hash_table_destroy(filenames);
2632 return NULL;
2633}
2634
Benoît Canetc054b3f2012-09-05 13:09:02 +02002635static int img_info(int argc, char **argv)
2636{
2637 int c;
2638 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002639 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002640 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002641 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002642 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002643 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002644
bellardea2384d2004-08-01 21:59:26 +00002645 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002646 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002647 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002648 int option_index = 0;
2649 static const struct option long_options[] = {
2650 {"help", no_argument, 0, 'h'},
2651 {"format", required_argument, 0, 'f'},
2652 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002653 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002654 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002655 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002656 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002657 {0, 0, 0, 0}
2658 };
Fam Zheng335e9932017-05-03 00:35:39 +08002659 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002660 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002661 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002662 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002663 }
bellardea2384d2004-08-01 21:59:26 +00002664 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002665 case ':':
2666 missing_argument(argv[optind - 1]);
2667 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002668 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002669 unrecognized_option(argv[optind - 1]);
2670 break;
bellardea2384d2004-08-01 21:59:26 +00002671 case 'h':
2672 help();
2673 break;
2674 case 'f':
2675 fmt = optarg;
2676 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002677 case 'U':
2678 force_share = true;
2679 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002680 case OPTION_OUTPUT:
2681 output = optarg;
2682 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002683 case OPTION_BACKING_CHAIN:
2684 chain = true;
2685 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002686 case OPTION_OBJECT: {
2687 QemuOpts *opts;
2688 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2689 optarg, true);
2690 if (!opts) {
2691 return 1;
2692 }
2693 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002694 case OPTION_IMAGE_OPTS:
2695 image_opts = true;
2696 break;
bellardea2384d2004-08-01 21:59:26 +00002697 }
2698 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002699 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002700 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002701 }
bellardea2384d2004-08-01 21:59:26 +00002702 filename = argv[optind++];
2703
Benoît Canetc054b3f2012-09-05 13:09:02 +02002704 if (output && !strcmp(output, "json")) {
2705 output_format = OFORMAT_JSON;
2706 } else if (output && !strcmp(output, "human")) {
2707 output_format = OFORMAT_HUMAN;
2708 } else if (output) {
2709 error_report("--output must be used with human or json as argument.");
2710 return 1;
2711 }
2712
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002713 if (qemu_opts_foreach(&qemu_object_opts,
2714 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002715 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002716 return 1;
2717 }
2718
Fam Zheng335e9932017-05-03 00:35:39 +08002719 list = collect_image_info_list(image_opts, filename, fmt, chain,
2720 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002721 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002722 return 1;
2723 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002724
Benoît Canetc054b3f2012-09-05 13:09:02 +02002725 switch (output_format) {
2726 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002727 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002728 break;
2729 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002730 if (chain) {
2731 dump_json_image_info_list(list);
2732 } else {
2733 dump_json_image_info(list->value);
2734 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002735 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002736 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002737
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002738 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002739 return 0;
2740}
2741
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002742static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2743 MapEntry *next)
2744{
2745 switch (output_format) {
2746 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002747 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002748 error_report("File contains external, encrypted or compressed clusters.");
2749 exit(1);
2750 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002751 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002752 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002753 e->start, e->length,
2754 e->has_offset ? e->offset : 0,
2755 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002756 }
2757 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2758 * Modify the flags here to allow more coalescing.
2759 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002760 if (next && (!next->data || next->zero)) {
2761 next->data = false;
2762 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002763 }
2764 break;
2765 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002766 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2767 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002768 (e->start == 0 ? "[" : ",\n"),
2769 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002770 e->zero ? "true" : "false",
2771 e->data ? "true" : "false");
2772 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002773 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002774 }
2775 putchar('}');
2776
2777 if (!next) {
2778 printf("]\n");
2779 }
2780 break;
2781 }
2782}
2783
Eric Blake5e344dd2017-10-11 22:47:02 -05002784static int get_block_status(BlockDriverState *bs, int64_t offset,
2785 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002786{
Eric Blake237d78f2017-10-11 22:47:03 -05002787 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002788 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002789 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002790 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002791 int64_t map;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002792
2793 /* As an optimization, we could cache the current range of unallocated
2794 * clusters in each file of the chain, and avoid querying the same
2795 * range repeatedly.
2796 */
2797
2798 depth = 0;
2799 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002800 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002801 if (ret < 0) {
2802 return ret;
2803 }
Eric Blake237d78f2017-10-11 22:47:03 -05002804 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002805 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2806 break;
2807 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002808 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002809 if (bs == NULL) {
2810 ret = 0;
2811 break;
2812 }
2813
2814 depth++;
2815 }
2816
John Snow28756452016-02-05 13:12:33 -05002817 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2818
2819 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002820 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002821 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002822 .data = !!(ret & BDRV_BLOCK_DATA),
2823 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002824 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002825 .has_offset = has_offset,
2826 .depth = depth,
2827 .has_filename = file && has_offset,
2828 .filename = file && has_offset ? file->filename : NULL,
2829 };
2830
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002831 return 0;
2832}
2833
Fam Zheng16b0d552016-01-26 11:59:02 +08002834static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2835{
2836 if (curr->length == 0) {
2837 return false;
2838 }
2839 if (curr->zero != next->zero ||
2840 curr->data != next->data ||
2841 curr->depth != next->depth ||
2842 curr->has_filename != next->has_filename ||
2843 curr->has_offset != next->has_offset) {
2844 return false;
2845 }
2846 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2847 return false;
2848 }
2849 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2850 return false;
2851 }
2852 return true;
2853}
2854
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002855static int img_map(int argc, char **argv)
2856{
2857 int c;
2858 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002859 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002860 BlockDriverState *bs;
2861 const char *filename, *fmt, *output;
2862 int64_t length;
2863 MapEntry curr = { .length = 0 }, next;
2864 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002865 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002866 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002867
2868 fmt = NULL;
2869 output = NULL;
2870 for (;;) {
2871 int option_index = 0;
2872 static const struct option long_options[] = {
2873 {"help", no_argument, 0, 'h'},
2874 {"format", required_argument, 0, 'f'},
2875 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002876 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002877 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002878 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002879 {0, 0, 0, 0}
2880 };
Fam Zheng335e9932017-05-03 00:35:39 +08002881 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002882 long_options, &option_index);
2883 if (c == -1) {
2884 break;
2885 }
2886 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002887 case ':':
2888 missing_argument(argv[optind - 1]);
2889 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002890 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002891 unrecognized_option(argv[optind - 1]);
2892 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002893 case 'h':
2894 help();
2895 break;
2896 case 'f':
2897 fmt = optarg;
2898 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002899 case 'U':
2900 force_share = true;
2901 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002902 case OPTION_OUTPUT:
2903 output = optarg;
2904 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002905 case OPTION_OBJECT: {
2906 QemuOpts *opts;
2907 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2908 optarg, true);
2909 if (!opts) {
2910 return 1;
2911 }
2912 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002913 case OPTION_IMAGE_OPTS:
2914 image_opts = true;
2915 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002916 }
2917 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002918 if (optind != argc - 1) {
2919 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002920 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002921 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002922
2923 if (output && !strcmp(output, "json")) {
2924 output_format = OFORMAT_JSON;
2925 } else if (output && !strcmp(output, "human")) {
2926 output_format = OFORMAT_HUMAN;
2927 } else if (output) {
2928 error_report("--output must be used with human or json as argument.");
2929 return 1;
2930 }
2931
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002932 if (qemu_opts_foreach(&qemu_object_opts,
2933 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002934 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002935 return 1;
2936 }
2937
Fam Zheng335e9932017-05-03 00:35:39 +08002938 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002939 if (!blk) {
2940 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002941 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002942 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002943
2944 if (output_format == OFORMAT_HUMAN) {
2945 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2946 }
2947
Max Reitzf1d3cd72015-02-05 13:58:18 -05002948 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002949 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002950 int64_t offset = curr.start + curr.length;
2951 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002952
2953 /* Probe up to 1 GiB at a time. */
Eric Blakee0b371e2018-06-11 16:39:26 -05002954 n = MIN(1 << 30, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002955 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002956
2957 if (ret < 0) {
2958 error_report("Could not read file metadata: %s", strerror(-ret));
2959 goto out;
2960 }
2961
Fam Zheng16b0d552016-01-26 11:59:02 +08002962 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002963 curr.length += next.length;
2964 continue;
2965 }
2966
2967 if (curr.length > 0) {
2968 dump_map_entry(output_format, &curr, &next);
2969 }
2970 curr = next;
2971 }
2972
2973 dump_map_entry(output_format, &curr, NULL);
2974
2975out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002976 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002977 return ret < 0;
2978}
2979
aliguorif7b4a942009-01-07 17:40:15 +00002980#define SNAPSHOT_LIST 1
2981#define SNAPSHOT_CREATE 2
2982#define SNAPSHOT_APPLY 3
2983#define SNAPSHOT_DELETE 4
2984
Stuart Brady153859b2009-06-07 00:42:17 +01002985static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002986{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002987 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002988 BlockDriverState *bs;
2989 QEMUSnapshotInfo sn;
2990 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002991 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002992 int action = 0;
2993 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002994 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002995 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002996 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002997 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002998
Kevin Wolfce099542016-03-15 13:01:04 +01002999 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003000 /* Parse commandline parameters */
3001 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003002 static const struct option long_options[] = {
3003 {"help", no_argument, 0, 'h'},
3004 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003005 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003006 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003007 {0, 0, 0, 0}
3008 };
Fam Zheng335e9932017-05-03 00:35:39 +08003009 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003010 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003011 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003012 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003013 }
aliguorif7b4a942009-01-07 17:40:15 +00003014 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003015 case ':':
3016 missing_argument(argv[optind - 1]);
3017 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003018 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003019 unrecognized_option(argv[optind - 1]);
3020 break;
aliguorif7b4a942009-01-07 17:40:15 +00003021 case 'h':
3022 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003023 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003024 case 'l':
3025 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003026 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003027 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003028 }
3029 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003030 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003031 break;
3032 case 'a':
3033 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003034 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003035 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003036 }
3037 action = SNAPSHOT_APPLY;
3038 snapshot_name = optarg;
3039 break;
3040 case 'c':
3041 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003042 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003043 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003044 }
3045 action = SNAPSHOT_CREATE;
3046 snapshot_name = optarg;
3047 break;
3048 case 'd':
3049 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003050 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003051 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003052 }
3053 action = SNAPSHOT_DELETE;
3054 snapshot_name = optarg;
3055 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003056 case 'q':
3057 quiet = true;
3058 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003059 case 'U':
3060 force_share = true;
3061 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003062 case OPTION_OBJECT: {
3063 QemuOpts *opts;
3064 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3065 optarg, true);
3066 if (!opts) {
3067 return 1;
3068 }
3069 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003070 case OPTION_IMAGE_OPTS:
3071 image_opts = true;
3072 break;
aliguorif7b4a942009-01-07 17:40:15 +00003073 }
3074 }
3075
Kevin Wolffc11eb22013-08-05 10:53:04 +02003076 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003077 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003078 }
aliguorif7b4a942009-01-07 17:40:15 +00003079 filename = argv[optind++];
3080
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003081 if (qemu_opts_foreach(&qemu_object_opts,
3082 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003083 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003084 return 1;
3085 }
3086
aliguorif7b4a942009-01-07 17:40:15 +00003087 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003088 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3089 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003090 if (!blk) {
3091 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003092 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003093 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003094
3095 /* Perform the requested action */
3096 switch(action) {
3097 case SNAPSHOT_LIST:
3098 dump_snapshots(bs);
3099 break;
3100
3101 case SNAPSHOT_CREATE:
3102 memset(&sn, 0, sizeof(sn));
3103 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3104
3105 qemu_gettimeofday(&tv);
3106 sn.date_sec = tv.tv_sec;
3107 sn.date_nsec = tv.tv_usec * 1000;
3108
3109 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003110 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003111 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003112 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003113 }
aliguorif7b4a942009-01-07 17:40:15 +00003114 break;
3115
3116 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003117 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003118 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003119 error_reportf_err(err, "Could not apply snapshot '%s': ",
3120 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003121 }
aliguorif7b4a942009-01-07 17:40:15 +00003122 break;
3123
3124 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003125 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003126 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003127 error_reportf_err(err, "Could not delete snapshot '%s': ",
3128 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003129 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003130 }
aliguorif7b4a942009-01-07 17:40:15 +00003131 break;
3132 }
3133
3134 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003135 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003136 if (ret) {
3137 return 1;
3138 }
Stuart Brady153859b2009-06-07 00:42:17 +01003139 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003140}
3141
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003142static int img_rebase(int argc, char **argv)
3143{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003144 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003145 uint8_t *buf_old = NULL;
3146 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003147 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003148 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003149 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3150 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003151 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003152 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003153 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003154 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003155 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003156 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003157 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003158
3159 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003160 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003161 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003162 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003163 out_baseimg = NULL;
3164 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003165 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003166 static const struct option long_options[] = {
3167 {"help", no_argument, 0, 'h'},
3168 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003169 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003170 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003171 {0, 0, 0, 0}
3172 };
Fam Zheng335e9932017-05-03 00:35:39 +08003173 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003174 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003175 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003176 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003177 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003178 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003179 case ':':
3180 missing_argument(argv[optind - 1]);
3181 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003182 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003183 unrecognized_option(argv[optind - 1]);
3184 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003185 case 'h':
3186 help();
3187 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003188 case 'f':
3189 fmt = optarg;
3190 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003191 case 'F':
3192 out_basefmt = optarg;
3193 break;
3194 case 'b':
3195 out_baseimg = optarg;
3196 break;
3197 case 'u':
3198 unsafe = 1;
3199 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003200 case 'p':
3201 progress = 1;
3202 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003203 case 't':
3204 cache = optarg;
3205 break;
Max Reitz40055952014-07-22 22:58:42 +02003206 case 'T':
3207 src_cache = optarg;
3208 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003209 case 'q':
3210 quiet = true;
3211 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003212 case OPTION_OBJECT: {
3213 QemuOpts *opts;
3214 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3215 optarg, true);
3216 if (!opts) {
3217 return 1;
3218 }
3219 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003220 case OPTION_IMAGE_OPTS:
3221 image_opts = true;
3222 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003223 case 'U':
3224 force_share = true;
3225 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003226 }
3227 }
3228
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003229 if (quiet) {
3230 progress = 0;
3231 }
3232
Fam Zhengac1307a2014-04-22 13:36:11 +08003233 if (optind != argc - 1) {
3234 error_exit("Expecting one image file name");
3235 }
3236 if (!unsafe && !out_baseimg) {
3237 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003238 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003239 filename = argv[optind++];
3240
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003241 if (qemu_opts_foreach(&qemu_object_opts,
3242 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003243 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003244 return 1;
3245 }
3246
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003247 qemu_progress_init(progress, 2.0);
3248 qemu_progress_print(0, 100);
3249
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003250 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003251 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003252 if (ret < 0) {
3253 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003254 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003255 }
3256
Kevin Wolfce099542016-03-15 13:01:04 +01003257 src_flags = 0;
3258 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003259 if (ret < 0) {
3260 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003261 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003262 }
3263
Kevin Wolfce099542016-03-15 13:01:04 +01003264 /* The source files are opened read-only, don't care about WCE */
3265 assert((src_flags & BDRV_O_RDWR) == 0);
3266 (void) src_writethrough;
3267
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003268 /*
3269 * Open the images.
3270 *
3271 * Ignore the old backing file for unsafe rebase in case we want to correct
3272 * the reference to a renamed or moved backing file.
3273 */
Fam Zheng335e9932017-05-03 00:35:39 +08003274 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3275 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003276 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003277 ret = -1;
3278 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003279 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003280 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003281
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003282 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003283 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003284 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003285 ret = -1;
3286 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003287 }
3288 }
3289
3290 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003291 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003292 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003293 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003294
Max Reitz644483d2015-02-05 13:58:17 -05003295 if (bs->backing_format[0] != '\0') {
3296 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003297 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003298 }
3299
Fam Zheng335e9932017-05-03 00:35:39 +08003300 if (force_share) {
3301 if (!options) {
3302 options = qdict_new();
3303 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003304 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003305 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003306 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003307 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003308 options, src_flags, &local_err);
3309 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003310 error_reportf_err(local_err,
3311 "Could not open old backing file '%s': ",
3312 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003313 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003314 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003315 }
Max Reitz644483d2015-02-05 13:58:17 -05003316
Alex Bligha6166732012-10-16 13:46:18 +01003317 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003318 const char *overlay_filename;
3319 char *out_real_path;
3320
Fam Zheng335e9932017-05-03 00:35:39 +08003321 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003322 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003323 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003324 }
3325 if (force_share) {
3326 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003327 }
3328
Max Reitzd16699b2018-05-09 20:20:01 +02003329 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3330 : bs->filename;
3331 out_real_path = g_malloc(PATH_MAX);
3332
3333 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3334 out_baseimg,
3335 out_real_path,
3336 PATH_MAX,
3337 &local_err);
3338 if (local_err) {
3339 error_reportf_err(local_err,
3340 "Could not resolve backing filename: ");
3341 ret = -1;
3342 g_free(out_real_path);
3343 goto out;
3344 }
3345
3346 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003347 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003348 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003349 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003350 error_reportf_err(local_err,
3351 "Could not open new backing file '%s': ",
3352 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003353 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003354 goto out;
3355 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003356 }
3357 }
3358
3359 /*
3360 * Check each unallocated cluster in the COW file. If it is unallocated,
3361 * accesses go to the backing file. We must therefore compare this cluster
3362 * in the old and new backing file, and if they differ we need to copy it
3363 * from the old backing file into the COW file.
3364 *
3365 * If qemu-img crashes during this step, no harm is done. The content of
3366 * the image is the same as the original one at any time.
3367 */
3368 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003369 int64_t size;
3370 int64_t old_backing_size;
3371 int64_t new_backing_size = 0;
3372 uint64_t offset;
3373 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003374 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003375
Max Reitzf1d3cd72015-02-05 13:58:18 -05003376 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3377 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003378
Eric Blake41536282017-10-11 22:47:15 -05003379 size = blk_getlength(blk);
3380 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003381 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003382 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003383 ret = -1;
3384 goto out;
3385 }
Eric Blake41536282017-10-11 22:47:15 -05003386 old_backing_size = blk_getlength(blk_old_backing);
3387 if (old_backing_size < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003388 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003389
3390 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3391 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003392 backing_name, strerror(-old_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003393 ret = -1;
3394 goto out;
3395 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003396 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003397 new_backing_size = blk_getlength(blk_new_backing);
3398 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003399 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003400 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003401 ret = -1;
3402 goto out;
3403 }
Alex Bligha6166732012-10-16 13:46:18 +01003404 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003405
Eric Blake41536282017-10-11 22:47:15 -05003406 if (size != 0) {
3407 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003408 }
3409
Eric Blake41536282017-10-11 22:47:15 -05003410 for (offset = 0; offset < size; offset += n) {
3411 /* How many bytes can we handle with the next read? */
3412 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003413
3414 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003415 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003416 if (ret < 0) {
3417 error_report("error while reading image metadata: %s",
3418 strerror(-ret));
3419 goto out;
3420 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003421 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003422 continue;
3423 }
3424
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003425 /*
3426 * Read old and new backing file and take into consideration that
3427 * backing files may be smaller than the COW image.
3428 */
Eric Blake41536282017-10-11 22:47:15 -05003429 if (offset >= old_backing_size) {
3430 memset(buf_old, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003431 } else {
Eric Blake41536282017-10-11 22:47:15 -05003432 if (offset + n > old_backing_size) {
3433 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003434 }
3435
Eric Blake41536282017-10-11 22:47:15 -05003436 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003437 if (ret < 0) {
3438 error_report("error while reading from old backing file");
3439 goto out;
3440 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003441 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003442
Eric Blake41536282017-10-11 22:47:15 -05003443 if (offset >= new_backing_size || !blk_new_backing) {
3444 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003445 } else {
Eric Blake41536282017-10-11 22:47:15 -05003446 if (offset + n > new_backing_size) {
3447 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003448 }
3449
Eric Blake41536282017-10-11 22:47:15 -05003450 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003451 if (ret < 0) {
3452 error_report("error while reading from new backing file");
3453 goto out;
3454 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003455 }
3456
3457 /* If they differ, we need to write to the COW file */
3458 uint64_t written = 0;
3459
Eric Blake41536282017-10-11 22:47:15 -05003460 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003461 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003462
Eric Blake41536282017-10-11 22:47:15 -05003463 if (compare_buffers(buf_old + written, buf_new + written,
3464 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003465 {
Eric Blake41536282017-10-11 22:47:15 -05003466 ret = blk_pwrite(blk, offset + written,
Eric Blakedc61cd32017-10-11 22:47:14 -05003467 buf_old + written, pnum, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003468 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003469 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003470 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003471 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003472 }
3473 }
3474
3475 written += pnum;
3476 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003477 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003478 }
3479 }
3480
3481 /*
3482 * Change the backing file. All clusters that are different from the old
3483 * backing file are overwritten in the COW file now, so the visible content
3484 * doesn't change when we switch the backing file.
3485 */
Alex Bligha6166732012-10-16 13:46:18 +01003486 if (out_baseimg && *out_baseimg) {
3487 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3488 } else {
3489 ret = bdrv_change_backing_file(bs, NULL, NULL);
3490 }
3491
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003492 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003493 error_report("Could not change the backing file to '%s': No "
3494 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003495 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003496 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003497 out_baseimg, strerror(-ret));
3498 }
3499
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003500 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003501 /*
3502 * TODO At this point it is possible to check if any clusters that are
3503 * allocated in the COW file are the same in the backing file. If so, they
3504 * could be dropped from the COW file. Don't do this before switching the
3505 * backing file, in case of a crash this would lead to corruption.
3506 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003507out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003508 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003509 /* Cleanup */
3510 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003511 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003512 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003513 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003514 qemu_vfree(buf_old);
3515 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003516
Markus Armbruster26f54e92014-10-07 13:59:04 +02003517 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003518 if (ret) {
3519 return 1;
3520 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003521 return 0;
3522}
3523
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003524static int img_resize(int argc, char **argv)
3525{
Markus Armbruster6750e792015-02-12 17:43:08 +01003526 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003527 int c, ret, relative;
3528 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003529 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003530 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003531 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003532 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003533 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003534
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003535 static QemuOptsList resize_options = {
3536 .name = "resize_options",
3537 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3538 .desc = {
3539 {
3540 .name = BLOCK_OPT_SIZE,
3541 .type = QEMU_OPT_SIZE,
3542 .help = "Virtual disk size"
3543 }, {
3544 /* end of list */
3545 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003546 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003547 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003548 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003549 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003550
Kevin Wolfe80fec72011-04-29 10:58:12 +02003551 /* Remove size from argv manually so that negative numbers are not treated
3552 * as options by getopt. */
3553 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003554 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003555 return 1;
3556 }
3557
3558 size = argv[--argc];
3559
3560 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003561 fmt = NULL;
3562 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003563 static const struct option long_options[] = {
3564 {"help", no_argument, 0, 'h'},
3565 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003566 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003567 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003568 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003569 {0, 0, 0, 0}
3570 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003571 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003572 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003573 if (c == -1) {
3574 break;
3575 }
3576 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003577 case ':':
3578 missing_argument(argv[optind - 1]);
3579 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003580 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003581 unrecognized_option(argv[optind - 1]);
3582 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003583 case 'h':
3584 help();
3585 break;
3586 case 'f':
3587 fmt = optarg;
3588 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003589 case 'q':
3590 quiet = true;
3591 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003592 case OPTION_OBJECT: {
3593 QemuOpts *opts;
3594 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3595 optarg, true);
3596 if (!opts) {
3597 return 1;
3598 }
3599 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003600 case OPTION_IMAGE_OPTS:
3601 image_opts = true;
3602 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003603 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003604 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003605 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003606 if (prealloc == PREALLOC_MODE__MAX) {
3607 error_report("Invalid preallocation mode '%s'", optarg);
3608 return 1;
3609 }
3610 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003611 case OPTION_SHRINK:
3612 shrink = true;
3613 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003614 }
3615 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003616 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003617 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003618 }
3619 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003620
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003621 if (qemu_opts_foreach(&qemu_object_opts,
3622 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003623 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003624 return 1;
3625 }
3626
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003627 /* Choose grow, shrink, or absolute resize mode */
3628 switch (size[0]) {
3629 case '+':
3630 relative = 1;
3631 size++;
3632 break;
3633 case '-':
3634 relative = -1;
3635 size++;
3636 break;
3637 default:
3638 relative = 0;
3639 break;
3640 }
3641
3642 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003643 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003644 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003645 if (err) {
3646 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003647 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003648 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003649 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003650 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003651 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3652 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003653
Max Reitzefaa7c42016-03-16 19:54:38 +01003654 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003655 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3656 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003657 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003658 ret = -1;
3659 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003660 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003661
Max Reitzdc5f6902017-06-13 22:20:55 +02003662 current_size = blk_getlength(blk);
3663 if (current_size < 0) {
3664 error_report("Failed to inquire current image length: %s",
3665 strerror(-current_size));
3666 ret = -1;
3667 goto out;
3668 }
3669
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003670 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003671 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003672 } else {
3673 total_size = n;
3674 }
3675 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003676 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003677 ret = -1;
3678 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003679 }
3680
Max Reitzdc5f6902017-06-13 22:20:55 +02003681 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3682 error_report("Preallocation can only be used for growing images");
3683 ret = -1;
3684 goto out;
3685 }
3686
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003687 if (total_size < current_size && !shrink) {
3688 warn_report("Shrinking an image will delete all data beyond the "
3689 "shrunken image's end. Before performing such an "
3690 "operation, make sure there is no important data there.");
3691
3692 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3693 error_report(
3694 "Use the --shrink option to perform a shrink operation.");
3695 ret = -1;
3696 goto out;
3697 } else {
3698 warn_report("Using the --shrink option will suppress this message. "
3699 "Note that future versions of qemu-img may refuse to "
3700 "shrink images without this option.");
3701 }
3702 }
3703
Max Reitzdc5f6902017-06-13 22:20:55 +02003704 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003705 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003706 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003707 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003708 }
Max Reitz5279b302018-04-21 18:39:57 +02003709
3710 new_size = blk_getlength(blk);
3711 if (new_size < 0) {
3712 error_report("Failed to verify truncated image length: %s",
3713 strerror(-new_size));
3714 ret = -1;
3715 goto out;
3716 }
3717
3718 /* Some block drivers implement a truncation method, but only so
3719 * the user can cause qemu to refresh the image's size from disk.
3720 * The idea is that the user resizes the image outside of qemu and
3721 * then invokes block_resize to inform qemu about it.
3722 * (This includes iscsi and file-posix for device files.)
3723 * Of course, that is not the behavior someone invoking
3724 * qemu-img resize would find useful, so we catch that behavior
3725 * here and tell the user. */
3726 if (new_size != total_size && new_size == current_size) {
3727 error_report("Image was not resized; resizing may not be supported "
3728 "for this image");
3729 ret = -1;
3730 goto out;
3731 }
3732
3733 if (new_size != total_size) {
3734 warn_report("Image should have been resized to %" PRIi64
3735 " bytes, but was resized to %" PRIi64 " bytes",
3736 total_size, new_size);
3737 }
3738
3739 qprintf(quiet, "Image resized.\n");
3740
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003741out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003742 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003743 if (ret) {
3744 return 1;
3745 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003746 return 0;
3747}
3748
Max Reitz76a3a342014-10-27 11:12:51 +01003749static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003750 int64_t offset, int64_t total_work_size,
3751 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003752{
3753 qemu_progress_print(100.f * offset / total_work_size, 0);
3754}
3755
Max Reitz51641352018-05-09 23:00:20 +02003756static int print_amend_option_help(const char *format)
3757{
3758 BlockDriver *drv;
3759
3760 /* Find driver and parse its options */
3761 drv = bdrv_find_format(format);
3762 if (!drv) {
3763 error_report("Unknown file format '%s'", format);
3764 return 1;
3765 }
3766
3767 if (!drv->bdrv_amend_options) {
3768 error_report("Format driver '%s' does not support option amendment",
3769 format);
3770 return 1;
3771 }
3772
3773 /* Every driver supporting amendment must have create_opts */
3774 assert(drv->create_opts);
3775
3776 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003777 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003778 printf("\nNote that not all of these options may be amendable.\n");
3779 return 0;
3780}
3781
Max Reitz6f176b42013-09-03 10:09:50 +02003782static int img_amend(int argc, char **argv)
3783{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003784 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003785 int c, ret = 0;
3786 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003787 QemuOptsList *create_opts = NULL;
3788 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003789 const char *fmt = NULL, *filename, *cache;
3790 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003791 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003792 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003793 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003794 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003795 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003796
Max Reitzbd39e6e2014-07-22 22:58:43 +02003797 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003798 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003799 static const struct option long_options[] = {
3800 {"help", no_argument, 0, 'h'},
3801 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003802 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003803 {0, 0, 0, 0}
3804 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003805 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003806 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003807 if (c == -1) {
3808 break;
3809 }
3810
3811 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003812 case ':':
3813 missing_argument(argv[optind - 1]);
3814 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003815 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003816 unrecognized_option(argv[optind - 1]);
3817 break;
3818 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003819 help();
3820 break;
3821 case 'o':
3822 if (!is_valid_option_list(optarg)) {
3823 error_report("Invalid option list: %s", optarg);
3824 ret = -1;
3825 goto out_no_progress;
3826 }
3827 if (!options) {
3828 options = g_strdup(optarg);
3829 } else {
3830 char *old_options = options;
3831 options = g_strdup_printf("%s,%s", options, optarg);
3832 g_free(old_options);
3833 }
3834 break;
3835 case 'f':
3836 fmt = optarg;
3837 break;
3838 case 't':
3839 cache = optarg;
3840 break;
3841 case 'p':
3842 progress = true;
3843 break;
3844 case 'q':
3845 quiet = true;
3846 break;
3847 case OPTION_OBJECT:
3848 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3849 optarg, true);
3850 if (!opts) {
3851 ret = -1;
3852 goto out_no_progress;
3853 }
3854 break;
3855 case OPTION_IMAGE_OPTS:
3856 image_opts = true;
3857 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003858 }
3859 }
3860
Max Reitz6f176b42013-09-03 10:09:50 +02003861 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003862 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003863 }
3864
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003865 if (qemu_opts_foreach(&qemu_object_opts,
3866 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003867 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003868 ret = -1;
3869 goto out_no_progress;
3870 }
3871
Max Reitz76a3a342014-10-27 11:12:51 +01003872 if (quiet) {
3873 progress = false;
3874 }
3875 qemu_progress_init(progress, 1.0);
3876
Kevin Wolfa283cb62014-02-21 16:24:07 +01003877 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3878 if (fmt && has_help_option(options)) {
3879 /* If a format is explicitly specified (and possibly no filename is
3880 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003881 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003882 goto out;
3883 }
3884
3885 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003886 error_report("Expecting one image file name");
3887 ret = -1;
3888 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003889 }
Max Reitz6f176b42013-09-03 10:09:50 +02003890
Kevin Wolfce099542016-03-15 13:01:04 +01003891 flags = BDRV_O_RDWR;
3892 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003893 if (ret < 0) {
3894 error_report("Invalid cache option: %s", cache);
3895 goto out;
3896 }
3897
Fam Zheng335e9932017-05-03 00:35:39 +08003898 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3899 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003900 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003901 ret = -1;
3902 goto out;
3903 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003904 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003905
3906 fmt = bs->drv->format_name;
3907
Kevin Wolf626f84f2014-02-21 16:24:06 +01003908 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003909 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003910 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003911 goto out;
3912 }
3913
Max Reitz1f996682018-05-09 23:00:17 +02003914 if (!bs->drv->bdrv_amend_options) {
3915 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003916 fmt);
3917 ret = -1;
3918 goto out;
3919 }
3920
Max Reitz1f996682018-05-09 23:00:17 +02003921 /* Every driver supporting amendment must have create_opts */
3922 assert(bs->drv->create_opts);
3923
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003924 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003925 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003926 qemu_opts_do_parse(opts, options, NULL, &err);
3927 if (err) {
3928 error_report_err(err);
3929 ret = -1;
3930 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003931 }
3932
Max Reitz76a3a342014-10-27 11:12:51 +01003933 /* In case the driver does not call amend_status_cb() */
3934 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003935 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003936 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003937 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003938 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003939 goto out;
3940 }
3941
3942out:
Max Reitz76a3a342014-10-27 11:12:51 +01003943 qemu_progress_end();
3944
Max Reitze814dff2015-08-20 16:00:38 -07003945out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003946 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003947 qemu_opts_del(opts);
3948 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003949 g_free(options);
3950
Max Reitz6f176b42013-09-03 10:09:50 +02003951 if (ret) {
3952 return 1;
3953 }
3954 return 0;
3955}
3956
Kevin Wolfb6133b82014-08-05 14:17:13 +02003957typedef struct BenchData {
3958 BlockBackend *blk;
3959 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003960 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003961 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003962 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003963 int nrreq;
3964 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003965 int flush_interval;
3966 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003967 uint8_t *buf;
3968 QEMUIOVector *qiov;
3969
3970 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003971 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003972 uint64_t offset;
3973} BenchData;
3974
Kevin Wolf55d539c2016-06-03 13:59:41 +02003975static void bench_undrained_flush_cb(void *opaque, int ret)
3976{
3977 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003978 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003979 exit(EXIT_FAILURE);
3980 }
3981}
3982
Kevin Wolfb6133b82014-08-05 14:17:13 +02003983static void bench_cb(void *opaque, int ret)
3984{
3985 BenchData *b = opaque;
3986 BlockAIOCB *acb;
3987
3988 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003989 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003990 exit(EXIT_FAILURE);
3991 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003992
3993 if (b->in_flush) {
3994 /* Just finished a flush with drained queue: Start next requests */
3995 assert(b->in_flight == 0);
3996 b->in_flush = false;
3997 } else if (b->in_flight > 0) {
3998 int remaining = b->n - b->in_flight;
3999
Kevin Wolfb6133b82014-08-05 14:17:13 +02004000 b->n--;
4001 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004002
4003 /* Time for flush? Drain queue if requested, then flush */
4004 if (b->flush_interval && remaining % b->flush_interval == 0) {
4005 if (!b->in_flight || !b->drain_on_flush) {
4006 BlockCompletionFunc *cb;
4007
4008 if (b->drain_on_flush) {
4009 b->in_flush = true;
4010 cb = bench_cb;
4011 } else {
4012 cb = bench_undrained_flush_cb;
4013 }
4014
4015 acb = blk_aio_flush(b->blk, cb, b);
4016 if (!acb) {
4017 error_report("Failed to issue flush request");
4018 exit(EXIT_FAILURE);
4019 }
4020 }
4021 if (b->drain_on_flush) {
4022 return;
4023 }
4024 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004025 }
4026
4027 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004028 int64_t offset = b->offset;
4029 /* blk_aio_* might look for completed I/Os and kick bench_cb
4030 * again, so make sure this operation is counted by in_flight
4031 * and b->offset is ready for the next submission.
4032 */
4033 b->in_flight++;
4034 b->offset += b->step;
4035 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004036 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004037 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004038 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004039 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004040 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004041 if (!acb) {
4042 error_report("Failed to issue request");
4043 exit(EXIT_FAILURE);
4044 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004045 }
4046}
4047
4048static int img_bench(int argc, char **argv)
4049{
4050 int c, ret = 0;
4051 const char *fmt = NULL, *filename;
4052 bool quiet = false;
4053 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004054 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004055 int count = 75000;
4056 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004057 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004058 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004059 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004060 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004061 int flush_interval = 0;
4062 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004063 int64_t image_size;
4064 BlockBackend *blk = NULL;
4065 BenchData data = {};
4066 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004067 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004068 struct timeval t1, t2;
4069 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004070 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004071 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004072
4073 for (;;) {
4074 static const struct option long_options[] = {
4075 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004076 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004077 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004078 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004079 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004080 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004081 {0, 0, 0, 0}
4082 };
Fam Zheng335e9932017-05-03 00:35:39 +08004083 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004084 if (c == -1) {
4085 break;
4086 }
4087
4088 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004089 case ':':
4090 missing_argument(argv[optind - 1]);
4091 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004092 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004093 unrecognized_option(argv[optind - 1]);
4094 break;
4095 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004096 help();
4097 break;
4098 case 'c':
4099 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004100 unsigned long res;
4101
4102 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004103 error_report("Invalid request count specified");
4104 return 1;
4105 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004106 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004107 break;
4108 }
4109 case 'd':
4110 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004111 unsigned long res;
4112
4113 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004114 error_report("Invalid queue depth specified");
4115 return 1;
4116 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004117 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004118 break;
4119 }
4120 case 'f':
4121 fmt = optarg;
4122 break;
4123 case 'n':
4124 flags |= BDRV_O_NATIVE_AIO;
4125 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004126 case 'o':
4127 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004128 offset = cvtnum(optarg);
4129 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004130 error_report("Invalid offset specified");
4131 return 1;
4132 }
4133 break;
4134 }
4135 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004136 case 'q':
4137 quiet = true;
4138 break;
4139 case 's':
4140 {
4141 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004142
Markus Armbruster606caa02017-02-21 21:14:04 +01004143 sval = cvtnum(optarg);
4144 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004145 error_report("Invalid buffer size specified");
4146 return 1;
4147 }
4148
4149 bufsize = sval;
4150 break;
4151 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004152 case 'S':
4153 {
4154 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004155
Markus Armbruster606caa02017-02-21 21:14:04 +01004156 sval = cvtnum(optarg);
4157 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004158 error_report("Invalid step size specified");
4159 return 1;
4160 }
4161
4162 step = sval;
4163 break;
4164 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004165 case 't':
4166 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4167 if (ret < 0) {
4168 error_report("Invalid cache mode");
4169 ret = -1;
4170 goto out;
4171 }
4172 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004173 case 'w':
4174 flags |= BDRV_O_RDWR;
4175 is_write = true;
4176 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004177 case 'U':
4178 force_share = true;
4179 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004180 case OPTION_PATTERN:
4181 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004182 unsigned long res;
4183
4184 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004185 error_report("Invalid pattern byte specified");
4186 return 1;
4187 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004188 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004189 break;
4190 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004191 case OPTION_FLUSH_INTERVAL:
4192 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004193 unsigned long res;
4194
4195 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004196 error_report("Invalid flush interval specified");
4197 return 1;
4198 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004199 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004200 break;
4201 }
4202 case OPTION_NO_DRAIN:
4203 drain_on_flush = false;
4204 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004205 case OPTION_IMAGE_OPTS:
4206 image_opts = true;
4207 break;
4208 }
4209 }
4210
4211 if (optind != argc - 1) {
4212 error_exit("Expecting one image file name");
4213 }
4214 filename = argv[argc - 1];
4215
Kevin Wolf55d539c2016-06-03 13:59:41 +02004216 if (!is_write && flush_interval) {
4217 error_report("--flush-interval is only available in write tests");
4218 ret = -1;
4219 goto out;
4220 }
4221 if (flush_interval && flush_interval < depth) {
4222 error_report("Flush interval can't be smaller than depth");
4223 ret = -1;
4224 goto out;
4225 }
4226
Fam Zheng335e9932017-05-03 00:35:39 +08004227 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4228 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004229 if (!blk) {
4230 ret = -1;
4231 goto out;
4232 }
4233
4234 image_size = blk_getlength(blk);
4235 if (image_size < 0) {
4236 ret = image_size;
4237 goto out;
4238 }
4239
4240 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004241 .blk = blk,
4242 .image_size = image_size,
4243 .bufsize = bufsize,
4244 .step = step ?: bufsize,
4245 .nrreq = depth,
4246 .n = count,
4247 .offset = offset,
4248 .write = is_write,
4249 .flush_interval = flush_interval,
4250 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004251 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004252 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004253 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004254 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004255 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004256 if (flush_interval) {
4257 printf("Sending flush every %d requests\n", flush_interval);
4258 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004259
Fam Zheng79d46582018-01-16 14:08:58 +08004260 buf_size = data.nrreq * data.bufsize;
4261 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004262 memset(data.buf, pattern, data.nrreq * data.bufsize);
4263
Fam Zheng79d46582018-01-16 14:08:58 +08004264 blk_register_buf(blk, data.buf, buf_size);
4265
Kevin Wolfb6133b82014-08-05 14:17:13 +02004266 data.qiov = g_new(QEMUIOVector, data.nrreq);
4267 for (i = 0; i < data.nrreq; i++) {
4268 qemu_iovec_init(&data.qiov[i], 1);
4269 qemu_iovec_add(&data.qiov[i],
4270 data.buf + i * data.bufsize, data.bufsize);
4271 }
4272
4273 gettimeofday(&t1, NULL);
4274 bench_cb(&data, 0);
4275
4276 while (data.n > 0) {
4277 main_loop_wait(false);
4278 }
4279 gettimeofday(&t2, NULL);
4280
4281 printf("Run completed in %3.3f seconds.\n",
4282 (t2.tv_sec - t1.tv_sec)
4283 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4284
4285out:
Fam Zheng79d46582018-01-16 14:08:58 +08004286 if (data.buf) {
4287 blk_unregister_buf(blk, data.buf);
4288 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004289 qemu_vfree(data.buf);
4290 blk_unref(blk);
4291
4292 if (ret) {
4293 return 1;
4294 }
4295 return 0;
4296}
4297
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004298#define C_BS 01
4299#define C_COUNT 02
4300#define C_IF 04
4301#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004302#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004303
4304struct DdInfo {
4305 unsigned int flags;
4306 int64_t count;
4307};
4308
4309struct DdIo {
4310 int bsz; /* Block size */
4311 char *filename;
4312 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004313 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004314};
4315
4316struct DdOpts {
4317 const char *name;
4318 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4319 unsigned int flag;
4320};
4321
4322static int img_dd_bs(const char *arg,
4323 struct DdIo *in, struct DdIo *out,
4324 struct DdInfo *dd)
4325{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004326 int64_t res;
4327
Markus Armbruster606caa02017-02-21 21:14:04 +01004328 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004329
Markus Armbruster606caa02017-02-21 21:14:04 +01004330 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004331 error_report("invalid number: '%s'", arg);
4332 return 1;
4333 }
4334 in->bsz = out->bsz = res;
4335
4336 return 0;
4337}
4338
4339static int img_dd_count(const char *arg,
4340 struct DdIo *in, struct DdIo *out,
4341 struct DdInfo *dd)
4342{
Markus Armbruster606caa02017-02-21 21:14:04 +01004343 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004344
Markus Armbruster606caa02017-02-21 21:14:04 +01004345 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004346 error_report("invalid number: '%s'", arg);
4347 return 1;
4348 }
4349
4350 return 0;
4351}
4352
4353static int img_dd_if(const char *arg,
4354 struct DdIo *in, struct DdIo *out,
4355 struct DdInfo *dd)
4356{
4357 in->filename = g_strdup(arg);
4358
4359 return 0;
4360}
4361
4362static int img_dd_of(const char *arg,
4363 struct DdIo *in, struct DdIo *out,
4364 struct DdInfo *dd)
4365{
4366 out->filename = g_strdup(arg);
4367
4368 return 0;
4369}
4370
Reda Sallahif7c15532016-08-10 16:16:09 +02004371static int img_dd_skip(const char *arg,
4372 struct DdIo *in, struct DdIo *out,
4373 struct DdInfo *dd)
4374{
Markus Armbruster606caa02017-02-21 21:14:04 +01004375 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004376
Markus Armbruster606caa02017-02-21 21:14:04 +01004377 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004378 error_report("invalid number: '%s'", arg);
4379 return 1;
4380 }
4381
4382 return 0;
4383}
4384
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004385static int img_dd(int argc, char **argv)
4386{
4387 int ret = 0;
4388 char *arg = NULL;
4389 char *tmp;
4390 BlockDriver *drv = NULL, *proto_drv = NULL;
4391 BlockBackend *blk1 = NULL, *blk2 = NULL;
4392 QemuOpts *opts = NULL;
4393 QemuOptsList *create_opts = NULL;
4394 Error *local_err = NULL;
4395 bool image_opts = false;
4396 int c, i;
4397 const char *out_fmt = "raw";
4398 const char *fmt = NULL;
4399 int64_t size = 0;
4400 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004401 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004402 struct DdInfo dd = {
4403 .flags = 0,
4404 .count = 0,
4405 };
4406 struct DdIo in = {
4407 .bsz = 512, /* Block size is by default 512 bytes */
4408 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004409 .buf = NULL,
4410 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004411 };
4412 struct DdIo out = {
4413 .bsz = 512,
4414 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004415 .buf = NULL,
4416 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004417 };
4418
4419 const struct DdOpts options[] = {
4420 { "bs", img_dd_bs, C_BS },
4421 { "count", img_dd_count, C_COUNT },
4422 { "if", img_dd_if, C_IF },
4423 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004424 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004425 { NULL, NULL, 0 }
4426 };
4427 const struct option long_options[] = {
4428 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004429 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004430 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004431 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004432 { 0, 0, 0, 0 }
4433 };
4434
Fam Zheng335e9932017-05-03 00:35:39 +08004435 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004436 if (c == EOF) {
4437 break;
4438 }
4439 switch (c) {
4440 case 'O':
4441 out_fmt = optarg;
4442 break;
4443 case 'f':
4444 fmt = optarg;
4445 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004446 case ':':
4447 missing_argument(argv[optind - 1]);
4448 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004449 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004450 unrecognized_option(argv[optind - 1]);
4451 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004452 case 'h':
4453 help();
4454 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004455 case 'U':
4456 force_share = true;
4457 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004458 case OPTION_OBJECT:
4459 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004460 ret = -1;
4461 goto out;
4462 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004463 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004464 case OPTION_IMAGE_OPTS:
4465 image_opts = true;
4466 break;
4467 }
4468 }
4469
4470 for (i = optind; i < argc; i++) {
4471 int j;
4472 arg = g_strdup(argv[i]);
4473
4474 tmp = strchr(arg, '=');
4475 if (tmp == NULL) {
4476 error_report("unrecognized operand %s", arg);
4477 ret = -1;
4478 goto out;
4479 }
4480
4481 *tmp++ = '\0';
4482
4483 for (j = 0; options[j].name != NULL; j++) {
4484 if (!strcmp(arg, options[j].name)) {
4485 break;
4486 }
4487 }
4488 if (options[j].name == NULL) {
4489 error_report("unrecognized operand %s", arg);
4490 ret = -1;
4491 goto out;
4492 }
4493
4494 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4495 ret = -1;
4496 goto out;
4497 }
4498 dd.flags |= options[j].flag;
4499 g_free(arg);
4500 arg = NULL;
4501 }
4502
4503 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4504 error_report("Must specify both input and output files");
4505 ret = -1;
4506 goto out;
4507 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004508
4509 if (qemu_opts_foreach(&qemu_object_opts,
4510 user_creatable_add_opts_foreach,
4511 NULL, NULL)) {
4512 ret = -1;
4513 goto out;
4514 }
4515
Fam Zheng335e9932017-05-03 00:35:39 +08004516 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4517 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004518
4519 if (!blk1) {
4520 ret = -1;
4521 goto out;
4522 }
4523
4524 drv = bdrv_find_format(out_fmt);
4525 if (!drv) {
4526 error_report("Unknown file format");
4527 ret = -1;
4528 goto out;
4529 }
4530 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4531
4532 if (!proto_drv) {
4533 error_report_err(local_err);
4534 ret = -1;
4535 goto out;
4536 }
4537 if (!drv->create_opts) {
4538 error_report("Format driver '%s' does not support image creation",
4539 drv->format_name);
4540 ret = -1;
4541 goto out;
4542 }
4543 if (!proto_drv->create_opts) {
4544 error_report("Protocol driver '%s' does not support image creation",
4545 proto_drv->format_name);
4546 ret = -1;
4547 goto out;
4548 }
4549 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4550 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4551
4552 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4553
4554 size = blk_getlength(blk1);
4555 if (size < 0) {
4556 error_report("Failed to get size for '%s'", in.filename);
4557 ret = -1;
4558 goto out;
4559 }
4560
4561 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4562 dd.count * in.bsz < size) {
4563 size = dd.count * in.bsz;
4564 }
4565
Reda Sallahif7c15532016-08-10 16:16:09 +02004566 /* Overflow means the specified offset is beyond input image's size */
4567 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4568 size < in.bsz * in.offset)) {
4569 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4570 } else {
4571 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4572 size - in.bsz * in.offset, &error_abort);
4573 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004574
4575 ret = bdrv_create(drv, out.filename, opts, &local_err);
4576 if (ret < 0) {
4577 error_reportf_err(local_err,
4578 "%s: error while creating output image: ",
4579 out.filename);
4580 ret = -1;
4581 goto out;
4582 }
4583
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004584 /* TODO, we can't honour --image-opts for the target,
4585 * since it needs to be given in a format compatible
4586 * with the bdrv_create() call above which does not
4587 * support image-opts style.
4588 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004589 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004590 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004591
4592 if (!blk2) {
4593 ret = -1;
4594 goto out;
4595 }
4596
Reda Sallahif7c15532016-08-10 16:16:09 +02004597 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4598 size < in.offset * in.bsz)) {
4599 /* We give a warning if the skip option is bigger than the input
4600 * size and create an empty output disk image (i.e. like dd(1)).
4601 */
4602 error_report("%s: cannot skip to specified offset", in.filename);
4603 in_pos = size;
4604 } else {
4605 in_pos = in.offset * in.bsz;
4606 }
4607
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004608 in.buf = g_new(uint8_t, in.bsz);
4609
Reda Sallahif7c15532016-08-10 16:16:09 +02004610 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004611 int in_ret, out_ret;
4612
4613 if (in_pos + in.bsz > size) {
4614 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4615 } else {
4616 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4617 }
4618 if (in_ret < 0) {
4619 error_report("error while reading from input image file: %s",
4620 strerror(-in_ret));
4621 ret = -1;
4622 goto out;
4623 }
4624 in_pos += in_ret;
4625
4626 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4627
4628 if (out_ret < 0) {
4629 error_report("error while writing to output image file: %s",
4630 strerror(-out_ret));
4631 ret = -1;
4632 goto out;
4633 }
4634 out_pos += out_ret;
4635 }
4636
4637out:
4638 g_free(arg);
4639 qemu_opts_del(opts);
4640 qemu_opts_free(create_opts);
4641 blk_unref(blk1);
4642 blk_unref(blk2);
4643 g_free(in.filename);
4644 g_free(out.filename);
4645 g_free(in.buf);
4646 g_free(out.buf);
4647
4648 if (ret) {
4649 return 1;
4650 }
4651 return 0;
4652}
4653
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004654static void dump_json_block_measure_info(BlockMeasureInfo *info)
4655{
4656 QString *str;
4657 QObject *obj;
4658 Visitor *v = qobject_output_visitor_new(&obj);
4659
4660 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4661 visit_complete(v, &obj);
4662 str = qobject_to_json_pretty(obj);
4663 assert(str != NULL);
4664 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004665 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004666 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004667 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004668}
4669
4670static int img_measure(int argc, char **argv)
4671{
4672 static const struct option long_options[] = {
4673 {"help", no_argument, 0, 'h'},
4674 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4675 {"object", required_argument, 0, OPTION_OBJECT},
4676 {"output", required_argument, 0, OPTION_OUTPUT},
4677 {"size", required_argument, 0, OPTION_SIZE},
4678 {"force-share", no_argument, 0, 'U'},
4679 {0, 0, 0, 0}
4680 };
4681 OutputFormat output_format = OFORMAT_HUMAN;
4682 BlockBackend *in_blk = NULL;
4683 BlockDriver *drv;
4684 const char *filename = NULL;
4685 const char *fmt = NULL;
4686 const char *out_fmt = "raw";
4687 char *options = NULL;
4688 char *snapshot_name = NULL;
4689 bool force_share = false;
4690 QemuOpts *opts = NULL;
4691 QemuOpts *object_opts = NULL;
4692 QemuOpts *sn_opts = NULL;
4693 QemuOptsList *create_opts = NULL;
4694 bool image_opts = false;
4695 uint64_t img_size = UINT64_MAX;
4696 BlockMeasureInfo *info = NULL;
4697 Error *local_err = NULL;
4698 int ret = 1;
4699 int c;
4700
4701 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4702 long_options, NULL)) != -1) {
4703 switch (c) {
4704 case '?':
4705 case 'h':
4706 help();
4707 break;
4708 case 'f':
4709 fmt = optarg;
4710 break;
4711 case 'O':
4712 out_fmt = optarg;
4713 break;
4714 case 'o':
4715 if (!is_valid_option_list(optarg)) {
4716 error_report("Invalid option list: %s", optarg);
4717 goto out;
4718 }
4719 if (!options) {
4720 options = g_strdup(optarg);
4721 } else {
4722 char *old_options = options;
4723 options = g_strdup_printf("%s,%s", options, optarg);
4724 g_free(old_options);
4725 }
4726 break;
4727 case 'l':
4728 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4729 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4730 optarg, false);
4731 if (!sn_opts) {
4732 error_report("Failed in parsing snapshot param '%s'",
4733 optarg);
4734 goto out;
4735 }
4736 } else {
4737 snapshot_name = optarg;
4738 }
4739 break;
4740 case 'U':
4741 force_share = true;
4742 break;
4743 case OPTION_OBJECT:
4744 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4745 optarg, true);
4746 if (!object_opts) {
4747 goto out;
4748 }
4749 break;
4750 case OPTION_IMAGE_OPTS:
4751 image_opts = true;
4752 break;
4753 case OPTION_OUTPUT:
4754 if (!strcmp(optarg, "json")) {
4755 output_format = OFORMAT_JSON;
4756 } else if (!strcmp(optarg, "human")) {
4757 output_format = OFORMAT_HUMAN;
4758 } else {
4759 error_report("--output must be used with human or json "
4760 "as argument.");
4761 goto out;
4762 }
4763 break;
4764 case OPTION_SIZE:
4765 {
4766 int64_t sval;
4767
4768 sval = cvtnum(optarg);
4769 if (sval < 0) {
4770 if (sval == -ERANGE) {
4771 error_report("Image size must be less than 8 EiB!");
4772 } else {
4773 error_report("Invalid image size specified! You may use "
4774 "k, M, G, T, P or E suffixes for ");
4775 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4776 "petabytes and exabytes.");
4777 }
4778 goto out;
4779 }
4780 img_size = (uint64_t)sval;
4781 }
4782 break;
4783 }
4784 }
4785
4786 if (qemu_opts_foreach(&qemu_object_opts,
4787 user_creatable_add_opts_foreach,
4788 NULL, NULL)) {
4789 goto out;
4790 }
4791
4792 if (argc - optind > 1) {
4793 error_report("At most one filename argument is allowed.");
4794 goto out;
4795 } else if (argc - optind == 1) {
4796 filename = argv[optind];
4797 }
4798
4799 if (!filename &&
4800 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4801 error_report("--object, --image-opts, -f, and -l "
4802 "require a filename argument.");
4803 goto out;
4804 }
4805 if (filename && img_size != UINT64_MAX) {
4806 error_report("--size N cannot be used together with a filename.");
4807 goto out;
4808 }
4809 if (!filename && img_size == UINT64_MAX) {
4810 error_report("Either --size N or one filename must be specified.");
4811 goto out;
4812 }
4813
4814 if (filename) {
4815 in_blk = img_open(image_opts, filename, fmt, 0,
4816 false, false, force_share);
4817 if (!in_blk) {
4818 goto out;
4819 }
4820
4821 if (sn_opts) {
4822 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4823 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4824 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4825 &local_err);
4826 } else if (snapshot_name != NULL) {
4827 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4828 snapshot_name, &local_err);
4829 }
4830 if (local_err) {
4831 error_reportf_err(local_err, "Failed to load snapshot: ");
4832 goto out;
4833 }
4834 }
4835
4836 drv = bdrv_find_format(out_fmt);
4837 if (!drv) {
4838 error_report("Unknown file format '%s'", out_fmt);
4839 goto out;
4840 }
4841 if (!drv->create_opts) {
4842 error_report("Format driver '%s' does not support image creation",
4843 drv->format_name);
4844 goto out;
4845 }
4846
4847 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4848 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4849 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4850 if (options) {
4851 qemu_opts_do_parse(opts, options, NULL, &local_err);
4852 if (local_err) {
4853 error_report_err(local_err);
4854 error_report("Invalid options for file format '%s'", out_fmt);
4855 goto out;
4856 }
4857 }
4858 if (img_size != UINT64_MAX) {
4859 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4860 }
4861
4862 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4863 if (local_err) {
4864 error_report_err(local_err);
4865 goto out;
4866 }
4867
4868 if (output_format == OFORMAT_HUMAN) {
4869 printf("required size: %" PRIu64 "\n", info->required);
4870 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4871 } else {
4872 dump_json_block_measure_info(info);
4873 }
4874
4875 ret = 0;
4876
4877out:
4878 qapi_free_BlockMeasureInfo(info);
4879 qemu_opts_del(object_opts);
4880 qemu_opts_del(opts);
4881 qemu_opts_del(sn_opts);
4882 qemu_opts_free(create_opts);
4883 g_free(options);
4884 blk_unref(in_blk);
4885 return ret;
4886}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004887
Anthony Liguoric227f092009-10-01 16:12:16 -05004888static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004889#define DEF(option, callback, arg_string) \
4890 { option, callback },
4891#include "qemu-img-cmds.h"
4892#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004893 { NULL, NULL, },
4894};
4895
bellardea2384d2004-08-01 21:59:26 +00004896int main(int argc, char **argv)
4897{
Anthony Liguoric227f092009-10-01 16:12:16 -05004898 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004899 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004900 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004901 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004902 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004903 static const struct option long_options[] = {
4904 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004905 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004906 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004907 {0, 0, 0, 0}
4908 };
bellardea2384d2004-08-01 21:59:26 +00004909
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004910#ifdef CONFIG_POSIX
4911 signal(SIGPIPE, SIG_IGN);
4912#endif
4913
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004914 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004915 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004916 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004917
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004918 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004919 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004920 exit(EXIT_FAILURE);
4921 }
4922
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004923 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004924
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004925 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004926 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004927 if (argc < 2) {
4928 error_exit("Not enough arguments");
4929 }
Stuart Brady153859b2009-06-07 00:42:17 +01004930
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004931 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004932 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004933 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004934
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004935 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004936 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004937 case ':':
4938 missing_argument(argv[optind - 1]);
4939 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004940 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004941 unrecognized_option(argv[optind - 1]);
4942 return 0;
4943 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004944 help();
4945 return 0;
4946 case 'V':
4947 printf(QEMU_IMG_VERSION);
4948 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004949 case 'T':
4950 g_free(trace_file);
4951 trace_file = trace_opt_parse(optarg);
4952 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004953 }
bellardea2384d2004-08-01 21:59:26 +00004954 }
Stuart Brady153859b2009-06-07 00:42:17 +01004955
Denis V. Lunev10985132016-06-17 17:44:13 +03004956 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004957
Denis V. Lunev10985132016-06-17 17:44:13 +03004958 /* reset getopt_long scanning */
4959 argc -= optind;
4960 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004961 return 0;
4962 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004963 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004964 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004965
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004966 if (!trace_init_backends()) {
4967 exit(1);
4968 }
4969 trace_init_file(trace_file);
4970 qemu_set_log(LOG_TRACE);
4971
Denis V. Lunev10985132016-06-17 17:44:13 +03004972 /* find the command */
4973 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4974 if (!strcmp(cmdname, cmd->name)) {
4975 return cmd->handler(argc, argv);
4976 }
4977 }
Jeff Cody7db16892014-04-25 17:02:32 -04004978
Stuart Brady153859b2009-06-07 00:42:17 +01004979 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004980 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004981}