blob: fd62e3ad5da0d0a1f91b7e98186a7cf41fcd9e19 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Markus Armbrustera8d25322019-05-23 16:35:08 +020028#include "qemu-common.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080029#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010030#include "qapi/error.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010031#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010032#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010033#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010034#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010035#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020036#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000037#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010038#include "qemu/option.h"
39#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030040#include "qemu/log.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020041#include "qemu/module.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020042#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000043#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010044#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020045#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010046#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020047#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080048#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010049#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030050#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000051
Thomas Huth7e563bf2018-02-15 12:06:47 +010052#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020053 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040054
Anthony Liguoric227f092009-10-01 16:12:16 -050055typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010056 const char *name;
57 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050058} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010059
Federico Simoncelli8599ea42013-01-28 06:59:47 -050060enum {
61 OPTION_OUTPUT = 256,
62 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000063 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000064 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020065 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020066 OPTION_FLUSH_INTERVAL = 261,
67 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010068 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010069 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020070 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030071 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050072};
73
74typedef enum OutputFormat {
75 OFORMAT_JSON,
76 OFORMAT_HUMAN,
77} OutputFormat;
78
Kevin Wolfe6996142016-03-15 13:03:11 +010079/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040080#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000081
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010082static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000083{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010084 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000085}
86
Fam Zhengac1307a2014-04-22 13:36:11 +080087static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
88{
89 va_list ap;
90
Fam Zhengac1307a2014-04-22 13:36:11 +080091 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +020092 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +080093 va_end(ap);
94
Markus Armbrustere9e1d922019-04-17 21:06:27 +020095 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +080096 exit(EXIT_FAILURE);
97}
98
Stefan Hajnoczic9192972017-03-17 18:45:41 +080099static void QEMU_NORETURN missing_argument(const char *option)
100{
101 error_exit("missing argument for option '%s'", option);
102}
103
104static void QEMU_NORETURN unrecognized_option(const char *option)
105{
106 error_exit("unrecognized option '%s'", option);
107}
108
blueswir1d2c639d2009-01-24 18:19:25 +0000109/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800110static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000111{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100112 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400113 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300114 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300115 "QEMU disk image utility\n"
116 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300117 " '-h', '--help' display this help and exit\n"
118 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300119 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
120 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300121 "\n"
malc3f020d72010-02-08 12:04:56 +0300122 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100123#define DEF(option, callback, arg_string) \
124 " " arg_string "\n"
125#include "qemu-img-cmds.h"
126#undef DEF
malc3f020d72010-02-08 12:04:56 +0300127 "\n"
128 "Command parameters:\n"
129 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000130 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
131 " manual page for a description of the object properties. The most common\n"
132 " object type is a 'secret', which is used to supply passwords and/or\n"
133 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300134 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400135 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800136 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
137 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100138 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
139 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300140 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200141 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
142 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
143 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300144 " 'output_filename' is the destination disk image filename\n"
145 " 'output_fmt' is the destination format\n"
146 " 'options' is a comma separated list of format specific options in a\n"
147 " name=value format. Use -o ? for an overview of the options supported by the\n"
148 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800149 " 'snapshot_param' is param used for internal snapshot, format\n"
150 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
151 " '[ID_OR_NAME]'\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);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300202 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500203 printf("\n\n" QEMU_HELP_BOTTOM "\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
Max Reitzd402b6a2018-05-09 23:00:21 +0200251 if (!drv->create_opts) {
252 error_report("Format driver '%s' does not support image creation", fmt);
253 return 1;
254 }
255
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800256 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100257 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500258 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100259 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100260 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800261 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100262 return 1;
263 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200264 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100265 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200266 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100267 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200268 return 1;
269 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800270 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100271 }
272
Max Reitzf4619af2019-04-13 17:20:37 +0200273 if (filename) {
274 printf("Supported options:\n");
275 } else {
276 printf("Supported %s options:\n", fmt);
277 }
Max Reitz63898712018-10-19 18:49:25 +0200278 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800279 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200280
281 if (!filename) {
282 printf("\n"
283 "The protocol level may support further options.\n"
284 "Specify the target filename to include those options.\n");
285 }
286
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100287 return 0;
288}
289
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000290
Max Reitzefaa7c42016-03-16 19:54:38 +0100291static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100292 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800293 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000294{
295 QDict *options;
296 Error *local_err = NULL;
297 BlockBackend *blk;
298 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800299 if (force_share) {
300 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200301 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800302 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200303 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800304 return NULL;
305 }
Max Reitz4615f872018-05-02 22:20:50 +0200306 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800307 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100308 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000309 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100310 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000311 return NULL;
312 }
Kevin Wolfce099542016-03-15 13:01:04 +0100313 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000314
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000315 return blk;
316}
317
Max Reitzefaa7c42016-03-16 19:54:38 +0100318static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100319 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000320 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800321 bool writethrough, bool quiet,
322 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000323{
324 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200325 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100326
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100327 if (!options) {
328 options = qdict_new();
329 }
bellard75c23802004-08-27 21:28:58 +0000330 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500331 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000332 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100333
Fam Zheng335e9932017-05-03 00:35:39 +0800334 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500335 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800336 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100337 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500338 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100339 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000340 return NULL;
bellard75c23802004-08-27 21:28:58 +0000341 }
Kevin Wolfce099542016-03-15 13:01:04 +0100342 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100343
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200344 return blk;
bellard75c23802004-08-27 21:28:58 +0000345}
346
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000347
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100348static int img_add_key_secrets(void *opaque,
349 const char *name, const char *value,
350 Error **errp)
351{
352 QDict *options = opaque;
353
354 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600355 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100356 }
357
358 return 0;
359}
360
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100361
Max Reitzefaa7c42016-03-16 19:54:38 +0100362static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000363 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100364 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800365 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000366{
367 BlockBackend *blk;
368 if (image_opts) {
369 QemuOpts *opts;
370 if (fmt) {
371 error_report("--image-opts and --format are mutually exclusive");
372 return NULL;
373 }
374 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
375 filename, true);
376 if (!opts) {
377 return NULL;
378 }
Fam Zheng335e9932017-05-03 00:35:39 +0800379 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
380 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000381 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100382 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800383 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000384 }
385 return blk;
386}
387
388
Chunyan Liu83d05212014-06-05 17:20:51 +0800389static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100390 const char *base_filename,
391 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200392{
Markus Armbruster6750e792015-02-12 17:43:08 +0100393 Error *err = NULL;
394
Kevin Wolfefa84d42009-05-18 16:42:12 +0200395 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100396 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100397 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100398 error_report("Backing file not supported for file format '%s'",
399 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100400 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900401 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200402 }
403 }
404 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100405 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100406 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100407 error_report("Backing file format not supported for file "
408 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100409 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900410 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200411 }
412 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900413 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200414}
415
Markus Armbruster606caa02017-02-21 21:14:04 +0100416static int64_t cvtnum(const char *s)
417{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100418 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100419 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100420
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100421 err = qemu_strtosz(s, NULL, &value);
422 if (err < 0) {
423 return err;
424 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100425 if (value > INT64_MAX) {
426 return -ERANGE;
427 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100428 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100429}
430
bellardea2384d2004-08-01 21:59:26 +0000431static int img_create(int argc, char **argv)
432{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200433 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100434 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000435 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000436 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000437 const char *filename;
438 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200439 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200440 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100441 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400442 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000443
bellardea2384d2004-08-01 21:59:26 +0000444 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000445 static const struct option long_options[] = {
446 {"help", no_argument, 0, 'h'},
447 {"object", required_argument, 0, OPTION_OBJECT},
448 {0, 0, 0, 0}
449 };
John Snow6e6e55f2017-07-17 20:34:22 -0400450 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000451 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100452 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000453 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100454 }
bellardea2384d2004-08-01 21:59:26 +0000455 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800456 case ':':
457 missing_argument(argv[optind - 1]);
458 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100459 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800460 unrecognized_option(argv[optind - 1]);
461 break;
bellardea2384d2004-08-01 21:59:26 +0000462 case 'h':
463 help();
464 break;
aliguori9230eaf2009-03-28 17:55:19 +0000465 case 'F':
466 base_fmt = optarg;
467 break;
bellardea2384d2004-08-01 21:59:26 +0000468 case 'b':
469 base_filename = optarg;
470 break;
471 case 'f':
472 fmt = optarg;
473 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200474 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100475 if (!is_valid_option_list(optarg)) {
476 error_report("Invalid option list: %s", optarg);
477 goto fail;
478 }
479 if (!options) {
480 options = g_strdup(optarg);
481 } else {
482 char *old_options = options;
483 options = g_strdup_printf("%s,%s", options, optarg);
484 g_free(old_options);
485 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200486 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100487 case 'q':
488 quiet = true;
489 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400490 case 'u':
491 flags |= BDRV_O_NO_BACKING;
492 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000493 case OPTION_OBJECT: {
494 QemuOpts *opts;
495 opts = qemu_opts_parse_noisily(&qemu_object_opts,
496 optarg, true);
497 if (!opts) {
498 goto fail;
499 }
500 } break;
bellardea2384d2004-08-01 21:59:26 +0000501 }
502 }
aliguori9230eaf2009-03-28 17:55:19 +0000503
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900504 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100505 filename = (optind < argc) ? argv[optind] : NULL;
506 if (options && has_help_option(options)) {
507 g_free(options);
508 return print_block_option_help(filename, fmt);
509 }
510
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100511 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800512 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100513 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100514 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900515
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000516 if (qemu_opts_foreach(&qemu_object_opts,
517 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000518 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000519 goto fail;
520 }
521
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100522 /* Get image size, if specified */
523 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100524 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100525
526 sval = cvtnum(argv[optind++]);
527 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800528 if (sval == -ERANGE) {
529 error_report("Image size must be less than 8 EiB!");
530 } else {
531 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200532 "G, T, P or E suffixes for ");
533 error_report("kilobytes, megabytes, gigabytes, terabytes, "
534 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800535 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100536 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100537 }
538 img_size = (uint64_t)sval;
539 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200540 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800541 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200542 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100543
Luiz Capitulino9b375252012-11-30 10:52:05 -0200544 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400545 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100546 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100547 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100548 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900549 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200550
Kevin Wolf77386bf2014-02-21 16:24:04 +0100551 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000552 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100553
554fail:
555 g_free(options);
556 return 1;
bellardea2384d2004-08-01 21:59:26 +0000557}
558
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100559static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500561 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500562 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100563 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600564
565 visit_type_ImageCheck(v, NULL, &check, &error_abort);
566 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500567 str = qobject_to_json_pretty(obj);
568 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100569 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200570 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600571 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200572 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500573}
574
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100575static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500576{
577 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100578 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500579 } else {
580 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100581 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
582 "Data may be corrupted, or further writes to the image "
583 "may corrupt it.\n",
584 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500585 }
586
587 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100588 qprintf(quiet,
589 "\n%" PRId64 " leaked clusters were found on the image.\n"
590 "This means waste of disk space, but no harm to data.\n",
591 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500592 }
593
594 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100595 qprintf(quiet,
596 "\n%" PRId64
597 " internal errors have occurred during the check.\n",
598 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500599 }
600 }
601
602 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100603 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
604 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
605 check->allocated_clusters, check->total_clusters,
606 check->allocated_clusters * 100.0 / check->total_clusters,
607 check->fragmented_clusters * 100.0 / check->allocated_clusters,
608 check->compressed_clusters * 100.0 /
609 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500610 }
611
612 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100613 qprintf(quiet,
614 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500615 }
616}
617
618static int collect_image_check(BlockDriverState *bs,
619 ImageCheck *check,
620 const char *filename,
621 const char *fmt,
622 int fix)
623{
624 int ret;
625 BdrvCheckResult result;
626
627 ret = bdrv_check(bs, &result, fix);
628 if (ret < 0) {
629 return ret;
630 }
631
632 check->filename = g_strdup(filename);
633 check->format = g_strdup(bdrv_get_format_name(bs));
634 check->check_errors = result.check_errors;
635 check->corruptions = result.corruptions;
636 check->has_corruptions = result.corruptions != 0;
637 check->leaks = result.leaks;
638 check->has_leaks = result.leaks != 0;
639 check->corruptions_fixed = result.corruptions_fixed;
640 check->has_corruptions_fixed = result.corruptions != 0;
641 check->leaks_fixed = result.leaks_fixed;
642 check->has_leaks_fixed = result.leaks != 0;
643 check->image_end_offset = result.image_end_offset;
644 check->has_image_end_offset = result.image_end_offset != 0;
645 check->total_clusters = result.bfi.total_clusters;
646 check->has_total_clusters = result.bfi.total_clusters != 0;
647 check->allocated_clusters = result.bfi.allocated_clusters;
648 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
649 check->fragmented_clusters = result.bfi.fragmented_clusters;
650 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100651 check->compressed_clusters = result.bfi.compressed_clusters;
652 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500653
654 return 0;
655}
656
Kevin Wolfe076f332010-06-29 11:43:13 +0200657/*
658 * Checks an image for consistency. Exit codes:
659 *
Max Reitzd6635c42014-06-02 22:15:21 +0200660 * 0 - Check completed, image is good
661 * 1 - Check not completed because of internal errors
662 * 2 - Check completed, image is corrupted
663 * 3 - Check completed, image has leaked clusters, but is good otherwise
664 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200665 */
aliguori15859692009-04-21 23:11:53 +0000666static int img_check(int argc, char **argv)
667{
668 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500669 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200670 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200671 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000672 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200673 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100674 int flags = BDRV_O_CHECK;
675 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200676 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100677 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000678 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800679 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000680
681 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500682 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200683 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100684
aliguori15859692009-04-21 23:11:53 +0000685 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500686 int option_index = 0;
687 static const struct option long_options[] = {
688 {"help", no_argument, 0, 'h'},
689 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530690 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500691 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000692 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000693 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800694 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500695 {0, 0, 0, 0}
696 };
Fam Zheng335e9932017-05-03 00:35:39 +0800697 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500698 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100699 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000700 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100701 }
aliguori15859692009-04-21 23:11:53 +0000702 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800703 case ':':
704 missing_argument(argv[optind - 1]);
705 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100706 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800707 unrecognized_option(argv[optind - 1]);
708 break;
aliguori15859692009-04-21 23:11:53 +0000709 case 'h':
710 help();
711 break;
712 case 'f':
713 fmt = optarg;
714 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200715 case 'r':
716 flags |= BDRV_O_RDWR;
717
718 if (!strcmp(optarg, "leaks")) {
719 fix = BDRV_FIX_LEAKS;
720 } else if (!strcmp(optarg, "all")) {
721 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
722 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800723 error_exit("Unknown option value for -r "
724 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200725 }
726 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500727 case OPTION_OUTPUT:
728 output = optarg;
729 break;
Max Reitz40055952014-07-22 22:58:42 +0200730 case 'T':
731 cache = optarg;
732 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100733 case 'q':
734 quiet = true;
735 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800736 case 'U':
737 force_share = true;
738 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000739 case OPTION_OBJECT: {
740 QemuOpts *opts;
741 opts = qemu_opts_parse_noisily(&qemu_object_opts,
742 optarg, true);
743 if (!opts) {
744 return 1;
745 }
746 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000747 case OPTION_IMAGE_OPTS:
748 image_opts = true;
749 break;
aliguori15859692009-04-21 23:11:53 +0000750 }
751 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200752 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800753 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100754 }
aliguori15859692009-04-21 23:11:53 +0000755 filename = argv[optind++];
756
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500757 if (output && !strcmp(output, "json")) {
758 output_format = OFORMAT_JSON;
759 } else if (output && !strcmp(output, "human")) {
760 output_format = OFORMAT_HUMAN;
761 } else if (output) {
762 error_report("--output must be used with human or json as argument.");
763 return 1;
764 }
765
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000766 if (qemu_opts_foreach(&qemu_object_opts,
767 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000768 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000769 return 1;
770 }
771
Kevin Wolfce099542016-03-15 13:01:04 +0100772 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200773 if (ret < 0) {
774 error_report("Invalid source cache option: %s", cache);
775 return 1;
776 }
777
Fam Zheng335e9932017-05-03 00:35:39 +0800778 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
779 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200780 if (!blk) {
781 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900782 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200783 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500784
785 check = g_new0(ImageCheck, 1);
786 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200787
788 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200789 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200790 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500791 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200792 }
793
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500794 if (check->corruptions_fixed || check->leaks_fixed) {
795 int corruptions_fixed, leaks_fixed;
796
797 leaks_fixed = check->leaks_fixed;
798 corruptions_fixed = check->corruptions_fixed;
799
800 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100801 qprintf(quiet,
802 "The following inconsistencies were found and repaired:\n\n"
803 " %" PRId64 " leaked clusters\n"
804 " %" PRId64 " corruptions\n\n"
805 "Double checking the fixed image now...\n",
806 check->leaks_fixed,
807 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500808 }
809
810 ret = collect_image_check(bs, check, filename, fmt, 0);
811
812 check->leaks_fixed = leaks_fixed;
813 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200814 }
815
Max Reitz832390a2014-10-23 15:29:12 +0200816 if (!ret) {
817 switch (output_format) {
818 case OFORMAT_HUMAN:
819 dump_human_image_check(check, quiet);
820 break;
821 case OFORMAT_JSON:
822 dump_json_image_check(check, quiet);
823 break;
824 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500825 }
826
827 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200828 if (ret) {
829 error_report("Check failed: %s", strerror(-ret));
830 } else {
831 error_report("Check failed");
832 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500833 ret = 1;
834 goto fail;
835 }
836
837 if (check->corruptions) {
838 ret = 2;
839 } else if (check->leaks) {
840 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200841 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500842 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000843 }
844
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500845fail:
846 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200847 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500848 return ret;
aliguori15859692009-04-21 23:11:53 +0000849}
850
Max Reitzd4a32382014-10-24 15:57:37 +0200851typedef struct CommonBlockJobCBInfo {
852 BlockDriverState *bs;
853 Error **errp;
854} CommonBlockJobCBInfo;
855
856static void common_block_job_cb(void *opaque, int ret)
857{
858 CommonBlockJobCBInfo *cbi = opaque;
859
860 if (ret < 0) {
861 error_setg_errno(cbi->errp, -ret, "Block job failed");
862 }
Max Reitzd4a32382014-10-24 15:57:37 +0200863}
864
865static void run_block_job(BlockJob *job, Error **errp)
866{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200867 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800868 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200869
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200870 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200871 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200872 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200873 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200874 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200875 if (job->job.progress_total) {
876 progress = (float)job->job.progress_current /
877 job->job.progress_total * 100.f;
878 }
879 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200880 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200881
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200882 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200883 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800884 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200885 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800886 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200887 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200888 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200889
sochin.jiang4172a002017-06-15 14:47:33 +0800890 /* publish completion progress only when success */
891 if (!ret) {
892 qemu_progress_print(100.f, 0);
893 }
Max Reitzd4a32382014-10-24 15:57:37 +0200894}
895
bellardea2384d2004-08-01 21:59:26 +0000896static int img_commit(int argc, char **argv)
897{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400898 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200899 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200900 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200901 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100902 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200903 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100904 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200905 Error *local_err = NULL;
906 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000907 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200908 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000909
910 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400911 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200912 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000913 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000914 static const struct option long_options[] = {
915 {"help", no_argument, 0, 'h'},
916 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000917 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000918 {0, 0, 0, 0}
919 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800920 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000921 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100922 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000923 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100924 }
bellardea2384d2004-08-01 21:59:26 +0000925 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800926 case ':':
927 missing_argument(argv[optind - 1]);
928 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100929 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800930 unrecognized_option(argv[optind - 1]);
931 break;
bellardea2384d2004-08-01 21:59:26 +0000932 case 'h':
933 help();
934 break;
935 case 'f':
936 fmt = optarg;
937 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400938 case 't':
939 cache = optarg;
940 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200941 case 'b':
942 base = optarg;
943 /* -b implies -d */
944 drop = true;
945 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200946 case 'd':
947 drop = true;
948 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200949 case 'p':
950 progress = true;
951 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100952 case 'q':
953 quiet = true;
954 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000955 case OPTION_OBJECT: {
956 QemuOpts *opts;
957 opts = qemu_opts_parse_noisily(&qemu_object_opts,
958 optarg, true);
959 if (!opts) {
960 return 1;
961 }
962 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000963 case OPTION_IMAGE_OPTS:
964 image_opts = true;
965 break;
bellardea2384d2004-08-01 21:59:26 +0000966 }
967 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200968
969 /* Progress is not shown in Quiet mode */
970 if (quiet) {
971 progress = false;
972 }
973
Kevin Wolffc11eb22013-08-05 10:53:04 +0200974 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800975 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100976 }
bellardea2384d2004-08-01 21:59:26 +0000977 filename = argv[optind++];
978
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000979 if (qemu_opts_foreach(&qemu_object_opts,
980 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000981 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000982 return 1;
983 }
984
Max Reitz9a86fe42014-10-24 15:57:38 +0200985 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100986 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400987 if (ret < 0) {
988 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100989 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400990 }
991
Fam Zheng335e9932017-05-03 00:35:39 +0800992 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
993 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200994 if (!blk) {
995 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900996 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200997 bs = blk_bs(blk);
998
Max Reitz687fa1d2014-10-24 15:57:39 +0200999 qemu_progress_init(progress, 1.f);
1000 qemu_progress_print(0.f, 100);
1001
Max Reitz1b22bff2014-10-24 15:57:40 +02001002 if (base) {
1003 base_bs = bdrv_find_backing_image(bs, base);
1004 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001005 error_setg(&local_err,
1006 "Did not find '%s' in the backing chain of '%s'",
1007 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001008 goto done;
1009 }
1010 } else {
1011 /* This is different from QMP, which by default uses the deepest file in
1012 * the backing chain (i.e., the very base); however, the traditional
1013 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001014 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001015 if (!base_bs) {
1016 error_setg(&local_err, "Image does not have a backing file");
1017 goto done;
1018 }
bellardea2384d2004-08-01 21:59:26 +00001019 }
1020
Max Reitzd4a32382014-10-24 15:57:37 +02001021 cbi = (CommonBlockJobCBInfo){
1022 .errp = &local_err,
1023 .bs = bs,
1024 };
1025
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001026 aio_context = bdrv_get_aio_context(bs);
1027 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001028 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001029 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001030 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001031 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001032 if (local_err) {
1033 goto done;
1034 }
1035
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001036 /* When the block job completes, the BlockBackend reference will point to
1037 * the old backing file. In order to avoid that the top image is already
1038 * deleted, so we can still empty it afterwards, increment the reference
1039 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001040 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001041 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001042 }
1043
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001044 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001045 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001046 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001047 if (local_err) {
1048 goto unref_backing;
1049 }
1050
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001051 if (!drop && bs->drv->bdrv_make_empty) {
1052 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001053 if (ret) {
1054 error_setg_errno(&local_err, -ret, "Could not empty %s",
1055 filename);
1056 goto unref_backing;
1057 }
1058 }
1059
1060unref_backing:
1061 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001062 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001063 }
Max Reitzd4a32382014-10-24 15:57:37 +02001064
1065done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001066 qemu_progress_end();
1067
Markus Armbruster26f54e92014-10-07 13:59:04 +02001068 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001069
1070 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001071 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001072 return 1;
1073 }
Max Reitzd4a32382014-10-24 15:57:37 +02001074
1075 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001076 return 0;
1077}
1078
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001079/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001080 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1081 * of the first sector boundary within buf where the sector contains a
1082 * non-zero byte. This function is robust to a buffer that is not
1083 * sector-aligned.
1084 */
1085static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1086{
1087 int64_t i;
1088 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1089
1090 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1091 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1092 return i;
1093 }
1094 }
1095 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1096 return i;
1097 }
1098 return -1;
1099}
1100
1101/*
thsf58c7b32008-06-05 21:53:49 +00001102 * Returns true iff the first sector pointed to by 'buf' contains at least
1103 * a non-NUL byte.
1104 *
1105 * 'pnum' is set to the number of sectors (including and immediately following
1106 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001107 * The function will try to align the end offset to alignment boundaries so
1108 * that the request will at least end aligned and consequtive requests will
1109 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001110 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001111static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1112 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001113{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001114 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001115 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001116
1117 if (n <= 0) {
1118 *pnum = 0;
1119 return 0;
1120 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001121 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001122 for(i = 1; i < n; i++) {
1123 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001124 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001125 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001126 }
bellardea2384d2004-08-01 21:59:26 +00001127 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001128
1129 tail = (sector_num + i) & (alignment - 1);
1130 if (tail) {
1131 if (is_zero && i <= tail) {
1132 /* treat unallocated areas which only consist
1133 * of a small tail as allocated. */
1134 is_zero = false;
1135 }
1136 if (!is_zero) {
1137 /* align up end offset of allocated areas. */
1138 i += alignment - tail;
1139 i = MIN(i, n);
1140 } else {
1141 /* align down end offset of zero areas. */
1142 i -= tail;
1143 }
1144 }
bellardea2384d2004-08-01 21:59:26 +00001145 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001146 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001147}
1148
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001149/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001150 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1151 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1152 * breaking up write requests for only small sparse areas.
1153 */
1154static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001155 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001156{
1157 int ret;
1158 int num_checked, num_used;
1159
1160 if (n < min) {
1161 min = n;
1162 }
1163
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001164 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001165 if (!ret) {
1166 return ret;
1167 }
1168
1169 num_used = *pnum;
1170 buf += BDRV_SECTOR_SIZE * *pnum;
1171 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001172 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001173 num_checked = num_used;
1174
1175 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001176 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001177
1178 buf += BDRV_SECTOR_SIZE * *pnum;
1179 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001180 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001181 num_checked += *pnum;
1182 if (ret) {
1183 num_used = num_checked;
1184 } else if (*pnum >= min) {
1185 break;
1186 }
1187 }
1188
1189 *pnum = num_used;
1190 return 1;
1191}
1192
1193/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001194 * Compares two buffers sector by sector. Returns 0 if the first
1195 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001196 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001197 * pnum is set to the sector-aligned size of the buffer prefix that
1198 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001199 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001200static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1201 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001202{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001203 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001204 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001205
Eric Blakedc61cd32017-10-11 22:47:14 -05001206 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001207
Eric Blakedc61cd32017-10-11 22:47:14 -05001208 res = !!memcmp(buf1, buf2, i);
1209 while (i < bytes) {
1210 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001211
Eric Blakedc61cd32017-10-11 22:47:14 -05001212 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001213 break;
1214 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001215 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001216 }
1217
1218 *pnum = i;
1219 return res;
1220}
1221
Stefano Garzarella97ede572019-05-08 12:43:24 +02001222#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001223
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001224/*
1225 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1226 *
Eric Blake0608e402017-10-11 22:47:12 -05001227 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1228 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1229 * failure), and 4 on error (the exit status for read errors), after emitting
1230 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001231 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001232 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001233 * @param offset: Starting offset to check
1234 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001235 * @param filename: Name of disk file we are checking (logging purpose)
1236 * @param buffer: Allocated buffer for storing read data
1237 * @param quiet: Flag for quiet mode
1238 */
Eric Blakec41508e2017-10-11 22:47:13 -05001239static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1240 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001241 uint8_t *buffer, bool quiet)
1242{
Eric Blakedebb38a2017-10-11 22:47:11 -05001243 int ret = 0;
1244 int64_t idx;
1245
Eric Blakec41508e2017-10-11 22:47:13 -05001246 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001247 if (ret < 0) {
1248 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001249 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001250 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001251 }
Eric Blakec41508e2017-10-11 22:47:13 -05001252 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001253 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001254 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001255 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001256 return 1;
1257 }
1258
1259 return 0;
1260}
1261
1262/*
1263 * Compares two images. Exit codes:
1264 *
1265 * 0 - Images are identical
1266 * 1 - Images differ
1267 * >1 - Error occurred
1268 */
1269static int img_compare(int argc, char **argv)
1270{
Max Reitz40055952014-07-22 22:58:42 +02001271 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001272 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001273 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001274 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001275 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001276 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001277 int allocated1, allocated2;
1278 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1279 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001280 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001281 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001282 int64_t total_size;
1283 int64_t offset = 0;
1284 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001285 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001286 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001287 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001288 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001289
Max Reitz40055952014-07-22 22:58:42 +02001290 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001291 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001292 static const struct option long_options[] = {
1293 {"help", no_argument, 0, 'h'},
1294 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001295 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001296 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001297 {0, 0, 0, 0}
1298 };
Fam Zheng335e9932017-05-03 00:35:39 +08001299 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001300 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001301 if (c == -1) {
1302 break;
1303 }
1304 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001305 case ':':
1306 missing_argument(argv[optind - 1]);
1307 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001308 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001309 unrecognized_option(argv[optind - 1]);
1310 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001311 case 'h':
1312 help();
1313 break;
1314 case 'f':
1315 fmt1 = optarg;
1316 break;
1317 case 'F':
1318 fmt2 = optarg;
1319 break;
Max Reitz40055952014-07-22 22:58:42 +02001320 case 'T':
1321 cache = optarg;
1322 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001323 case 'p':
1324 progress = true;
1325 break;
1326 case 'q':
1327 quiet = true;
1328 break;
1329 case 's':
1330 strict = true;
1331 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001332 case 'U':
1333 force_share = true;
1334 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001335 case OPTION_OBJECT: {
1336 QemuOpts *opts;
1337 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1338 optarg, true);
1339 if (!opts) {
1340 ret = 2;
1341 goto out4;
1342 }
1343 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001344 case OPTION_IMAGE_OPTS:
1345 image_opts = true;
1346 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001347 }
1348 }
1349
1350 /* Progress is not shown in Quiet mode */
1351 if (quiet) {
1352 progress = false;
1353 }
1354
1355
Kevin Wolffc11eb22013-08-05 10:53:04 +02001356 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001357 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001358 }
1359 filename1 = argv[optind++];
1360 filename2 = argv[optind++];
1361
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001362 if (qemu_opts_foreach(&qemu_object_opts,
1363 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00001364 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001365 ret = 2;
1366 goto out4;
1367 }
1368
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001369 /* Initialize before goto out */
1370 qemu_progress_init(progress, 2.0);
1371
Kevin Wolfce099542016-03-15 13:01:04 +01001372 flags = 0;
1373 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001374 if (ret < 0) {
1375 error_report("Invalid source cache option: %s", cache);
1376 ret = 2;
1377 goto out3;
1378 }
1379
Fam Zheng335e9932017-05-03 00:35:39 +08001380 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1381 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001382 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001383 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001384 goto out3;
1385 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001386
Fam Zheng335e9932017-05-03 00:35:39 +08001387 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1388 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001389 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001390 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001391 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001393 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001394 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001395
Max Reitzf1d3cd72015-02-05 13:58:18 -05001396 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1397 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001398 total_size1 = blk_getlength(blk1);
1399 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001400 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001401 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001402 ret = 4;
1403 goto out;
1404 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001405 total_size2 = blk_getlength(blk2);
1406 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001407 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001408 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001409 ret = 4;
1410 goto out;
1411 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001412 total_size = MIN(total_size1, total_size2);
1413 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001414
1415 qemu_progress_print(0, 100);
1416
Eric Blake033d9fc2017-10-11 22:47:16 -05001417 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001418 ret = 1;
1419 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1420 goto out;
1421 }
1422
Eric Blake033d9fc2017-10-11 22:47:16 -05001423 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001424 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001425
Eric Blake033d9fc2017-10-11 22:47:16 -05001426 status1 = bdrv_block_status_above(bs1, NULL, offset,
1427 total_size1 - offset, &pnum1, NULL,
1428 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001429 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001430 ret = 3;
1431 error_report("Sector allocation test failed for %s", filename1);
1432 goto out;
1433 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001434 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001435
Eric Blake033d9fc2017-10-11 22:47:16 -05001436 status2 = bdrv_block_status_above(bs2, NULL, offset,
1437 total_size2 - offset, &pnum2, NULL,
1438 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001439 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001440 ret = 3;
1441 error_report("Sector allocation test failed for %s", filename2);
1442 goto out;
1443 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001444 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001445
1446 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001447 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001448
Fam Zheng25ad8e62016-01-13 16:37:41 +08001449 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001450 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001451 ret = 1;
1452 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001453 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001454 goto out;
1455 }
1456 }
1457 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001458 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001459 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001460 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001461 int64_t pnum;
1462
Eric Blake033d9fc2017-10-11 22:47:16 -05001463 chunk = MIN(chunk, IO_BUF_SIZE);
1464 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001465 if (ret < 0) {
1466 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001467 " of %s: %s",
1468 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001469 ret = 4;
1470 goto out;
1471 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001472 ret = blk_pread(blk2, offset, buf2, chunk);
1473 if (ret < 0) {
1474 error_report("Error while reading offset %" PRId64
1475 " of %s: %s",
1476 offset, filename2, strerror(-ret));
1477 ret = 4;
1478 goto out;
1479 }
1480 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1481 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001482 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001483 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001484 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001485 goto out;
1486 }
1487 }
1488 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001489 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001490 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001491 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001492 filename1, buf1, quiet);
1493 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001494 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001495 filename2, buf1, quiet);
1496 }
1497 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001498 goto out;
1499 }
1500 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001501 offset += chunk;
1502 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001503 }
1504
Eric Blake033d9fc2017-10-11 22:47:16 -05001505 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001506 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001507 const char *filename_over;
1508
1509 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001510 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001511 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001512 filename_over = filename1;
1513 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001514 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001515 filename_over = filename2;
1516 }
1517
Eric Blake033d9fc2017-10-11 22:47:16 -05001518 while (offset < progress_base) {
1519 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1520 progress_base - offset, &chunk,
1521 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001522 if (ret < 0) {
1523 ret = 3;
1524 error_report("Sector allocation test failed for %s",
1525 filename_over);
1526 goto out;
1527
1528 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001529 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001530 chunk = MIN(chunk, IO_BUF_SIZE);
1531 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 filename_over, buf1, quiet);
1533 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001534 goto out;
1535 }
1536 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001537 offset += chunk;
1538 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001539 }
1540 }
1541
1542 qprintf(quiet, "Images are identical.\n");
1543 ret = 0;
1544
1545out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001546 qemu_vfree(buf1);
1547 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001548 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001549out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001550 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551out3:
1552 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001553out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001554 return ret;
1555}
1556
Kevin Wolf690c7302015-03-19 13:33:32 +01001557enum ImgConvertBlockStatus {
1558 BLK_DATA,
1559 BLK_ZERO,
1560 BLK_BACKING_FILE,
1561};
1562
Peter Lieven2d9187b2017-02-28 13:40:07 +01001563#define MAX_COROUTINES 16
1564
Kevin Wolf690c7302015-03-19 13:33:32 +01001565typedef struct ImgConvertState {
1566 BlockBackend **src;
1567 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001568 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001569 int64_t total_sectors;
1570 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001571 int64_t allocated_done;
1572 int64_t sector_num;
1573 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001574 enum ImgConvertBlockStatus status;
1575 int64_t sector_next_status;
1576 BlockBackend *target;
1577 bool has_zero_init;
1578 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001579 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001580 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001581 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001582 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001583 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001584 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001585 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001586 size_t cluster_sectors;
1587 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001588 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001589 int running_coroutines;
1590 Coroutine *co[MAX_COROUTINES];
1591 int64_t wait_sector_num[MAX_COROUTINES];
1592 CoMutex lock;
1593 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001594} ImgConvertState;
1595
Peter Lieven2d9187b2017-02-28 13:40:07 +01001596static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1597 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001598{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001599 *src_cur = 0;
1600 *src_cur_offset = 0;
1601 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1602 *src_cur_offset += s->src_sectors[*src_cur];
1603 (*src_cur)++;
1604 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001605 }
1606}
1607
1608static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1609{
Eric Blake31826642017-10-11 22:47:08 -05001610 int64_t src_cur_offset;
1611 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001612 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001613
Peter Lieven2d9187b2017-02-28 13:40:07 +01001614 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001615
1616 assert(s->total_sectors > sector_num);
1617 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1618
Max Reitz351c8ef2018-05-01 18:57:49 +02001619 if (s->target_backing_sectors >= 0) {
1620 if (sector_num >= s->target_backing_sectors) {
1621 post_backing_zero = s->unallocated_blocks_are_zero;
1622 } else if (sector_num + n > s->target_backing_sectors) {
1623 /* Split requests around target_backing_sectors (because
1624 * starting from there, zeros are handled differently) */
1625 n = s->target_backing_sectors - sector_num;
1626 }
1627 }
1628
Kevin Wolf690c7302015-03-19 13:33:32 +01001629 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001630 int64_t count = n * BDRV_SECTOR_SIZE;
1631
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001632 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001633
1634 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1635 (sector_num - src_cur_offset) *
1636 BDRV_SECTOR_SIZE,
1637 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001638 } else {
Eric Blake31826642017-10-11 22:47:08 -05001639 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1640 (sector_num - src_cur_offset) *
1641 BDRV_SECTOR_SIZE,
1642 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001643 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001644 if (ret < 0) {
Eric Blake2058c2a2019-03-23 16:26:38 -05001645 error_report("error while reading block status of sector %" PRId64
1646 ": %s", sector_num, strerror(-ret));
Kevin Wolf690c7302015-03-19 13:33:32 +01001647 return ret;
1648 }
Eric Blake31826642017-10-11 22:47:08 -05001649 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001650
1651 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001652 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001653 } else if (ret & BDRV_BLOCK_DATA) {
1654 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001655 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001656 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001657 }
1658
1659 s->sector_next_status = sector_num + n;
1660 }
1661
1662 n = MIN(n, s->sector_next_status - sector_num);
1663 if (s->status == BLK_DATA) {
1664 n = MIN(n, s->buf_sectors);
1665 }
1666
1667 /* We need to write complete clusters for compressed images, so if an
1668 * unallocated area is shorter than that, we must consider the whole
1669 * cluster allocated. */
1670 if (s->compressed) {
1671 if (n < s->cluster_sectors) {
1672 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1673 s->status = BLK_DATA;
1674 } else {
1675 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1676 }
1677 }
1678
1679 return n;
1680}
1681
Peter Lieven2d9187b2017-02-28 13:40:07 +01001682static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1683 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001684{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001685 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001686
Kevin Wolf690c7302015-03-19 13:33:32 +01001687 assert(nb_sectors <= s->buf_sectors);
1688 while (nb_sectors > 0) {
1689 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001690 int src_cur;
1691 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001692
1693 /* In the case of compression with multiple source files, we can get a
1694 * nb_sectors that spreads into the next part. So we must be able to
1695 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001696 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1697 blk = s->src[src_cur];
1698 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001699
Peter Lieven2d9187b2017-02-28 13:40:07 +01001700 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
Peter Lieven2d9187b2017-02-28 13:40:07 +01001701
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001702 ret = blk_co_pread(
Peter Lieven2d9187b2017-02-28 13:40:07 +01001703 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001704 n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001705 if (ret < 0) {
1706 return ret;
1707 }
1708
1709 sector_num += n;
1710 nb_sectors -= n;
1711 buf += n * BDRV_SECTOR_SIZE;
1712 }
1713
1714 return 0;
1715}
1716
Peter Lieven2d9187b2017-02-28 13:40:07 +01001717
1718static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1719 int nb_sectors, uint8_t *buf,
1720 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001721{
1722 int ret;
1723
1724 while (nb_sectors > 0) {
1725 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001726 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1727
Peter Lieven2d9187b2017-02-28 13:40:07 +01001728 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001729 case BLK_BACKING_FILE:
1730 /* If we have a backing file, leave clusters unallocated that are
1731 * unallocated in the source image, so that the backing file is
1732 * visible at the respective offset. */
1733 assert(s->target_has_backing);
1734 break;
1735
1736 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001737 /* If we're told to keep the target fully allocated (-S 0) or there
1738 * is real non-zero data, we must write it. Otherwise we can treat
1739 * it as zero sectors.
1740 * Compressed clusters need to be written as a whole, so in that
1741 * case we can only save the write if the buffer is completely
1742 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001743 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001744 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001745 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1746 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001747 (s->compressed &&
1748 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001749 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001750 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1751 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001752 if (ret < 0) {
1753 return ret;
1754 }
1755 break;
1756 }
1757 /* fall-through */
1758
1759 case BLK_ZERO:
1760 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001761 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001762 break;
1763 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001764 ret = blk_co_pwrite_zeroes(s->target,
1765 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001766 n << BDRV_SECTOR_BITS,
1767 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001768 if (ret < 0) {
1769 return ret;
1770 }
1771 break;
1772 }
1773
1774 sector_num += n;
1775 nb_sectors -= n;
1776 buf += n * BDRV_SECTOR_SIZE;
1777 }
1778
1779 return 0;
1780}
1781
Fam Zhengee5306d2018-06-01 17:26:48 +08001782static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1783 int nb_sectors)
1784{
1785 int n, ret;
1786
1787 while (nb_sectors > 0) {
1788 BlockBackend *blk;
1789 int src_cur;
1790 int64_t bs_sectors, src_cur_offset;
1791 int64_t offset;
1792
1793 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1794 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1795 blk = s->src[src_cur];
1796 bs_sectors = s->src_sectors[src_cur];
1797
1798 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1799
1800 ret = blk_co_copy_range(blk, offset, s->target,
1801 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001802 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001803 if (ret < 0) {
1804 return ret;
1805 }
1806
1807 sector_num += n;
1808 nb_sectors -= n;
1809 }
1810 return 0;
1811}
1812
Peter Lieven2d9187b2017-02-28 13:40:07 +01001813static void coroutine_fn convert_co_do_copy(void *opaque)
1814{
1815 ImgConvertState *s = opaque;
1816 uint8_t *buf = NULL;
1817 int ret, i;
1818 int index = -1;
1819
1820 for (i = 0; i < s->num_coroutines; i++) {
1821 if (s->co[i] == qemu_coroutine_self()) {
1822 index = i;
1823 break;
1824 }
1825 }
1826 assert(index >= 0);
1827
1828 s->running_coroutines++;
1829 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1830
1831 while (1) {
1832 int n;
1833 int64_t sector_num;
1834 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001835 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001836
1837 qemu_co_mutex_lock(&s->lock);
1838 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1839 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001840 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001841 }
1842 n = convert_iteration_sectors(s, s->sector_num);
1843 if (n < 0) {
1844 qemu_co_mutex_unlock(&s->lock);
1845 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001846 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001847 }
1848 /* save current sector and allocation status to local variables */
1849 sector_num = s->sector_num;
1850 status = s->status;
1851 if (!s->min_sparse && s->status == BLK_ZERO) {
1852 n = MIN(n, s->buf_sectors);
1853 }
1854 /* increment global sector counter so that other coroutines can
1855 * already continue reading beyond this request */
1856 s->sector_num += n;
1857 qemu_co_mutex_unlock(&s->lock);
1858
1859 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1860 s->allocated_done += n;
1861 qemu_progress_print(100.0 * s->allocated_done /
1862 s->allocated_sectors, 0);
1863 }
1864
Fam Zhengee5306d2018-06-01 17:26:48 +08001865retry:
1866 copy_range = s->copy_range && s->status == BLK_DATA;
1867 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001868 ret = convert_co_read(s, sector_num, n, buf);
1869 if (ret < 0) {
1870 error_report("error while reading sector %" PRId64
1871 ": %s", sector_num, strerror(-ret));
1872 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001873 }
1874 } else if (!s->min_sparse && status == BLK_ZERO) {
1875 status = BLK_DATA;
1876 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1877 }
1878
1879 if (s->wr_in_order) {
1880 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001881 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001882 s->wait_sector_num[index] = sector_num;
1883 qemu_coroutine_yield();
1884 }
1885 s->wait_sector_num[index] = -1;
1886 }
1887
Anton Nefedovb91127e2017-04-26 11:33:15 +03001888 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001889 if (copy_range) {
1890 ret = convert_co_copy_range(s, sector_num, n);
1891 if (ret) {
1892 s->copy_range = false;
1893 goto retry;
1894 }
1895 } else {
1896 ret = convert_co_write(s, sector_num, n, buf, status);
1897 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001898 if (ret < 0) {
1899 error_report("error while writing sector %" PRId64
1900 ": %s", sector_num, strerror(-ret));
1901 s->ret = ret;
1902 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001903 }
1904
1905 if (s->wr_in_order) {
1906 /* reenter the coroutine that might have waited
1907 * for this write to complete */
1908 s->wr_offs = sector_num + n;
1909 for (i = 0; i < s->num_coroutines; i++) {
1910 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1911 /*
1912 * A -> B -> A cannot occur because A has
1913 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1914 * B will never enter A during this time window.
1915 */
1916 qemu_coroutine_enter(s->co[i]);
1917 break;
1918 }
1919 }
1920 }
1921 }
1922
Peter Lieven2d9187b2017-02-28 13:40:07 +01001923 qemu_vfree(buf);
1924 s->co[index] = NULL;
1925 s->running_coroutines--;
1926 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1927 /* the convert job finished successfully */
1928 s->ret = 0;
1929 }
1930}
1931
Kevin Wolf690c7302015-03-19 13:33:32 +01001932static int convert_do_copy(ImgConvertState *s)
1933{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001934 int ret, i, n;
1935 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001936
1937 /* Check whether we have zero initialisation or can get it efficiently */
1938 s->has_zero_init = s->min_sparse && !s->target_has_backing
1939 ? bdrv_has_zero_init(blk_bs(s->target))
1940 : false;
1941
1942 if (!s->has_zero_init && !s->target_has_backing &&
1943 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1944 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001945 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001946 if (ret == 0) {
1947 s->has_zero_init = true;
1948 }
1949 }
1950
1951 /* Allocate buffer for copied data. For compressed images, only one cluster
1952 * can be copied at a time. */
1953 if (s->compressed) {
1954 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1955 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001956 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001957 }
1958 s->buf_sectors = s->cluster_sectors;
1959 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001960
Kevin Wolf690c7302015-03-19 13:33:32 +01001961 while (sector_num < s->total_sectors) {
1962 n = convert_iteration_sectors(s, sector_num);
1963 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001964 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001965 }
Max Reitzaad15de2016-03-24 23:33:57 +01001966 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1967 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001968 s->allocated_sectors += n;
1969 }
1970 sector_num += n;
1971 }
1972
1973 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001974 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001975 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001976
Peter Lieven2d9187b2017-02-28 13:40:07 +01001977 qemu_co_mutex_init(&s->lock);
1978 for (i = 0; i < s->num_coroutines; i++) {
1979 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1980 s->wait_sector_num[i] = -1;
1981 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001982 }
1983
Anton Nefedovb91127e2017-04-26 11:33:15 +03001984 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001985 main_loop_wait(false);
1986 }
1987
1988 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001989 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001990 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001991 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001992 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001993 }
1994 }
1995
Peter Lieven2d9187b2017-02-28 13:40:07 +01001996 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001997}
1998
Peter Lieven6360ab22018-07-13 09:15:39 +02001999#define MAX_BUF_SECTORS 32768
2000
bellardea2384d2004-08-01 21:59:26 +00002001static int img_convert(int argc, char **argv)
2002{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002003 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002004 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002005 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2006 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002007 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002008 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002009 BlockDriverState *out_bs;
2010 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002011 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002012 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002013 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002014 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002015 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002016 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002017 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002018 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002019 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002020
Peter Lieven9fd77f92017-04-21 11:11:55 +02002021 ImgConvertState s = (ImgConvertState) {
2022 /* Need at least 4k of zeros for sparse detection */
2023 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002024 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002025 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2026 .wr_in_order = true,
2027 .num_coroutines = 8,
2028 };
2029
bellardea2384d2004-08-01 21:59:26 +00002030 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002031 static const struct option long_options[] = {
2032 {"help", no_argument, 0, 'h'},
2033 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002034 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002035 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002036 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002037 {0, 0, 0, 0}
2038 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002039 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002040 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002041 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002042 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002043 }
bellardea2384d2004-08-01 21:59:26 +00002044 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002045 case ':':
2046 missing_argument(argv[optind - 1]);
2047 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002048 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002049 unrecognized_option(argv[optind - 1]);
2050 break;
bellardea2384d2004-08-01 21:59:26 +00002051 case 'h':
2052 help();
2053 break;
2054 case 'f':
2055 fmt = optarg;
2056 break;
2057 case 'O':
2058 out_fmt = optarg;
2059 break;
thsf58c7b32008-06-05 21:53:49 +00002060 case 'B':
2061 out_baseimg = optarg;
2062 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002063 case 'C':
2064 s.copy_range = true;
2065 break;
bellardea2384d2004-08-01 21:59:26 +00002066 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002067 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002068 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002069 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002070 if (!is_valid_option_list(optarg)) {
2071 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002072 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002073 }
2074 if (!options) {
2075 options = g_strdup(optarg);
2076 } else {
2077 char *old_options = options;
2078 options = g_strdup_printf("%s,%s", options, optarg);
2079 g_free(old_options);
2080 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002081 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002082 case 'l':
2083 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002084 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2085 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002086 if (!sn_opts) {
2087 error_report("Failed in parsing snapshot param '%s'",
2088 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002089 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002090 }
2091 } else {
2092 snapshot_name = optarg;
2093 }
2094 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002095 case 'S':
2096 {
2097 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002098
2099 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002100 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2101 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2102 error_report("Invalid buffer size for sparse output specified. "
2103 "Valid sizes are multiples of %llu up to %llu. Select "
2104 "0 to disable sparse detection (fully allocates output).",
2105 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002106 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002107 }
2108
Peter Lieven9fd77f92017-04-21 11:11:55 +02002109 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002110 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002111 break;
2112 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002113 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002114 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002115 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002116 case 't':
2117 cache = optarg;
2118 break;
Max Reitz40055952014-07-22 22:58:42 +02002119 case 'T':
2120 src_cache = optarg;
2121 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002122 case 'q':
2123 quiet = true;
2124 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002125 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002126 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002127 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002128 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002129 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2130 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002131 error_report("Invalid number of coroutines. Allowed number of"
2132 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002133 goto fail_getopt;
2134 }
2135 break;
2136 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002137 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002138 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002139 case 'U':
2140 force_share = true;
2141 break;
Max Reitz3258b912017-04-26 15:46:47 +02002142 case OPTION_OBJECT: {
2143 QemuOpts *object_opts;
2144 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2145 optarg, true);
2146 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002147 goto fail_getopt;
2148 }
2149 break;
Max Reitz3258b912017-04-26 15:46:47 +02002150 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002151 case OPTION_IMAGE_OPTS:
2152 image_opts = true;
2153 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002154 case OPTION_TARGET_IMAGE_OPTS:
2155 tgt_image_opts = true;
2156 break;
bellardea2384d2004-08-01 21:59:26 +00002157 }
2158 }
ths3b46e622007-09-17 08:09:54 +00002159
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002160 if (!out_fmt && !tgt_image_opts) {
2161 out_fmt = "raw";
2162 }
2163
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002164 if (qemu_opts_foreach(&qemu_object_opts,
2165 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002166 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002167 goto fail_getopt;
2168 }
2169
Fam Zhenge11ce122018-07-27 11:34:01 +08002170 if (s.compressed && s.copy_range) {
2171 error_report("Cannot enable copy offloading when -c is used");
2172 goto fail_getopt;
2173 }
2174
2175 if (explict_min_sparse && s.copy_range) {
2176 error_report("Cannot enable copy offloading when -S is used");
2177 goto fail_getopt;
2178 }
2179
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002180 if (tgt_image_opts && !skip_create) {
2181 error_report("--target-image-opts requires use of -n flag");
2182 goto fail_getopt;
2183 }
2184
Peter Lieven9fd77f92017-04-21 11:11:55 +02002185 s.src_num = argc - optind - 1;
2186 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2187
2188 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002189 if (out_fmt) {
2190 ret = print_block_option_help(out_filename, out_fmt);
2191 goto fail_getopt;
2192 } else {
2193 error_report("Option help requires a format be specified");
2194 goto fail_getopt;
2195 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002196 }
2197
2198 if (s.src_num < 1) {
2199 error_report("Must specify image file name");
2200 goto fail_getopt;
2201 }
2202
2203
Peter Lieven9fd77f92017-04-21 11:11:55 +02002204 /* ret is still -EINVAL until here */
2205 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2206 if (ret < 0) {
2207 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002208 goto fail_getopt;
2209 }
2210
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002211 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002212 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002213 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002214 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002215 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002216 qemu_progress_print(0, 100);
2217
Peter Lieven9fd77f92017-04-21 11:11:55 +02002218 s.src = g_new0(BlockBackend *, s.src_num);
2219 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002220
Peter Lieven9fd77f92017-04-21 11:11:55 +02002221 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2222 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002223 fmt, src_flags, src_writethrough, quiet,
2224 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002225 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002226 ret = -1;
2227 goto out;
2228 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002229 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2230 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002231 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002232 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002233 ret = -1;
2234 goto out;
2235 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002236 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002237 }
bellardea2384d2004-08-01 21:59:26 +00002238
Wenchao Xiaef806542013-12-04 17:10:57 +08002239 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002240 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002241 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2242 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2243 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002244 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002245 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002246 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002247 ret = -1;
2248 goto out;
2249 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002250
Peter Lieven9fd77f92017-04-21 11:11:55 +02002251 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2252 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002253 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002254 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002255 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002256 ret = -1;
2257 goto out;
edison51ef6722010-09-21 19:58:41 -07002258 }
2259
Max Reitz2e024cd2015-02-11 09:58:46 -05002260 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002261 /* Find driver and parse its options */
2262 drv = bdrv_find_format(out_fmt);
2263 if (!drv) {
2264 error_report("Unknown file format '%s'", out_fmt);
2265 ret = -1;
2266 goto out;
2267 }
2268
2269 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2270 if (!proto_drv) {
2271 error_report_err(local_err);
2272 ret = -1;
2273 goto out;
2274 }
2275
Max Reitz2e024cd2015-02-11 09:58:46 -05002276 if (!drv->create_opts) {
2277 error_report("Format driver '%s' does not support image creation",
2278 drv->format_name);
2279 ret = -1;
2280 goto out;
2281 }
Max Reitzf75613c2014-12-02 18:32:46 +01002282
Max Reitz2e024cd2015-02-11 09:58:46 -05002283 if (!proto_drv->create_opts) {
2284 error_report("Protocol driver '%s' does not support image creation",
2285 proto_drv->format_name);
2286 ret = -1;
2287 goto out;
2288 }
Max Reitzf75613c2014-12-02 18:32:46 +01002289
Max Reitz2e024cd2015-02-11 09:58:46 -05002290 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2291 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002292
Max Reitz2e024cd2015-02-11 09:58:46 -05002293 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002294 if (options) {
2295 qemu_opts_do_parse(opts, options, NULL, &local_err);
2296 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002297 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002298 ret = -1;
2299 goto out;
2300 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002301 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002302
Peter Lieven9fd77f92017-04-21 11:11:55 +02002303 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002304 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002305 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2306 if (ret < 0) {
2307 goto out;
2308 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002309 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002310
Kevin Wolfa18953f2010-10-14 15:46:04 +02002311 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002312 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002313 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002314 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002315 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002316 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002317
Max Reitz48758a82017-04-26 15:46:48 +02002318 if (s.src_num > 1 && out_baseimg) {
2319 error_report("Having a backing file for the target makes no sense when "
2320 "concatenating multiple input images");
2321 ret = -1;
2322 goto out;
2323 }
2324
Kevin Wolfefa84d42009-05-18 16:42:12 +02002325 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002326 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002327 bool encryption =
2328 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002329 const char *encryptfmt =
2330 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002331 const char *preallocation =
2332 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002333
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002334 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002335 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002336 ret = -1;
2337 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002338 }
2339
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002340 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002341 error_report("Compression and encryption not supported at "
2342 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002343 ret = -1;
2344 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002345 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002346
Chunyan Liu83d05212014-06-05 17:20:51 +08002347 if (preallocation
2348 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002349 {
2350 error_report("Compression and preallocation not supported at "
2351 "the same time");
2352 ret = -1;
2353 goto out;
2354 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002355 }
2356
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002357 /*
2358 * The later open call will need any decryption secrets, and
2359 * bdrv_create() will purge "opts", so extract them now before
2360 * they are lost.
2361 */
2362 if (!skip_create) {
2363 open_opts = qdict_new();
2364 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2365 }
2366
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002367 if (!skip_create) {
2368 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002369 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002370 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002371 error_reportf_err(local_err, "%s: error while converting %s: ",
2372 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002373 goto out;
bellardea2384d2004-08-01 21:59:26 +00002374 }
2375 }
ths3b46e622007-09-17 08:09:54 +00002376
Peter Lieven9fd77f92017-04-21 11:11:55 +02002377 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002378 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002379 if (ret < 0) {
2380 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002381 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002382 }
2383
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002384 if (skip_create) {
2385 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2386 flags, writethrough, quiet, false);
2387 } else {
2388 /* TODO ultimately we should allow --target-image-opts
2389 * to be used even when -n is not given.
2390 * That has to wait for bdrv_create to be improved
2391 * to allow filenames in option syntax
2392 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002393 s.target = img_open_file(out_filename, open_opts, out_fmt,
2394 flags, writethrough, quiet, false);
2395 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002396 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002397 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002398 ret = -1;
2399 goto out;
2400 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002401 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002402
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002403 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2404 error_report("Compression not supported for this file format");
2405 ret = -1;
2406 goto out;
2407 }
2408
Eric Blake5def6b82016-06-23 16:37:19 -06002409 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002410 * or discard_alignment of the out_bs is greater. Limit to
2411 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2412 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002413 MAX(s.buf_sectors,
2414 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2415 out_bs->bl.pdiscard_alignment >>
2416 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002417
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002418 /* try to align the write requests to the destination to avoid unnecessary
2419 * RMW cycles. */
2420 s.alignment = MAX(pow2floor(s.min_sparse),
2421 DIV_ROUND_UP(out_bs->bl.request_alignment,
2422 BDRV_SECTOR_SIZE));
2423 assert(is_power_of_2(s.alignment));
2424
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002425 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002426 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002427 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002428 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002429 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002430 ret = -1;
2431 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002432 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002433 error_report("output file is smaller than input file");
2434 ret = -1;
2435 goto out;
2436 }
2437 }
2438
Max Reitz351c8ef2018-05-01 18:57:49 +02002439 if (s.target_has_backing) {
2440 /* Errors are treated as "backing length unknown" (which means
2441 * s.target_backing_sectors has to be negative, which it will
2442 * be automatically). The backing file length is used only
2443 * for optimizations, so such a case is not fatal. */
2444 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2445 } else {
2446 s.target_backing_sectors = -1;
2447 }
2448
Peter Lieven24f833c2013-11-27 11:07:07 +01002449 ret = bdrv_get_info(out_bs, &bdi);
2450 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002451 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002452 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002453 goto out;
2454 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002455 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002456 s.compressed = s.compressed || bdi.needs_compressed_writes;
2457 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002458 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002459 }
2460
Peter Lieven9fd77f92017-04-21 11:11:55 +02002461 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002462out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002463 if (!ret) {
2464 qemu_progress_print(100, 0);
2465 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002466 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002467 qemu_opts_del(opts);
2468 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002469 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002470 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002471 blk_unref(s.target);
2472 if (s.src) {
2473 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2474 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002475 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002476 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002477 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002478 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002479fail_getopt:
2480 g_free(options);
2481
Peter Lieven9fd77f92017-04-21 11:11:55 +02002482 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002483}
2484
bellard57d1a2b2004-08-03 21:15:11 +00002485
bellardfaea38e2006-08-05 21:31:00 +00002486static void dump_snapshots(BlockDriverState *bs)
2487{
2488 QEMUSnapshotInfo *sn_tab, *sn;
2489 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002490
2491 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2492 if (nb_sns <= 0)
2493 return;
2494 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002495 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002496 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002497 for(i = 0; i < nb_sns; i++) {
2498 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002499 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002500 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002501 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002502 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002503}
2504
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002505static void dump_json_image_info_list(ImageInfoList *list)
2506{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002507 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002508 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002509 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002510
2511 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2512 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002513 str = qobject_to_json_pretty(obj);
2514 assert(str != NULL);
2515 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002516 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002517 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002518 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002519}
2520
Benoît Canetc054b3f2012-09-05 13:09:02 +02002521static void dump_json_image_info(ImageInfo *info)
2522{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002523 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002524 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002525 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002526
2527 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2528 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002529 str = qobject_to_json_pretty(obj);
2530 assert(str != NULL);
2531 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002532 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002533 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002534 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002535}
2536
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002537static void dump_human_image_info_list(ImageInfoList *list)
2538{
2539 ImageInfoList *elem;
2540 bool delim = false;
2541
2542 for (elem = list; elem; elem = elem->next) {
2543 if (delim) {
2544 printf("\n");
2545 }
2546 delim = true;
2547
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002548 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002549 }
2550}
2551
2552static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2553{
2554 return strcmp(a, b) == 0;
2555}
2556
2557/**
2558 * Open an image file chain and return an ImageInfoList
2559 *
2560 * @filename: topmost image filename
2561 * @fmt: topmost image format (may be NULL to autodetect)
2562 * @chain: true - enumerate entire backing file chain
2563 * false - only topmost image file
2564 *
2565 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2566 * image file. If there was an error a message will have been printed to
2567 * stderr.
2568 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002569static ImageInfoList *collect_image_info_list(bool image_opts,
2570 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002571 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002572 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002573{
2574 ImageInfoList *head = NULL;
2575 ImageInfoList **last = &head;
2576 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002577 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002578
2579 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2580
2581 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002582 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002583 BlockDriverState *bs;
2584 ImageInfo *info;
2585 ImageInfoList *elem;
2586
2587 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2588 error_report("Backing file '%s' creates an infinite loop.",
2589 filename);
2590 goto err;
2591 }
2592 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2593
Max Reitzefaa7c42016-03-16 19:54:38 +01002594 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002595 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2596 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002597 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002598 goto err;
2599 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002600 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002601
Wenchao Xia43526ec2013-06-06 12:27:58 +08002602 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002603 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002604 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002605 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002606 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002607 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002608
2609 elem = g_new0(ImageInfoList, 1);
2610 elem->value = info;
2611 *last = elem;
2612 last = &elem->next;
2613
Markus Armbruster26f54e92014-10-07 13:59:04 +02002614 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002615
2616 filename = fmt = NULL;
2617 if (chain) {
2618 if (info->has_full_backing_filename) {
2619 filename = info->full_backing_filename;
2620 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002621 error_report("Could not determine absolute backing filename,"
2622 " but backing filename '%s' present",
2623 info->backing_filename);
2624 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002625 }
2626 if (info->has_backing_filename_format) {
2627 fmt = info->backing_filename_format;
2628 }
2629 }
2630 }
2631 g_hash_table_destroy(filenames);
2632 return head;
2633
2634err:
2635 qapi_free_ImageInfoList(head);
2636 g_hash_table_destroy(filenames);
2637 return NULL;
2638}
2639
Benoît Canetc054b3f2012-09-05 13:09:02 +02002640static int img_info(int argc, char **argv)
2641{
2642 int c;
2643 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002644 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002645 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002646 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002647 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002648 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002649
bellardea2384d2004-08-01 21:59:26 +00002650 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002651 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002652 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002653 int option_index = 0;
2654 static const struct option long_options[] = {
2655 {"help", no_argument, 0, 'h'},
2656 {"format", required_argument, 0, 'f'},
2657 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002658 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002659 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002660 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002661 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002662 {0, 0, 0, 0}
2663 };
Fam Zheng335e9932017-05-03 00:35:39 +08002664 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002665 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002666 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002667 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002668 }
bellardea2384d2004-08-01 21:59:26 +00002669 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002670 case ':':
2671 missing_argument(argv[optind - 1]);
2672 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002673 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002674 unrecognized_option(argv[optind - 1]);
2675 break;
bellardea2384d2004-08-01 21:59:26 +00002676 case 'h':
2677 help();
2678 break;
2679 case 'f':
2680 fmt = optarg;
2681 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002682 case 'U':
2683 force_share = true;
2684 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002685 case OPTION_OUTPUT:
2686 output = optarg;
2687 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002688 case OPTION_BACKING_CHAIN:
2689 chain = true;
2690 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002691 case OPTION_OBJECT: {
2692 QemuOpts *opts;
2693 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2694 optarg, true);
2695 if (!opts) {
2696 return 1;
2697 }
2698 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002699 case OPTION_IMAGE_OPTS:
2700 image_opts = true;
2701 break;
bellardea2384d2004-08-01 21:59:26 +00002702 }
2703 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002704 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002705 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002706 }
bellardea2384d2004-08-01 21:59:26 +00002707 filename = argv[optind++];
2708
Benoît Canetc054b3f2012-09-05 13:09:02 +02002709 if (output && !strcmp(output, "json")) {
2710 output_format = OFORMAT_JSON;
2711 } else if (output && !strcmp(output, "human")) {
2712 output_format = OFORMAT_HUMAN;
2713 } else if (output) {
2714 error_report("--output must be used with human or json as argument.");
2715 return 1;
2716 }
2717
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002718 if (qemu_opts_foreach(&qemu_object_opts,
2719 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002720 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002721 return 1;
2722 }
2723
Fam Zheng335e9932017-05-03 00:35:39 +08002724 list = collect_image_info_list(image_opts, filename, fmt, chain,
2725 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002726 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002727 return 1;
2728 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002729
Benoît Canetc054b3f2012-09-05 13:09:02 +02002730 switch (output_format) {
2731 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002732 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002733 break;
2734 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002735 if (chain) {
2736 dump_json_image_info_list(list);
2737 } else {
2738 dump_json_image_info(list->value);
2739 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002740 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002741 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002742
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002743 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002744 return 0;
2745}
2746
Eric Blake30065d12019-03-26 13:40:43 -05002747static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2748 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002749{
2750 switch (output_format) {
2751 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002752 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002753 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002754 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002755 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002756 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002757 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002758 e->start, e->length,
2759 e->has_offset ? e->offset : 0,
2760 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002761 }
2762 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2763 * Modify the flags here to allow more coalescing.
2764 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002765 if (next && (!next->data || next->zero)) {
2766 next->data = false;
2767 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002768 }
2769 break;
2770 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002771 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2772 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002773 (e->start == 0 ? "[" : ",\n"),
2774 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002775 e->zero ? "true" : "false",
2776 e->data ? "true" : "false");
2777 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002778 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002779 }
2780 putchar('}');
2781
2782 if (!next) {
2783 printf("]\n");
2784 }
2785 break;
2786 }
Eric Blake30065d12019-03-26 13:40:43 -05002787 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002788}
2789
Eric Blake5e344dd2017-10-11 22:47:02 -05002790static int get_block_status(BlockDriverState *bs, int64_t offset,
2791 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002792{
Eric Blake237d78f2017-10-11 22:47:03 -05002793 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002794 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002795 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002796 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002797 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002798 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002799
2800 /* As an optimization, we could cache the current range of unallocated
2801 * clusters in each file of the chain, and avoid querying the same
2802 * range repeatedly.
2803 */
2804
2805 depth = 0;
2806 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002807 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002808 if (ret < 0) {
2809 return ret;
2810 }
Eric Blake237d78f2017-10-11 22:47:03 -05002811 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002812 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2813 break;
2814 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002815 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002816 if (bs == NULL) {
2817 ret = 0;
2818 break;
2819 }
2820
2821 depth++;
2822 }
2823
John Snow28756452016-02-05 13:12:33 -05002824 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2825
Max Reitzf30c66b2019-02-01 20:29:05 +01002826 if (file && has_offset) {
2827 bdrv_refresh_filename(file);
2828 filename = file->filename;
2829 }
2830
John Snow28756452016-02-05 13:12:33 -05002831 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002832 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002833 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002834 .data = !!(ret & BDRV_BLOCK_DATA),
2835 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002836 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002837 .has_offset = has_offset,
2838 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002839 .has_filename = filename,
2840 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002841 };
2842
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002843 return 0;
2844}
2845
Fam Zheng16b0d552016-01-26 11:59:02 +08002846static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2847{
2848 if (curr->length == 0) {
2849 return false;
2850 }
2851 if (curr->zero != next->zero ||
2852 curr->data != next->data ||
2853 curr->depth != next->depth ||
2854 curr->has_filename != next->has_filename ||
2855 curr->has_offset != next->has_offset) {
2856 return false;
2857 }
2858 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2859 return false;
2860 }
2861 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2862 return false;
2863 }
2864 return true;
2865}
2866
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002867static int img_map(int argc, char **argv)
2868{
2869 int c;
2870 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002871 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002872 BlockDriverState *bs;
2873 const char *filename, *fmt, *output;
2874 int64_t length;
2875 MapEntry curr = { .length = 0 }, next;
2876 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002877 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002878 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002879
2880 fmt = NULL;
2881 output = NULL;
2882 for (;;) {
2883 int option_index = 0;
2884 static const struct option long_options[] = {
2885 {"help", no_argument, 0, 'h'},
2886 {"format", required_argument, 0, 'f'},
2887 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002888 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002889 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002890 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002891 {0, 0, 0, 0}
2892 };
Fam Zheng335e9932017-05-03 00:35:39 +08002893 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002894 long_options, &option_index);
2895 if (c == -1) {
2896 break;
2897 }
2898 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002899 case ':':
2900 missing_argument(argv[optind - 1]);
2901 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002902 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002903 unrecognized_option(argv[optind - 1]);
2904 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002905 case 'h':
2906 help();
2907 break;
2908 case 'f':
2909 fmt = optarg;
2910 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002911 case 'U':
2912 force_share = true;
2913 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002914 case OPTION_OUTPUT:
2915 output = optarg;
2916 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002917 case OPTION_OBJECT: {
2918 QemuOpts *opts;
2919 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2920 optarg, true);
2921 if (!opts) {
2922 return 1;
2923 }
2924 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002925 case OPTION_IMAGE_OPTS:
2926 image_opts = true;
2927 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002928 }
2929 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002930 if (optind != argc - 1) {
2931 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002932 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002933 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002934
2935 if (output && !strcmp(output, "json")) {
2936 output_format = OFORMAT_JSON;
2937 } else if (output && !strcmp(output, "human")) {
2938 output_format = OFORMAT_HUMAN;
2939 } else if (output) {
2940 error_report("--output must be used with human or json as argument.");
2941 return 1;
2942 }
2943
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002944 if (qemu_opts_foreach(&qemu_object_opts,
2945 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002946 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002947 return 1;
2948 }
2949
Fam Zheng335e9932017-05-03 00:35:39 +08002950 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002951 if (!blk) {
2952 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002953 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002954 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002955
2956 if (output_format == OFORMAT_HUMAN) {
2957 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2958 }
2959
Max Reitzf1d3cd72015-02-05 13:58:18 -05002960 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002961 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002962 int64_t offset = curr.start + curr.length;
2963 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002964
2965 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02002966 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002967 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002968
2969 if (ret < 0) {
2970 error_report("Could not read file metadata: %s", strerror(-ret));
2971 goto out;
2972 }
2973
Fam Zheng16b0d552016-01-26 11:59:02 +08002974 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002975 curr.length += next.length;
2976 continue;
2977 }
2978
2979 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05002980 ret = dump_map_entry(output_format, &curr, &next);
2981 if (ret < 0) {
2982 goto out;
2983 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002984 }
2985 curr = next;
2986 }
2987
Eric Blake30065d12019-03-26 13:40:43 -05002988 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002989
2990out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002991 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002992 return ret < 0;
2993}
2994
aliguorif7b4a942009-01-07 17:40:15 +00002995#define SNAPSHOT_LIST 1
2996#define SNAPSHOT_CREATE 2
2997#define SNAPSHOT_APPLY 3
2998#define SNAPSHOT_DELETE 4
2999
Stuart Brady153859b2009-06-07 00:42:17 +01003000static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003001{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003002 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003003 BlockDriverState *bs;
3004 QEMUSnapshotInfo sn;
3005 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003006 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003007 int action = 0;
3008 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003009 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003010 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003011 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003012 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003013
Kevin Wolfce099542016-03-15 13:01:04 +01003014 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003015 /* Parse commandline parameters */
3016 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003017 static const struct option long_options[] = {
3018 {"help", no_argument, 0, 'h'},
3019 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003020 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003021 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003022 {0, 0, 0, 0}
3023 };
Fam Zheng335e9932017-05-03 00:35:39 +08003024 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003025 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003026 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003027 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003028 }
aliguorif7b4a942009-01-07 17:40:15 +00003029 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003030 case ':':
3031 missing_argument(argv[optind - 1]);
3032 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003033 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003034 unrecognized_option(argv[optind - 1]);
3035 break;
aliguorif7b4a942009-01-07 17:40:15 +00003036 case 'h':
3037 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003038 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003039 case 'l':
3040 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003041 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003042 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003043 }
3044 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003045 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003046 break;
3047 case 'a':
3048 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003049 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003050 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003051 }
3052 action = SNAPSHOT_APPLY;
3053 snapshot_name = optarg;
3054 break;
3055 case 'c':
3056 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003057 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003058 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003059 }
3060 action = SNAPSHOT_CREATE;
3061 snapshot_name = optarg;
3062 break;
3063 case 'd':
3064 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003065 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003066 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003067 }
3068 action = SNAPSHOT_DELETE;
3069 snapshot_name = optarg;
3070 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003071 case 'q':
3072 quiet = true;
3073 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003074 case 'U':
3075 force_share = true;
3076 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003077 case OPTION_OBJECT: {
3078 QemuOpts *opts;
3079 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3080 optarg, true);
3081 if (!opts) {
3082 return 1;
3083 }
3084 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003085 case OPTION_IMAGE_OPTS:
3086 image_opts = true;
3087 break;
aliguorif7b4a942009-01-07 17:40:15 +00003088 }
3089 }
3090
Kevin Wolffc11eb22013-08-05 10:53:04 +02003091 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003092 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003093 }
aliguorif7b4a942009-01-07 17:40:15 +00003094 filename = argv[optind++];
3095
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003096 if (qemu_opts_foreach(&qemu_object_opts,
3097 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003098 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003099 return 1;
3100 }
3101
aliguorif7b4a942009-01-07 17:40:15 +00003102 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003103 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3104 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003105 if (!blk) {
3106 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003107 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003108 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003109
3110 /* Perform the requested action */
3111 switch(action) {
3112 case SNAPSHOT_LIST:
3113 dump_snapshots(bs);
3114 break;
3115
3116 case SNAPSHOT_CREATE:
3117 memset(&sn, 0, sizeof(sn));
3118 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3119
3120 qemu_gettimeofday(&tv);
3121 sn.date_sec = tv.tv_sec;
3122 sn.date_nsec = tv.tv_usec * 1000;
3123
3124 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003125 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003126 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003127 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003128 }
aliguorif7b4a942009-01-07 17:40:15 +00003129 break;
3130
3131 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003132 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003133 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003134 error_reportf_err(err, "Could not apply snapshot '%s': ",
3135 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003136 }
aliguorif7b4a942009-01-07 17:40:15 +00003137 break;
3138
3139 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003140 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3141 if (ret < 0) {
3142 error_report("Could not delete snapshot '%s': snapshot not "
3143 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003144 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003145 } else {
3146 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3147 if (ret < 0) {
3148 error_reportf_err(err, "Could not delete snapshot '%s': ",
3149 snapshot_name);
3150 ret = 1;
3151 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003152 }
aliguorif7b4a942009-01-07 17:40:15 +00003153 break;
3154 }
3155
3156 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003157 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003158 if (ret) {
3159 return 1;
3160 }
Stuart Brady153859b2009-06-07 00:42:17 +01003161 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003162}
3163
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003164static int img_rebase(int argc, char **argv)
3165{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003166 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003167 uint8_t *buf_old = NULL;
3168 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003169 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003170 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003171 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3172 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003173 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003174 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003175 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003176 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003177 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003178 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003179 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003180
3181 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003182 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003183 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003184 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003185 out_baseimg = NULL;
3186 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003187 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003188 static const struct option long_options[] = {
3189 {"help", no_argument, 0, 'h'},
3190 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003191 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003192 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003193 {0, 0, 0, 0}
3194 };
Fam Zheng335e9932017-05-03 00:35:39 +08003195 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003196 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003197 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003198 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003199 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003200 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003201 case ':':
3202 missing_argument(argv[optind - 1]);
3203 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003204 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003205 unrecognized_option(argv[optind - 1]);
3206 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003207 case 'h':
3208 help();
3209 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003210 case 'f':
3211 fmt = optarg;
3212 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003213 case 'F':
3214 out_basefmt = optarg;
3215 break;
3216 case 'b':
3217 out_baseimg = optarg;
3218 break;
3219 case 'u':
3220 unsafe = 1;
3221 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003222 case 'p':
3223 progress = 1;
3224 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003225 case 't':
3226 cache = optarg;
3227 break;
Max Reitz40055952014-07-22 22:58:42 +02003228 case 'T':
3229 src_cache = optarg;
3230 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003231 case 'q':
3232 quiet = true;
3233 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003234 case OPTION_OBJECT: {
3235 QemuOpts *opts;
3236 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3237 optarg, true);
3238 if (!opts) {
3239 return 1;
3240 }
3241 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003242 case OPTION_IMAGE_OPTS:
3243 image_opts = true;
3244 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003245 case 'U':
3246 force_share = true;
3247 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003248 }
3249 }
3250
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003251 if (quiet) {
3252 progress = 0;
3253 }
3254
Fam Zhengac1307a2014-04-22 13:36:11 +08003255 if (optind != argc - 1) {
3256 error_exit("Expecting one image file name");
3257 }
3258 if (!unsafe && !out_baseimg) {
3259 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003260 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003261 filename = argv[optind++];
3262
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003263 if (qemu_opts_foreach(&qemu_object_opts,
3264 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003265 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003266 return 1;
3267 }
3268
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003269 qemu_progress_init(progress, 2.0);
3270 qemu_progress_print(0, 100);
3271
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003272 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003273 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003274 if (ret < 0) {
3275 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003276 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003277 }
3278
Kevin Wolfce099542016-03-15 13:01:04 +01003279 src_flags = 0;
3280 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003281 if (ret < 0) {
3282 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003283 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003284 }
3285
Kevin Wolfce099542016-03-15 13:01:04 +01003286 /* The source files are opened read-only, don't care about WCE */
3287 assert((src_flags & BDRV_O_RDWR) == 0);
3288 (void) src_writethrough;
3289
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003290 /*
3291 * Open the images.
3292 *
3293 * Ignore the old backing file for unsafe rebase in case we want to correct
3294 * the reference to a renamed or moved backing file.
3295 */
Fam Zheng335e9932017-05-03 00:35:39 +08003296 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3297 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003298 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003299 ret = -1;
3300 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003301 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003302 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003303
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003304 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003305 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003306 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003307 ret = -1;
3308 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003309 }
3310 }
3311
3312 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003313 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003314 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003315 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003316
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003317 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003318 blk_old_backing = blk_new(qemu_get_aio_context(),
3319 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003320 BLK_PERM_ALL);
3321 ret = blk_insert_bs(blk_old_backing, base_bs,
3322 &local_err);
3323 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003324 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003325 "Could not reuse old backing file '%s': ",
3326 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003327 goto out;
3328 }
3329 } else {
3330 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003331 }
Max Reitz644483d2015-02-05 13:58:17 -05003332
Alex Bligha6166732012-10-16 13:46:18 +01003333 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003334 const char *overlay_filename;
3335 char *out_real_path;
3336
Fam Zheng335e9932017-05-03 00:35:39 +08003337 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003338 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003339 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003340 }
3341 if (force_share) {
3342 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003343 }
3344
Max Reitzf30c66b2019-02-01 20:29:05 +01003345 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003346 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3347 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003348 out_real_path =
3349 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3350 out_baseimg,
3351 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003352 if (local_err) {
3353 error_reportf_err(local_err,
3354 "Could not resolve backing filename: ");
3355 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003356 goto out;
3357 }
3358
Sam Eiderman863cc782019-05-23 19:33:36 +03003359 /*
3360 * Find out whether we rebase an image on top of a previous image
3361 * in its chain.
3362 */
3363 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003364 if (prefix_chain_bs) {
3365 g_free(out_real_path);
Kevin Wolfd861ab32019-04-25 14:25:10 +02003366 blk_new_backing = blk_new(qemu_get_aio_context(),
3367 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003368 BLK_PERM_ALL);
3369 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3370 &local_err);
3371 if (ret < 0) {
3372 error_reportf_err(local_err,
3373 "Could not reuse backing file '%s': ",
3374 out_baseimg);
3375 goto out;
3376 }
3377 } else {
3378 blk_new_backing = blk_new_open(out_real_path, NULL,
3379 options, src_flags, &local_err);
3380 g_free(out_real_path);
3381 if (!blk_new_backing) {
3382 error_reportf_err(local_err,
3383 "Could not open new backing file '%s': ",
3384 out_baseimg);
3385 ret = -1;
3386 goto out;
3387 }
Alex Bligha6166732012-10-16 13:46:18 +01003388 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003389 }
3390 }
3391
3392 /*
3393 * Check each unallocated cluster in the COW file. If it is unallocated,
3394 * accesses go to the backing file. We must therefore compare this cluster
3395 * in the old and new backing file, and if they differ we need to copy it
3396 * from the old backing file into the COW file.
3397 *
3398 * If qemu-img crashes during this step, no harm is done. The content of
3399 * the image is the same as the original one at any time.
3400 */
3401 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003402 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003403 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003404 int64_t new_backing_size = 0;
3405 uint64_t offset;
3406 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003407 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003408
Max Reitzf1d3cd72015-02-05 13:58:18 -05003409 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3410 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003411
Eric Blake41536282017-10-11 22:47:15 -05003412 size = blk_getlength(blk);
3413 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003414 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003415 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003416 ret = -1;
3417 goto out;
3418 }
Max Reitz35ddd932019-05-09 19:52:35 +02003419 if (blk_old_backing) {
3420 old_backing_size = blk_getlength(blk_old_backing);
3421 if (old_backing_size < 0) {
3422 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003423
Max Reitz35ddd932019-05-09 19:52:35 +02003424 bdrv_get_backing_filename(bs, backing_name,
3425 sizeof(backing_name));
3426 error_report("Could not get size of '%s': %s",
3427 backing_name, strerror(-old_backing_size));
3428 ret = -1;
3429 goto out;
3430 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003431 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003432 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003433 new_backing_size = blk_getlength(blk_new_backing);
3434 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003435 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003436 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003437 ret = -1;
3438 goto out;
3439 }
Alex Bligha6166732012-10-16 13:46:18 +01003440 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003441
Eric Blake41536282017-10-11 22:47:15 -05003442 if (size != 0) {
3443 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003444 }
3445
Eric Blake41536282017-10-11 22:47:15 -05003446 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003447 bool buf_old_is_zero = false;
3448
Eric Blake41536282017-10-11 22:47:15 -05003449 /* How many bytes can we handle with the next read? */
3450 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003451
3452 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003453 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003454 if (ret < 0) {
3455 error_report("error while reading image metadata: %s",
3456 strerror(-ret));
3457 goto out;
3458 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003459 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003460 continue;
3461 }
3462
Sam Eiderman863cc782019-05-23 19:33:36 +03003463 if (prefix_chain_bs) {
3464 /*
3465 * If cluster wasn't changed since prefix_chain, we don't need
3466 * to take action
3467 */
3468 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3469 offset, n, &n);
3470 if (ret < 0) {
3471 error_report("error while reading image metadata: %s",
3472 strerror(-ret));
3473 goto out;
3474 }
3475 if (!ret) {
3476 continue;
3477 }
3478 }
3479
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003480 /*
3481 * Read old and new backing file and take into consideration that
3482 * backing files may be smaller than the COW image.
3483 */
Eric Blake41536282017-10-11 22:47:15 -05003484 if (offset >= old_backing_size) {
3485 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003486 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003487 } else {
Eric Blake41536282017-10-11 22:47:15 -05003488 if (offset + n > old_backing_size) {
3489 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003490 }
3491
Eric Blake41536282017-10-11 22:47:15 -05003492 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003493 if (ret < 0) {
3494 error_report("error while reading from old backing file");
3495 goto out;
3496 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003497 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003498
Eric Blake41536282017-10-11 22:47:15 -05003499 if (offset >= new_backing_size || !blk_new_backing) {
3500 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003501 } else {
Eric Blake41536282017-10-11 22:47:15 -05003502 if (offset + n > new_backing_size) {
3503 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003504 }
3505
Eric Blake41536282017-10-11 22:47:15 -05003506 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003507 if (ret < 0) {
3508 error_report("error while reading from new backing file");
3509 goto out;
3510 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003511 }
3512
3513 /* If they differ, we need to write to the COW file */
3514 uint64_t written = 0;
3515
Eric Blake41536282017-10-11 22:47:15 -05003516 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003517 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003518
Eric Blake41536282017-10-11 22:47:15 -05003519 if (compare_buffers(buf_old + written, buf_new + written,
3520 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003521 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003522 if (buf_old_is_zero) {
3523 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3524 } else {
3525 ret = blk_pwrite(blk, offset + written,
3526 buf_old + written, pnum, 0);
3527 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003528 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003529 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003530 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003531 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003532 }
3533 }
3534
3535 written += pnum;
3536 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003537 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003538 }
3539 }
3540
3541 /*
3542 * Change the backing file. All clusters that are different from the old
3543 * backing file are overwritten in the COW file now, so the visible content
3544 * doesn't change when we switch the backing file.
3545 */
Alex Bligha6166732012-10-16 13:46:18 +01003546 if (out_baseimg && *out_baseimg) {
3547 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3548 } else {
3549 ret = bdrv_change_backing_file(bs, NULL, NULL);
3550 }
3551
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003552 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003553 error_report("Could not change the backing file to '%s': No "
3554 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003555 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003556 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003557 out_baseimg, strerror(-ret));
3558 }
3559
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003560 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003561 /*
3562 * TODO At this point it is possible to check if any clusters that are
3563 * allocated in the COW file are the same in the backing file. If so, they
3564 * could be dropped from the COW file. Don't do this before switching the
3565 * backing file, in case of a crash this would lead to corruption.
3566 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003567out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003568 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003569 /* Cleanup */
3570 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003571 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003572 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003573 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003574 qemu_vfree(buf_old);
3575 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003576
Markus Armbruster26f54e92014-10-07 13:59:04 +02003577 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003578 if (ret) {
3579 return 1;
3580 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003581 return 0;
3582}
3583
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003584static int img_resize(int argc, char **argv)
3585{
Markus Armbruster6750e792015-02-12 17:43:08 +01003586 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003587 int c, ret, relative;
3588 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003589 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003590 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003591 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003592 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003593 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003594
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003595 static QemuOptsList resize_options = {
3596 .name = "resize_options",
3597 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3598 .desc = {
3599 {
3600 .name = BLOCK_OPT_SIZE,
3601 .type = QEMU_OPT_SIZE,
3602 .help = "Virtual disk size"
3603 }, {
3604 /* end of list */
3605 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003606 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003607 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003608 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003609 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003610
Kevin Wolfe80fec72011-04-29 10:58:12 +02003611 /* Remove size from argv manually so that negative numbers are not treated
3612 * as options by getopt. */
3613 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003614 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003615 return 1;
3616 }
3617
3618 size = argv[--argc];
3619
3620 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003621 fmt = NULL;
3622 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003623 static const struct option long_options[] = {
3624 {"help", no_argument, 0, 'h'},
3625 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003626 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003627 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003628 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003629 {0, 0, 0, 0}
3630 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003631 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003632 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003633 if (c == -1) {
3634 break;
3635 }
3636 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003637 case ':':
3638 missing_argument(argv[optind - 1]);
3639 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003640 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003641 unrecognized_option(argv[optind - 1]);
3642 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003643 case 'h':
3644 help();
3645 break;
3646 case 'f':
3647 fmt = optarg;
3648 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003649 case 'q':
3650 quiet = true;
3651 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003652 case OPTION_OBJECT: {
3653 QemuOpts *opts;
3654 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3655 optarg, true);
3656 if (!opts) {
3657 return 1;
3658 }
3659 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003660 case OPTION_IMAGE_OPTS:
3661 image_opts = true;
3662 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003663 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003664 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003665 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003666 if (prealloc == PREALLOC_MODE__MAX) {
3667 error_report("Invalid preallocation mode '%s'", optarg);
3668 return 1;
3669 }
3670 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003671 case OPTION_SHRINK:
3672 shrink = true;
3673 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003674 }
3675 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003676 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003677 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003678 }
3679 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003680
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003681 if (qemu_opts_foreach(&qemu_object_opts,
3682 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003683 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003684 return 1;
3685 }
3686
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003687 /* Choose grow, shrink, or absolute resize mode */
3688 switch (size[0]) {
3689 case '+':
3690 relative = 1;
3691 size++;
3692 break;
3693 case '-':
3694 relative = -1;
3695 size++;
3696 break;
3697 default:
3698 relative = 0;
3699 break;
3700 }
3701
3702 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003703 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003704 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003705 if (err) {
3706 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003707 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003708 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003709 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003710 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003711 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3712 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003713
Max Reitzefaa7c42016-03-16 19:54:38 +01003714 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003715 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3716 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003717 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003718 ret = -1;
3719 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003720 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003721
Max Reitzdc5f6902017-06-13 22:20:55 +02003722 current_size = blk_getlength(blk);
3723 if (current_size < 0) {
3724 error_report("Failed to inquire current image length: %s",
3725 strerror(-current_size));
3726 ret = -1;
3727 goto out;
3728 }
3729
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003730 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003731 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003732 } else {
3733 total_size = n;
3734 }
3735 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003736 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003737 ret = -1;
3738 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003739 }
3740
Max Reitzdc5f6902017-06-13 22:20:55 +02003741 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3742 error_report("Preallocation can only be used for growing images");
3743 ret = -1;
3744 goto out;
3745 }
3746
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003747 if (total_size < current_size && !shrink) {
3748 warn_report("Shrinking an image will delete all data beyond the "
3749 "shrunken image's end. Before performing such an "
3750 "operation, make sure there is no important data there.");
3751
3752 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3753 error_report(
3754 "Use the --shrink option to perform a shrink operation.");
3755 ret = -1;
3756 goto out;
3757 } else {
3758 warn_report("Using the --shrink option will suppress this message. "
3759 "Note that future versions of qemu-img may refuse to "
3760 "shrink images without this option.");
3761 }
3762 }
3763
Max Reitzdc5f6902017-06-13 22:20:55 +02003764 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003765 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003766 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003767 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003768 }
Max Reitz5279b302018-04-21 18:39:57 +02003769
3770 new_size = blk_getlength(blk);
3771 if (new_size < 0) {
3772 error_report("Failed to verify truncated image length: %s",
3773 strerror(-new_size));
3774 ret = -1;
3775 goto out;
3776 }
3777
3778 /* Some block drivers implement a truncation method, but only so
3779 * the user can cause qemu to refresh the image's size from disk.
3780 * The idea is that the user resizes the image outside of qemu and
3781 * then invokes block_resize to inform qemu about it.
3782 * (This includes iscsi and file-posix for device files.)
3783 * Of course, that is not the behavior someone invoking
3784 * qemu-img resize would find useful, so we catch that behavior
3785 * here and tell the user. */
3786 if (new_size != total_size && new_size == current_size) {
3787 error_report("Image was not resized; resizing may not be supported "
3788 "for this image");
3789 ret = -1;
3790 goto out;
3791 }
3792
3793 if (new_size != total_size) {
3794 warn_report("Image should have been resized to %" PRIi64
3795 " bytes, but was resized to %" PRIi64 " bytes",
3796 total_size, new_size);
3797 }
3798
3799 qprintf(quiet, "Image resized.\n");
3800
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003801out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003802 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003803 if (ret) {
3804 return 1;
3805 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003806 return 0;
3807}
3808
Max Reitz76a3a342014-10-27 11:12:51 +01003809static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003810 int64_t offset, int64_t total_work_size,
3811 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003812{
3813 qemu_progress_print(100.f * offset / total_work_size, 0);
3814}
3815
Max Reitz51641352018-05-09 23:00:20 +02003816static int print_amend_option_help(const char *format)
3817{
3818 BlockDriver *drv;
3819
3820 /* Find driver and parse its options */
3821 drv = bdrv_find_format(format);
3822 if (!drv) {
3823 error_report("Unknown file format '%s'", format);
3824 return 1;
3825 }
3826
3827 if (!drv->bdrv_amend_options) {
3828 error_report("Format driver '%s' does not support option amendment",
3829 format);
3830 return 1;
3831 }
3832
3833 /* Every driver supporting amendment must have create_opts */
3834 assert(drv->create_opts);
3835
3836 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003837 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003838 printf("\nNote that not all of these options may be amendable.\n");
3839 return 0;
3840}
3841
Max Reitz6f176b42013-09-03 10:09:50 +02003842static int img_amend(int argc, char **argv)
3843{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003844 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003845 int c, ret = 0;
3846 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003847 QemuOptsList *create_opts = NULL;
3848 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003849 const char *fmt = NULL, *filename, *cache;
3850 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003851 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003852 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003853 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003854 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003855 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003856
Max Reitzbd39e6e2014-07-22 22:58:43 +02003857 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003858 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003859 static const struct option long_options[] = {
3860 {"help", no_argument, 0, 'h'},
3861 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003862 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003863 {0, 0, 0, 0}
3864 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003865 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003866 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003867 if (c == -1) {
3868 break;
3869 }
3870
3871 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003872 case ':':
3873 missing_argument(argv[optind - 1]);
3874 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003875 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003876 unrecognized_option(argv[optind - 1]);
3877 break;
3878 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003879 help();
3880 break;
3881 case 'o':
3882 if (!is_valid_option_list(optarg)) {
3883 error_report("Invalid option list: %s", optarg);
3884 ret = -1;
3885 goto out_no_progress;
3886 }
3887 if (!options) {
3888 options = g_strdup(optarg);
3889 } else {
3890 char *old_options = options;
3891 options = g_strdup_printf("%s,%s", options, optarg);
3892 g_free(old_options);
3893 }
3894 break;
3895 case 'f':
3896 fmt = optarg;
3897 break;
3898 case 't':
3899 cache = optarg;
3900 break;
3901 case 'p':
3902 progress = true;
3903 break;
3904 case 'q':
3905 quiet = true;
3906 break;
3907 case OPTION_OBJECT:
3908 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3909 optarg, true);
3910 if (!opts) {
3911 ret = -1;
3912 goto out_no_progress;
3913 }
3914 break;
3915 case OPTION_IMAGE_OPTS:
3916 image_opts = true;
3917 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003918 }
3919 }
3920
Max Reitz6f176b42013-09-03 10:09:50 +02003921 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003922 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003923 }
3924
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003925 if (qemu_opts_foreach(&qemu_object_opts,
3926 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003927 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003928 ret = -1;
3929 goto out_no_progress;
3930 }
3931
Max Reitz76a3a342014-10-27 11:12:51 +01003932 if (quiet) {
3933 progress = false;
3934 }
3935 qemu_progress_init(progress, 1.0);
3936
Kevin Wolfa283cb62014-02-21 16:24:07 +01003937 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3938 if (fmt && has_help_option(options)) {
3939 /* If a format is explicitly specified (and possibly no filename is
3940 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003941 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003942 goto out;
3943 }
3944
3945 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003946 error_report("Expecting one image file name");
3947 ret = -1;
3948 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003949 }
Max Reitz6f176b42013-09-03 10:09:50 +02003950
Kevin Wolfce099542016-03-15 13:01:04 +01003951 flags = BDRV_O_RDWR;
3952 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003953 if (ret < 0) {
3954 error_report("Invalid cache option: %s", cache);
3955 goto out;
3956 }
3957
Fam Zheng335e9932017-05-03 00:35:39 +08003958 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3959 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003960 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003961 ret = -1;
3962 goto out;
3963 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003964 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003965
3966 fmt = bs->drv->format_name;
3967
Kevin Wolf626f84f2014-02-21 16:24:06 +01003968 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003969 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003970 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003971 goto out;
3972 }
3973
Max Reitz1f996682018-05-09 23:00:17 +02003974 if (!bs->drv->bdrv_amend_options) {
3975 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003976 fmt);
3977 ret = -1;
3978 goto out;
3979 }
3980
Max Reitz1f996682018-05-09 23:00:17 +02003981 /* Every driver supporting amendment must have create_opts */
3982 assert(bs->drv->create_opts);
3983
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003984 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003985 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003986 qemu_opts_do_parse(opts, options, NULL, &err);
3987 if (err) {
3988 error_report_err(err);
3989 ret = -1;
3990 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003991 }
3992
Max Reitz76a3a342014-10-27 11:12:51 +01003993 /* In case the driver does not call amend_status_cb() */
3994 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003995 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003996 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003997 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003998 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003999 goto out;
4000 }
4001
4002out:
Max Reitz76a3a342014-10-27 11:12:51 +01004003 qemu_progress_end();
4004
Max Reitze814dff2015-08-20 16:00:38 -07004005out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004006 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004007 qemu_opts_del(opts);
4008 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004009 g_free(options);
4010
Max Reitz6f176b42013-09-03 10:09:50 +02004011 if (ret) {
4012 return 1;
4013 }
4014 return 0;
4015}
4016
Kevin Wolfb6133b82014-08-05 14:17:13 +02004017typedef struct BenchData {
4018 BlockBackend *blk;
4019 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004020 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004021 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004022 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004023 int nrreq;
4024 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004025 int flush_interval;
4026 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004027 uint8_t *buf;
4028 QEMUIOVector *qiov;
4029
4030 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004031 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004032 uint64_t offset;
4033} BenchData;
4034
Kevin Wolf55d539c2016-06-03 13:59:41 +02004035static void bench_undrained_flush_cb(void *opaque, int ret)
4036{
4037 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004038 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004039 exit(EXIT_FAILURE);
4040 }
4041}
4042
Kevin Wolfb6133b82014-08-05 14:17:13 +02004043static void bench_cb(void *opaque, int ret)
4044{
4045 BenchData *b = opaque;
4046 BlockAIOCB *acb;
4047
4048 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004049 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004050 exit(EXIT_FAILURE);
4051 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004052
4053 if (b->in_flush) {
4054 /* Just finished a flush with drained queue: Start next requests */
4055 assert(b->in_flight == 0);
4056 b->in_flush = false;
4057 } else if (b->in_flight > 0) {
4058 int remaining = b->n - b->in_flight;
4059
Kevin Wolfb6133b82014-08-05 14:17:13 +02004060 b->n--;
4061 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004062
4063 /* Time for flush? Drain queue if requested, then flush */
4064 if (b->flush_interval && remaining % b->flush_interval == 0) {
4065 if (!b->in_flight || !b->drain_on_flush) {
4066 BlockCompletionFunc *cb;
4067
4068 if (b->drain_on_flush) {
4069 b->in_flush = true;
4070 cb = bench_cb;
4071 } else {
4072 cb = bench_undrained_flush_cb;
4073 }
4074
4075 acb = blk_aio_flush(b->blk, cb, b);
4076 if (!acb) {
4077 error_report("Failed to issue flush request");
4078 exit(EXIT_FAILURE);
4079 }
4080 }
4081 if (b->drain_on_flush) {
4082 return;
4083 }
4084 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004085 }
4086
4087 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004088 int64_t offset = b->offset;
4089 /* blk_aio_* might look for completed I/Os and kick bench_cb
4090 * again, so make sure this operation is counted by in_flight
4091 * and b->offset is ready for the next submission.
4092 */
4093 b->in_flight++;
4094 b->offset += b->step;
4095 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004096 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004097 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004098 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004099 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004100 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004101 if (!acb) {
4102 error_report("Failed to issue request");
4103 exit(EXIT_FAILURE);
4104 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004105 }
4106}
4107
4108static int img_bench(int argc, char **argv)
4109{
4110 int c, ret = 0;
4111 const char *fmt = NULL, *filename;
4112 bool quiet = false;
4113 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004114 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004115 int count = 75000;
4116 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004117 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004118 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004119 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004120 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004121 int flush_interval = 0;
4122 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004123 int64_t image_size;
4124 BlockBackend *blk = NULL;
4125 BenchData data = {};
4126 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004127 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004128 struct timeval t1, t2;
4129 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004130 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004131 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004132
4133 for (;;) {
4134 static const struct option long_options[] = {
4135 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004136 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004137 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004138 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004139 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004140 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004141 {0, 0, 0, 0}
4142 };
Fam Zheng335e9932017-05-03 00:35:39 +08004143 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004144 if (c == -1) {
4145 break;
4146 }
4147
4148 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004149 case ':':
4150 missing_argument(argv[optind - 1]);
4151 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004152 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004153 unrecognized_option(argv[optind - 1]);
4154 break;
4155 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004156 help();
4157 break;
4158 case 'c':
4159 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004160 unsigned long res;
4161
4162 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004163 error_report("Invalid request count specified");
4164 return 1;
4165 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004166 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004167 break;
4168 }
4169 case 'd':
4170 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004171 unsigned long res;
4172
4173 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004174 error_report("Invalid queue depth specified");
4175 return 1;
4176 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004177 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004178 break;
4179 }
4180 case 'f':
4181 fmt = optarg;
4182 break;
4183 case 'n':
4184 flags |= BDRV_O_NATIVE_AIO;
4185 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004186 case 'o':
4187 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004188 offset = cvtnum(optarg);
4189 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004190 error_report("Invalid offset specified");
4191 return 1;
4192 }
4193 break;
4194 }
4195 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004196 case 'q':
4197 quiet = true;
4198 break;
4199 case 's':
4200 {
4201 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004202
Markus Armbruster606caa02017-02-21 21:14:04 +01004203 sval = cvtnum(optarg);
4204 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004205 error_report("Invalid buffer size specified");
4206 return 1;
4207 }
4208
4209 bufsize = sval;
4210 break;
4211 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004212 case 'S':
4213 {
4214 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004215
Markus Armbruster606caa02017-02-21 21:14:04 +01004216 sval = cvtnum(optarg);
4217 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004218 error_report("Invalid step size specified");
4219 return 1;
4220 }
4221
4222 step = sval;
4223 break;
4224 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004225 case 't':
4226 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4227 if (ret < 0) {
4228 error_report("Invalid cache mode");
4229 ret = -1;
4230 goto out;
4231 }
4232 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004233 case 'w':
4234 flags |= BDRV_O_RDWR;
4235 is_write = true;
4236 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004237 case 'U':
4238 force_share = true;
4239 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004240 case OPTION_PATTERN:
4241 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004242 unsigned long res;
4243
4244 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004245 error_report("Invalid pattern byte specified");
4246 return 1;
4247 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004248 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004249 break;
4250 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004251 case OPTION_FLUSH_INTERVAL:
4252 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004253 unsigned long res;
4254
4255 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004256 error_report("Invalid flush interval specified");
4257 return 1;
4258 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004259 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004260 break;
4261 }
4262 case OPTION_NO_DRAIN:
4263 drain_on_flush = false;
4264 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004265 case OPTION_IMAGE_OPTS:
4266 image_opts = true;
4267 break;
4268 }
4269 }
4270
4271 if (optind != argc - 1) {
4272 error_exit("Expecting one image file name");
4273 }
4274 filename = argv[argc - 1];
4275
Kevin Wolf55d539c2016-06-03 13:59:41 +02004276 if (!is_write && flush_interval) {
4277 error_report("--flush-interval is only available in write tests");
4278 ret = -1;
4279 goto out;
4280 }
4281 if (flush_interval && flush_interval < depth) {
4282 error_report("Flush interval can't be smaller than depth");
4283 ret = -1;
4284 goto out;
4285 }
4286
Fam Zheng335e9932017-05-03 00:35:39 +08004287 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4288 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004289 if (!blk) {
4290 ret = -1;
4291 goto out;
4292 }
4293
4294 image_size = blk_getlength(blk);
4295 if (image_size < 0) {
4296 ret = image_size;
4297 goto out;
4298 }
4299
4300 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004301 .blk = blk,
4302 .image_size = image_size,
4303 .bufsize = bufsize,
4304 .step = step ?: bufsize,
4305 .nrreq = depth,
4306 .n = count,
4307 .offset = offset,
4308 .write = is_write,
4309 .flush_interval = flush_interval,
4310 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004311 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004312 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004313 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004314 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004315 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004316 if (flush_interval) {
4317 printf("Sending flush every %d requests\n", flush_interval);
4318 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004319
Fam Zheng79d46582018-01-16 14:08:58 +08004320 buf_size = data.nrreq * data.bufsize;
4321 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004322 memset(data.buf, pattern, data.nrreq * data.bufsize);
4323
Fam Zheng79d46582018-01-16 14:08:58 +08004324 blk_register_buf(blk, data.buf, buf_size);
4325
Kevin Wolfb6133b82014-08-05 14:17:13 +02004326 data.qiov = g_new(QEMUIOVector, data.nrreq);
4327 for (i = 0; i < data.nrreq; i++) {
4328 qemu_iovec_init(&data.qiov[i], 1);
4329 qemu_iovec_add(&data.qiov[i],
4330 data.buf + i * data.bufsize, data.bufsize);
4331 }
4332
4333 gettimeofday(&t1, NULL);
4334 bench_cb(&data, 0);
4335
4336 while (data.n > 0) {
4337 main_loop_wait(false);
4338 }
4339 gettimeofday(&t2, NULL);
4340
4341 printf("Run completed in %3.3f seconds.\n",
4342 (t2.tv_sec - t1.tv_sec)
4343 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4344
4345out:
Fam Zheng79d46582018-01-16 14:08:58 +08004346 if (data.buf) {
4347 blk_unregister_buf(blk, data.buf);
4348 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004349 qemu_vfree(data.buf);
4350 blk_unref(blk);
4351
4352 if (ret) {
4353 return 1;
4354 }
4355 return 0;
4356}
4357
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004358#define C_BS 01
4359#define C_COUNT 02
4360#define C_IF 04
4361#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004362#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004363
4364struct DdInfo {
4365 unsigned int flags;
4366 int64_t count;
4367};
4368
4369struct DdIo {
4370 int bsz; /* Block size */
4371 char *filename;
4372 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004373 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004374};
4375
4376struct DdOpts {
4377 const char *name;
4378 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4379 unsigned int flag;
4380};
4381
4382static int img_dd_bs(const char *arg,
4383 struct DdIo *in, struct DdIo *out,
4384 struct DdInfo *dd)
4385{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004386 int64_t res;
4387
Markus Armbruster606caa02017-02-21 21:14:04 +01004388 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004389
Markus Armbruster606caa02017-02-21 21:14:04 +01004390 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004391 error_report("invalid number: '%s'", arg);
4392 return 1;
4393 }
4394 in->bsz = out->bsz = res;
4395
4396 return 0;
4397}
4398
4399static int img_dd_count(const char *arg,
4400 struct DdIo *in, struct DdIo *out,
4401 struct DdInfo *dd)
4402{
Markus Armbruster606caa02017-02-21 21:14:04 +01004403 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004404
Markus Armbruster606caa02017-02-21 21:14:04 +01004405 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004406 error_report("invalid number: '%s'", arg);
4407 return 1;
4408 }
4409
4410 return 0;
4411}
4412
4413static int img_dd_if(const char *arg,
4414 struct DdIo *in, struct DdIo *out,
4415 struct DdInfo *dd)
4416{
4417 in->filename = g_strdup(arg);
4418
4419 return 0;
4420}
4421
4422static int img_dd_of(const char *arg,
4423 struct DdIo *in, struct DdIo *out,
4424 struct DdInfo *dd)
4425{
4426 out->filename = g_strdup(arg);
4427
4428 return 0;
4429}
4430
Reda Sallahif7c15532016-08-10 16:16:09 +02004431static int img_dd_skip(const char *arg,
4432 struct DdIo *in, struct DdIo *out,
4433 struct DdInfo *dd)
4434{
Markus Armbruster606caa02017-02-21 21:14:04 +01004435 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004436
Markus Armbruster606caa02017-02-21 21:14:04 +01004437 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004438 error_report("invalid number: '%s'", arg);
4439 return 1;
4440 }
4441
4442 return 0;
4443}
4444
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004445static int img_dd(int argc, char **argv)
4446{
4447 int ret = 0;
4448 char *arg = NULL;
4449 char *tmp;
4450 BlockDriver *drv = NULL, *proto_drv = NULL;
4451 BlockBackend *blk1 = NULL, *blk2 = NULL;
4452 QemuOpts *opts = NULL;
4453 QemuOptsList *create_opts = NULL;
4454 Error *local_err = NULL;
4455 bool image_opts = false;
4456 int c, i;
4457 const char *out_fmt = "raw";
4458 const char *fmt = NULL;
4459 int64_t size = 0;
4460 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004461 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004462 struct DdInfo dd = {
4463 .flags = 0,
4464 .count = 0,
4465 };
4466 struct DdIo in = {
4467 .bsz = 512, /* Block size is by default 512 bytes */
4468 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004469 .buf = NULL,
4470 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004471 };
4472 struct DdIo out = {
4473 .bsz = 512,
4474 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004475 .buf = NULL,
4476 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004477 };
4478
4479 const struct DdOpts options[] = {
4480 { "bs", img_dd_bs, C_BS },
4481 { "count", img_dd_count, C_COUNT },
4482 { "if", img_dd_if, C_IF },
4483 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004484 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004485 { NULL, NULL, 0 }
4486 };
4487 const struct option long_options[] = {
4488 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004489 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004490 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004491 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004492 { 0, 0, 0, 0 }
4493 };
4494
Fam Zheng335e9932017-05-03 00:35:39 +08004495 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004496 if (c == EOF) {
4497 break;
4498 }
4499 switch (c) {
4500 case 'O':
4501 out_fmt = optarg;
4502 break;
4503 case 'f':
4504 fmt = optarg;
4505 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004506 case ':':
4507 missing_argument(argv[optind - 1]);
4508 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004509 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004510 unrecognized_option(argv[optind - 1]);
4511 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004512 case 'h':
4513 help();
4514 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004515 case 'U':
4516 force_share = true;
4517 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004518 case OPTION_OBJECT:
4519 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004520 ret = -1;
4521 goto out;
4522 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004523 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004524 case OPTION_IMAGE_OPTS:
4525 image_opts = true;
4526 break;
4527 }
4528 }
4529
4530 for (i = optind; i < argc; i++) {
4531 int j;
4532 arg = g_strdup(argv[i]);
4533
4534 tmp = strchr(arg, '=');
4535 if (tmp == NULL) {
4536 error_report("unrecognized operand %s", arg);
4537 ret = -1;
4538 goto out;
4539 }
4540
4541 *tmp++ = '\0';
4542
4543 for (j = 0; options[j].name != NULL; j++) {
4544 if (!strcmp(arg, options[j].name)) {
4545 break;
4546 }
4547 }
4548 if (options[j].name == NULL) {
4549 error_report("unrecognized operand %s", arg);
4550 ret = -1;
4551 goto out;
4552 }
4553
4554 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4555 ret = -1;
4556 goto out;
4557 }
4558 dd.flags |= options[j].flag;
4559 g_free(arg);
4560 arg = NULL;
4561 }
4562
4563 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4564 error_report("Must specify both input and output files");
4565 ret = -1;
4566 goto out;
4567 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004568
4569 if (qemu_opts_foreach(&qemu_object_opts,
4570 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004571 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004572 ret = -1;
4573 goto out;
4574 }
4575
Fam Zheng335e9932017-05-03 00:35:39 +08004576 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4577 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004578
4579 if (!blk1) {
4580 ret = -1;
4581 goto out;
4582 }
4583
4584 drv = bdrv_find_format(out_fmt);
4585 if (!drv) {
4586 error_report("Unknown file format");
4587 ret = -1;
4588 goto out;
4589 }
4590 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4591
4592 if (!proto_drv) {
4593 error_report_err(local_err);
4594 ret = -1;
4595 goto out;
4596 }
4597 if (!drv->create_opts) {
4598 error_report("Format driver '%s' does not support image creation",
4599 drv->format_name);
4600 ret = -1;
4601 goto out;
4602 }
4603 if (!proto_drv->create_opts) {
4604 error_report("Protocol driver '%s' does not support image creation",
4605 proto_drv->format_name);
4606 ret = -1;
4607 goto out;
4608 }
4609 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4610 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4611
4612 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4613
4614 size = blk_getlength(blk1);
4615 if (size < 0) {
4616 error_report("Failed to get size for '%s'", in.filename);
4617 ret = -1;
4618 goto out;
4619 }
4620
4621 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4622 dd.count * in.bsz < size) {
4623 size = dd.count * in.bsz;
4624 }
4625
Reda Sallahif7c15532016-08-10 16:16:09 +02004626 /* Overflow means the specified offset is beyond input image's size */
4627 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4628 size < in.bsz * in.offset)) {
4629 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4630 } else {
4631 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4632 size - in.bsz * in.offset, &error_abort);
4633 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004634
4635 ret = bdrv_create(drv, out.filename, opts, &local_err);
4636 if (ret < 0) {
4637 error_reportf_err(local_err,
4638 "%s: error while creating output image: ",
4639 out.filename);
4640 ret = -1;
4641 goto out;
4642 }
4643
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004644 /* TODO, we can't honour --image-opts for the target,
4645 * since it needs to be given in a format compatible
4646 * with the bdrv_create() call above which does not
4647 * support image-opts style.
4648 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004649 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004650 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004651
4652 if (!blk2) {
4653 ret = -1;
4654 goto out;
4655 }
4656
Reda Sallahif7c15532016-08-10 16:16:09 +02004657 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4658 size < in.offset * in.bsz)) {
4659 /* We give a warning if the skip option is bigger than the input
4660 * size and create an empty output disk image (i.e. like dd(1)).
4661 */
4662 error_report("%s: cannot skip to specified offset", in.filename);
4663 in_pos = size;
4664 } else {
4665 in_pos = in.offset * in.bsz;
4666 }
4667
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004668 in.buf = g_new(uint8_t, in.bsz);
4669
Reda Sallahif7c15532016-08-10 16:16:09 +02004670 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004671 int in_ret, out_ret;
4672
4673 if (in_pos + in.bsz > size) {
4674 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4675 } else {
4676 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4677 }
4678 if (in_ret < 0) {
4679 error_report("error while reading from input image file: %s",
4680 strerror(-in_ret));
4681 ret = -1;
4682 goto out;
4683 }
4684 in_pos += in_ret;
4685
4686 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4687
4688 if (out_ret < 0) {
4689 error_report("error while writing to output image file: %s",
4690 strerror(-out_ret));
4691 ret = -1;
4692 goto out;
4693 }
4694 out_pos += out_ret;
4695 }
4696
4697out:
4698 g_free(arg);
4699 qemu_opts_del(opts);
4700 qemu_opts_free(create_opts);
4701 blk_unref(blk1);
4702 blk_unref(blk2);
4703 g_free(in.filename);
4704 g_free(out.filename);
4705 g_free(in.buf);
4706 g_free(out.buf);
4707
4708 if (ret) {
4709 return 1;
4710 }
4711 return 0;
4712}
4713
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004714static void dump_json_block_measure_info(BlockMeasureInfo *info)
4715{
4716 QString *str;
4717 QObject *obj;
4718 Visitor *v = qobject_output_visitor_new(&obj);
4719
4720 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4721 visit_complete(v, &obj);
4722 str = qobject_to_json_pretty(obj);
4723 assert(str != NULL);
4724 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004725 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004726 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004727 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004728}
4729
4730static int img_measure(int argc, char **argv)
4731{
4732 static const struct option long_options[] = {
4733 {"help", no_argument, 0, 'h'},
4734 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4735 {"object", required_argument, 0, OPTION_OBJECT},
4736 {"output", required_argument, 0, OPTION_OUTPUT},
4737 {"size", required_argument, 0, OPTION_SIZE},
4738 {"force-share", no_argument, 0, 'U'},
4739 {0, 0, 0, 0}
4740 };
4741 OutputFormat output_format = OFORMAT_HUMAN;
4742 BlockBackend *in_blk = NULL;
4743 BlockDriver *drv;
4744 const char *filename = NULL;
4745 const char *fmt = NULL;
4746 const char *out_fmt = "raw";
4747 char *options = NULL;
4748 char *snapshot_name = NULL;
4749 bool force_share = false;
4750 QemuOpts *opts = NULL;
4751 QemuOpts *object_opts = NULL;
4752 QemuOpts *sn_opts = NULL;
4753 QemuOptsList *create_opts = NULL;
4754 bool image_opts = false;
4755 uint64_t img_size = UINT64_MAX;
4756 BlockMeasureInfo *info = NULL;
4757 Error *local_err = NULL;
4758 int ret = 1;
4759 int c;
4760
4761 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4762 long_options, NULL)) != -1) {
4763 switch (c) {
4764 case '?':
4765 case 'h':
4766 help();
4767 break;
4768 case 'f':
4769 fmt = optarg;
4770 break;
4771 case 'O':
4772 out_fmt = optarg;
4773 break;
4774 case 'o':
4775 if (!is_valid_option_list(optarg)) {
4776 error_report("Invalid option list: %s", optarg);
4777 goto out;
4778 }
4779 if (!options) {
4780 options = g_strdup(optarg);
4781 } else {
4782 char *old_options = options;
4783 options = g_strdup_printf("%s,%s", options, optarg);
4784 g_free(old_options);
4785 }
4786 break;
4787 case 'l':
4788 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4789 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4790 optarg, false);
4791 if (!sn_opts) {
4792 error_report("Failed in parsing snapshot param '%s'",
4793 optarg);
4794 goto out;
4795 }
4796 } else {
4797 snapshot_name = optarg;
4798 }
4799 break;
4800 case 'U':
4801 force_share = true;
4802 break;
4803 case OPTION_OBJECT:
4804 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4805 optarg, true);
4806 if (!object_opts) {
4807 goto out;
4808 }
4809 break;
4810 case OPTION_IMAGE_OPTS:
4811 image_opts = true;
4812 break;
4813 case OPTION_OUTPUT:
4814 if (!strcmp(optarg, "json")) {
4815 output_format = OFORMAT_JSON;
4816 } else if (!strcmp(optarg, "human")) {
4817 output_format = OFORMAT_HUMAN;
4818 } else {
4819 error_report("--output must be used with human or json "
4820 "as argument.");
4821 goto out;
4822 }
4823 break;
4824 case OPTION_SIZE:
4825 {
4826 int64_t sval;
4827
4828 sval = cvtnum(optarg);
4829 if (sval < 0) {
4830 if (sval == -ERANGE) {
4831 error_report("Image size must be less than 8 EiB!");
4832 } else {
4833 error_report("Invalid image size specified! You may use "
4834 "k, M, G, T, P or E suffixes for ");
4835 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4836 "petabytes and exabytes.");
4837 }
4838 goto out;
4839 }
4840 img_size = (uint64_t)sval;
4841 }
4842 break;
4843 }
4844 }
4845
4846 if (qemu_opts_foreach(&qemu_object_opts,
4847 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004848 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004849 goto out;
4850 }
4851
4852 if (argc - optind > 1) {
4853 error_report("At most one filename argument is allowed.");
4854 goto out;
4855 } else if (argc - optind == 1) {
4856 filename = argv[optind];
4857 }
4858
4859 if (!filename &&
4860 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4861 error_report("--object, --image-opts, -f, and -l "
4862 "require a filename argument.");
4863 goto out;
4864 }
4865 if (filename && img_size != UINT64_MAX) {
4866 error_report("--size N cannot be used together with a filename.");
4867 goto out;
4868 }
4869 if (!filename && img_size == UINT64_MAX) {
4870 error_report("Either --size N or one filename must be specified.");
4871 goto out;
4872 }
4873
4874 if (filename) {
4875 in_blk = img_open(image_opts, filename, fmt, 0,
4876 false, false, force_share);
4877 if (!in_blk) {
4878 goto out;
4879 }
4880
4881 if (sn_opts) {
4882 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4883 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4884 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4885 &local_err);
4886 } else if (snapshot_name != NULL) {
4887 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4888 snapshot_name, &local_err);
4889 }
4890 if (local_err) {
4891 error_reportf_err(local_err, "Failed to load snapshot: ");
4892 goto out;
4893 }
4894 }
4895
4896 drv = bdrv_find_format(out_fmt);
4897 if (!drv) {
4898 error_report("Unknown file format '%s'", out_fmt);
4899 goto out;
4900 }
4901 if (!drv->create_opts) {
4902 error_report("Format driver '%s' does not support image creation",
4903 drv->format_name);
4904 goto out;
4905 }
4906
4907 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4908 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4909 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4910 if (options) {
4911 qemu_opts_do_parse(opts, options, NULL, &local_err);
4912 if (local_err) {
4913 error_report_err(local_err);
4914 error_report("Invalid options for file format '%s'", out_fmt);
4915 goto out;
4916 }
4917 }
4918 if (img_size != UINT64_MAX) {
4919 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4920 }
4921
4922 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4923 if (local_err) {
4924 error_report_err(local_err);
4925 goto out;
4926 }
4927
4928 if (output_format == OFORMAT_HUMAN) {
4929 printf("required size: %" PRIu64 "\n", info->required);
4930 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4931 } else {
4932 dump_json_block_measure_info(info);
4933 }
4934
4935 ret = 0;
4936
4937out:
4938 qapi_free_BlockMeasureInfo(info);
4939 qemu_opts_del(object_opts);
4940 qemu_opts_del(opts);
4941 qemu_opts_del(sn_opts);
4942 qemu_opts_free(create_opts);
4943 g_free(options);
4944 blk_unref(in_blk);
4945 return ret;
4946}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004947
Anthony Liguoric227f092009-10-01 16:12:16 -05004948static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004949#define DEF(option, callback, arg_string) \
4950 { option, callback },
4951#include "qemu-img-cmds.h"
4952#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004953 { NULL, NULL, },
4954};
4955
bellardea2384d2004-08-01 21:59:26 +00004956int main(int argc, char **argv)
4957{
Anthony Liguoric227f092009-10-01 16:12:16 -05004958 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004959 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004960 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004961 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004962 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004963 static const struct option long_options[] = {
4964 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004965 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004966 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004967 {0, 0, 0, 0}
4968 };
bellardea2384d2004-08-01 21:59:26 +00004969
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004970#ifdef CONFIG_POSIX
4971 signal(SIGPIPE, SIG_IGN);
4972#endif
4973
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01004974 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004975 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004976 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004977
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004978 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004979 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004980 exit(EXIT_FAILURE);
4981 }
4982
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004983 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004984
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004985 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004986 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004987 if (argc < 2) {
4988 error_exit("Not enough arguments");
4989 }
Stuart Brady153859b2009-06-07 00:42:17 +01004990
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004991 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004992 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004993 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004994
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004995 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004996 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004997 case ':':
4998 missing_argument(argv[optind - 1]);
4999 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005000 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005001 unrecognized_option(argv[optind - 1]);
5002 return 0;
5003 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005004 help();
5005 return 0;
5006 case 'V':
5007 printf(QEMU_IMG_VERSION);
5008 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005009 case 'T':
5010 g_free(trace_file);
5011 trace_file = trace_opt_parse(optarg);
5012 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005013 }
bellardea2384d2004-08-01 21:59:26 +00005014 }
Stuart Brady153859b2009-06-07 00:42:17 +01005015
Denis V. Lunev10985132016-06-17 17:44:13 +03005016 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005017
Denis V. Lunev10985132016-06-17 17:44:13 +03005018 /* reset getopt_long scanning */
5019 argc -= optind;
5020 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005021 return 0;
5022 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005023 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005024 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005025
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005026 if (!trace_init_backends()) {
5027 exit(1);
5028 }
5029 trace_init_file(trace_file);
5030 qemu_set_log(LOG_TRACE);
5031
Denis V. Lunev10985132016-06-17 17:44:13 +03005032 /* find the command */
5033 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5034 if (!strcmp(cmdname, cmd->name)) {
5035 return cmd->handler(argc, argv);
5036 }
5037 }
Jeff Cody7db16892014-04-25 17:02:32 -04005038
Stuart Brady153859b2009-06-07 00:42:17 +01005039 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005040 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005041}