blob: eb32b93e904a664a9fa9a24711ea421dd125c4a1 [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 */
Peter Maydell80c71a22016-01-18 18:01:42 +000024#include "qemu/osdep.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080025#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010026#include "qapi/error.h"
Max Reitzdc5f6902017-06-13 22:20:55 +020027#include "qapi/util.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020028#include "qapi-visit.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010029#include "qapi/qobject-output-visitor.h"
Markus Armbrustercc7a8ea2015-03-17 17:22:46 +010030#include "qapi/qmp/qerror.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010031#include "qapi/qmp/qjson.h"
Fam Zheng335e9932017-05-03 00:35:39 +080032#include "qapi/qmp/qbool.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020033#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000034#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010035#include "qemu/option.h"
36#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030037#include "qemu/log.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000038#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010039#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020040#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010041#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020042#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080043#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010044#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030045#include "trace/control.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020046#include <getopt.h>
bellarde8445332006-06-14 15:32:10 +000047
Don Slutz61979a62015-01-09 10:17:35 -050048#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020049 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040050
Anthony Liguoric227f092009-10-01 16:12:16 -050051typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010052 const char *name;
53 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050054} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010055
Federico Simoncelli8599ea42013-01-28 06:59:47 -050056enum {
57 OPTION_OUTPUT = 256,
58 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000059 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000060 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020061 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020062 OPTION_FLUSH_INTERVAL = 261,
63 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010064 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010065 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020066 OPTION_PREALLOCATION = 265,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050067};
68
69typedef enum OutputFormat {
70 OFORMAT_JSON,
71 OFORMAT_HUMAN,
72} OutputFormat;
73
Kevin Wolfe6996142016-03-15 13:03:11 +010074/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040075#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000076
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010077static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000078{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010079 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000080}
81
Fam Zhengac1307a2014-04-22 13:36:11 +080082static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
83{
84 va_list ap;
85
86 error_printf("qemu-img: ");
87
88 va_start(ap, fmt);
89 error_vprintf(fmt, ap);
90 va_end(ap);
91
92 error_printf("\nTry 'qemu-img --help' for more information\n");
93 exit(EXIT_FAILURE);
94}
95
Stefan Hajnoczic9192972017-03-17 18:45:41 +080096static void QEMU_NORETURN missing_argument(const char *option)
97{
98 error_exit("missing argument for option '%s'", option);
99}
100
101static void QEMU_NORETURN unrecognized_option(const char *option)
102{
103 error_exit("unrecognized option '%s'", option);
104}
105
blueswir1d2c639d2009-01-24 18:19:25 +0000106/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800107static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000108{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100109 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400110 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300111 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300112 "QEMU disk image utility\n"
113 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300114 " '-h', '--help' display this help and exit\n"
115 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300116 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
117 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300118 "\n"
malc3f020d72010-02-08 12:04:56 +0300119 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100120#define DEF(option, callback, arg_string) \
121 " " arg_string "\n"
122#include "qemu-img-cmds.h"
123#undef DEF
124#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +0300125 "\n"
126 "Command parameters:\n"
127 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000128 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
129 " manual page for a description of the object properties. The most common\n"
130 " object type is a 'secret', which is used to supply passwords and/or\n"
131 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300132 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400133 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800134 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
135 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100136 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
137 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300138 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200139 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
140 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
141 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300142 " 'output_filename' is the destination disk image filename\n"
143 " 'output_fmt' is the destination format\n"
144 " 'options' is a comma separated list of format specific options in a\n"
145 " name=value format. Use -o ? for an overview of the options supported by the\n"
146 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800147 " 'snapshot_param' is param used for internal snapshot, format\n"
148 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
149 " '[ID_OR_NAME]'\n"
150 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
151 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300152 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400153 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
154 " new backing file match exactly. The image doesn't need a working\n"
155 " backing file before rebasing in this case (useful for renaming the\n"
156 " backing file). For image creation, allow creating without attempting\n"
157 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300158 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200159 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100160 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200161 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
162 " contain only zeros for qemu-img to create a sparse image during\n"
163 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
164 " unallocated or zero sectors, and the destination image will always be\n"
165 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200166 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100167 " '-n' skips the target volume creation (useful if the volume is created\n"
168 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300169 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200170 "Parameters to check subcommand:\n"
171 " '-r' tries to repair any inconsistencies that are found during the check.\n"
172 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
173 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200174 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200175 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100176 "Parameters to convert subcommand:\n"
177 " '-m' specifies how many coroutines work in parallel during the convert\n"
178 " process (defaults to 8)\n"
179 " '-W' allow to write to the target out of order rather than sequential\n"
180 "\n"
malc3f020d72010-02-08 12:04:56 +0300181 "Parameters to snapshot subcommand:\n"
182 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
183 " '-a' applies a snapshot (revert disk to saved state)\n"
184 " '-c' creates a snapshot\n"
185 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100186 " '-l' lists all snapshots in the given image\n"
187 "\n"
188 "Parameters to compare subcommand:\n"
189 " '-f' first image format\n"
190 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200191 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
192 "\n"
193 "Parameters to dd subcommand:\n"
194 " 'bs=BYTES' read and write up to BYTES bytes at a time "
195 "(default: 512)\n"
196 " 'count=N' copy only N input blocks\n"
197 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200198 " 'of=FILE' write to FILE\n"
199 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100200
201 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100202 bdrv_iterate_format(format_print, NULL);
bellardea2384d2004-08-01 21:59:26 +0000203 printf("\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800204 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000205}
206
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000207static QemuOptsList qemu_object_opts = {
208 .name = "object",
209 .implied_opt_name = "qom-type",
210 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
211 .desc = {
212 { }
213 },
214};
215
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000216static QemuOptsList qemu_source_opts = {
217 .name = "source",
218 .implied_opt_name = "file",
219 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
220 .desc = {
221 { }
222 },
223};
224
Stefan Weil7c30f652013-06-16 17:01:05 +0200225static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100226{
227 int ret = 0;
228 if (!quiet) {
229 va_list args;
230 va_start(args, fmt);
231 ret = vprintf(fmt, args);
232 va_end(args);
233 }
234 return ret;
235}
236
bellardea2384d2004-08-01 21:59:26 +0000237
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100238static int print_block_option_help(const char *filename, const char *fmt)
239{
240 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800241 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500242 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100243
244 /* Find driver and parse its options */
245 drv = bdrv_find_format(fmt);
246 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100247 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100248 return 1;
249 }
250
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800251 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100252 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500253 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100254 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100255 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800256 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100257 return 1;
258 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800259 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100260 }
261
Chunyan Liu83d05212014-06-05 17:20:51 +0800262 qemu_opts_print_help(create_opts);
263 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100264 return 0;
265}
266
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000267
Max Reitzefaa7c42016-03-16 19:54:38 +0100268static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100269 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800270 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000271{
272 QDict *options;
273 Error *local_err = NULL;
274 BlockBackend *blk;
275 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800276 if (force_share) {
277 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
278 && !qdict_get_bool(options, BDRV_OPT_FORCE_SHARE)) {
279 error_report("--force-share/-U conflicts with image options");
Fam Zhengadb998c2017-05-15 22:10:14 +0800280 QDECREF(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800281 return NULL;
282 }
Eric Blake579cf1d2017-05-15 14:54:39 -0500283 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800284 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100285 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000286 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100287 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000288 return NULL;
289 }
Kevin Wolfce099542016-03-15 13:01:04 +0100290 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000291
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000292 return blk;
293}
294
Max Reitzefaa7c42016-03-16 19:54:38 +0100295static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100296 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000297 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800298 bool writethrough, bool quiet,
299 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000300{
301 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200302 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100303
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100304 if (!options) {
305 options = qdict_new();
306 }
bellard75c23802004-08-27 21:28:58 +0000307 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500308 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000309 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100310
Fam Zheng335e9932017-05-03 00:35:39 +0800311 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500312 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800313 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100314 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500315 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100316 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000317 return NULL;
bellard75c23802004-08-27 21:28:58 +0000318 }
Kevin Wolfce099542016-03-15 13:01:04 +0100319 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100320
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200321 return blk;
bellard75c23802004-08-27 21:28:58 +0000322}
323
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000324
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100325static int img_add_key_secrets(void *opaque,
326 const char *name, const char *value,
327 Error **errp)
328{
329 QDict *options = opaque;
330
331 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600332 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100333 }
334
335 return 0;
336}
337
338static BlockBackend *img_open_new_file(const char *filename,
339 QemuOpts *create_opts,
340 const char *fmt, int flags,
341 bool writethrough, bool quiet,
342 bool force_share)
343{
344 QDict *options = NULL;
345
346 options = qdict_new();
347 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
348
349 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
350 force_share);
351}
352
353
Max Reitzefaa7c42016-03-16 19:54:38 +0100354static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000355 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100356 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800357 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000358{
359 BlockBackend *blk;
360 if (image_opts) {
361 QemuOpts *opts;
362 if (fmt) {
363 error_report("--image-opts and --format are mutually exclusive");
364 return NULL;
365 }
366 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
367 filename, true);
368 if (!opts) {
369 return NULL;
370 }
Fam Zheng335e9932017-05-03 00:35:39 +0800371 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
372 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000373 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100374 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800375 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000376 }
377 return blk;
378}
379
380
Chunyan Liu83d05212014-06-05 17:20:51 +0800381static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100382 const char *base_filename,
383 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200384{
Markus Armbruster6750e792015-02-12 17:43:08 +0100385 Error *err = NULL;
386
Kevin Wolfefa84d42009-05-18 16:42:12 +0200387 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100388 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100389 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100390 error_report("Backing file not supported for file format '%s'",
391 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100392 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900393 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200394 }
395 }
396 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100397 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100398 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100399 error_report("Backing file format not supported for file "
400 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100401 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900402 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200403 }
404 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900405 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200406}
407
Markus Armbruster606caa02017-02-21 21:14:04 +0100408static int64_t cvtnum(const char *s)
409{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100410 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100411 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100412
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100413 err = qemu_strtosz(s, NULL, &value);
414 if (err < 0) {
415 return err;
416 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100417 if (value > INT64_MAX) {
418 return -ERANGE;
419 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100420 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100421}
422
bellardea2384d2004-08-01 21:59:26 +0000423static int img_create(int argc, char **argv)
424{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200425 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100426 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000427 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000428 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000429 const char *filename;
430 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200431 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200432 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100433 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400434 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000435
bellardea2384d2004-08-01 21:59:26 +0000436 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000437 static const struct option long_options[] = {
438 {"help", no_argument, 0, 'h'},
439 {"object", required_argument, 0, OPTION_OBJECT},
440 {0, 0, 0, 0}
441 };
John Snow6e6e55f2017-07-17 20:34:22 -0400442 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000443 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100444 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000445 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100446 }
bellardea2384d2004-08-01 21:59:26 +0000447 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800448 case ':':
449 missing_argument(argv[optind - 1]);
450 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100451 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800452 unrecognized_option(argv[optind - 1]);
453 break;
bellardea2384d2004-08-01 21:59:26 +0000454 case 'h':
455 help();
456 break;
aliguori9230eaf2009-03-28 17:55:19 +0000457 case 'F':
458 base_fmt = optarg;
459 break;
bellardea2384d2004-08-01 21:59:26 +0000460 case 'b':
461 base_filename = optarg;
462 break;
463 case 'f':
464 fmt = optarg;
465 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200466 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100467 if (!is_valid_option_list(optarg)) {
468 error_report("Invalid option list: %s", optarg);
469 goto fail;
470 }
471 if (!options) {
472 options = g_strdup(optarg);
473 } else {
474 char *old_options = options;
475 options = g_strdup_printf("%s,%s", options, optarg);
476 g_free(old_options);
477 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200478 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100479 case 'q':
480 quiet = true;
481 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400482 case 'u':
483 flags |= BDRV_O_NO_BACKING;
484 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000485 case OPTION_OBJECT: {
486 QemuOpts *opts;
487 opts = qemu_opts_parse_noisily(&qemu_object_opts,
488 optarg, true);
489 if (!opts) {
490 goto fail;
491 }
492 } break;
bellardea2384d2004-08-01 21:59:26 +0000493 }
494 }
aliguori9230eaf2009-03-28 17:55:19 +0000495
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900496 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100497 filename = (optind < argc) ? argv[optind] : NULL;
498 if (options && has_help_option(options)) {
499 g_free(options);
500 return print_block_option_help(filename, fmt);
501 }
502
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100503 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800504 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100505 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100506 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900507
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000508 if (qemu_opts_foreach(&qemu_object_opts,
509 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200510 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000511 goto fail;
512 }
513
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100514 /* Get image size, if specified */
515 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100516 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100517
518 sval = cvtnum(argv[optind++]);
519 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800520 if (sval == -ERANGE) {
521 error_report("Image size must be less than 8 EiB!");
522 } else {
523 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200524 "G, T, P or E suffixes for ");
525 error_report("kilobytes, megabytes, gigabytes, terabytes, "
526 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800527 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100528 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100529 }
530 img_size = (uint64_t)sval;
531 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200532 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800533 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200534 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100535
Luiz Capitulino9b375252012-11-30 10:52:05 -0200536 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400537 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100538 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100539 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100540 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900541 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200542
Kevin Wolf77386bf2014-02-21 16:24:04 +0100543 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000544 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100545
546fail:
547 g_free(options);
548 return 1;
bellardea2384d2004-08-01 21:59:26 +0000549}
550
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100551static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500552{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500553 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500554 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100555 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600556
557 visit_type_ImageCheck(v, NULL, &check, &error_abort);
558 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500559 str = qobject_to_json_pretty(obj);
560 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100561 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500562 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600563 visit_free(v);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500564 QDECREF(str);
565}
566
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100567static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500568{
569 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100570 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500571 } else {
572 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100573 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
574 "Data may be corrupted, or further writes to the image "
575 "may corrupt it.\n",
576 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500577 }
578
579 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100580 qprintf(quiet,
581 "\n%" PRId64 " leaked clusters were found on the image.\n"
582 "This means waste of disk space, but no harm to data.\n",
583 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500584 }
585
586 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100587 qprintf(quiet,
588 "\n%" PRId64
589 " internal errors have occurred during the check.\n",
590 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500591 }
592 }
593
594 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100595 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
596 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
597 check->allocated_clusters, check->total_clusters,
598 check->allocated_clusters * 100.0 / check->total_clusters,
599 check->fragmented_clusters * 100.0 / check->allocated_clusters,
600 check->compressed_clusters * 100.0 /
601 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500602 }
603
604 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100605 qprintf(quiet,
606 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500607 }
608}
609
610static int collect_image_check(BlockDriverState *bs,
611 ImageCheck *check,
612 const char *filename,
613 const char *fmt,
614 int fix)
615{
616 int ret;
617 BdrvCheckResult result;
618
619 ret = bdrv_check(bs, &result, fix);
620 if (ret < 0) {
621 return ret;
622 }
623
624 check->filename = g_strdup(filename);
625 check->format = g_strdup(bdrv_get_format_name(bs));
626 check->check_errors = result.check_errors;
627 check->corruptions = result.corruptions;
628 check->has_corruptions = result.corruptions != 0;
629 check->leaks = result.leaks;
630 check->has_leaks = result.leaks != 0;
631 check->corruptions_fixed = result.corruptions_fixed;
632 check->has_corruptions_fixed = result.corruptions != 0;
633 check->leaks_fixed = result.leaks_fixed;
634 check->has_leaks_fixed = result.leaks != 0;
635 check->image_end_offset = result.image_end_offset;
636 check->has_image_end_offset = result.image_end_offset != 0;
637 check->total_clusters = result.bfi.total_clusters;
638 check->has_total_clusters = result.bfi.total_clusters != 0;
639 check->allocated_clusters = result.bfi.allocated_clusters;
640 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
641 check->fragmented_clusters = result.bfi.fragmented_clusters;
642 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100643 check->compressed_clusters = result.bfi.compressed_clusters;
644 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500645
646 return 0;
647}
648
Kevin Wolfe076f332010-06-29 11:43:13 +0200649/*
650 * Checks an image for consistency. Exit codes:
651 *
Max Reitzd6635c42014-06-02 22:15:21 +0200652 * 0 - Check completed, image is good
653 * 1 - Check not completed because of internal errors
654 * 2 - Check completed, image is corrupted
655 * 3 - Check completed, image has leaked clusters, but is good otherwise
656 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200657 */
aliguori15859692009-04-21 23:11:53 +0000658static int img_check(int argc, char **argv)
659{
660 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500661 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200662 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200663 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000664 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200665 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100666 int flags = BDRV_O_CHECK;
667 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200668 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100669 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000670 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800671 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000672
673 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500674 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200675 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100676
aliguori15859692009-04-21 23:11:53 +0000677 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500678 int option_index = 0;
679 static const struct option long_options[] = {
680 {"help", no_argument, 0, 'h'},
681 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530682 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500683 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000684 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000685 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800686 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500687 {0, 0, 0, 0}
688 };
Fam Zheng335e9932017-05-03 00:35:39 +0800689 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500690 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100691 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000692 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100693 }
aliguori15859692009-04-21 23:11:53 +0000694 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800695 case ':':
696 missing_argument(argv[optind - 1]);
697 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100698 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800699 unrecognized_option(argv[optind - 1]);
700 break;
aliguori15859692009-04-21 23:11:53 +0000701 case 'h':
702 help();
703 break;
704 case 'f':
705 fmt = optarg;
706 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200707 case 'r':
708 flags |= BDRV_O_RDWR;
709
710 if (!strcmp(optarg, "leaks")) {
711 fix = BDRV_FIX_LEAKS;
712 } else if (!strcmp(optarg, "all")) {
713 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
714 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800715 error_exit("Unknown option value for -r "
716 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200717 }
718 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500719 case OPTION_OUTPUT:
720 output = optarg;
721 break;
Max Reitz40055952014-07-22 22:58:42 +0200722 case 'T':
723 cache = optarg;
724 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100725 case 'q':
726 quiet = true;
727 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800728 case 'U':
729 force_share = true;
730 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000731 case OPTION_OBJECT: {
732 QemuOpts *opts;
733 opts = qemu_opts_parse_noisily(&qemu_object_opts,
734 optarg, true);
735 if (!opts) {
736 return 1;
737 }
738 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000739 case OPTION_IMAGE_OPTS:
740 image_opts = true;
741 break;
aliguori15859692009-04-21 23:11:53 +0000742 }
743 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200744 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800745 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100746 }
aliguori15859692009-04-21 23:11:53 +0000747 filename = argv[optind++];
748
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500749 if (output && !strcmp(output, "json")) {
750 output_format = OFORMAT_JSON;
751 } else if (output && !strcmp(output, "human")) {
752 output_format = OFORMAT_HUMAN;
753 } else if (output) {
754 error_report("--output must be used with human or json as argument.");
755 return 1;
756 }
757
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000758 if (qemu_opts_foreach(&qemu_object_opts,
759 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200760 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000761 return 1;
762 }
763
Kevin Wolfce099542016-03-15 13:01:04 +0100764 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200765 if (ret < 0) {
766 error_report("Invalid source cache option: %s", cache);
767 return 1;
768 }
769
Fam Zheng335e9932017-05-03 00:35:39 +0800770 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
771 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200772 if (!blk) {
773 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900774 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200775 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500776
777 check = g_new0(ImageCheck, 1);
778 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200779
780 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200781 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200782 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500783 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200784 }
785
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500786 if (check->corruptions_fixed || check->leaks_fixed) {
787 int corruptions_fixed, leaks_fixed;
788
789 leaks_fixed = check->leaks_fixed;
790 corruptions_fixed = check->corruptions_fixed;
791
792 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100793 qprintf(quiet,
794 "The following inconsistencies were found and repaired:\n\n"
795 " %" PRId64 " leaked clusters\n"
796 " %" PRId64 " corruptions\n\n"
797 "Double checking the fixed image now...\n",
798 check->leaks_fixed,
799 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500800 }
801
802 ret = collect_image_check(bs, check, filename, fmt, 0);
803
804 check->leaks_fixed = leaks_fixed;
805 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200806 }
807
Max Reitz832390a2014-10-23 15:29:12 +0200808 if (!ret) {
809 switch (output_format) {
810 case OFORMAT_HUMAN:
811 dump_human_image_check(check, quiet);
812 break;
813 case OFORMAT_JSON:
814 dump_json_image_check(check, quiet);
815 break;
816 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500817 }
818
819 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200820 if (ret) {
821 error_report("Check failed: %s", strerror(-ret));
822 } else {
823 error_report("Check failed");
824 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500825 ret = 1;
826 goto fail;
827 }
828
829 if (check->corruptions) {
830 ret = 2;
831 } else if (check->leaks) {
832 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200833 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500834 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000835 }
836
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500837fail:
838 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200839 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500840 return ret;
aliguori15859692009-04-21 23:11:53 +0000841}
842
Max Reitzd4a32382014-10-24 15:57:37 +0200843typedef struct CommonBlockJobCBInfo {
844 BlockDriverState *bs;
845 Error **errp;
846} CommonBlockJobCBInfo;
847
848static void common_block_job_cb(void *opaque, int ret)
849{
850 CommonBlockJobCBInfo *cbi = opaque;
851
852 if (ret < 0) {
853 error_setg_errno(cbi->errp, -ret, "Block job failed");
854 }
Max Reitzd4a32382014-10-24 15:57:37 +0200855}
856
857static void run_block_job(BlockJob *job, Error **errp)
858{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200859 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800860 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200861
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200862 aio_context_acquire(aio_context);
sochin.jiang4172a002017-06-15 14:47:33 +0800863 block_job_ref(job);
Max Reitzd4a32382014-10-24 15:57:37 +0200864 do {
865 aio_poll(aio_context, true);
John Snow62547b82015-11-02 18:28:20 -0500866 qemu_progress_print(job->len ?
867 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
sochin.jiang4172a002017-06-15 14:47:33 +0800868 } while (!job->ready && !job->completed);
Max Reitzd4a32382014-10-24 15:57:37 +0200869
sochin.jiang4172a002017-06-15 14:47:33 +0800870 if (!job->completed) {
871 ret = block_job_complete_sync(job, errp);
872 } else {
873 ret = job->ret;
874 }
875 block_job_unref(job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200876 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200877
sochin.jiang4172a002017-06-15 14:47:33 +0800878 /* publish completion progress only when success */
879 if (!ret) {
880 qemu_progress_print(100.f, 0);
881 }
Max Reitzd4a32382014-10-24 15:57:37 +0200882}
883
bellardea2384d2004-08-01 21:59:26 +0000884static int img_commit(int argc, char **argv)
885{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400886 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200887 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200888 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200889 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100890 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200891 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100892 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200893 Error *local_err = NULL;
894 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000895 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200896 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000897
898 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400899 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200900 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000901 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000902 static const struct option long_options[] = {
903 {"help", no_argument, 0, 'h'},
904 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000905 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000906 {0, 0, 0, 0}
907 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800908 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000909 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100910 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000911 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100912 }
bellardea2384d2004-08-01 21:59:26 +0000913 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800914 case ':':
915 missing_argument(argv[optind - 1]);
916 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100917 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800918 unrecognized_option(argv[optind - 1]);
919 break;
bellardea2384d2004-08-01 21:59:26 +0000920 case 'h':
921 help();
922 break;
923 case 'f':
924 fmt = optarg;
925 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400926 case 't':
927 cache = optarg;
928 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200929 case 'b':
930 base = optarg;
931 /* -b implies -d */
932 drop = true;
933 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200934 case 'd':
935 drop = true;
936 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200937 case 'p':
938 progress = true;
939 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100940 case 'q':
941 quiet = true;
942 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000943 case OPTION_OBJECT: {
944 QemuOpts *opts;
945 opts = qemu_opts_parse_noisily(&qemu_object_opts,
946 optarg, true);
947 if (!opts) {
948 return 1;
949 }
950 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000951 case OPTION_IMAGE_OPTS:
952 image_opts = true;
953 break;
bellardea2384d2004-08-01 21:59:26 +0000954 }
955 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200956
957 /* Progress is not shown in Quiet mode */
958 if (quiet) {
959 progress = false;
960 }
961
Kevin Wolffc11eb22013-08-05 10:53:04 +0200962 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800963 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100964 }
bellardea2384d2004-08-01 21:59:26 +0000965 filename = argv[optind++];
966
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000967 if (qemu_opts_foreach(&qemu_object_opts,
968 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200969 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000970 return 1;
971 }
972
Max Reitz9a86fe42014-10-24 15:57:38 +0200973 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100974 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400975 if (ret < 0) {
976 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100977 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400978 }
979
Fam Zheng335e9932017-05-03 00:35:39 +0800980 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
981 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200982 if (!blk) {
983 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900984 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200985 bs = blk_bs(blk);
986
Max Reitz687fa1d2014-10-24 15:57:39 +0200987 qemu_progress_init(progress, 1.f);
988 qemu_progress_print(0.f, 100);
989
Max Reitz1b22bff2014-10-24 15:57:40 +0200990 if (base) {
991 base_bs = bdrv_find_backing_image(bs, base);
992 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100993 error_setg(&local_err,
994 "Did not find '%s' in the backing chain of '%s'",
995 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200996 goto done;
997 }
998 } else {
999 /* This is different from QMP, which by default uses the deepest file in
1000 * the backing chain (i.e., the very base); however, the traditional
1001 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001002 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001003 if (!base_bs) {
1004 error_setg(&local_err, "Image does not have a backing file");
1005 goto done;
1006 }
bellardea2384d2004-08-01 21:59:26 +00001007 }
1008
Max Reitzd4a32382014-10-24 15:57:37 +02001009 cbi = (CommonBlockJobCBInfo){
1010 .errp = &local_err,
1011 .bs = bs,
1012 };
1013
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001014 aio_context = bdrv_get_aio_context(bs);
1015 aio_context_acquire(aio_context);
John Snow47970df2016-10-27 12:06:57 -04001016 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001017 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001018 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001019 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001020 if (local_err) {
1021 goto done;
1022 }
1023
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001024 /* When the block job completes, the BlockBackend reference will point to
1025 * the old backing file. In order to avoid that the top image is already
1026 * deleted, so we can still empty it afterwards, increment the reference
1027 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001028 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001029 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001030 }
1031
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001032 job = block_job_get("commit");
1033 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/*
thsf58c7b32008-06-05 21:53:49 +00001067 * Returns true iff the first sector pointed to by 'buf' contains at least
1068 * a non-NUL byte.
1069 *
1070 * 'pnum' is set to the number of sectors (including and immediately following
1071 * the first one) that are known to be in the same allocated/unallocated state.
1072 */
bellardea2384d2004-08-01 21:59:26 +00001073static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1074{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001075 bool is_zero;
1076 int i;
bellardea2384d2004-08-01 21:59:26 +00001077
1078 if (n <= 0) {
1079 *pnum = 0;
1080 return 0;
1081 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001082 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001083 for(i = 1; i < n; i++) {
1084 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001085 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001086 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001087 }
bellardea2384d2004-08-01 21:59:26 +00001088 }
1089 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001090 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001091}
1092
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001093/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001094 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1095 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1096 * breaking up write requests for only small sparse areas.
1097 */
1098static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1099 int min)
1100{
1101 int ret;
1102 int num_checked, num_used;
1103
1104 if (n < min) {
1105 min = n;
1106 }
1107
1108 ret = is_allocated_sectors(buf, n, pnum);
1109 if (!ret) {
1110 return ret;
1111 }
1112
1113 num_used = *pnum;
1114 buf += BDRV_SECTOR_SIZE * *pnum;
1115 n -= *pnum;
1116 num_checked = num_used;
1117
1118 while (n > 0) {
1119 ret = is_allocated_sectors(buf, n, pnum);
1120
1121 buf += BDRV_SECTOR_SIZE * *pnum;
1122 n -= *pnum;
1123 num_checked += *pnum;
1124 if (ret) {
1125 num_used = num_checked;
1126 } else if (*pnum >= min) {
1127 break;
1128 }
1129 }
1130
1131 *pnum = num_used;
1132 return 1;
1133}
1134
1135/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001136 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1137 * buffers matches, non-zero otherwise.
1138 *
1139 * pnum is set to the number of sectors (including and immediately following
1140 * the first one) that are known to have the same comparison result
1141 */
1142static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1143 int *pnum)
1144{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001145 bool res;
1146 int i;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001147
1148 if (n <= 0) {
1149 *pnum = 0;
1150 return 0;
1151 }
1152
1153 res = !!memcmp(buf1, buf2, 512);
1154 for(i = 1; i < n; i++) {
1155 buf1 += 512;
1156 buf2 += 512;
1157
1158 if (!!memcmp(buf1, buf2, 512) != res) {
1159 break;
1160 }
1161 }
1162
1163 *pnum = i;
1164 return res;
1165}
1166
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001167#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001168
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001169static int64_t sectors_to_bytes(int64_t sectors)
1170{
1171 return sectors << BDRV_SECTOR_BITS;
1172}
1173
1174static int64_t sectors_to_process(int64_t total, int64_t from)
1175{
1176 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1177}
1178
1179/*
1180 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1181 *
1182 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1183 * data and negative value on error.
1184 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001185 * @param blk: BlockBackend for the image
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001186 * @param sect_num: Number of first sector to check
1187 * @param sect_count: Number of sectors to check
1188 * @param filename: Name of disk file we are checking (logging purpose)
1189 * @param buffer: Allocated buffer for storing read data
1190 * @param quiet: Flag for quiet mode
1191 */
Max Reitzf1d3cd72015-02-05 13:58:18 -05001192static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001193 int sect_count, const char *filename,
1194 uint8_t *buffer, bool quiet)
1195{
1196 int pnum, ret = 0;
Eric Blake91669202016-05-06 10:26:43 -06001197 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1198 sect_count << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001199 if (ret < 0) {
1200 error_report("Error while reading offset %" PRId64 " of %s: %s",
1201 sectors_to_bytes(sect_num), filename, strerror(-ret));
1202 return ret;
1203 }
1204 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1205 if (ret || pnum != sect_count) {
1206 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1207 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1208 return 1;
1209 }
1210
1211 return 0;
1212}
1213
1214/*
1215 * Compares two images. Exit codes:
1216 *
1217 * 0 - Images are identical
1218 * 1 - Images differ
1219 * >1 - Error occurred
1220 */
1221static int img_compare(int argc, char **argv)
1222{
Max Reitz40055952014-07-22 22:58:42 +02001223 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001224 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001225 BlockDriverState *bs1, *bs2;
1226 int64_t total_sectors1, total_sectors2;
1227 uint8_t *buf1 = NULL, *buf2 = NULL;
1228 int pnum1, pnum2;
1229 int allocated1, allocated2;
1230 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1231 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001232 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001233 bool writethrough;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001234 int64_t total_sectors;
1235 int64_t sector_num = 0;
1236 int64_t nb_sectors;
1237 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001238 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001239 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001240 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001241
Max Reitz40055952014-07-22 22:58:42 +02001242 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001243 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001244 static const struct option long_options[] = {
1245 {"help", no_argument, 0, 'h'},
1246 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001247 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001248 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001249 {0, 0, 0, 0}
1250 };
Fam Zheng335e9932017-05-03 00:35:39 +08001251 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001252 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001253 if (c == -1) {
1254 break;
1255 }
1256 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001257 case ':':
1258 missing_argument(argv[optind - 1]);
1259 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001260 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001261 unrecognized_option(argv[optind - 1]);
1262 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001263 case 'h':
1264 help();
1265 break;
1266 case 'f':
1267 fmt1 = optarg;
1268 break;
1269 case 'F':
1270 fmt2 = optarg;
1271 break;
Max Reitz40055952014-07-22 22:58:42 +02001272 case 'T':
1273 cache = optarg;
1274 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001275 case 'p':
1276 progress = true;
1277 break;
1278 case 'q':
1279 quiet = true;
1280 break;
1281 case 's':
1282 strict = true;
1283 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001284 case 'U':
1285 force_share = true;
1286 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001287 case OPTION_OBJECT: {
1288 QemuOpts *opts;
1289 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1290 optarg, true);
1291 if (!opts) {
1292 ret = 2;
1293 goto out4;
1294 }
1295 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001296 case OPTION_IMAGE_OPTS:
1297 image_opts = true;
1298 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001299 }
1300 }
1301
1302 /* Progress is not shown in Quiet mode */
1303 if (quiet) {
1304 progress = false;
1305 }
1306
1307
Kevin Wolffc11eb22013-08-05 10:53:04 +02001308 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001309 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001310 }
1311 filename1 = argv[optind++];
1312 filename2 = argv[optind++];
1313
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001314 if (qemu_opts_foreach(&qemu_object_opts,
1315 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001316 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001317 ret = 2;
1318 goto out4;
1319 }
1320
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001321 /* Initialize before goto out */
1322 qemu_progress_init(progress, 2.0);
1323
Kevin Wolfce099542016-03-15 13:01:04 +01001324 flags = 0;
1325 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001326 if (ret < 0) {
1327 error_report("Invalid source cache option: %s", cache);
1328 ret = 2;
1329 goto out3;
1330 }
1331
Fam Zheng335e9932017-05-03 00:35:39 +08001332 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1333 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001334 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001335 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001336 goto out3;
1337 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001338
Fam Zheng335e9932017-05-03 00:35:39 +08001339 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1340 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001341 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001342 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001343 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001344 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001345 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001346 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001347
Max Reitzf1d3cd72015-02-05 13:58:18 -05001348 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1349 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1350 total_sectors1 = blk_nb_sectors(blk1);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001351 if (total_sectors1 < 0) {
1352 error_report("Can't get size of %s: %s",
1353 filename1, strerror(-total_sectors1));
1354 ret = 4;
1355 goto out;
1356 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001357 total_sectors2 = blk_nb_sectors(blk2);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001358 if (total_sectors2 < 0) {
1359 error_report("Can't get size of %s: %s",
1360 filename2, strerror(-total_sectors2));
1361 ret = 4;
1362 goto out;
1363 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001364 total_sectors = MIN(total_sectors1, total_sectors2);
1365 progress_base = MAX(total_sectors1, total_sectors2);
1366
1367 qemu_progress_print(0, 100);
1368
1369 if (strict && total_sectors1 != total_sectors2) {
1370 ret = 1;
1371 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1372 goto out;
1373 }
1374
1375 for (;;) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001376 int64_t status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001377 BlockDriverState *file;
1378
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001379 nb_sectors = sectors_to_process(total_sectors, sector_num);
1380 if (nb_sectors <= 0) {
1381 break;
1382 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001383 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1384 total_sectors1 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001385 &pnum1, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001386 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001387 ret = 3;
1388 error_report("Sector allocation test failed for %s", filename1);
1389 goto out;
1390 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001391 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392
Fam Zheng25ad8e62016-01-13 16:37:41 +08001393 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1394 total_sectors2 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001395 &pnum2, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001396 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001397 ret = 3;
1398 error_report("Sector allocation test failed for %s", filename2);
1399 goto out;
1400 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001401 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1402 if (pnum1) {
1403 nb_sectors = MIN(nb_sectors, pnum1);
1404 }
1405 if (pnum2) {
1406 nb_sectors = MIN(nb_sectors, pnum2);
1407 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001408
Fam Zheng25ad8e62016-01-13 16:37:41 +08001409 if (strict) {
1410 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1411 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1412 ret = 1;
1413 qprintf(quiet, "Strict mode: Offset %" PRId64
1414 " block status mismatch!\n",
1415 sectors_to_bytes(sector_num));
1416 goto out;
1417 }
1418 }
1419 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1420 nb_sectors = MIN(pnum1, pnum2);
1421 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001422 if (allocated1) {
Eric Blake91669202016-05-06 10:26:43 -06001423 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1424 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001425 if (ret < 0) {
1426 error_report("Error while reading offset %" PRId64 " of %s:"
1427 " %s", sectors_to_bytes(sector_num), filename1,
1428 strerror(-ret));
1429 ret = 4;
1430 goto out;
1431 }
Eric Blake91669202016-05-06 10:26:43 -06001432 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1433 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001434 if (ret < 0) {
1435 error_report("Error while reading offset %" PRId64
1436 " of %s: %s", sectors_to_bytes(sector_num),
1437 filename2, strerror(-ret));
1438 ret = 4;
1439 goto out;
1440 }
1441 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1442 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001443 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1444 sectors_to_bytes(
1445 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001446 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001447 goto out;
1448 }
1449 }
1450 } else {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001451
1452 if (allocated1) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001453 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001454 filename1, buf1, quiet);
1455 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001456 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001457 filename2, buf1, quiet);
1458 }
1459 if (ret) {
1460 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001461 error_report("Error while reading offset %" PRId64 ": %s",
1462 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001463 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001464 }
1465 goto out;
1466 }
1467 }
1468 sector_num += nb_sectors;
1469 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1470 }
1471
1472 if (total_sectors1 != total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001473 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001474 int64_t total_sectors_over;
1475 const char *filename_over;
1476
1477 qprintf(quiet, "Warning: Image size mismatch!\n");
1478 if (total_sectors1 > total_sectors2) {
1479 total_sectors_over = total_sectors1;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001480 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001481 filename_over = filename1;
1482 } else {
1483 total_sectors_over = total_sectors2;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001484 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001485 filename_over = filename2;
1486 }
1487
1488 for (;;) {
Eric Blake51b0a482017-07-07 07:44:59 -05001489 int64_t count;
1490
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1492 if (nb_sectors <= 0) {
1493 break;
1494 }
Eric Blake51b0a482017-07-07 07:44:59 -05001495 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL,
1496 sector_num * BDRV_SECTOR_SIZE,
1497 nb_sectors * BDRV_SECTOR_SIZE,
1498 &count);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 if (ret < 0) {
1500 ret = 3;
1501 error_report("Sector allocation test failed for %s",
1502 filename_over);
1503 goto out;
1504
1505 }
Eric Blake51b0a482017-07-07 07:44:59 -05001506 /* TODO relax this once bdrv_is_allocated_above does not enforce
1507 * sector alignment */
1508 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
1509 nb_sectors = count >> BDRV_SECTOR_BITS;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001510 if (ret) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001511 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001512 filename_over, buf1, quiet);
1513 if (ret) {
1514 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001515 error_report("Error while reading offset %" PRId64
1516 " of %s: %s", sectors_to_bytes(sector_num),
1517 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001518 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519 }
1520 goto out;
1521 }
1522 }
1523 sector_num += nb_sectors;
1524 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1525 }
1526 }
1527
1528 qprintf(quiet, "Images are identical.\n");
1529 ret = 0;
1530
1531out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 qemu_vfree(buf1);
1533 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001534 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001535out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001536 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001537out3:
1538 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001539out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001540 return ret;
1541}
1542
Kevin Wolf690c7302015-03-19 13:33:32 +01001543enum ImgConvertBlockStatus {
1544 BLK_DATA,
1545 BLK_ZERO,
1546 BLK_BACKING_FILE,
1547};
1548
Peter Lieven2d9187b2017-02-28 13:40:07 +01001549#define MAX_COROUTINES 16
1550
Kevin Wolf690c7302015-03-19 13:33:32 +01001551typedef struct ImgConvertState {
1552 BlockBackend **src;
1553 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001554 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001555 int64_t total_sectors;
1556 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001557 int64_t allocated_done;
1558 int64_t sector_num;
1559 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001560 enum ImgConvertBlockStatus status;
1561 int64_t sector_next_status;
1562 BlockBackend *target;
1563 bool has_zero_init;
1564 bool compressed;
1565 bool target_has_backing;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001566 bool wr_in_order;
Kevin Wolf690c7302015-03-19 13:33:32 +01001567 int min_sparse;
1568 size_t cluster_sectors;
1569 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001570 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001571 int running_coroutines;
1572 Coroutine *co[MAX_COROUTINES];
1573 int64_t wait_sector_num[MAX_COROUTINES];
1574 CoMutex lock;
1575 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001576} ImgConvertState;
1577
Peter Lieven2d9187b2017-02-28 13:40:07 +01001578static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1579 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001580{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001581 *src_cur = 0;
1582 *src_cur_offset = 0;
1583 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1584 *src_cur_offset += s->src_sectors[*src_cur];
1585 (*src_cur)++;
1586 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001587 }
1588}
1589
1590static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1591{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001592 int64_t ret, src_cur_offset;
1593 int n, src_cur;
Kevin Wolf690c7302015-03-19 13:33:32 +01001594
Peter Lieven2d9187b2017-02-28 13:40:07 +01001595 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001596
1597 assert(s->total_sectors > sector_num);
1598 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1599
1600 if (s->sector_next_status <= sector_num) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08001601 BlockDriverState *file;
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001602 if (s->target_has_backing) {
1603 ret = bdrv_get_block_status(blk_bs(s->src[src_cur]),
1604 sector_num - src_cur_offset,
1605 n, &n, &file);
1606 } else {
1607 ret = bdrv_get_block_status_above(blk_bs(s->src[src_cur]), NULL,
1608 sector_num - src_cur_offset,
1609 n, &n, &file);
1610 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001611 if (ret < 0) {
1612 return ret;
1613 }
1614
1615 if (ret & BDRV_BLOCK_ZERO) {
1616 s->status = BLK_ZERO;
1617 } else if (ret & BDRV_BLOCK_DATA) {
1618 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001619 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001620 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001621 }
1622
1623 s->sector_next_status = sector_num + n;
1624 }
1625
1626 n = MIN(n, s->sector_next_status - sector_num);
1627 if (s->status == BLK_DATA) {
1628 n = MIN(n, s->buf_sectors);
1629 }
1630
1631 /* We need to write complete clusters for compressed images, so if an
1632 * unallocated area is shorter than that, we must consider the whole
1633 * cluster allocated. */
1634 if (s->compressed) {
1635 if (n < s->cluster_sectors) {
1636 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1637 s->status = BLK_DATA;
1638 } else {
1639 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1640 }
1641 }
1642
1643 return n;
1644}
1645
Peter Lieven2d9187b2017-02-28 13:40:07 +01001646static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1647 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001648{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001649 int n, ret;
1650 QEMUIOVector qiov;
1651 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001652
Kevin Wolf690c7302015-03-19 13:33:32 +01001653 assert(nb_sectors <= s->buf_sectors);
1654 while (nb_sectors > 0) {
1655 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001656 int src_cur;
1657 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001658
1659 /* In the case of compression with multiple source files, we can get a
1660 * nb_sectors that spreads into the next part. So we must be able to
1661 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001662 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1663 blk = s->src[src_cur];
1664 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001665
Peter Lieven2d9187b2017-02-28 13:40:07 +01001666 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1667 iov.iov_base = buf;
1668 iov.iov_len = n << BDRV_SECTOR_BITS;
1669 qemu_iovec_init_external(&qiov, &iov, 1);
1670
1671 ret = blk_co_preadv(
1672 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1673 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001674 if (ret < 0) {
1675 return ret;
1676 }
1677
1678 sector_num += n;
1679 nb_sectors -= n;
1680 buf += n * BDRV_SECTOR_SIZE;
1681 }
1682
1683 return 0;
1684}
1685
Peter Lieven2d9187b2017-02-28 13:40:07 +01001686
1687static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1688 int nb_sectors, uint8_t *buf,
1689 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001690{
1691 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001692 QEMUIOVector qiov;
1693 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001694
1695 while (nb_sectors > 0) {
1696 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001697 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1698
Peter Lieven2d9187b2017-02-28 13:40:07 +01001699 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001700 case BLK_BACKING_FILE:
1701 /* If we have a backing file, leave clusters unallocated that are
1702 * unallocated in the source image, so that the backing file is
1703 * visible at the respective offset. */
1704 assert(s->target_has_backing);
1705 break;
1706
1707 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001708 /* If we're told to keep the target fully allocated (-S 0) or there
1709 * is real non-zero data, we must write it. Otherwise we can treat
1710 * it as zero sectors.
1711 * Compressed clusters need to be written as a whole, so in that
1712 * case we can only save the write if the buffer is completely
1713 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001714 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001715 (!s->compressed &&
1716 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1717 (s->compressed &&
1718 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001719 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001720 iov.iov_base = buf;
1721 iov.iov_len = n << BDRV_SECTOR_BITS;
1722 qemu_iovec_init_external(&qiov, &iov, 1);
1723
1724 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001725 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001726 if (ret < 0) {
1727 return ret;
1728 }
1729 break;
1730 }
1731 /* fall-through */
1732
1733 case BLK_ZERO:
1734 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001735 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001736 break;
1737 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001738 ret = blk_co_pwrite_zeroes(s->target,
1739 sector_num << BDRV_SECTOR_BITS,
1740 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001741 if (ret < 0) {
1742 return ret;
1743 }
1744 break;
1745 }
1746
1747 sector_num += n;
1748 nb_sectors -= n;
1749 buf += n * BDRV_SECTOR_SIZE;
1750 }
1751
1752 return 0;
1753}
1754
Peter Lieven2d9187b2017-02-28 13:40:07 +01001755static void coroutine_fn convert_co_do_copy(void *opaque)
1756{
1757 ImgConvertState *s = opaque;
1758 uint8_t *buf = NULL;
1759 int ret, i;
1760 int index = -1;
1761
1762 for (i = 0; i < s->num_coroutines; i++) {
1763 if (s->co[i] == qemu_coroutine_self()) {
1764 index = i;
1765 break;
1766 }
1767 }
1768 assert(index >= 0);
1769
1770 s->running_coroutines++;
1771 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1772
1773 while (1) {
1774 int n;
1775 int64_t sector_num;
1776 enum ImgConvertBlockStatus status;
1777
1778 qemu_co_mutex_lock(&s->lock);
1779 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1780 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001781 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001782 }
1783 n = convert_iteration_sectors(s, s->sector_num);
1784 if (n < 0) {
1785 qemu_co_mutex_unlock(&s->lock);
1786 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001787 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001788 }
1789 /* save current sector and allocation status to local variables */
1790 sector_num = s->sector_num;
1791 status = s->status;
1792 if (!s->min_sparse && s->status == BLK_ZERO) {
1793 n = MIN(n, s->buf_sectors);
1794 }
1795 /* increment global sector counter so that other coroutines can
1796 * already continue reading beyond this request */
1797 s->sector_num += n;
1798 qemu_co_mutex_unlock(&s->lock);
1799
1800 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1801 s->allocated_done += n;
1802 qemu_progress_print(100.0 * s->allocated_done /
1803 s->allocated_sectors, 0);
1804 }
1805
1806 if (status == BLK_DATA) {
1807 ret = convert_co_read(s, sector_num, n, buf);
1808 if (ret < 0) {
1809 error_report("error while reading sector %" PRId64
1810 ": %s", sector_num, strerror(-ret));
1811 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001812 }
1813 } else if (!s->min_sparse && status == BLK_ZERO) {
1814 status = BLK_DATA;
1815 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1816 }
1817
1818 if (s->wr_in_order) {
1819 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001820 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001821 s->wait_sector_num[index] = sector_num;
1822 qemu_coroutine_yield();
1823 }
1824 s->wait_sector_num[index] = -1;
1825 }
1826
Anton Nefedovb91127e2017-04-26 11:33:15 +03001827 if (s->ret == -EINPROGRESS) {
1828 ret = convert_co_write(s, sector_num, n, buf, status);
1829 if (ret < 0) {
1830 error_report("error while writing sector %" PRId64
1831 ": %s", sector_num, strerror(-ret));
1832 s->ret = ret;
1833 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001834 }
1835
1836 if (s->wr_in_order) {
1837 /* reenter the coroutine that might have waited
1838 * for this write to complete */
1839 s->wr_offs = sector_num + n;
1840 for (i = 0; i < s->num_coroutines; i++) {
1841 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1842 /*
1843 * A -> B -> A cannot occur because A has
1844 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1845 * B will never enter A during this time window.
1846 */
1847 qemu_coroutine_enter(s->co[i]);
1848 break;
1849 }
1850 }
1851 }
1852 }
1853
Peter Lieven2d9187b2017-02-28 13:40:07 +01001854 qemu_vfree(buf);
1855 s->co[index] = NULL;
1856 s->running_coroutines--;
1857 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1858 /* the convert job finished successfully */
1859 s->ret = 0;
1860 }
1861}
1862
Kevin Wolf690c7302015-03-19 13:33:32 +01001863static int convert_do_copy(ImgConvertState *s)
1864{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001865 int ret, i, n;
1866 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001867
1868 /* Check whether we have zero initialisation or can get it efficiently */
1869 s->has_zero_init = s->min_sparse && !s->target_has_backing
1870 ? bdrv_has_zero_init(blk_bs(s->target))
1871 : false;
1872
1873 if (!s->has_zero_init && !s->target_has_backing &&
1874 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1875 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001876 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001877 if (ret == 0) {
1878 s->has_zero_init = true;
1879 }
1880 }
1881
1882 /* Allocate buffer for copied data. For compressed images, only one cluster
1883 * can be copied at a time. */
1884 if (s->compressed) {
1885 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1886 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001887 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001888 }
1889 s->buf_sectors = s->cluster_sectors;
1890 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001891
Kevin Wolf690c7302015-03-19 13:33:32 +01001892 while (sector_num < s->total_sectors) {
1893 n = convert_iteration_sectors(s, sector_num);
1894 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001895 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001896 }
Max Reitzaad15de2016-03-24 23:33:57 +01001897 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1898 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001899 s->allocated_sectors += n;
1900 }
1901 sector_num += n;
1902 }
1903
1904 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001905 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001906 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001907
Peter Lieven2d9187b2017-02-28 13:40:07 +01001908 qemu_co_mutex_init(&s->lock);
1909 for (i = 0; i < s->num_coroutines; i++) {
1910 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1911 s->wait_sector_num[i] = -1;
1912 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001913 }
1914
Anton Nefedovb91127e2017-04-26 11:33:15 +03001915 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001916 main_loop_wait(false);
1917 }
1918
1919 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001920 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001921 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001922 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001923 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001924 }
1925 }
1926
Peter Lieven2d9187b2017-02-28 13:40:07 +01001927 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001928}
1929
bellardea2384d2004-08-01 21:59:26 +00001930static int img_convert(int argc, char **argv)
1931{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001932 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001933 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001934 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1935 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001936 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00001937 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001938 BlockDriverState *out_bs;
1939 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08001940 QemuOptsList *create_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001941 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02001942 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001943 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001944 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001945 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08001946 bool force_share = false;
bellardea2384d2004-08-01 21:59:26 +00001947
Peter Lieven9fd77f92017-04-21 11:11:55 +02001948 ImgConvertState s = (ImgConvertState) {
1949 /* Need at least 4k of zeros for sparse detection */
1950 .min_sparse = 8,
1951 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1952 .wr_in_order = true,
1953 .num_coroutines = 8,
1954 };
1955
bellardea2384d2004-08-01 21:59:26 +00001956 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001957 static const struct option long_options[] = {
1958 {"help", no_argument, 0, 'h'},
1959 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001960 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001961 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001962 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001963 {0, 0, 0, 0}
1964 };
Daniel P. Berrange6b4df542017-07-04 13:30:09 +01001965 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001966 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001967 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001968 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001969 }
bellardea2384d2004-08-01 21:59:26 +00001970 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001971 case ':':
1972 missing_argument(argv[optind - 1]);
1973 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001974 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001975 unrecognized_option(argv[optind - 1]);
1976 break;
bellardea2384d2004-08-01 21:59:26 +00001977 case 'h':
1978 help();
1979 break;
1980 case 'f':
1981 fmt = optarg;
1982 break;
1983 case 'O':
1984 out_fmt = optarg;
1985 break;
thsf58c7b32008-06-05 21:53:49 +00001986 case 'B':
1987 out_baseimg = optarg;
1988 break;
bellardea2384d2004-08-01 21:59:26 +00001989 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02001990 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00001991 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001992 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001993 if (!is_valid_option_list(optarg)) {
1994 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001995 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001996 }
1997 if (!options) {
1998 options = g_strdup(optarg);
1999 } else {
2000 char *old_options = options;
2001 options = g_strdup_printf("%s,%s", options, optarg);
2002 g_free(old_options);
2003 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002004 break;
edison51ef6722010-09-21 19:58:41 -07002005 case 's':
2006 snapshot_name = optarg;
2007 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002008 case 'l':
2009 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002010 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2011 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002012 if (!sn_opts) {
2013 error_report("Failed in parsing snapshot param '%s'",
2014 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002015 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002016 }
2017 } else {
2018 snapshot_name = optarg;
2019 }
2020 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002021 case 'S':
2022 {
2023 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002024
2025 sval = cvtnum(optarg);
2026 if (sval < 0) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02002027 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002028 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002029 }
2030
Peter Lieven9fd77f92017-04-21 11:11:55 +02002031 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002032 break;
2033 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002034 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002035 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002036 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002037 case 't':
2038 cache = optarg;
2039 break;
Max Reitz40055952014-07-22 22:58:42 +02002040 case 'T':
2041 src_cache = optarg;
2042 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002043 case 'q':
2044 quiet = true;
2045 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002046 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002047 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002048 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002049 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002050 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2051 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002052 error_report("Invalid number of coroutines. Allowed number of"
2053 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002054 goto fail_getopt;
2055 }
2056 break;
2057 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002058 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002059 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002060 case 'U':
2061 force_share = true;
2062 break;
Max Reitz3258b912017-04-26 15:46:47 +02002063 case OPTION_OBJECT: {
2064 QemuOpts *object_opts;
2065 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2066 optarg, true);
2067 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002068 goto fail_getopt;
2069 }
2070 break;
Max Reitz3258b912017-04-26 15:46:47 +02002071 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002072 case OPTION_IMAGE_OPTS:
2073 image_opts = true;
2074 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002075 case OPTION_TARGET_IMAGE_OPTS:
2076 tgt_image_opts = true;
2077 break;
bellardea2384d2004-08-01 21:59:26 +00002078 }
2079 }
ths3b46e622007-09-17 08:09:54 +00002080
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002081 if (!out_fmt && !tgt_image_opts) {
2082 out_fmt = "raw";
2083 }
2084
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002085 if (qemu_opts_foreach(&qemu_object_opts,
2086 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002087 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002088 goto fail_getopt;
2089 }
2090
Peter Lieven9fd77f92017-04-21 11:11:55 +02002091 if (!s.wr_in_order && s.compressed) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002092 error_report("Out of order write and compress are mutually exclusive");
Peter Lieven9fd77f92017-04-21 11:11:55 +02002093 goto fail_getopt;
2094 }
2095
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002096 if (tgt_image_opts && !skip_create) {
2097 error_report("--target-image-opts requires use of -n flag");
2098 goto fail_getopt;
2099 }
2100
Peter Lieven9fd77f92017-04-21 11:11:55 +02002101 s.src_num = argc - optind - 1;
2102 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2103
2104 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002105 if (out_fmt) {
2106 ret = print_block_option_help(out_filename, out_fmt);
2107 goto fail_getopt;
2108 } else {
2109 error_report("Option help requires a format be specified");
2110 goto fail_getopt;
2111 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002112 }
2113
2114 if (s.src_num < 1) {
2115 error_report("Must specify image file name");
2116 goto fail_getopt;
2117 }
2118
2119
Peter Lieven9fd77f92017-04-21 11:11:55 +02002120 /* ret is still -EINVAL until here */
2121 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2122 if (ret < 0) {
2123 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002124 goto fail_getopt;
2125 }
2126
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002127 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002128 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002129 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002130 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002131 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002132 qemu_progress_print(0, 100);
2133
Peter Lieven9fd77f92017-04-21 11:11:55 +02002134 s.src = g_new0(BlockBackend *, s.src_num);
2135 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002136
Peter Lieven9fd77f92017-04-21 11:11:55 +02002137 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2138 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002139 fmt, src_flags, src_writethrough, quiet,
2140 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002141 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002142 ret = -1;
2143 goto out;
2144 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002145 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2146 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002147 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002148 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002149 ret = -1;
2150 goto out;
2151 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002152 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002153 }
bellardea2384d2004-08-01 21:59:26 +00002154
Wenchao Xiaef806542013-12-04 17:10:57 +08002155 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002156 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002157 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2158 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2159 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002160 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002161 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002162 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002163 ret = -1;
2164 goto out;
2165 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002166
Peter Lieven9fd77f92017-04-21 11:11:55 +02002167 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2168 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002169 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002170 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002171 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002172 ret = -1;
2173 goto out;
edison51ef6722010-09-21 19:58:41 -07002174 }
2175
Max Reitz2e024cd2015-02-11 09:58:46 -05002176 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002177 /* Find driver and parse its options */
2178 drv = bdrv_find_format(out_fmt);
2179 if (!drv) {
2180 error_report("Unknown file format '%s'", out_fmt);
2181 ret = -1;
2182 goto out;
2183 }
2184
2185 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2186 if (!proto_drv) {
2187 error_report_err(local_err);
2188 ret = -1;
2189 goto out;
2190 }
2191
Max Reitz2e024cd2015-02-11 09:58:46 -05002192 if (!drv->create_opts) {
2193 error_report("Format driver '%s' does not support image creation",
2194 drv->format_name);
2195 ret = -1;
2196 goto out;
2197 }
Max Reitzf75613c2014-12-02 18:32:46 +01002198
Max Reitz2e024cd2015-02-11 09:58:46 -05002199 if (!proto_drv->create_opts) {
2200 error_report("Protocol driver '%s' does not support image creation",
2201 proto_drv->format_name);
2202 ret = -1;
2203 goto out;
2204 }
Max Reitzf75613c2014-12-02 18:32:46 +01002205
Max Reitz2e024cd2015-02-11 09:58:46 -05002206 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2207 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002208
Max Reitz2e024cd2015-02-11 09:58:46 -05002209 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002210 if (options) {
2211 qemu_opts_do_parse(opts, options, NULL, &local_err);
2212 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002213 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002214 ret = -1;
2215 goto out;
2216 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002217 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002218
Peter Lieven9fd77f92017-04-21 11:11:55 +02002219 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002220 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002221 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2222 if (ret < 0) {
2223 goto out;
2224 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002225 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002226
Kevin Wolfa18953f2010-10-14 15:46:04 +02002227 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002228 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002229 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002230 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002231 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002232 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002233
Max Reitz48758a82017-04-26 15:46:48 +02002234 if (s.src_num > 1 && out_baseimg) {
2235 error_report("Having a backing file for the target makes no sense when "
2236 "concatenating multiple input images");
2237 ret = -1;
2238 goto out;
2239 }
2240
Kevin Wolfefa84d42009-05-18 16:42:12 +02002241 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002242 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002243 bool encryption =
2244 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002245 const char *encryptfmt =
2246 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002247 const char *preallocation =
2248 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002249
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002250 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002251 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002252 ret = -1;
2253 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002254 }
2255
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002256 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002257 error_report("Compression and encryption not supported at "
2258 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002259 ret = -1;
2260 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002261 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002262
Chunyan Liu83d05212014-06-05 17:20:51 +08002263 if (preallocation
2264 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002265 {
2266 error_report("Compression and preallocation not supported at "
2267 "the same time");
2268 ret = -1;
2269 goto out;
2270 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002271 }
2272
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002273 if (!skip_create) {
2274 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002275 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002276 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002277 error_reportf_err(local_err, "%s: error while converting %s: ",
2278 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002279 goto out;
bellardea2384d2004-08-01 21:59:26 +00002280 }
2281 }
ths3b46e622007-09-17 08:09:54 +00002282
Peter Lieven9fd77f92017-04-21 11:11:55 +02002283 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002284 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002285 if (ret < 0) {
2286 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002287 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002288 }
2289
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002290 if (skip_create) {
2291 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2292 flags, writethrough, quiet, false);
2293 } else {
2294 /* TODO ultimately we should allow --target-image-opts
2295 * to be used even when -n is not given.
2296 * That has to wait for bdrv_create to be improved
2297 * to allow filenames in option syntax
2298 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01002299 s.target = img_open_new_file(out_filename, opts, out_fmt,
2300 flags, writethrough, quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002301 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002302 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002303 ret = -1;
2304 goto out;
2305 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002306 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002307
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002308 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2309 error_report("Compression not supported for this file format");
2310 ret = -1;
2311 goto out;
2312 }
2313
Eric Blake5def6b82016-06-23 16:37:19 -06002314 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002315 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2316 * as maximum. */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002317 s.buf_sectors = MIN(32768,
2318 MAX(s.buf_sectors,
2319 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2320 out_bs->bl.pdiscard_alignment >>
2321 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002322
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002323 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002324 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002325 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002326 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002327 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002328 ret = -1;
2329 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002330 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002331 error_report("output file is smaller than input file");
2332 ret = -1;
2333 goto out;
2334 }
2335 }
2336
Peter Lieven24f833c2013-11-27 11:07:07 +01002337 ret = bdrv_get_info(out_bs, &bdi);
2338 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002339 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002340 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002341 goto out;
2342 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002343 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002344 s.compressed = s.compressed || bdi.needs_compressed_writes;
2345 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002346 }
2347
Peter Lieven9fd77f92017-04-21 11:11:55 +02002348 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002349out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002350 if (!ret) {
2351 qemu_progress_print(100, 0);
2352 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002353 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002354 qemu_opts_del(opts);
2355 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002356 qemu_opts_del(sn_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002357 blk_unref(s.target);
2358 if (s.src) {
2359 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2360 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002361 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002362 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002363 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002364 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002365fail_getopt:
2366 g_free(options);
2367
Peter Lieven9fd77f92017-04-21 11:11:55 +02002368 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002369}
2370
bellard57d1a2b2004-08-03 21:15:11 +00002371
bellardfaea38e2006-08-05 21:31:00 +00002372static void dump_snapshots(BlockDriverState *bs)
2373{
2374 QEMUSnapshotInfo *sn_tab, *sn;
2375 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002376
2377 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2378 if (nb_sns <= 0)
2379 return;
2380 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002381 bdrv_snapshot_dump(fprintf, stdout, NULL);
2382 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002383 for(i = 0; i < nb_sns; i++) {
2384 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002385 bdrv_snapshot_dump(fprintf, stdout, sn);
2386 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002387 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002388 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002389}
2390
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002391static void dump_json_image_info_list(ImageInfoList *list)
2392{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002393 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002394 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002395 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002396
2397 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2398 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002399 str = qobject_to_json_pretty(obj);
2400 assert(str != NULL);
2401 printf("%s\n", qstring_get_str(str));
2402 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002403 visit_free(v);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002404 QDECREF(str);
2405}
2406
Benoît Canetc054b3f2012-09-05 13:09:02 +02002407static void dump_json_image_info(ImageInfo *info)
2408{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002409 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002410 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002411 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002412
2413 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2414 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002415 str = qobject_to_json_pretty(obj);
2416 assert(str != NULL);
2417 printf("%s\n", qstring_get_str(str));
2418 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002419 visit_free(v);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002420 QDECREF(str);
2421}
2422
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002423static void dump_human_image_info_list(ImageInfoList *list)
2424{
2425 ImageInfoList *elem;
2426 bool delim = false;
2427
2428 for (elem = list; elem; elem = elem->next) {
2429 if (delim) {
2430 printf("\n");
2431 }
2432 delim = true;
2433
Wenchao Xia5b917042013-05-25 11:09:45 +08002434 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002435 }
2436}
2437
2438static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2439{
2440 return strcmp(a, b) == 0;
2441}
2442
2443/**
2444 * Open an image file chain and return an ImageInfoList
2445 *
2446 * @filename: topmost image filename
2447 * @fmt: topmost image format (may be NULL to autodetect)
2448 * @chain: true - enumerate entire backing file chain
2449 * false - only topmost image file
2450 *
2451 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2452 * image file. If there was an error a message will have been printed to
2453 * stderr.
2454 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002455static ImageInfoList *collect_image_info_list(bool image_opts,
2456 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002457 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002458 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002459{
2460 ImageInfoList *head = NULL;
2461 ImageInfoList **last = &head;
2462 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002463 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002464
2465 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2466
2467 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002468 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002469 BlockDriverState *bs;
2470 ImageInfo *info;
2471 ImageInfoList *elem;
2472
2473 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2474 error_report("Backing file '%s' creates an infinite loop.",
2475 filename);
2476 goto err;
2477 }
2478 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2479
Max Reitzefaa7c42016-03-16 19:54:38 +01002480 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002481 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2482 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002483 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002484 goto err;
2485 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002486 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002487
Wenchao Xia43526ec2013-06-06 12:27:58 +08002488 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002489 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002490 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002491 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002492 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002493 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002494
2495 elem = g_new0(ImageInfoList, 1);
2496 elem->value = info;
2497 *last = elem;
2498 last = &elem->next;
2499
Markus Armbruster26f54e92014-10-07 13:59:04 +02002500 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002501
2502 filename = fmt = NULL;
2503 if (chain) {
2504 if (info->has_full_backing_filename) {
2505 filename = info->full_backing_filename;
2506 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002507 error_report("Could not determine absolute backing filename,"
2508 " but backing filename '%s' present",
2509 info->backing_filename);
2510 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002511 }
2512 if (info->has_backing_filename_format) {
2513 fmt = info->backing_filename_format;
2514 }
2515 }
2516 }
2517 g_hash_table_destroy(filenames);
2518 return head;
2519
2520err:
2521 qapi_free_ImageInfoList(head);
2522 g_hash_table_destroy(filenames);
2523 return NULL;
2524}
2525
Benoît Canetc054b3f2012-09-05 13:09:02 +02002526static int img_info(int argc, char **argv)
2527{
2528 int c;
2529 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002530 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002531 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002532 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002533 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002534 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002535
bellardea2384d2004-08-01 21:59:26 +00002536 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002537 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002538 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002539 int option_index = 0;
2540 static const struct option long_options[] = {
2541 {"help", no_argument, 0, 'h'},
2542 {"format", required_argument, 0, 'f'},
2543 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002544 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002545 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002546 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002547 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002548 {0, 0, 0, 0}
2549 };
Fam Zheng335e9932017-05-03 00:35:39 +08002550 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002551 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002552 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002553 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002554 }
bellardea2384d2004-08-01 21:59:26 +00002555 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002556 case ':':
2557 missing_argument(argv[optind - 1]);
2558 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002559 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002560 unrecognized_option(argv[optind - 1]);
2561 break;
bellardea2384d2004-08-01 21:59:26 +00002562 case 'h':
2563 help();
2564 break;
2565 case 'f':
2566 fmt = optarg;
2567 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002568 case 'U':
2569 force_share = true;
2570 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002571 case OPTION_OUTPUT:
2572 output = optarg;
2573 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002574 case OPTION_BACKING_CHAIN:
2575 chain = true;
2576 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002577 case OPTION_OBJECT: {
2578 QemuOpts *opts;
2579 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2580 optarg, true);
2581 if (!opts) {
2582 return 1;
2583 }
2584 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002585 case OPTION_IMAGE_OPTS:
2586 image_opts = true;
2587 break;
bellardea2384d2004-08-01 21:59:26 +00002588 }
2589 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002590 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002591 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002592 }
bellardea2384d2004-08-01 21:59:26 +00002593 filename = argv[optind++];
2594
Benoît Canetc054b3f2012-09-05 13:09:02 +02002595 if (output && !strcmp(output, "json")) {
2596 output_format = OFORMAT_JSON;
2597 } else if (output && !strcmp(output, "human")) {
2598 output_format = OFORMAT_HUMAN;
2599 } else if (output) {
2600 error_report("--output must be used with human or json as argument.");
2601 return 1;
2602 }
2603
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002604 if (qemu_opts_foreach(&qemu_object_opts,
2605 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002606 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002607 return 1;
2608 }
2609
Fam Zheng335e9932017-05-03 00:35:39 +08002610 list = collect_image_info_list(image_opts, filename, fmt, chain,
2611 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002612 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002613 return 1;
2614 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002615
Benoît Canetc054b3f2012-09-05 13:09:02 +02002616 switch (output_format) {
2617 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002618 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002619 break;
2620 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002621 if (chain) {
2622 dump_json_image_info_list(list);
2623 } else {
2624 dump_json_image_info(list->value);
2625 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002626 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002627 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002628
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002629 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002630 return 0;
2631}
2632
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002633static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2634 MapEntry *next)
2635{
2636 switch (output_format) {
2637 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002638 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002639 error_report("File contains external, encrypted or compressed clusters.");
2640 exit(1);
2641 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002642 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002643 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002644 e->start, e->length,
2645 e->has_offset ? e->offset : 0,
2646 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002647 }
2648 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2649 * Modify the flags here to allow more coalescing.
2650 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002651 if (next && (!next->data || next->zero)) {
2652 next->data = false;
2653 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002654 }
2655 break;
2656 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002657 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2658 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002659 (e->start == 0 ? "[" : ",\n"),
2660 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002661 e->zero ? "true" : "false",
2662 e->data ? "true" : "false");
2663 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002664 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002665 }
2666 putchar('}');
2667
2668 if (!next) {
2669 printf("]\n");
2670 }
2671 break;
2672 }
2673}
2674
2675static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2676 int nb_sectors, MapEntry *e)
2677{
2678 int64_t ret;
2679 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002680 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002681 bool has_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002682
2683 /* As an optimization, we could cache the current range of unallocated
2684 * clusters in each file of the chain, and avoid querying the same
2685 * range repeatedly.
2686 */
2687
2688 depth = 0;
2689 for (;;) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08002690 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2691 &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002692 if (ret < 0) {
2693 return ret;
2694 }
2695 assert(nb_sectors);
2696 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2697 break;
2698 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002699 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002700 if (bs == NULL) {
2701 ret = 0;
2702 break;
2703 }
2704
2705 depth++;
2706 }
2707
John Snow28756452016-02-05 13:12:33 -05002708 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2709
2710 *e = (MapEntry) {
2711 .start = sector_num * BDRV_SECTOR_SIZE,
2712 .length = nb_sectors * BDRV_SECTOR_SIZE,
2713 .data = !!(ret & BDRV_BLOCK_DATA),
2714 .zero = !!(ret & BDRV_BLOCK_ZERO),
2715 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2716 .has_offset = has_offset,
2717 .depth = depth,
2718 .has_filename = file && has_offset,
2719 .filename = file && has_offset ? file->filename : NULL,
2720 };
2721
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002722 return 0;
2723}
2724
Fam Zheng16b0d552016-01-26 11:59:02 +08002725static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2726{
2727 if (curr->length == 0) {
2728 return false;
2729 }
2730 if (curr->zero != next->zero ||
2731 curr->data != next->data ||
2732 curr->depth != next->depth ||
2733 curr->has_filename != next->has_filename ||
2734 curr->has_offset != next->has_offset) {
2735 return false;
2736 }
2737 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2738 return false;
2739 }
2740 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2741 return false;
2742 }
2743 return true;
2744}
2745
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002746static int img_map(int argc, char **argv)
2747{
2748 int c;
2749 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002750 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002751 BlockDriverState *bs;
2752 const char *filename, *fmt, *output;
2753 int64_t length;
2754 MapEntry curr = { .length = 0 }, next;
2755 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002756 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002757 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002758
2759 fmt = NULL;
2760 output = NULL;
2761 for (;;) {
2762 int option_index = 0;
2763 static const struct option long_options[] = {
2764 {"help", no_argument, 0, 'h'},
2765 {"format", required_argument, 0, 'f'},
2766 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002767 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002768 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002769 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002770 {0, 0, 0, 0}
2771 };
Fam Zheng335e9932017-05-03 00:35:39 +08002772 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002773 long_options, &option_index);
2774 if (c == -1) {
2775 break;
2776 }
2777 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002778 case ':':
2779 missing_argument(argv[optind - 1]);
2780 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002781 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002782 unrecognized_option(argv[optind - 1]);
2783 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002784 case 'h':
2785 help();
2786 break;
2787 case 'f':
2788 fmt = optarg;
2789 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002790 case 'U':
2791 force_share = true;
2792 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002793 case OPTION_OUTPUT:
2794 output = optarg;
2795 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002796 case OPTION_OBJECT: {
2797 QemuOpts *opts;
2798 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2799 optarg, true);
2800 if (!opts) {
2801 return 1;
2802 }
2803 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002804 case OPTION_IMAGE_OPTS:
2805 image_opts = true;
2806 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002807 }
2808 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002809 if (optind != argc - 1) {
2810 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002811 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002812 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002813
2814 if (output && !strcmp(output, "json")) {
2815 output_format = OFORMAT_JSON;
2816 } else if (output && !strcmp(output, "human")) {
2817 output_format = OFORMAT_HUMAN;
2818 } else if (output) {
2819 error_report("--output must be used with human or json as argument.");
2820 return 1;
2821 }
2822
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002823 if (qemu_opts_foreach(&qemu_object_opts,
2824 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002825 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002826 return 1;
2827 }
2828
Fam Zheng335e9932017-05-03 00:35:39 +08002829 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002830 if (!blk) {
2831 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002832 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002833 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002834
2835 if (output_format == OFORMAT_HUMAN) {
2836 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2837 }
2838
Max Reitzf1d3cd72015-02-05 13:58:18 -05002839 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002840 while (curr.start + curr.length < length) {
2841 int64_t nsectors_left;
2842 int64_t sector_num;
2843 int n;
2844
2845 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2846
2847 /* Probe up to 1 GiB at a time. */
2848 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2849 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2850 ret = get_block_status(bs, sector_num, n, &next);
2851
2852 if (ret < 0) {
2853 error_report("Could not read file metadata: %s", strerror(-ret));
2854 goto out;
2855 }
2856
Fam Zheng16b0d552016-01-26 11:59:02 +08002857 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002858 curr.length += next.length;
2859 continue;
2860 }
2861
2862 if (curr.length > 0) {
2863 dump_map_entry(output_format, &curr, &next);
2864 }
2865 curr = next;
2866 }
2867
2868 dump_map_entry(output_format, &curr, NULL);
2869
2870out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002871 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002872 return ret < 0;
2873}
2874
aliguorif7b4a942009-01-07 17:40:15 +00002875#define SNAPSHOT_LIST 1
2876#define SNAPSHOT_CREATE 2
2877#define SNAPSHOT_APPLY 3
2878#define SNAPSHOT_DELETE 4
2879
Stuart Brady153859b2009-06-07 00:42:17 +01002880static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002881{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002882 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002883 BlockDriverState *bs;
2884 QEMUSnapshotInfo sn;
2885 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002886 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002887 int action = 0;
2888 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002889 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002890 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002891 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002892 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002893
Kevin Wolfce099542016-03-15 13:01:04 +01002894 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002895 /* Parse commandline parameters */
2896 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002897 static const struct option long_options[] = {
2898 {"help", no_argument, 0, 'h'},
2899 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002900 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002901 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002902 {0, 0, 0, 0}
2903 };
Fam Zheng335e9932017-05-03 00:35:39 +08002904 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002905 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002906 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002907 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002908 }
aliguorif7b4a942009-01-07 17:40:15 +00002909 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002910 case ':':
2911 missing_argument(argv[optind - 1]);
2912 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002913 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002914 unrecognized_option(argv[optind - 1]);
2915 break;
aliguorif7b4a942009-01-07 17:40:15 +00002916 case 'h':
2917 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002918 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002919 case 'l':
2920 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002921 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002922 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002923 }
2924 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002925 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002926 break;
2927 case 'a':
2928 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002929 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002930 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002931 }
2932 action = SNAPSHOT_APPLY;
2933 snapshot_name = optarg;
2934 break;
2935 case 'c':
2936 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002937 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002938 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002939 }
2940 action = SNAPSHOT_CREATE;
2941 snapshot_name = optarg;
2942 break;
2943 case 'd':
2944 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002945 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002946 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002947 }
2948 action = SNAPSHOT_DELETE;
2949 snapshot_name = optarg;
2950 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002951 case 'q':
2952 quiet = true;
2953 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002954 case 'U':
2955 force_share = true;
2956 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002957 case OPTION_OBJECT: {
2958 QemuOpts *opts;
2959 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2960 optarg, true);
2961 if (!opts) {
2962 return 1;
2963 }
2964 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002965 case OPTION_IMAGE_OPTS:
2966 image_opts = true;
2967 break;
aliguorif7b4a942009-01-07 17:40:15 +00002968 }
2969 }
2970
Kevin Wolffc11eb22013-08-05 10:53:04 +02002971 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002972 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002973 }
aliguorif7b4a942009-01-07 17:40:15 +00002974 filename = argv[optind++];
2975
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002976 if (qemu_opts_foreach(&qemu_object_opts,
2977 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002978 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002979 return 1;
2980 }
2981
aliguorif7b4a942009-01-07 17:40:15 +00002982 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08002983 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2984 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002985 if (!blk) {
2986 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002987 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002988 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002989
2990 /* Perform the requested action */
2991 switch(action) {
2992 case SNAPSHOT_LIST:
2993 dump_snapshots(bs);
2994 break;
2995
2996 case SNAPSHOT_CREATE:
2997 memset(&sn, 0, sizeof(sn));
2998 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2999
3000 qemu_gettimeofday(&tv);
3001 sn.date_sec = tv.tv_sec;
3002 sn.date_nsec = tv.tv_usec * 1000;
3003
3004 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003005 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003006 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003007 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003008 }
aliguorif7b4a942009-01-07 17:40:15 +00003009 break;
3010
3011 case SNAPSHOT_APPLY:
3012 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003013 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003014 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003015 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003016 }
aliguorif7b4a942009-01-07 17:40:15 +00003017 break;
3018
3019 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003020 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003021 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003022 error_reportf_err(err, "Could not delete snapshot '%s': ",
3023 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003024 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003025 }
aliguorif7b4a942009-01-07 17:40:15 +00003026 break;
3027 }
3028
3029 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003030 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003031 if (ret) {
3032 return 1;
3033 }
Stuart Brady153859b2009-06-07 00:42:17 +01003034 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003035}
3036
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003037static int img_rebase(int argc, char **argv)
3038{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003039 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003040 uint8_t *buf_old = NULL;
3041 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003042 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003043 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003044 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3045 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003046 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003047 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003048 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003049 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003050 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003051 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003052 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003053
3054 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003055 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003056 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003057 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003058 out_baseimg = NULL;
3059 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003060 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003061 static const struct option long_options[] = {
3062 {"help", no_argument, 0, 'h'},
3063 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003064 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003065 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003066 {0, 0, 0, 0}
3067 };
Fam Zheng335e9932017-05-03 00:35:39 +08003068 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003069 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003070 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003071 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003072 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003073 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003074 case ':':
3075 missing_argument(argv[optind - 1]);
3076 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003077 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003078 unrecognized_option(argv[optind - 1]);
3079 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003080 case 'h':
3081 help();
3082 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003083 case 'f':
3084 fmt = optarg;
3085 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003086 case 'F':
3087 out_basefmt = optarg;
3088 break;
3089 case 'b':
3090 out_baseimg = optarg;
3091 break;
3092 case 'u':
3093 unsafe = 1;
3094 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003095 case 'p':
3096 progress = 1;
3097 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003098 case 't':
3099 cache = optarg;
3100 break;
Max Reitz40055952014-07-22 22:58:42 +02003101 case 'T':
3102 src_cache = optarg;
3103 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003104 case 'q':
3105 quiet = true;
3106 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003107 case OPTION_OBJECT: {
3108 QemuOpts *opts;
3109 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3110 optarg, true);
3111 if (!opts) {
3112 return 1;
3113 }
3114 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003115 case OPTION_IMAGE_OPTS:
3116 image_opts = true;
3117 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003118 case 'U':
3119 force_share = true;
3120 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003121 }
3122 }
3123
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003124 if (quiet) {
3125 progress = 0;
3126 }
3127
Fam Zhengac1307a2014-04-22 13:36:11 +08003128 if (optind != argc - 1) {
3129 error_exit("Expecting one image file name");
3130 }
3131 if (!unsafe && !out_baseimg) {
3132 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003133 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003134 filename = argv[optind++];
3135
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003136 if (qemu_opts_foreach(&qemu_object_opts,
3137 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003138 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003139 return 1;
3140 }
3141
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003142 qemu_progress_init(progress, 2.0);
3143 qemu_progress_print(0, 100);
3144
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003145 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003146 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003147 if (ret < 0) {
3148 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003149 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003150 }
3151
Kevin Wolfce099542016-03-15 13:01:04 +01003152 src_flags = 0;
3153 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003154 if (ret < 0) {
3155 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003156 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003157 }
3158
Kevin Wolfce099542016-03-15 13:01:04 +01003159 /* The source files are opened read-only, don't care about WCE */
3160 assert((src_flags & BDRV_O_RDWR) == 0);
3161 (void) src_writethrough;
3162
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003163 /*
3164 * Open the images.
3165 *
3166 * Ignore the old backing file for unsafe rebase in case we want to correct
3167 * the reference to a renamed or moved backing file.
3168 */
Fam Zheng335e9932017-05-03 00:35:39 +08003169 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3170 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003171 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003172 ret = -1;
3173 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003174 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003175 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003176
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003177 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003178 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003179 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003180 ret = -1;
3181 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003182 }
3183 }
3184
3185 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003186 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003187 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003188 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003189
Max Reitz644483d2015-02-05 13:58:17 -05003190 if (bs->backing_format[0] != '\0') {
3191 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003192 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003193 }
3194
Fam Zheng335e9932017-05-03 00:35:39 +08003195 if (force_share) {
3196 if (!options) {
3197 options = qdict_new();
3198 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003199 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003200 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003201 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003202 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003203 options, src_flags, &local_err);
3204 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003205 error_reportf_err(local_err,
3206 "Could not open old backing file '%s': ",
3207 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003208 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003209 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003210 }
Max Reitz644483d2015-02-05 13:58:17 -05003211
Alex Bligha6166732012-10-16 13:46:18 +01003212 if (out_baseimg[0]) {
Fam Zheng335e9932017-05-03 00:35:39 +08003213 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003214 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003215 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003216 }
3217 if (force_share) {
3218 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003219 }
3220
Max Reitzefaa7c42016-03-16 19:54:38 +01003221 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003222 options, src_flags, &local_err);
3223 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003224 error_reportf_err(local_err,
3225 "Could not open new backing file '%s': ",
3226 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003227 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003228 goto out;
3229 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003230 }
3231 }
3232
3233 /*
3234 * Check each unallocated cluster in the COW file. If it is unallocated,
3235 * accesses go to the backing file. We must therefore compare this cluster
3236 * in the old and new backing file, and if they differ we need to copy it
3237 * from the old backing file into the COW file.
3238 *
3239 * If qemu-img crashes during this step, no harm is done. The content of
3240 * the image is the same as the original one at any time.
3241 */
3242 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003243 int64_t num_sectors;
3244 int64_t old_backing_num_sectors;
3245 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003246 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003247 int n;
Eric Blaked6a644b2017-07-07 07:44:57 -05003248 int64_t count;
Kevin Wolf1f710492012-10-12 14:29:18 +02003249 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003250
Max Reitzf1d3cd72015-02-05 13:58:18 -05003251 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3252 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003253
Max Reitzf1d3cd72015-02-05 13:58:18 -05003254 num_sectors = blk_nb_sectors(blk);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003255 if (num_sectors < 0) {
3256 error_report("Could not get size of '%s': %s",
3257 filename, strerror(-num_sectors));
3258 ret = -1;
3259 goto out;
3260 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003261 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003262 if (old_backing_num_sectors < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003263 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003264
3265 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3266 error_report("Could not get size of '%s': %s",
3267 backing_name, strerror(-old_backing_num_sectors));
3268 ret = -1;
3269 goto out;
3270 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003271 if (blk_new_backing) {
3272 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003273 if (new_backing_num_sectors < 0) {
3274 error_report("Could not get size of '%s': %s",
3275 out_baseimg, strerror(-new_backing_num_sectors));
3276 ret = -1;
3277 goto out;
3278 }
Alex Bligha6166732012-10-16 13:46:18 +01003279 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003280
Kevin Wolf1f710492012-10-12 14:29:18 +02003281 if (num_sectors != 0) {
3282 local_progress = (float)100 /
3283 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3284 }
3285
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003286 for (sector = 0; sector < num_sectors; sector += n) {
3287
3288 /* How many sectors can we handle with the next read? */
3289 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3290 n = (IO_BUF_SIZE / 512);
3291 } else {
3292 n = num_sectors - sector;
3293 }
3294
3295 /* If the cluster is allocated, we don't need to take action */
Eric Blaked6a644b2017-07-07 07:44:57 -05003296 ret = bdrv_is_allocated(bs, sector << BDRV_SECTOR_BITS,
3297 n << BDRV_SECTOR_BITS, &count);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003298 if (ret < 0) {
3299 error_report("error while reading image metadata: %s",
3300 strerror(-ret));
3301 goto out;
3302 }
Eric Blaked6a644b2017-07-07 07:44:57 -05003303 /* TODO relax this once bdrv_is_allocated does not enforce
3304 * sector alignment */
3305 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
3306 n = count >> BDRV_SECTOR_BITS;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003307 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003308 continue;
3309 }
3310
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003311 /*
3312 * Read old and new backing file and take into consideration that
3313 * backing files may be smaller than the COW image.
3314 */
3315 if (sector >= old_backing_num_sectors) {
3316 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3317 } else {
3318 if (sector + n > old_backing_num_sectors) {
3319 n = old_backing_num_sectors - sector;
3320 }
3321
Eric Blake91669202016-05-06 10:26:43 -06003322 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3323 buf_old, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003324 if (ret < 0) {
3325 error_report("error while reading from old backing file");
3326 goto out;
3327 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003328 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003329
Max Reitzf1d3cd72015-02-05 13:58:18 -05003330 if (sector >= new_backing_num_sectors || !blk_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003331 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3332 } else {
3333 if (sector + n > new_backing_num_sectors) {
3334 n = new_backing_num_sectors - sector;
3335 }
3336
Eric Blake91669202016-05-06 10:26:43 -06003337 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3338 buf_new, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003339 if (ret < 0) {
3340 error_report("error while reading from new backing file");
3341 goto out;
3342 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003343 }
3344
3345 /* If they differ, we need to write to the COW file */
3346 uint64_t written = 0;
3347
3348 while (written < n) {
3349 int pnum;
3350
3351 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01003352 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003353 {
Eric Blake91669202016-05-06 10:26:43 -06003354 ret = blk_pwrite(blk,
3355 (sector + written) << BDRV_SECTOR_BITS,
3356 buf_old + written * 512,
3357 pnum << BDRV_SECTOR_BITS, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003358 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003359 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003360 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003361 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003362 }
3363 }
3364
3365 written += pnum;
3366 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003367 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003368 }
3369 }
3370
3371 /*
3372 * Change the backing file. All clusters that are different from the old
3373 * backing file are overwritten in the COW file now, so the visible content
3374 * doesn't change when we switch the backing file.
3375 */
Alex Bligha6166732012-10-16 13:46:18 +01003376 if (out_baseimg && *out_baseimg) {
3377 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3378 } else {
3379 ret = bdrv_change_backing_file(bs, NULL, NULL);
3380 }
3381
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003382 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003383 error_report("Could not change the backing file to '%s': No "
3384 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003385 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003386 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003387 out_baseimg, strerror(-ret));
3388 }
3389
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003390 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003391 /*
3392 * TODO At this point it is possible to check if any clusters that are
3393 * allocated in the COW file are the same in the backing file. If so, they
3394 * could be dropped from the COW file. Don't do this before switching the
3395 * backing file, in case of a crash this would lead to corruption.
3396 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003397out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003398 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003399 /* Cleanup */
3400 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003401 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003402 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003403 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003404 qemu_vfree(buf_old);
3405 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003406
Markus Armbruster26f54e92014-10-07 13:59:04 +02003407 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003408 if (ret) {
3409 return 1;
3410 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003411 return 0;
3412}
3413
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003414static int img_resize(int argc, char **argv)
3415{
Markus Armbruster6750e792015-02-12 17:43:08 +01003416 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003417 int c, ret, relative;
3418 const char *filename, *fmt, *size;
Max Reitzdc5f6902017-06-13 22:20:55 +02003419 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003420 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003421 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003422 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003423 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003424
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003425 static QemuOptsList resize_options = {
3426 .name = "resize_options",
3427 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3428 .desc = {
3429 {
3430 .name = BLOCK_OPT_SIZE,
3431 .type = QEMU_OPT_SIZE,
3432 .help = "Virtual disk size"
3433 }, {
3434 /* end of list */
3435 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003436 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003437 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003438 bool image_opts = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003439
Kevin Wolfe80fec72011-04-29 10:58:12 +02003440 /* Remove size from argv manually so that negative numbers are not treated
3441 * as options by getopt. */
3442 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003443 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003444 return 1;
3445 }
3446
3447 size = argv[--argc];
3448
3449 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003450 fmt = NULL;
3451 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003452 static const struct option long_options[] = {
3453 {"help", no_argument, 0, 'h'},
3454 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003455 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003456 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003457 {0, 0, 0, 0}
3458 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003459 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003460 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003461 if (c == -1) {
3462 break;
3463 }
3464 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003465 case ':':
3466 missing_argument(argv[optind - 1]);
3467 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003468 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003469 unrecognized_option(argv[optind - 1]);
3470 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003471 case 'h':
3472 help();
3473 break;
3474 case 'f':
3475 fmt = optarg;
3476 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003477 case 'q':
3478 quiet = true;
3479 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003480 case OPTION_OBJECT: {
3481 QemuOpts *opts;
3482 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3483 optarg, true);
3484 if (!opts) {
3485 return 1;
3486 }
3487 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003488 case OPTION_IMAGE_OPTS:
3489 image_opts = true;
3490 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003491 case OPTION_PREALLOCATION:
3492 prealloc = qapi_enum_parse(PreallocMode_lookup, optarg,
3493 PREALLOC_MODE__MAX, PREALLOC_MODE__MAX,
3494 NULL);
3495 if (prealloc == PREALLOC_MODE__MAX) {
3496 error_report("Invalid preallocation mode '%s'", optarg);
3497 return 1;
3498 }
3499 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003500 }
3501 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003502 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003503 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003504 }
3505 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003506
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003507 if (qemu_opts_foreach(&qemu_object_opts,
3508 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003509 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003510 return 1;
3511 }
3512
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003513 /* Choose grow, shrink, or absolute resize mode */
3514 switch (size[0]) {
3515 case '+':
3516 relative = 1;
3517 size++;
3518 break;
3519 case '-':
3520 relative = -1;
3521 size++;
3522 break;
3523 default:
3524 relative = 0;
3525 break;
3526 }
3527
3528 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003529 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003530 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003531 if (err) {
3532 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003533 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003534 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003535 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003536 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003537 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3538 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003539
Max Reitzefaa7c42016-03-16 19:54:38 +01003540 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003541 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3542 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003543 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003544 ret = -1;
3545 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003546 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003547
Max Reitzdc5f6902017-06-13 22:20:55 +02003548 current_size = blk_getlength(blk);
3549 if (current_size < 0) {
3550 error_report("Failed to inquire current image length: %s",
3551 strerror(-current_size));
3552 ret = -1;
3553 goto out;
3554 }
3555
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003556 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003557 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003558 } else {
3559 total_size = n;
3560 }
3561 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003562 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003563 ret = -1;
3564 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003565 }
3566
Max Reitzdc5f6902017-06-13 22:20:55 +02003567 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3568 error_report("Preallocation can only be used for growing images");
3569 ret = -1;
3570 goto out;
3571 }
3572
3573 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitzed3d2ec2017-03-28 22:51:27 +02003574 if (!ret) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003575 qprintf(quiet, "Image resized.\n");
Max Reitzed3d2ec2017-03-28 22:51:27 +02003576 } else {
3577 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003578 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003579out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003580 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003581 if (ret) {
3582 return 1;
3583 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003584 return 0;
3585}
3586
Max Reitz76a3a342014-10-27 11:12:51 +01003587static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003588 int64_t offset, int64_t total_work_size,
3589 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003590{
3591 qemu_progress_print(100.f * offset / total_work_size, 0);
3592}
3593
Max Reitz6f176b42013-09-03 10:09:50 +02003594static int img_amend(int argc, char **argv)
3595{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003596 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003597 int c, ret = 0;
3598 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003599 QemuOptsList *create_opts = NULL;
3600 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003601 const char *fmt = NULL, *filename, *cache;
3602 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003603 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003604 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003605 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003606 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003607 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003608
Max Reitzbd39e6e2014-07-22 22:58:43 +02003609 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003610 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003611 static const struct option long_options[] = {
3612 {"help", no_argument, 0, 'h'},
3613 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003614 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003615 {0, 0, 0, 0}
3616 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003617 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003618 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003619 if (c == -1) {
3620 break;
3621 }
3622
3623 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003624 case ':':
3625 missing_argument(argv[optind - 1]);
3626 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003627 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003628 unrecognized_option(argv[optind - 1]);
3629 break;
3630 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003631 help();
3632 break;
3633 case 'o':
3634 if (!is_valid_option_list(optarg)) {
3635 error_report("Invalid option list: %s", optarg);
3636 ret = -1;
3637 goto out_no_progress;
3638 }
3639 if (!options) {
3640 options = g_strdup(optarg);
3641 } else {
3642 char *old_options = options;
3643 options = g_strdup_printf("%s,%s", options, optarg);
3644 g_free(old_options);
3645 }
3646 break;
3647 case 'f':
3648 fmt = optarg;
3649 break;
3650 case 't':
3651 cache = optarg;
3652 break;
3653 case 'p':
3654 progress = true;
3655 break;
3656 case 'q':
3657 quiet = true;
3658 break;
3659 case OPTION_OBJECT:
3660 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3661 optarg, true);
3662 if (!opts) {
3663 ret = -1;
3664 goto out_no_progress;
3665 }
3666 break;
3667 case OPTION_IMAGE_OPTS:
3668 image_opts = true;
3669 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003670 }
3671 }
3672
Max Reitz6f176b42013-09-03 10:09:50 +02003673 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003674 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003675 }
3676
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003677 if (qemu_opts_foreach(&qemu_object_opts,
3678 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003679 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003680 ret = -1;
3681 goto out_no_progress;
3682 }
3683
Max Reitz76a3a342014-10-27 11:12:51 +01003684 if (quiet) {
3685 progress = false;
3686 }
3687 qemu_progress_init(progress, 1.0);
3688
Kevin Wolfa283cb62014-02-21 16:24:07 +01003689 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3690 if (fmt && has_help_option(options)) {
3691 /* If a format is explicitly specified (and possibly no filename is
3692 * given), print option help here */
3693 ret = print_block_option_help(filename, fmt);
3694 goto out;
3695 }
3696
3697 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003698 error_report("Expecting one image file name");
3699 ret = -1;
3700 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003701 }
Max Reitz6f176b42013-09-03 10:09:50 +02003702
Kevin Wolfce099542016-03-15 13:01:04 +01003703 flags = BDRV_O_RDWR;
3704 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003705 if (ret < 0) {
3706 error_report("Invalid cache option: %s", cache);
3707 goto out;
3708 }
3709
Fam Zheng335e9932017-05-03 00:35:39 +08003710 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3711 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003712 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003713 ret = -1;
3714 goto out;
3715 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003716 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003717
3718 fmt = bs->drv->format_name;
3719
Kevin Wolf626f84f2014-02-21 16:24:06 +01003720 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003721 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003722 ret = print_block_option_help(filename, fmt);
3723 goto out;
3724 }
3725
Max Reitzb2439d22014-12-02 18:32:47 +01003726 if (!bs->drv->create_opts) {
3727 error_report("Format driver '%s' does not support any options to amend",
3728 fmt);
3729 ret = -1;
3730 goto out;
3731 }
3732
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003733 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003734 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003735 qemu_opts_do_parse(opts, options, NULL, &err);
3736 if (err) {
3737 error_report_err(err);
3738 ret = -1;
3739 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003740 }
3741
Max Reitz76a3a342014-10-27 11:12:51 +01003742 /* In case the driver does not call amend_status_cb() */
3743 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003744 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003745 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003746 if (ret < 0) {
3747 error_report("Error while amending options: %s", strerror(-ret));
3748 goto out;
3749 }
3750
3751out:
Max Reitz76a3a342014-10-27 11:12:51 +01003752 qemu_progress_end();
3753
Max Reitze814dff2015-08-20 16:00:38 -07003754out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003755 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003756 qemu_opts_del(opts);
3757 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003758 g_free(options);
3759
Max Reitz6f176b42013-09-03 10:09:50 +02003760 if (ret) {
3761 return 1;
3762 }
3763 return 0;
3764}
3765
Kevin Wolfb6133b82014-08-05 14:17:13 +02003766typedef struct BenchData {
3767 BlockBackend *blk;
3768 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003769 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003770 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003771 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003772 int nrreq;
3773 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003774 int flush_interval;
3775 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003776 uint8_t *buf;
3777 QEMUIOVector *qiov;
3778
3779 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003780 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003781 uint64_t offset;
3782} BenchData;
3783
Kevin Wolf55d539c2016-06-03 13:59:41 +02003784static void bench_undrained_flush_cb(void *opaque, int ret)
3785{
3786 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003787 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003788 exit(EXIT_FAILURE);
3789 }
3790}
3791
Kevin Wolfb6133b82014-08-05 14:17:13 +02003792static void bench_cb(void *opaque, int ret)
3793{
3794 BenchData *b = opaque;
3795 BlockAIOCB *acb;
3796
3797 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003798 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003799 exit(EXIT_FAILURE);
3800 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003801
3802 if (b->in_flush) {
3803 /* Just finished a flush with drained queue: Start next requests */
3804 assert(b->in_flight == 0);
3805 b->in_flush = false;
3806 } else if (b->in_flight > 0) {
3807 int remaining = b->n - b->in_flight;
3808
Kevin Wolfb6133b82014-08-05 14:17:13 +02003809 b->n--;
3810 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003811
3812 /* Time for flush? Drain queue if requested, then flush */
3813 if (b->flush_interval && remaining % b->flush_interval == 0) {
3814 if (!b->in_flight || !b->drain_on_flush) {
3815 BlockCompletionFunc *cb;
3816
3817 if (b->drain_on_flush) {
3818 b->in_flush = true;
3819 cb = bench_cb;
3820 } else {
3821 cb = bench_undrained_flush_cb;
3822 }
3823
3824 acb = blk_aio_flush(b->blk, cb, b);
3825 if (!acb) {
3826 error_report("Failed to issue flush request");
3827 exit(EXIT_FAILURE);
3828 }
3829 }
3830 if (b->drain_on_flush) {
3831 return;
3832 }
3833 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003834 }
3835
3836 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003837 int64_t offset = b->offset;
3838 /* blk_aio_* might look for completed I/Os and kick bench_cb
3839 * again, so make sure this operation is counted by in_flight
3840 * and b->offset is ready for the next submission.
3841 */
3842 b->in_flight++;
3843 b->offset += b->step;
3844 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003845 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003846 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003847 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003848 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003849 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003850 if (!acb) {
3851 error_report("Failed to issue request");
3852 exit(EXIT_FAILURE);
3853 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003854 }
3855}
3856
3857static int img_bench(int argc, char **argv)
3858{
3859 int c, ret = 0;
3860 const char *fmt = NULL, *filename;
3861 bool quiet = false;
3862 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003863 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003864 int count = 75000;
3865 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003866 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003867 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003868 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003869 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003870 int flush_interval = 0;
3871 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003872 int64_t image_size;
3873 BlockBackend *blk = NULL;
3874 BenchData data = {};
3875 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003876 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003877 struct timeval t1, t2;
3878 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08003879 bool force_share = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003880
3881 for (;;) {
3882 static const struct option long_options[] = {
3883 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003884 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003885 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003886 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003887 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08003888 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003889 {0, 0, 0, 0}
3890 };
Fam Zheng335e9932017-05-03 00:35:39 +08003891 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003892 if (c == -1) {
3893 break;
3894 }
3895
3896 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003897 case ':':
3898 missing_argument(argv[optind - 1]);
3899 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003900 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003901 unrecognized_option(argv[optind - 1]);
3902 break;
3903 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02003904 help();
3905 break;
3906 case 'c':
3907 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003908 unsigned long res;
3909
3910 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003911 error_report("Invalid request count specified");
3912 return 1;
3913 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003914 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003915 break;
3916 }
3917 case 'd':
3918 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003919 unsigned long res;
3920
3921 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003922 error_report("Invalid queue depth specified");
3923 return 1;
3924 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003925 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003926 break;
3927 }
3928 case 'f':
3929 fmt = optarg;
3930 break;
3931 case 'n':
3932 flags |= BDRV_O_NATIVE_AIO;
3933 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003934 case 'o':
3935 {
Markus Armbruster606caa02017-02-21 21:14:04 +01003936 offset = cvtnum(optarg);
3937 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02003938 error_report("Invalid offset specified");
3939 return 1;
3940 }
3941 break;
3942 }
3943 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003944 case 'q':
3945 quiet = true;
3946 break;
3947 case 's':
3948 {
3949 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003950
Markus Armbruster606caa02017-02-21 21:14:04 +01003951 sval = cvtnum(optarg);
3952 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003953 error_report("Invalid buffer size specified");
3954 return 1;
3955 }
3956
3957 bufsize = sval;
3958 break;
3959 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003960 case 'S':
3961 {
3962 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003963
Markus Armbruster606caa02017-02-21 21:14:04 +01003964 sval = cvtnum(optarg);
3965 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02003966 error_report("Invalid step size specified");
3967 return 1;
3968 }
3969
3970 step = sval;
3971 break;
3972 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003973 case 't':
3974 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3975 if (ret < 0) {
3976 error_report("Invalid cache mode");
3977 ret = -1;
3978 goto out;
3979 }
3980 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003981 case 'w':
3982 flags |= BDRV_O_RDWR;
3983 is_write = true;
3984 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003985 case 'U':
3986 force_share = true;
3987 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003988 case OPTION_PATTERN:
3989 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003990 unsigned long res;
3991
3992 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003993 error_report("Invalid pattern byte specified");
3994 return 1;
3995 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003996 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003997 break;
3998 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003999 case OPTION_FLUSH_INTERVAL:
4000 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004001 unsigned long res;
4002
4003 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004004 error_report("Invalid flush interval specified");
4005 return 1;
4006 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004007 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004008 break;
4009 }
4010 case OPTION_NO_DRAIN:
4011 drain_on_flush = false;
4012 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004013 case OPTION_IMAGE_OPTS:
4014 image_opts = true;
4015 break;
4016 }
4017 }
4018
4019 if (optind != argc - 1) {
4020 error_exit("Expecting one image file name");
4021 }
4022 filename = argv[argc - 1];
4023
Kevin Wolf55d539c2016-06-03 13:59:41 +02004024 if (!is_write && flush_interval) {
4025 error_report("--flush-interval is only available in write tests");
4026 ret = -1;
4027 goto out;
4028 }
4029 if (flush_interval && flush_interval < depth) {
4030 error_report("Flush interval can't be smaller than depth");
4031 ret = -1;
4032 goto out;
4033 }
4034
Fam Zheng335e9932017-05-03 00:35:39 +08004035 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4036 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004037 if (!blk) {
4038 ret = -1;
4039 goto out;
4040 }
4041
4042 image_size = blk_getlength(blk);
4043 if (image_size < 0) {
4044 ret = image_size;
4045 goto out;
4046 }
4047
4048 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004049 .blk = blk,
4050 .image_size = image_size,
4051 .bufsize = bufsize,
4052 .step = step ?: bufsize,
4053 .nrreq = depth,
4054 .n = count,
4055 .offset = offset,
4056 .write = is_write,
4057 .flush_interval = flush_interval,
4058 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004059 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004060 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004061 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004062 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004063 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004064 if (flush_interval) {
4065 printf("Sending flush every %d requests\n", flush_interval);
4066 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004067
4068 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004069 memset(data.buf, pattern, data.nrreq * data.bufsize);
4070
Kevin Wolfb6133b82014-08-05 14:17:13 +02004071 data.qiov = g_new(QEMUIOVector, data.nrreq);
4072 for (i = 0; i < data.nrreq; i++) {
4073 qemu_iovec_init(&data.qiov[i], 1);
4074 qemu_iovec_add(&data.qiov[i],
4075 data.buf + i * data.bufsize, data.bufsize);
4076 }
4077
4078 gettimeofday(&t1, NULL);
4079 bench_cb(&data, 0);
4080
4081 while (data.n > 0) {
4082 main_loop_wait(false);
4083 }
4084 gettimeofday(&t2, NULL);
4085
4086 printf("Run completed in %3.3f seconds.\n",
4087 (t2.tv_sec - t1.tv_sec)
4088 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4089
4090out:
4091 qemu_vfree(data.buf);
4092 blk_unref(blk);
4093
4094 if (ret) {
4095 return 1;
4096 }
4097 return 0;
4098}
4099
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004100#define C_BS 01
4101#define C_COUNT 02
4102#define C_IF 04
4103#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004104#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004105
4106struct DdInfo {
4107 unsigned int flags;
4108 int64_t count;
4109};
4110
4111struct DdIo {
4112 int bsz; /* Block size */
4113 char *filename;
4114 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004115 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004116};
4117
4118struct DdOpts {
4119 const char *name;
4120 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4121 unsigned int flag;
4122};
4123
4124static int img_dd_bs(const char *arg,
4125 struct DdIo *in, struct DdIo *out,
4126 struct DdInfo *dd)
4127{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004128 int64_t res;
4129
Markus Armbruster606caa02017-02-21 21:14:04 +01004130 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004131
Markus Armbruster606caa02017-02-21 21:14:04 +01004132 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004133 error_report("invalid number: '%s'", arg);
4134 return 1;
4135 }
4136 in->bsz = out->bsz = res;
4137
4138 return 0;
4139}
4140
4141static int img_dd_count(const char *arg,
4142 struct DdIo *in, struct DdIo *out,
4143 struct DdInfo *dd)
4144{
Markus Armbruster606caa02017-02-21 21:14:04 +01004145 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004146
Markus Armbruster606caa02017-02-21 21:14:04 +01004147 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004148 error_report("invalid number: '%s'", arg);
4149 return 1;
4150 }
4151
4152 return 0;
4153}
4154
4155static int img_dd_if(const char *arg,
4156 struct DdIo *in, struct DdIo *out,
4157 struct DdInfo *dd)
4158{
4159 in->filename = g_strdup(arg);
4160
4161 return 0;
4162}
4163
4164static int img_dd_of(const char *arg,
4165 struct DdIo *in, struct DdIo *out,
4166 struct DdInfo *dd)
4167{
4168 out->filename = g_strdup(arg);
4169
4170 return 0;
4171}
4172
Reda Sallahif7c15532016-08-10 16:16:09 +02004173static int img_dd_skip(const char *arg,
4174 struct DdIo *in, struct DdIo *out,
4175 struct DdInfo *dd)
4176{
Markus Armbruster606caa02017-02-21 21:14:04 +01004177 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004178
Markus Armbruster606caa02017-02-21 21:14:04 +01004179 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004180 error_report("invalid number: '%s'", arg);
4181 return 1;
4182 }
4183
4184 return 0;
4185}
4186
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004187static int img_dd(int argc, char **argv)
4188{
4189 int ret = 0;
4190 char *arg = NULL;
4191 char *tmp;
4192 BlockDriver *drv = NULL, *proto_drv = NULL;
4193 BlockBackend *blk1 = NULL, *blk2 = NULL;
4194 QemuOpts *opts = NULL;
4195 QemuOptsList *create_opts = NULL;
4196 Error *local_err = NULL;
4197 bool image_opts = false;
4198 int c, i;
4199 const char *out_fmt = "raw";
4200 const char *fmt = NULL;
4201 int64_t size = 0;
4202 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004203 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004204 struct DdInfo dd = {
4205 .flags = 0,
4206 .count = 0,
4207 };
4208 struct DdIo in = {
4209 .bsz = 512, /* Block size is by default 512 bytes */
4210 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004211 .buf = NULL,
4212 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004213 };
4214 struct DdIo out = {
4215 .bsz = 512,
4216 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004217 .buf = NULL,
4218 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004219 };
4220
4221 const struct DdOpts options[] = {
4222 { "bs", img_dd_bs, C_BS },
4223 { "count", img_dd_count, C_COUNT },
4224 { "if", img_dd_if, C_IF },
4225 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004226 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004227 { NULL, NULL, 0 }
4228 };
4229 const struct option long_options[] = {
4230 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004231 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004232 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004233 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004234 { 0, 0, 0, 0 }
4235 };
4236
Fam Zheng335e9932017-05-03 00:35:39 +08004237 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004238 if (c == EOF) {
4239 break;
4240 }
4241 switch (c) {
4242 case 'O':
4243 out_fmt = optarg;
4244 break;
4245 case 'f':
4246 fmt = optarg;
4247 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004248 case ':':
4249 missing_argument(argv[optind - 1]);
4250 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004251 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004252 unrecognized_option(argv[optind - 1]);
4253 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004254 case 'h':
4255 help();
4256 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004257 case 'U':
4258 force_share = true;
4259 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004260 case OPTION_OBJECT:
4261 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004262 ret = -1;
4263 goto out;
4264 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004265 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004266 case OPTION_IMAGE_OPTS:
4267 image_opts = true;
4268 break;
4269 }
4270 }
4271
4272 for (i = optind; i < argc; i++) {
4273 int j;
4274 arg = g_strdup(argv[i]);
4275
4276 tmp = strchr(arg, '=');
4277 if (tmp == NULL) {
4278 error_report("unrecognized operand %s", arg);
4279 ret = -1;
4280 goto out;
4281 }
4282
4283 *tmp++ = '\0';
4284
4285 for (j = 0; options[j].name != NULL; j++) {
4286 if (!strcmp(arg, options[j].name)) {
4287 break;
4288 }
4289 }
4290 if (options[j].name == NULL) {
4291 error_report("unrecognized operand %s", arg);
4292 ret = -1;
4293 goto out;
4294 }
4295
4296 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4297 ret = -1;
4298 goto out;
4299 }
4300 dd.flags |= options[j].flag;
4301 g_free(arg);
4302 arg = NULL;
4303 }
4304
4305 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4306 error_report("Must specify both input and output files");
4307 ret = -1;
4308 goto out;
4309 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004310
4311 if (qemu_opts_foreach(&qemu_object_opts,
4312 user_creatable_add_opts_foreach,
4313 NULL, NULL)) {
4314 ret = -1;
4315 goto out;
4316 }
4317
Fam Zheng335e9932017-05-03 00:35:39 +08004318 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4319 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004320
4321 if (!blk1) {
4322 ret = -1;
4323 goto out;
4324 }
4325
4326 drv = bdrv_find_format(out_fmt);
4327 if (!drv) {
4328 error_report("Unknown file format");
4329 ret = -1;
4330 goto out;
4331 }
4332 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4333
4334 if (!proto_drv) {
4335 error_report_err(local_err);
4336 ret = -1;
4337 goto out;
4338 }
4339 if (!drv->create_opts) {
4340 error_report("Format driver '%s' does not support image creation",
4341 drv->format_name);
4342 ret = -1;
4343 goto out;
4344 }
4345 if (!proto_drv->create_opts) {
4346 error_report("Protocol driver '%s' does not support image creation",
4347 proto_drv->format_name);
4348 ret = -1;
4349 goto out;
4350 }
4351 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4352 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4353
4354 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4355
4356 size = blk_getlength(blk1);
4357 if (size < 0) {
4358 error_report("Failed to get size for '%s'", in.filename);
4359 ret = -1;
4360 goto out;
4361 }
4362
4363 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4364 dd.count * in.bsz < size) {
4365 size = dd.count * in.bsz;
4366 }
4367
Reda Sallahif7c15532016-08-10 16:16:09 +02004368 /* Overflow means the specified offset is beyond input image's size */
4369 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4370 size < in.bsz * in.offset)) {
4371 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4372 } else {
4373 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4374 size - in.bsz * in.offset, &error_abort);
4375 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004376
4377 ret = bdrv_create(drv, out.filename, opts, &local_err);
4378 if (ret < 0) {
4379 error_reportf_err(local_err,
4380 "%s: error while creating output image: ",
4381 out.filename);
4382 ret = -1;
4383 goto out;
4384 }
4385
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004386 /* TODO, we can't honour --image-opts for the target,
4387 * since it needs to be given in a format compatible
4388 * with the bdrv_create() call above which does not
4389 * support image-opts style.
4390 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004391 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004392 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004393
4394 if (!blk2) {
4395 ret = -1;
4396 goto out;
4397 }
4398
Reda Sallahif7c15532016-08-10 16:16:09 +02004399 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4400 size < in.offset * in.bsz)) {
4401 /* We give a warning if the skip option is bigger than the input
4402 * size and create an empty output disk image (i.e. like dd(1)).
4403 */
4404 error_report("%s: cannot skip to specified offset", in.filename);
4405 in_pos = size;
4406 } else {
4407 in_pos = in.offset * in.bsz;
4408 }
4409
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004410 in.buf = g_new(uint8_t, in.bsz);
4411
Reda Sallahif7c15532016-08-10 16:16:09 +02004412 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004413 int in_ret, out_ret;
4414
4415 if (in_pos + in.bsz > size) {
4416 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4417 } else {
4418 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4419 }
4420 if (in_ret < 0) {
4421 error_report("error while reading from input image file: %s",
4422 strerror(-in_ret));
4423 ret = -1;
4424 goto out;
4425 }
4426 in_pos += in_ret;
4427
4428 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4429
4430 if (out_ret < 0) {
4431 error_report("error while writing to output image file: %s",
4432 strerror(-out_ret));
4433 ret = -1;
4434 goto out;
4435 }
4436 out_pos += out_ret;
4437 }
4438
4439out:
4440 g_free(arg);
4441 qemu_opts_del(opts);
4442 qemu_opts_free(create_opts);
4443 blk_unref(blk1);
4444 blk_unref(blk2);
4445 g_free(in.filename);
4446 g_free(out.filename);
4447 g_free(in.buf);
4448 g_free(out.buf);
4449
4450 if (ret) {
4451 return 1;
4452 }
4453 return 0;
4454}
4455
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004456static void dump_json_block_measure_info(BlockMeasureInfo *info)
4457{
4458 QString *str;
4459 QObject *obj;
4460 Visitor *v = qobject_output_visitor_new(&obj);
4461
4462 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4463 visit_complete(v, &obj);
4464 str = qobject_to_json_pretty(obj);
4465 assert(str != NULL);
4466 printf("%s\n", qstring_get_str(str));
4467 qobject_decref(obj);
4468 visit_free(v);
4469 QDECREF(str);
4470}
4471
4472static int img_measure(int argc, char **argv)
4473{
4474 static const struct option long_options[] = {
4475 {"help", no_argument, 0, 'h'},
4476 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4477 {"object", required_argument, 0, OPTION_OBJECT},
4478 {"output", required_argument, 0, OPTION_OUTPUT},
4479 {"size", required_argument, 0, OPTION_SIZE},
4480 {"force-share", no_argument, 0, 'U'},
4481 {0, 0, 0, 0}
4482 };
4483 OutputFormat output_format = OFORMAT_HUMAN;
4484 BlockBackend *in_blk = NULL;
4485 BlockDriver *drv;
4486 const char *filename = NULL;
4487 const char *fmt = NULL;
4488 const char *out_fmt = "raw";
4489 char *options = NULL;
4490 char *snapshot_name = NULL;
4491 bool force_share = false;
4492 QemuOpts *opts = NULL;
4493 QemuOpts *object_opts = NULL;
4494 QemuOpts *sn_opts = NULL;
4495 QemuOptsList *create_opts = NULL;
4496 bool image_opts = false;
4497 uint64_t img_size = UINT64_MAX;
4498 BlockMeasureInfo *info = NULL;
4499 Error *local_err = NULL;
4500 int ret = 1;
4501 int c;
4502
4503 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4504 long_options, NULL)) != -1) {
4505 switch (c) {
4506 case '?':
4507 case 'h':
4508 help();
4509 break;
4510 case 'f':
4511 fmt = optarg;
4512 break;
4513 case 'O':
4514 out_fmt = optarg;
4515 break;
4516 case 'o':
4517 if (!is_valid_option_list(optarg)) {
4518 error_report("Invalid option list: %s", optarg);
4519 goto out;
4520 }
4521 if (!options) {
4522 options = g_strdup(optarg);
4523 } else {
4524 char *old_options = options;
4525 options = g_strdup_printf("%s,%s", options, optarg);
4526 g_free(old_options);
4527 }
4528 break;
4529 case 'l':
4530 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4531 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4532 optarg, false);
4533 if (!sn_opts) {
4534 error_report("Failed in parsing snapshot param '%s'",
4535 optarg);
4536 goto out;
4537 }
4538 } else {
4539 snapshot_name = optarg;
4540 }
4541 break;
4542 case 'U':
4543 force_share = true;
4544 break;
4545 case OPTION_OBJECT:
4546 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4547 optarg, true);
4548 if (!object_opts) {
4549 goto out;
4550 }
4551 break;
4552 case OPTION_IMAGE_OPTS:
4553 image_opts = true;
4554 break;
4555 case OPTION_OUTPUT:
4556 if (!strcmp(optarg, "json")) {
4557 output_format = OFORMAT_JSON;
4558 } else if (!strcmp(optarg, "human")) {
4559 output_format = OFORMAT_HUMAN;
4560 } else {
4561 error_report("--output must be used with human or json "
4562 "as argument.");
4563 goto out;
4564 }
4565 break;
4566 case OPTION_SIZE:
4567 {
4568 int64_t sval;
4569
4570 sval = cvtnum(optarg);
4571 if (sval < 0) {
4572 if (sval == -ERANGE) {
4573 error_report("Image size must be less than 8 EiB!");
4574 } else {
4575 error_report("Invalid image size specified! You may use "
4576 "k, M, G, T, P or E suffixes for ");
4577 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4578 "petabytes and exabytes.");
4579 }
4580 goto out;
4581 }
4582 img_size = (uint64_t)sval;
4583 }
4584 break;
4585 }
4586 }
4587
4588 if (qemu_opts_foreach(&qemu_object_opts,
4589 user_creatable_add_opts_foreach,
4590 NULL, NULL)) {
4591 goto out;
4592 }
4593
4594 if (argc - optind > 1) {
4595 error_report("At most one filename argument is allowed.");
4596 goto out;
4597 } else if (argc - optind == 1) {
4598 filename = argv[optind];
4599 }
4600
4601 if (!filename &&
4602 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4603 error_report("--object, --image-opts, -f, and -l "
4604 "require a filename argument.");
4605 goto out;
4606 }
4607 if (filename && img_size != UINT64_MAX) {
4608 error_report("--size N cannot be used together with a filename.");
4609 goto out;
4610 }
4611 if (!filename && img_size == UINT64_MAX) {
4612 error_report("Either --size N or one filename must be specified.");
4613 goto out;
4614 }
4615
4616 if (filename) {
4617 in_blk = img_open(image_opts, filename, fmt, 0,
4618 false, false, force_share);
4619 if (!in_blk) {
4620 goto out;
4621 }
4622
4623 if (sn_opts) {
4624 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4625 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4626 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4627 &local_err);
4628 } else if (snapshot_name != NULL) {
4629 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4630 snapshot_name, &local_err);
4631 }
4632 if (local_err) {
4633 error_reportf_err(local_err, "Failed to load snapshot: ");
4634 goto out;
4635 }
4636 }
4637
4638 drv = bdrv_find_format(out_fmt);
4639 if (!drv) {
4640 error_report("Unknown file format '%s'", out_fmt);
4641 goto out;
4642 }
4643 if (!drv->create_opts) {
4644 error_report("Format driver '%s' does not support image creation",
4645 drv->format_name);
4646 goto out;
4647 }
4648
4649 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4650 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4651 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4652 if (options) {
4653 qemu_opts_do_parse(opts, options, NULL, &local_err);
4654 if (local_err) {
4655 error_report_err(local_err);
4656 error_report("Invalid options for file format '%s'", out_fmt);
4657 goto out;
4658 }
4659 }
4660 if (img_size != UINT64_MAX) {
4661 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4662 }
4663
4664 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4665 if (local_err) {
4666 error_report_err(local_err);
4667 goto out;
4668 }
4669
4670 if (output_format == OFORMAT_HUMAN) {
4671 printf("required size: %" PRIu64 "\n", info->required);
4672 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4673 } else {
4674 dump_json_block_measure_info(info);
4675 }
4676
4677 ret = 0;
4678
4679out:
4680 qapi_free_BlockMeasureInfo(info);
4681 qemu_opts_del(object_opts);
4682 qemu_opts_del(opts);
4683 qemu_opts_del(sn_opts);
4684 qemu_opts_free(create_opts);
4685 g_free(options);
4686 blk_unref(in_blk);
4687 return ret;
4688}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004689
Anthony Liguoric227f092009-10-01 16:12:16 -05004690static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004691#define DEF(option, callback, arg_string) \
4692 { option, callback },
4693#include "qemu-img-cmds.h"
4694#undef DEF
4695#undef GEN_DOCS
4696 { NULL, NULL, },
4697};
4698
bellardea2384d2004-08-01 21:59:26 +00004699int main(int argc, char **argv)
4700{
Anthony Liguoric227f092009-10-01 16:12:16 -05004701 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004702 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004703 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004704 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004705 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004706 static const struct option long_options[] = {
4707 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004708 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004709 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004710 {0, 0, 0, 0}
4711 };
bellardea2384d2004-08-01 21:59:26 +00004712
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004713#ifdef CONFIG_POSIX
4714 signal(SIGPIPE, SIG_IGN);
4715#endif
4716
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004717 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004718 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004719 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004720
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004721 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004722 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004723 exit(EXIT_FAILURE);
4724 }
4725
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004726 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004727
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004728 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004729 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004730 if (argc < 2) {
4731 error_exit("Not enough arguments");
4732 }
Stuart Brady153859b2009-06-07 00:42:17 +01004733
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004734 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004735 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004736 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004737
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004738 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004739 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004740 case ':':
4741 missing_argument(argv[optind - 1]);
4742 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004743 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004744 unrecognized_option(argv[optind - 1]);
4745 return 0;
4746 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004747 help();
4748 return 0;
4749 case 'V':
4750 printf(QEMU_IMG_VERSION);
4751 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004752 case 'T':
4753 g_free(trace_file);
4754 trace_file = trace_opt_parse(optarg);
4755 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004756 }
bellardea2384d2004-08-01 21:59:26 +00004757 }
Stuart Brady153859b2009-06-07 00:42:17 +01004758
Denis V. Lunev10985132016-06-17 17:44:13 +03004759 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004760
Denis V. Lunev10985132016-06-17 17:44:13 +03004761 /* reset getopt_long scanning */
4762 argc -= optind;
4763 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004764 return 0;
4765 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004766 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004767 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004768
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004769 if (!trace_init_backends()) {
4770 exit(1);
4771 }
4772 trace_init_file(trace_file);
4773 qemu_set_log(LOG_TRACE);
4774
Denis V. Lunev10985132016-06-17 17:44:13 +03004775 /* find the command */
4776 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4777 if (!strcmp(cmdname, cmd->name)) {
4778 return cmd->handler(argc, argv);
4779 }
4780 }
Jeff Cody7db16892014-04-25 17:02:32 -04004781
Stuart Brady153859b2009-06-07 00:42:17 +01004782 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004783 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004784}