blob: e15e617256e050d0efd4edb85d4068c70a096da1 [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;
Max Reitz3d96cb92019-05-07 22:35:02 +02001584 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001585 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001586 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001587 size_t cluster_sectors;
1588 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001589 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001590 int running_coroutines;
1591 Coroutine *co[MAX_COROUTINES];
1592 int64_t wait_sector_num[MAX_COROUTINES];
1593 CoMutex lock;
1594 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001595} ImgConvertState;
1596
Peter Lieven2d9187b2017-02-28 13:40:07 +01001597static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1598 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001599{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001600 *src_cur = 0;
1601 *src_cur_offset = 0;
1602 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1603 *src_cur_offset += s->src_sectors[*src_cur];
1604 (*src_cur)++;
1605 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001606 }
1607}
1608
1609static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1610{
Eric Blake31826642017-10-11 22:47:08 -05001611 int64_t src_cur_offset;
1612 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001613 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001614
Peter Lieven2d9187b2017-02-28 13:40:07 +01001615 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001616
1617 assert(s->total_sectors > sector_num);
1618 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1619
Max Reitz351c8ef2018-05-01 18:57:49 +02001620 if (s->target_backing_sectors >= 0) {
1621 if (sector_num >= s->target_backing_sectors) {
1622 post_backing_zero = s->unallocated_blocks_are_zero;
1623 } else if (sector_num + n > s->target_backing_sectors) {
1624 /* Split requests around target_backing_sectors (because
1625 * starting from there, zeros are handled differently) */
1626 n = s->target_backing_sectors - sector_num;
1627 }
1628 }
1629
Kevin Wolf690c7302015-03-19 13:33:32 +01001630 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001631 int64_t count = n * BDRV_SECTOR_SIZE;
1632
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001633 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001634
1635 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1636 (sector_num - src_cur_offset) *
1637 BDRV_SECTOR_SIZE,
1638 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001639 } else {
Eric Blake31826642017-10-11 22:47:08 -05001640 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1641 (sector_num - src_cur_offset) *
1642 BDRV_SECTOR_SIZE,
1643 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001644 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001645 if (ret < 0) {
Eric Blake2058c2a2019-03-23 16:26:38 -05001646 error_report("error while reading block status of sector %" PRId64
1647 ": %s", sector_num, strerror(-ret));
Kevin Wolf690c7302015-03-19 13:33:32 +01001648 return ret;
1649 }
Eric Blake31826642017-10-11 22:47:08 -05001650 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001651
1652 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001653 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001654 } else if (ret & BDRV_BLOCK_DATA) {
1655 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001656 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001657 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001658 }
1659
1660 s->sector_next_status = sector_num + n;
1661 }
1662
1663 n = MIN(n, s->sector_next_status - sector_num);
1664 if (s->status == BLK_DATA) {
1665 n = MIN(n, s->buf_sectors);
1666 }
1667
1668 /* We need to write complete clusters for compressed images, so if an
1669 * unallocated area is shorter than that, we must consider the whole
1670 * cluster allocated. */
1671 if (s->compressed) {
1672 if (n < s->cluster_sectors) {
1673 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1674 s->status = BLK_DATA;
1675 } else {
1676 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1677 }
1678 }
1679
1680 return n;
1681}
1682
Peter Lieven2d9187b2017-02-28 13:40:07 +01001683static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1684 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001685{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001686 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001687
Kevin Wolf690c7302015-03-19 13:33:32 +01001688 assert(nb_sectors <= s->buf_sectors);
1689 while (nb_sectors > 0) {
1690 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001691 int src_cur;
1692 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001693
1694 /* In the case of compression with multiple source files, we can get a
1695 * nb_sectors that spreads into the next part. So we must be able to
1696 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001697 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1698 blk = s->src[src_cur];
1699 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001700
Peter Lieven2d9187b2017-02-28 13:40:07 +01001701 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
Peter Lieven2d9187b2017-02-28 13:40:07 +01001702
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001703 ret = blk_co_pread(
Peter Lieven2d9187b2017-02-28 13:40:07 +01001704 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001705 n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001706 if (ret < 0) {
1707 return ret;
1708 }
1709
1710 sector_num += n;
1711 nb_sectors -= n;
1712 buf += n * BDRV_SECTOR_SIZE;
1713 }
1714
1715 return 0;
1716}
1717
Peter Lieven2d9187b2017-02-28 13:40:07 +01001718
1719static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1720 int nb_sectors, uint8_t *buf,
1721 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001722{
1723 int ret;
1724
1725 while (nb_sectors > 0) {
1726 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001727 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1728
Peter Lieven2d9187b2017-02-28 13:40:07 +01001729 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001730 case BLK_BACKING_FILE:
1731 /* If we have a backing file, leave clusters unallocated that are
1732 * unallocated in the source image, so that the backing file is
1733 * visible at the respective offset. */
1734 assert(s->target_has_backing);
1735 break;
1736
1737 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001738 /* If we're told to keep the target fully allocated (-S 0) or there
1739 * is real non-zero data, we must write it. Otherwise we can treat
1740 * it as zero sectors.
1741 * Compressed clusters need to be written as a whole, so in that
1742 * case we can only save the write if the buffer is completely
1743 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001744 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001745 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001746 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1747 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001748 (s->compressed &&
1749 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001750 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001751 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1752 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001753 if (ret < 0) {
1754 return ret;
1755 }
1756 break;
1757 }
1758 /* fall-through */
1759
1760 case BLK_ZERO:
1761 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001762 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001763 break;
1764 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001765 ret = blk_co_pwrite_zeroes(s->target,
1766 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001767 n << BDRV_SECTOR_BITS,
1768 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001769 if (ret < 0) {
1770 return ret;
1771 }
1772 break;
1773 }
1774
1775 sector_num += n;
1776 nb_sectors -= n;
1777 buf += n * BDRV_SECTOR_SIZE;
1778 }
1779
1780 return 0;
1781}
1782
Fam Zhengee5306d2018-06-01 17:26:48 +08001783static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1784 int nb_sectors)
1785{
1786 int n, ret;
1787
1788 while (nb_sectors > 0) {
1789 BlockBackend *blk;
1790 int src_cur;
1791 int64_t bs_sectors, src_cur_offset;
1792 int64_t offset;
1793
1794 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1795 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1796 blk = s->src[src_cur];
1797 bs_sectors = s->src_sectors[src_cur];
1798
1799 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1800
1801 ret = blk_co_copy_range(blk, offset, s->target,
1802 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001803 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001804 if (ret < 0) {
1805 return ret;
1806 }
1807
1808 sector_num += n;
1809 nb_sectors -= n;
1810 }
1811 return 0;
1812}
1813
Peter Lieven2d9187b2017-02-28 13:40:07 +01001814static void coroutine_fn convert_co_do_copy(void *opaque)
1815{
1816 ImgConvertState *s = opaque;
1817 uint8_t *buf = NULL;
1818 int ret, i;
1819 int index = -1;
1820
1821 for (i = 0; i < s->num_coroutines; i++) {
1822 if (s->co[i] == qemu_coroutine_self()) {
1823 index = i;
1824 break;
1825 }
1826 }
1827 assert(index >= 0);
1828
1829 s->running_coroutines++;
1830 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1831
1832 while (1) {
1833 int n;
1834 int64_t sector_num;
1835 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001836 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001837
1838 qemu_co_mutex_lock(&s->lock);
1839 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1840 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001841 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001842 }
1843 n = convert_iteration_sectors(s, s->sector_num);
1844 if (n < 0) {
1845 qemu_co_mutex_unlock(&s->lock);
1846 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001847 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001848 }
1849 /* save current sector and allocation status to local variables */
1850 sector_num = s->sector_num;
1851 status = s->status;
1852 if (!s->min_sparse && s->status == BLK_ZERO) {
1853 n = MIN(n, s->buf_sectors);
1854 }
1855 /* increment global sector counter so that other coroutines can
1856 * already continue reading beyond this request */
1857 s->sector_num += n;
1858 qemu_co_mutex_unlock(&s->lock);
1859
1860 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1861 s->allocated_done += n;
1862 qemu_progress_print(100.0 * s->allocated_done /
1863 s->allocated_sectors, 0);
1864 }
1865
Fam Zhengee5306d2018-06-01 17:26:48 +08001866retry:
1867 copy_range = s->copy_range && s->status == BLK_DATA;
1868 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001869 ret = convert_co_read(s, sector_num, n, buf);
1870 if (ret < 0) {
1871 error_report("error while reading sector %" PRId64
1872 ": %s", sector_num, strerror(-ret));
1873 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001874 }
1875 } else if (!s->min_sparse && status == BLK_ZERO) {
1876 status = BLK_DATA;
1877 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1878 }
1879
1880 if (s->wr_in_order) {
1881 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001882 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001883 s->wait_sector_num[index] = sector_num;
1884 qemu_coroutine_yield();
1885 }
1886 s->wait_sector_num[index] = -1;
1887 }
1888
Anton Nefedovb91127e2017-04-26 11:33:15 +03001889 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001890 if (copy_range) {
1891 ret = convert_co_copy_range(s, sector_num, n);
1892 if (ret) {
1893 s->copy_range = false;
1894 goto retry;
1895 }
1896 } else {
1897 ret = convert_co_write(s, sector_num, n, buf, status);
1898 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001899 if (ret < 0) {
1900 error_report("error while writing sector %" PRId64
1901 ": %s", sector_num, strerror(-ret));
1902 s->ret = ret;
1903 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001904 }
1905
1906 if (s->wr_in_order) {
1907 /* reenter the coroutine that might have waited
1908 * for this write to complete */
1909 s->wr_offs = sector_num + n;
1910 for (i = 0; i < s->num_coroutines; i++) {
1911 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1912 /*
1913 * A -> B -> A cannot occur because A has
1914 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1915 * B will never enter A during this time window.
1916 */
1917 qemu_coroutine_enter(s->co[i]);
1918 break;
1919 }
1920 }
1921 }
1922 }
1923
Peter Lieven2d9187b2017-02-28 13:40:07 +01001924 qemu_vfree(buf);
1925 s->co[index] = NULL;
1926 s->running_coroutines--;
1927 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1928 /* the convert job finished successfully */
1929 s->ret = 0;
1930 }
1931}
1932
Kevin Wolf690c7302015-03-19 13:33:32 +01001933static int convert_do_copy(ImgConvertState *s)
1934{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001935 int ret, i, n;
1936 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001937
1938 /* Check whether we have zero initialisation or can get it efficiently */
1939 s->has_zero_init = s->min_sparse && !s->target_has_backing
1940 ? bdrv_has_zero_init(blk_bs(s->target))
1941 : false;
1942
1943 if (!s->has_zero_init && !s->target_has_backing &&
1944 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1945 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001946 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001947 if (ret == 0) {
1948 s->has_zero_init = true;
1949 }
1950 }
1951
1952 /* Allocate buffer for copied data. For compressed images, only one cluster
1953 * can be copied at a time. */
1954 if (s->compressed) {
1955 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1956 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001957 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001958 }
1959 s->buf_sectors = s->cluster_sectors;
1960 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001961
Kevin Wolf690c7302015-03-19 13:33:32 +01001962 while (sector_num < s->total_sectors) {
1963 n = convert_iteration_sectors(s, sector_num);
1964 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001965 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001966 }
Max Reitzaad15de2016-03-24 23:33:57 +01001967 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1968 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001969 s->allocated_sectors += n;
1970 }
1971 sector_num += n;
1972 }
1973
1974 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001975 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001976 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001977
Peter Lieven2d9187b2017-02-28 13:40:07 +01001978 qemu_co_mutex_init(&s->lock);
1979 for (i = 0; i < s->num_coroutines; i++) {
1980 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1981 s->wait_sector_num[i] = -1;
1982 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001983 }
1984
Anton Nefedovb91127e2017-04-26 11:33:15 +03001985 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001986 main_loop_wait(false);
1987 }
1988
1989 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001990 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001991 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001992 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001993 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001994 }
1995 }
1996
Peter Lieven2d9187b2017-02-28 13:40:07 +01001997 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001998}
1999
Peter Lieven6360ab22018-07-13 09:15:39 +02002000#define MAX_BUF_SECTORS 32768
2001
bellardea2384d2004-08-01 21:59:26 +00002002static int img_convert(int argc, char **argv)
2003{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002004 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002005 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002006 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2007 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002008 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002009 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002010 BlockDriverState *out_bs;
2011 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002012 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002013 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002014 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002015 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002016 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002017 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002018 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002019 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002020 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002021
Peter Lieven9fd77f92017-04-21 11:11:55 +02002022 ImgConvertState s = (ImgConvertState) {
2023 /* Need at least 4k of zeros for sparse detection */
2024 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002025 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002026 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2027 .wr_in_order = true,
2028 .num_coroutines = 8,
2029 };
2030
bellardea2384d2004-08-01 21:59:26 +00002031 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002032 static const struct option long_options[] = {
2033 {"help", no_argument, 0, 'h'},
2034 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002035 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002036 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002037 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002038 {0, 0, 0, 0}
2039 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002040 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002041 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002042 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002043 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002044 }
bellardea2384d2004-08-01 21:59:26 +00002045 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002046 case ':':
2047 missing_argument(argv[optind - 1]);
2048 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002049 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002050 unrecognized_option(argv[optind - 1]);
2051 break;
bellardea2384d2004-08-01 21:59:26 +00002052 case 'h':
2053 help();
2054 break;
2055 case 'f':
2056 fmt = optarg;
2057 break;
2058 case 'O':
2059 out_fmt = optarg;
2060 break;
thsf58c7b32008-06-05 21:53:49 +00002061 case 'B':
2062 out_baseimg = optarg;
2063 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002064 case 'C':
2065 s.copy_range = true;
2066 break;
bellardea2384d2004-08-01 21:59:26 +00002067 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002068 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002069 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002070 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002071 if (!is_valid_option_list(optarg)) {
2072 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002073 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002074 }
2075 if (!options) {
2076 options = g_strdup(optarg);
2077 } else {
2078 char *old_options = options;
2079 options = g_strdup_printf("%s,%s", options, optarg);
2080 g_free(old_options);
2081 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002082 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002083 case 'l':
2084 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002085 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2086 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002087 if (!sn_opts) {
2088 error_report("Failed in parsing snapshot param '%s'",
2089 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002090 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002091 }
2092 } else {
2093 snapshot_name = optarg;
2094 }
2095 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002096 case 'S':
2097 {
2098 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002099
2100 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002101 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2102 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2103 error_report("Invalid buffer size for sparse output specified. "
2104 "Valid sizes are multiples of %llu up to %llu. Select "
2105 "0 to disable sparse detection (fully allocates output).",
2106 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002107 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002108 }
2109
Peter Lieven9fd77f92017-04-21 11:11:55 +02002110 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002111 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002112 break;
2113 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002114 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002115 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002116 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002117 case 't':
2118 cache = optarg;
2119 break;
Max Reitz40055952014-07-22 22:58:42 +02002120 case 'T':
2121 src_cache = optarg;
2122 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002123 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002124 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002125 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002126 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002127 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002128 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002129 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002130 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2131 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002132 error_report("Invalid number of coroutines. Allowed number of"
2133 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002134 goto fail_getopt;
2135 }
2136 break;
2137 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002138 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002139 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002140 case 'U':
2141 force_share = true;
2142 break;
Max Reitz3258b912017-04-26 15:46:47 +02002143 case OPTION_OBJECT: {
2144 QemuOpts *object_opts;
2145 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2146 optarg, true);
2147 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002148 goto fail_getopt;
2149 }
2150 break;
Max Reitz3258b912017-04-26 15:46:47 +02002151 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002152 case OPTION_IMAGE_OPTS:
2153 image_opts = true;
2154 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002155 case OPTION_TARGET_IMAGE_OPTS:
2156 tgt_image_opts = true;
2157 break;
bellardea2384d2004-08-01 21:59:26 +00002158 }
2159 }
ths3b46e622007-09-17 08:09:54 +00002160
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002161 if (!out_fmt && !tgt_image_opts) {
2162 out_fmt = "raw";
2163 }
2164
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002165 if (qemu_opts_foreach(&qemu_object_opts,
2166 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002167 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002168 goto fail_getopt;
2169 }
2170
Fam Zhenge11ce122018-07-27 11:34:01 +08002171 if (s.compressed && s.copy_range) {
2172 error_report("Cannot enable copy offloading when -c is used");
2173 goto fail_getopt;
2174 }
2175
2176 if (explict_min_sparse && s.copy_range) {
2177 error_report("Cannot enable copy offloading when -S is used");
2178 goto fail_getopt;
2179 }
2180
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002181 if (tgt_image_opts && !skip_create) {
2182 error_report("--target-image-opts requires use of -n flag");
2183 goto fail_getopt;
2184 }
2185
Peter Lieven9fd77f92017-04-21 11:11:55 +02002186 s.src_num = argc - optind - 1;
2187 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2188
2189 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002190 if (out_fmt) {
2191 ret = print_block_option_help(out_filename, out_fmt);
2192 goto fail_getopt;
2193 } else {
2194 error_report("Option help requires a format be specified");
2195 goto fail_getopt;
2196 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002197 }
2198
2199 if (s.src_num < 1) {
2200 error_report("Must specify image file name");
2201 goto fail_getopt;
2202 }
2203
2204
Peter Lieven9fd77f92017-04-21 11:11:55 +02002205 /* ret is still -EINVAL until here */
2206 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2207 if (ret < 0) {
2208 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002209 goto fail_getopt;
2210 }
2211
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002212 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002213 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002214 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002215 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002216 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002217 qemu_progress_print(0, 100);
2218
Peter Lieven9fd77f92017-04-21 11:11:55 +02002219 s.src = g_new0(BlockBackend *, s.src_num);
2220 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002221
Peter Lieven9fd77f92017-04-21 11:11:55 +02002222 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2223 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002224 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002225 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002226 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002227 ret = -1;
2228 goto out;
2229 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002230 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2231 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002232 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002233 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002234 ret = -1;
2235 goto out;
2236 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002237 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002238 }
bellardea2384d2004-08-01 21:59:26 +00002239
Wenchao Xiaef806542013-12-04 17:10:57 +08002240 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002241 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002242 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2243 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2244 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002245 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002246 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002247 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002248 ret = -1;
2249 goto out;
2250 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002251
Peter Lieven9fd77f92017-04-21 11:11:55 +02002252 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2253 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002254 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002255 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002256 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002257 ret = -1;
2258 goto out;
edison51ef6722010-09-21 19:58:41 -07002259 }
2260
Max Reitz2e024cd2015-02-11 09:58:46 -05002261 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002262 /* Find driver and parse its options */
2263 drv = bdrv_find_format(out_fmt);
2264 if (!drv) {
2265 error_report("Unknown file format '%s'", out_fmt);
2266 ret = -1;
2267 goto out;
2268 }
2269
2270 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2271 if (!proto_drv) {
2272 error_report_err(local_err);
2273 ret = -1;
2274 goto out;
2275 }
2276
Max Reitz2e024cd2015-02-11 09:58:46 -05002277 if (!drv->create_opts) {
2278 error_report("Format driver '%s' does not support image creation",
2279 drv->format_name);
2280 ret = -1;
2281 goto out;
2282 }
Max Reitzf75613c2014-12-02 18:32:46 +01002283
Max Reitz2e024cd2015-02-11 09:58:46 -05002284 if (!proto_drv->create_opts) {
2285 error_report("Protocol driver '%s' does not support image creation",
2286 proto_drv->format_name);
2287 ret = -1;
2288 goto out;
2289 }
Max Reitzf75613c2014-12-02 18:32:46 +01002290
Max Reitz2e024cd2015-02-11 09:58:46 -05002291 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2292 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002293
Max Reitz2e024cd2015-02-11 09:58:46 -05002294 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002295 if (options) {
2296 qemu_opts_do_parse(opts, options, NULL, &local_err);
2297 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002298 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002299 ret = -1;
2300 goto out;
2301 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002302 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002303
Peter Lieven9fd77f92017-04-21 11:11:55 +02002304 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002305 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002306 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2307 if (ret < 0) {
2308 goto out;
2309 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002310 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002311
Kevin Wolfa18953f2010-10-14 15:46:04 +02002312 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002313 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002314 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002315 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002316 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002317 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002318
Max Reitz48758a82017-04-26 15:46:48 +02002319 if (s.src_num > 1 && out_baseimg) {
2320 error_report("Having a backing file for the target makes no sense when "
2321 "concatenating multiple input images");
2322 ret = -1;
2323 goto out;
2324 }
2325
Kevin Wolfefa84d42009-05-18 16:42:12 +02002326 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002327 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002328 bool encryption =
2329 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002330 const char *encryptfmt =
2331 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002332 const char *preallocation =
2333 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002334
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002335 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002336 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002337 ret = -1;
2338 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002339 }
2340
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002341 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002342 error_report("Compression and encryption not supported at "
2343 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002344 ret = -1;
2345 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002346 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002347
Chunyan Liu83d05212014-06-05 17:20:51 +08002348 if (preallocation
2349 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002350 {
2351 error_report("Compression and preallocation not supported at "
2352 "the same time");
2353 ret = -1;
2354 goto out;
2355 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002356 }
2357
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002358 /*
2359 * The later open call will need any decryption secrets, and
2360 * bdrv_create() will purge "opts", so extract them now before
2361 * they are lost.
2362 */
2363 if (!skip_create) {
2364 open_opts = qdict_new();
2365 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2366 }
2367
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002368 if (!skip_create) {
2369 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002370 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002371 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002372 error_reportf_err(local_err, "%s: error while converting %s: ",
2373 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002374 goto out;
bellardea2384d2004-08-01 21:59:26 +00002375 }
2376 }
ths3b46e622007-09-17 08:09:54 +00002377
Peter Lieven9fd77f92017-04-21 11:11:55 +02002378 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002379 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002380 if (ret < 0) {
2381 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002382 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002383 }
2384
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002385 if (skip_create) {
2386 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002387 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002388 } else {
2389 /* TODO ultimately we should allow --target-image-opts
2390 * to be used even when -n is not given.
2391 * That has to wait for bdrv_create to be improved
2392 * to allow filenames in option syntax
2393 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002394 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002395 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002396 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002397 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002398 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002399 ret = -1;
2400 goto out;
2401 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002402 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002403
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002404 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2405 error_report("Compression not supported for this file format");
2406 ret = -1;
2407 goto out;
2408 }
2409
Eric Blake5def6b82016-06-23 16:37:19 -06002410 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002411 * or discard_alignment of the out_bs is greater. Limit to
2412 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2413 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002414 MAX(s.buf_sectors,
2415 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2416 out_bs->bl.pdiscard_alignment >>
2417 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002418
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002419 /* try to align the write requests to the destination to avoid unnecessary
2420 * RMW cycles. */
2421 s.alignment = MAX(pow2floor(s.min_sparse),
2422 DIV_ROUND_UP(out_bs->bl.request_alignment,
2423 BDRV_SECTOR_SIZE));
2424 assert(is_power_of_2(s.alignment));
2425
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002426 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002427 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002428 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002429 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002430 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002431 ret = -1;
2432 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002433 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002434 error_report("output file is smaller than input file");
2435 ret = -1;
2436 goto out;
2437 }
2438 }
2439
Max Reitz351c8ef2018-05-01 18:57:49 +02002440 if (s.target_has_backing) {
2441 /* Errors are treated as "backing length unknown" (which means
2442 * s.target_backing_sectors has to be negative, which it will
2443 * be automatically). The backing file length is used only
2444 * for optimizations, so such a case is not fatal. */
2445 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2446 } else {
2447 s.target_backing_sectors = -1;
2448 }
2449
Peter Lieven24f833c2013-11-27 11:07:07 +01002450 ret = bdrv_get_info(out_bs, &bdi);
2451 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002452 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002453 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002454 goto out;
2455 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002456 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002457 s.compressed = s.compressed || bdi.needs_compressed_writes;
2458 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002459 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002460 }
2461
Peter Lieven9fd77f92017-04-21 11:11:55 +02002462 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002463out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002464 if (!ret) {
2465 qemu_progress_print(100, 0);
2466 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002467 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002468 qemu_opts_del(opts);
2469 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002470 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002471 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002472 blk_unref(s.target);
2473 if (s.src) {
2474 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2475 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002476 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002477 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002478 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002479 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002480fail_getopt:
2481 g_free(options);
2482
Peter Lieven9fd77f92017-04-21 11:11:55 +02002483 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002484}
2485
bellard57d1a2b2004-08-03 21:15:11 +00002486
bellardfaea38e2006-08-05 21:31:00 +00002487static void dump_snapshots(BlockDriverState *bs)
2488{
2489 QEMUSnapshotInfo *sn_tab, *sn;
2490 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002491
2492 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2493 if (nb_sns <= 0)
2494 return;
2495 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002496 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002497 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002498 for(i = 0; i < nb_sns; i++) {
2499 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002500 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002501 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002502 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002503 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002504}
2505
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002506static void dump_json_image_info_list(ImageInfoList *list)
2507{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002508 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002509 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002510 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002511
2512 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2513 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002514 str = qobject_to_json_pretty(obj);
2515 assert(str != NULL);
2516 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002517 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002518 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002519 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002520}
2521
Benoît Canetc054b3f2012-09-05 13:09:02 +02002522static void dump_json_image_info(ImageInfo *info)
2523{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002524 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002525 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002526 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002527
2528 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2529 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002530 str = qobject_to_json_pretty(obj);
2531 assert(str != NULL);
2532 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002533 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002534 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002535 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002536}
2537
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002538static void dump_human_image_info_list(ImageInfoList *list)
2539{
2540 ImageInfoList *elem;
2541 bool delim = false;
2542
2543 for (elem = list; elem; elem = elem->next) {
2544 if (delim) {
2545 printf("\n");
2546 }
2547 delim = true;
2548
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002549 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002550 }
2551}
2552
2553static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2554{
2555 return strcmp(a, b) == 0;
2556}
2557
2558/**
2559 * Open an image file chain and return an ImageInfoList
2560 *
2561 * @filename: topmost image filename
2562 * @fmt: topmost image format (may be NULL to autodetect)
2563 * @chain: true - enumerate entire backing file chain
2564 * false - only topmost image file
2565 *
2566 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2567 * image file. If there was an error a message will have been printed to
2568 * stderr.
2569 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002570static ImageInfoList *collect_image_info_list(bool image_opts,
2571 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002572 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002573 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002574{
2575 ImageInfoList *head = NULL;
2576 ImageInfoList **last = &head;
2577 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002578 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002579
2580 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2581
2582 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002583 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002584 BlockDriverState *bs;
2585 ImageInfo *info;
2586 ImageInfoList *elem;
2587
2588 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2589 error_report("Backing file '%s' creates an infinite loop.",
2590 filename);
2591 goto err;
2592 }
2593 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2594
Max Reitzefaa7c42016-03-16 19:54:38 +01002595 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002596 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2597 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002598 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002599 goto err;
2600 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002601 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002602
Wenchao Xia43526ec2013-06-06 12:27:58 +08002603 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002604 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002605 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002606 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002607 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002608 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002609
2610 elem = g_new0(ImageInfoList, 1);
2611 elem->value = info;
2612 *last = elem;
2613 last = &elem->next;
2614
Markus Armbruster26f54e92014-10-07 13:59:04 +02002615 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002616
2617 filename = fmt = NULL;
2618 if (chain) {
2619 if (info->has_full_backing_filename) {
2620 filename = info->full_backing_filename;
2621 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002622 error_report("Could not determine absolute backing filename,"
2623 " but backing filename '%s' present",
2624 info->backing_filename);
2625 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002626 }
2627 if (info->has_backing_filename_format) {
2628 fmt = info->backing_filename_format;
2629 }
2630 }
2631 }
2632 g_hash_table_destroy(filenames);
2633 return head;
2634
2635err:
2636 qapi_free_ImageInfoList(head);
2637 g_hash_table_destroy(filenames);
2638 return NULL;
2639}
2640
Benoît Canetc054b3f2012-09-05 13:09:02 +02002641static int img_info(int argc, char **argv)
2642{
2643 int c;
2644 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002645 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002646 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002647 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002648 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002649 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002650
bellardea2384d2004-08-01 21:59:26 +00002651 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002652 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002653 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002654 int option_index = 0;
2655 static const struct option long_options[] = {
2656 {"help", no_argument, 0, 'h'},
2657 {"format", required_argument, 0, 'f'},
2658 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002659 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002660 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002661 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002662 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002663 {0, 0, 0, 0}
2664 };
Fam Zheng335e9932017-05-03 00:35:39 +08002665 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002666 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002667 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002668 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002669 }
bellardea2384d2004-08-01 21:59:26 +00002670 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002671 case ':':
2672 missing_argument(argv[optind - 1]);
2673 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002674 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002675 unrecognized_option(argv[optind - 1]);
2676 break;
bellardea2384d2004-08-01 21:59:26 +00002677 case 'h':
2678 help();
2679 break;
2680 case 'f':
2681 fmt = optarg;
2682 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002683 case 'U':
2684 force_share = true;
2685 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002686 case OPTION_OUTPUT:
2687 output = optarg;
2688 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002689 case OPTION_BACKING_CHAIN:
2690 chain = true;
2691 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002692 case OPTION_OBJECT: {
2693 QemuOpts *opts;
2694 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2695 optarg, true);
2696 if (!opts) {
2697 return 1;
2698 }
2699 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002700 case OPTION_IMAGE_OPTS:
2701 image_opts = true;
2702 break;
bellardea2384d2004-08-01 21:59:26 +00002703 }
2704 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002705 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002706 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002707 }
bellardea2384d2004-08-01 21:59:26 +00002708 filename = argv[optind++];
2709
Benoît Canetc054b3f2012-09-05 13:09:02 +02002710 if (output && !strcmp(output, "json")) {
2711 output_format = OFORMAT_JSON;
2712 } else if (output && !strcmp(output, "human")) {
2713 output_format = OFORMAT_HUMAN;
2714 } else if (output) {
2715 error_report("--output must be used with human or json as argument.");
2716 return 1;
2717 }
2718
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002719 if (qemu_opts_foreach(&qemu_object_opts,
2720 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002721 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002722 return 1;
2723 }
2724
Fam Zheng335e9932017-05-03 00:35:39 +08002725 list = collect_image_info_list(image_opts, filename, fmt, chain,
2726 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002727 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002728 return 1;
2729 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002730
Benoît Canetc054b3f2012-09-05 13:09:02 +02002731 switch (output_format) {
2732 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002733 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002734 break;
2735 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002736 if (chain) {
2737 dump_json_image_info_list(list);
2738 } else {
2739 dump_json_image_info(list->value);
2740 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002741 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002742 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002743
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002744 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002745 return 0;
2746}
2747
Eric Blake30065d12019-03-26 13:40:43 -05002748static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2749 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002750{
2751 switch (output_format) {
2752 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002753 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002754 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002755 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002756 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002757 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002758 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002759 e->start, e->length,
2760 e->has_offset ? e->offset : 0,
2761 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002762 }
2763 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2764 * Modify the flags here to allow more coalescing.
2765 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002766 if (next && (!next->data || next->zero)) {
2767 next->data = false;
2768 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002769 }
2770 break;
2771 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002772 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2773 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002774 (e->start == 0 ? "[" : ",\n"),
2775 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002776 e->zero ? "true" : "false",
2777 e->data ? "true" : "false");
2778 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002779 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002780 }
2781 putchar('}');
2782
2783 if (!next) {
2784 printf("]\n");
2785 }
2786 break;
2787 }
Eric Blake30065d12019-03-26 13:40:43 -05002788 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002789}
2790
Eric Blake5e344dd2017-10-11 22:47:02 -05002791static int get_block_status(BlockDriverState *bs, int64_t offset,
2792 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002793{
Eric Blake237d78f2017-10-11 22:47:03 -05002794 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002795 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002796 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002797 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002798 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002799 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002800
2801 /* As an optimization, we could cache the current range of unallocated
2802 * clusters in each file of the chain, and avoid querying the same
2803 * range repeatedly.
2804 */
2805
2806 depth = 0;
2807 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002808 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002809 if (ret < 0) {
2810 return ret;
2811 }
Eric Blake237d78f2017-10-11 22:47:03 -05002812 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002813 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2814 break;
2815 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002816 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002817 if (bs == NULL) {
2818 ret = 0;
2819 break;
2820 }
2821
2822 depth++;
2823 }
2824
John Snow28756452016-02-05 13:12:33 -05002825 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2826
Max Reitzf30c66b2019-02-01 20:29:05 +01002827 if (file && has_offset) {
2828 bdrv_refresh_filename(file);
2829 filename = file->filename;
2830 }
2831
John Snow28756452016-02-05 13:12:33 -05002832 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002833 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002834 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002835 .data = !!(ret & BDRV_BLOCK_DATA),
2836 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002837 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002838 .has_offset = has_offset,
2839 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002840 .has_filename = filename,
2841 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002842 };
2843
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002844 return 0;
2845}
2846
Fam Zheng16b0d552016-01-26 11:59:02 +08002847static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2848{
2849 if (curr->length == 0) {
2850 return false;
2851 }
2852 if (curr->zero != next->zero ||
2853 curr->data != next->data ||
2854 curr->depth != next->depth ||
2855 curr->has_filename != next->has_filename ||
2856 curr->has_offset != next->has_offset) {
2857 return false;
2858 }
2859 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2860 return false;
2861 }
2862 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2863 return false;
2864 }
2865 return true;
2866}
2867
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002868static int img_map(int argc, char **argv)
2869{
2870 int c;
2871 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002872 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002873 BlockDriverState *bs;
2874 const char *filename, *fmt, *output;
2875 int64_t length;
2876 MapEntry curr = { .length = 0 }, next;
2877 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002878 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002879 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002880
2881 fmt = NULL;
2882 output = NULL;
2883 for (;;) {
2884 int option_index = 0;
2885 static const struct option long_options[] = {
2886 {"help", no_argument, 0, 'h'},
2887 {"format", required_argument, 0, 'f'},
2888 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002889 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002890 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002891 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002892 {0, 0, 0, 0}
2893 };
Fam Zheng335e9932017-05-03 00:35:39 +08002894 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002895 long_options, &option_index);
2896 if (c == -1) {
2897 break;
2898 }
2899 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002900 case ':':
2901 missing_argument(argv[optind - 1]);
2902 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002903 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002904 unrecognized_option(argv[optind - 1]);
2905 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002906 case 'h':
2907 help();
2908 break;
2909 case 'f':
2910 fmt = optarg;
2911 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002912 case 'U':
2913 force_share = true;
2914 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002915 case OPTION_OUTPUT:
2916 output = optarg;
2917 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002918 case OPTION_OBJECT: {
2919 QemuOpts *opts;
2920 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2921 optarg, true);
2922 if (!opts) {
2923 return 1;
2924 }
2925 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002926 case OPTION_IMAGE_OPTS:
2927 image_opts = true;
2928 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002929 }
2930 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002931 if (optind != argc - 1) {
2932 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002933 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002934 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002935
2936 if (output && !strcmp(output, "json")) {
2937 output_format = OFORMAT_JSON;
2938 } else if (output && !strcmp(output, "human")) {
2939 output_format = OFORMAT_HUMAN;
2940 } else if (output) {
2941 error_report("--output must be used with human or json as argument.");
2942 return 1;
2943 }
2944
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002945 if (qemu_opts_foreach(&qemu_object_opts,
2946 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002947 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002948 return 1;
2949 }
2950
Fam Zheng335e9932017-05-03 00:35:39 +08002951 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002952 if (!blk) {
2953 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002954 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002955 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002956
2957 if (output_format == OFORMAT_HUMAN) {
2958 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2959 }
2960
Max Reitzf1d3cd72015-02-05 13:58:18 -05002961 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002962 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002963 int64_t offset = curr.start + curr.length;
2964 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002965
2966 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02002967 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002968 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002969
2970 if (ret < 0) {
2971 error_report("Could not read file metadata: %s", strerror(-ret));
2972 goto out;
2973 }
2974
Fam Zheng16b0d552016-01-26 11:59:02 +08002975 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002976 curr.length += next.length;
2977 continue;
2978 }
2979
2980 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05002981 ret = dump_map_entry(output_format, &curr, &next);
2982 if (ret < 0) {
2983 goto out;
2984 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002985 }
2986 curr = next;
2987 }
2988
Eric Blake30065d12019-03-26 13:40:43 -05002989 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002990
2991out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002992 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002993 return ret < 0;
2994}
2995
aliguorif7b4a942009-01-07 17:40:15 +00002996#define SNAPSHOT_LIST 1
2997#define SNAPSHOT_CREATE 2
2998#define SNAPSHOT_APPLY 3
2999#define SNAPSHOT_DELETE 4
3000
Stuart Brady153859b2009-06-07 00:42:17 +01003001static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003002{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003003 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003004 BlockDriverState *bs;
3005 QEMUSnapshotInfo sn;
3006 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003007 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003008 int action = 0;
3009 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003010 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003011 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003012 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003013 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003014
Kevin Wolfce099542016-03-15 13:01:04 +01003015 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003016 /* Parse commandline parameters */
3017 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003018 static const struct option long_options[] = {
3019 {"help", no_argument, 0, 'h'},
3020 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003021 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003022 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003023 {0, 0, 0, 0}
3024 };
Fam Zheng335e9932017-05-03 00:35:39 +08003025 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003026 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003027 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003028 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003029 }
aliguorif7b4a942009-01-07 17:40:15 +00003030 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003031 case ':':
3032 missing_argument(argv[optind - 1]);
3033 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003034 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003035 unrecognized_option(argv[optind - 1]);
3036 break;
aliguorif7b4a942009-01-07 17:40:15 +00003037 case 'h':
3038 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003039 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003040 case 'l':
3041 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003042 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003043 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003044 }
3045 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003046 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003047 break;
3048 case 'a':
3049 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003050 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003051 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003052 }
3053 action = SNAPSHOT_APPLY;
3054 snapshot_name = optarg;
3055 break;
3056 case 'c':
3057 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003058 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003059 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003060 }
3061 action = SNAPSHOT_CREATE;
3062 snapshot_name = optarg;
3063 break;
3064 case 'd':
3065 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003066 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003067 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003068 }
3069 action = SNAPSHOT_DELETE;
3070 snapshot_name = optarg;
3071 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003072 case 'q':
3073 quiet = true;
3074 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003075 case 'U':
3076 force_share = true;
3077 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003078 case OPTION_OBJECT: {
3079 QemuOpts *opts;
3080 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3081 optarg, true);
3082 if (!opts) {
3083 return 1;
3084 }
3085 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003086 case OPTION_IMAGE_OPTS:
3087 image_opts = true;
3088 break;
aliguorif7b4a942009-01-07 17:40:15 +00003089 }
3090 }
3091
Kevin Wolffc11eb22013-08-05 10:53:04 +02003092 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003093 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003094 }
aliguorif7b4a942009-01-07 17:40:15 +00003095 filename = argv[optind++];
3096
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003097 if (qemu_opts_foreach(&qemu_object_opts,
3098 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003099 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003100 return 1;
3101 }
3102
aliguorif7b4a942009-01-07 17:40:15 +00003103 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003104 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3105 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003106 if (!blk) {
3107 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003108 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003109 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003110
3111 /* Perform the requested action */
3112 switch(action) {
3113 case SNAPSHOT_LIST:
3114 dump_snapshots(bs);
3115 break;
3116
3117 case SNAPSHOT_CREATE:
3118 memset(&sn, 0, sizeof(sn));
3119 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3120
3121 qemu_gettimeofday(&tv);
3122 sn.date_sec = tv.tv_sec;
3123 sn.date_nsec = tv.tv_usec * 1000;
3124
3125 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003126 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003127 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003128 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003129 }
aliguorif7b4a942009-01-07 17:40:15 +00003130 break;
3131
3132 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003133 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003134 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003135 error_reportf_err(err, "Could not apply snapshot '%s': ",
3136 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003137 }
aliguorif7b4a942009-01-07 17:40:15 +00003138 break;
3139
3140 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003141 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3142 if (ret < 0) {
3143 error_report("Could not delete snapshot '%s': snapshot not "
3144 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003145 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003146 } else {
3147 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3148 if (ret < 0) {
3149 error_reportf_err(err, "Could not delete snapshot '%s': ",
3150 snapshot_name);
3151 ret = 1;
3152 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003153 }
aliguorif7b4a942009-01-07 17:40:15 +00003154 break;
3155 }
3156
3157 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003158 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003159 if (ret) {
3160 return 1;
3161 }
Stuart Brady153859b2009-06-07 00:42:17 +01003162 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003163}
3164
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003165static int img_rebase(int argc, char **argv)
3166{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003167 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003168 uint8_t *buf_old = NULL;
3169 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003170 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003171 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003172 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3173 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003174 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003175 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003176 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003177 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003178 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003179 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003180 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003181
3182 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003183 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003184 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003185 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003186 out_baseimg = NULL;
3187 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003188 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003189 static const struct option long_options[] = {
3190 {"help", no_argument, 0, 'h'},
3191 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003192 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003193 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003194 {0, 0, 0, 0}
3195 };
Fam Zheng335e9932017-05-03 00:35:39 +08003196 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003197 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003198 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003199 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003200 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003201 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003202 case ':':
3203 missing_argument(argv[optind - 1]);
3204 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003205 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003206 unrecognized_option(argv[optind - 1]);
3207 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003208 case 'h':
3209 help();
3210 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003211 case 'f':
3212 fmt = optarg;
3213 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003214 case 'F':
3215 out_basefmt = optarg;
3216 break;
3217 case 'b':
3218 out_baseimg = optarg;
3219 break;
3220 case 'u':
3221 unsafe = 1;
3222 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003223 case 'p':
3224 progress = 1;
3225 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003226 case 't':
3227 cache = optarg;
3228 break;
Max Reitz40055952014-07-22 22:58:42 +02003229 case 'T':
3230 src_cache = optarg;
3231 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003232 case 'q':
3233 quiet = true;
3234 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003235 case OPTION_OBJECT: {
3236 QemuOpts *opts;
3237 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3238 optarg, true);
3239 if (!opts) {
3240 return 1;
3241 }
3242 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003243 case OPTION_IMAGE_OPTS:
3244 image_opts = true;
3245 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003246 case 'U':
3247 force_share = true;
3248 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003249 }
3250 }
3251
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003252 if (quiet) {
3253 progress = 0;
3254 }
3255
Fam Zhengac1307a2014-04-22 13:36:11 +08003256 if (optind != argc - 1) {
3257 error_exit("Expecting one image file name");
3258 }
3259 if (!unsafe && !out_baseimg) {
3260 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003261 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003262 filename = argv[optind++];
3263
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003264 if (qemu_opts_foreach(&qemu_object_opts,
3265 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003266 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003267 return 1;
3268 }
3269
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003270 qemu_progress_init(progress, 2.0);
3271 qemu_progress_print(0, 100);
3272
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003273 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003274 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003275 if (ret < 0) {
3276 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003277 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003278 }
3279
Kevin Wolfce099542016-03-15 13:01:04 +01003280 src_flags = 0;
3281 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003282 if (ret < 0) {
3283 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003284 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003285 }
3286
Kevin Wolfce099542016-03-15 13:01:04 +01003287 /* The source files are opened read-only, don't care about WCE */
3288 assert((src_flags & BDRV_O_RDWR) == 0);
3289 (void) src_writethrough;
3290
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003291 /*
3292 * Open the images.
3293 *
3294 * Ignore the old backing file for unsafe rebase in case we want to correct
3295 * the reference to a renamed or moved backing file.
3296 */
Fam Zheng335e9932017-05-03 00:35:39 +08003297 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3298 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003299 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003300 ret = -1;
3301 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003302 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003303 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003304
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003305 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003306 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003307 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003308 ret = -1;
3309 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003310 }
3311 }
3312
3313 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003314 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003315 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003316 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003317
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003318 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003319 blk_old_backing = blk_new(qemu_get_aio_context(),
3320 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003321 BLK_PERM_ALL);
3322 ret = blk_insert_bs(blk_old_backing, base_bs,
3323 &local_err);
3324 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003325 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003326 "Could not reuse old backing file '%s': ",
3327 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003328 goto out;
3329 }
3330 } else {
3331 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003332 }
Max Reitz644483d2015-02-05 13:58:17 -05003333
Alex Bligha6166732012-10-16 13:46:18 +01003334 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003335 const char *overlay_filename;
3336 char *out_real_path;
3337
Fam Zheng335e9932017-05-03 00:35:39 +08003338 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003339 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003340 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003341 }
3342 if (force_share) {
3343 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003344 }
3345
Max Reitzf30c66b2019-02-01 20:29:05 +01003346 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003347 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3348 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003349 out_real_path =
3350 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3351 out_baseimg,
3352 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003353 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003354 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003355 error_reportf_err(local_err,
3356 "Could not resolve backing filename: ");
3357 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003358 goto out;
3359 }
3360
Sam Eiderman863cc782019-05-23 19:33:36 +03003361 /*
3362 * Find out whether we rebase an image on top of a previous image
3363 * in its chain.
3364 */
3365 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003366 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003367 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003368 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003369
Kevin Wolfd861ab32019-04-25 14:25:10 +02003370 blk_new_backing = blk_new(qemu_get_aio_context(),
3371 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003372 BLK_PERM_ALL);
3373 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3374 &local_err);
3375 if (ret < 0) {
3376 error_reportf_err(local_err,
3377 "Could not reuse backing file '%s': ",
3378 out_baseimg);
3379 goto out;
3380 }
3381 } else {
3382 blk_new_backing = blk_new_open(out_real_path, NULL,
3383 options, src_flags, &local_err);
3384 g_free(out_real_path);
3385 if (!blk_new_backing) {
3386 error_reportf_err(local_err,
3387 "Could not open new backing file '%s': ",
3388 out_baseimg);
3389 ret = -1;
3390 goto out;
3391 }
Alex Bligha6166732012-10-16 13:46:18 +01003392 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003393 }
3394 }
3395
3396 /*
3397 * Check each unallocated cluster in the COW file. If it is unallocated,
3398 * accesses go to the backing file. We must therefore compare this cluster
3399 * in the old and new backing file, and if they differ we need to copy it
3400 * from the old backing file into the COW file.
3401 *
3402 * If qemu-img crashes during this step, no harm is done. The content of
3403 * the image is the same as the original one at any time.
3404 */
3405 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003406 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003407 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003408 int64_t new_backing_size = 0;
3409 uint64_t offset;
3410 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003411 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003412
Max Reitzf1d3cd72015-02-05 13:58:18 -05003413 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3414 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003415
Eric Blake41536282017-10-11 22:47:15 -05003416 size = blk_getlength(blk);
3417 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003418 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003419 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003420 ret = -1;
3421 goto out;
3422 }
Max Reitz35ddd932019-05-09 19:52:35 +02003423 if (blk_old_backing) {
3424 old_backing_size = blk_getlength(blk_old_backing);
3425 if (old_backing_size < 0) {
3426 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003427
Max Reitz35ddd932019-05-09 19:52:35 +02003428 bdrv_get_backing_filename(bs, backing_name,
3429 sizeof(backing_name));
3430 error_report("Could not get size of '%s': %s",
3431 backing_name, strerror(-old_backing_size));
3432 ret = -1;
3433 goto out;
3434 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003435 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003436 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003437 new_backing_size = blk_getlength(blk_new_backing);
3438 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003439 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003440 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003441 ret = -1;
3442 goto out;
3443 }
Alex Bligha6166732012-10-16 13:46:18 +01003444 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003445
Eric Blake41536282017-10-11 22:47:15 -05003446 if (size != 0) {
3447 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003448 }
3449
Eric Blake41536282017-10-11 22:47:15 -05003450 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003451 bool buf_old_is_zero = false;
3452
Eric Blake41536282017-10-11 22:47:15 -05003453 /* How many bytes can we handle with the next read? */
3454 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003455
3456 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003457 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003458 if (ret < 0) {
3459 error_report("error while reading image metadata: %s",
3460 strerror(-ret));
3461 goto out;
3462 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003463 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003464 continue;
3465 }
3466
Sam Eiderman863cc782019-05-23 19:33:36 +03003467 if (prefix_chain_bs) {
3468 /*
3469 * If cluster wasn't changed since prefix_chain, we don't need
3470 * to take action
3471 */
3472 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3473 offset, n, &n);
3474 if (ret < 0) {
3475 error_report("error while reading image metadata: %s",
3476 strerror(-ret));
3477 goto out;
3478 }
3479 if (!ret) {
3480 continue;
3481 }
3482 }
3483
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003484 /*
3485 * Read old and new backing file and take into consideration that
3486 * backing files may be smaller than the COW image.
3487 */
Eric Blake41536282017-10-11 22:47:15 -05003488 if (offset >= old_backing_size) {
3489 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003490 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003491 } else {
Eric Blake41536282017-10-11 22:47:15 -05003492 if (offset + n > old_backing_size) {
3493 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003494 }
3495
Eric Blake41536282017-10-11 22:47:15 -05003496 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003497 if (ret < 0) {
3498 error_report("error while reading from old backing file");
3499 goto out;
3500 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003501 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003502
Eric Blake41536282017-10-11 22:47:15 -05003503 if (offset >= new_backing_size || !blk_new_backing) {
3504 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003505 } else {
Eric Blake41536282017-10-11 22:47:15 -05003506 if (offset + n > new_backing_size) {
3507 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003508 }
3509
Eric Blake41536282017-10-11 22:47:15 -05003510 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003511 if (ret < 0) {
3512 error_report("error while reading from new backing file");
3513 goto out;
3514 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003515 }
3516
3517 /* If they differ, we need to write to the COW file */
3518 uint64_t written = 0;
3519
Eric Blake41536282017-10-11 22:47:15 -05003520 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003521 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003522
Eric Blake41536282017-10-11 22:47:15 -05003523 if (compare_buffers(buf_old + written, buf_new + written,
3524 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003525 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003526 if (buf_old_is_zero) {
3527 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3528 } else {
3529 ret = blk_pwrite(blk, offset + written,
3530 buf_old + written, pnum, 0);
3531 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003532 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003533 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003534 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003535 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003536 }
3537 }
3538
3539 written += pnum;
3540 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003541 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003542 }
3543 }
3544
3545 /*
3546 * Change the backing file. All clusters that are different from the old
3547 * backing file are overwritten in the COW file now, so the visible content
3548 * doesn't change when we switch the backing file.
3549 */
Alex Bligha6166732012-10-16 13:46:18 +01003550 if (out_baseimg && *out_baseimg) {
3551 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3552 } else {
3553 ret = bdrv_change_backing_file(bs, NULL, NULL);
3554 }
3555
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003556 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003557 error_report("Could not change the backing file to '%s': No "
3558 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003559 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003560 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003561 out_baseimg, strerror(-ret));
3562 }
3563
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003564 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003565 /*
3566 * TODO At this point it is possible to check if any clusters that are
3567 * allocated in the COW file are the same in the backing file. If so, they
3568 * could be dropped from the COW file. Don't do this before switching the
3569 * backing file, in case of a crash this would lead to corruption.
3570 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003571out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003572 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003573 /* Cleanup */
3574 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003575 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003576 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003577 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003578 qemu_vfree(buf_old);
3579 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003580
Markus Armbruster26f54e92014-10-07 13:59:04 +02003581 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003582 if (ret) {
3583 return 1;
3584 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003585 return 0;
3586}
3587
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003588static int img_resize(int argc, char **argv)
3589{
Markus Armbruster6750e792015-02-12 17:43:08 +01003590 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003591 int c, ret, relative;
3592 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003593 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003594 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003595 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003596 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003597 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003598
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003599 static QemuOptsList resize_options = {
3600 .name = "resize_options",
3601 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3602 .desc = {
3603 {
3604 .name = BLOCK_OPT_SIZE,
3605 .type = QEMU_OPT_SIZE,
3606 .help = "Virtual disk size"
3607 }, {
3608 /* end of list */
3609 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003610 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003611 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003612 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003613 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003614
Kevin Wolfe80fec72011-04-29 10:58:12 +02003615 /* Remove size from argv manually so that negative numbers are not treated
3616 * as options by getopt. */
3617 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003618 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003619 return 1;
3620 }
3621
3622 size = argv[--argc];
3623
3624 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003625 fmt = NULL;
3626 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003627 static const struct option long_options[] = {
3628 {"help", no_argument, 0, 'h'},
3629 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003630 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003631 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003632 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003633 {0, 0, 0, 0}
3634 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003635 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003636 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003637 if (c == -1) {
3638 break;
3639 }
3640 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003641 case ':':
3642 missing_argument(argv[optind - 1]);
3643 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003644 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003645 unrecognized_option(argv[optind - 1]);
3646 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003647 case 'h':
3648 help();
3649 break;
3650 case 'f':
3651 fmt = optarg;
3652 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003653 case 'q':
3654 quiet = true;
3655 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003656 case OPTION_OBJECT: {
3657 QemuOpts *opts;
3658 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3659 optarg, true);
3660 if (!opts) {
3661 return 1;
3662 }
3663 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003664 case OPTION_IMAGE_OPTS:
3665 image_opts = true;
3666 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003667 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003668 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003669 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003670 if (prealloc == PREALLOC_MODE__MAX) {
3671 error_report("Invalid preallocation mode '%s'", optarg);
3672 return 1;
3673 }
3674 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003675 case OPTION_SHRINK:
3676 shrink = true;
3677 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003678 }
3679 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003680 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003681 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003682 }
3683 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003684
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003685 if (qemu_opts_foreach(&qemu_object_opts,
3686 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003687 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003688 return 1;
3689 }
3690
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003691 /* Choose grow, shrink, or absolute resize mode */
3692 switch (size[0]) {
3693 case '+':
3694 relative = 1;
3695 size++;
3696 break;
3697 case '-':
3698 relative = -1;
3699 size++;
3700 break;
3701 default:
3702 relative = 0;
3703 break;
3704 }
3705
3706 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003707 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003708 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003709 if (err) {
3710 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003711 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003712 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003713 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003714 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003715 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3716 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003717
Max Reitzefaa7c42016-03-16 19:54:38 +01003718 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003719 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3720 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003721 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003722 ret = -1;
3723 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003724 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003725
Max Reitzdc5f6902017-06-13 22:20:55 +02003726 current_size = blk_getlength(blk);
3727 if (current_size < 0) {
3728 error_report("Failed to inquire current image length: %s",
3729 strerror(-current_size));
3730 ret = -1;
3731 goto out;
3732 }
3733
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003734 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003735 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003736 } else {
3737 total_size = n;
3738 }
3739 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003740 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003741 ret = -1;
3742 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003743 }
3744
Max Reitzdc5f6902017-06-13 22:20:55 +02003745 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3746 error_report("Preallocation can only be used for growing images");
3747 ret = -1;
3748 goto out;
3749 }
3750
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003751 if (total_size < current_size && !shrink) {
3752 warn_report("Shrinking an image will delete all data beyond the "
3753 "shrunken image's end. Before performing such an "
3754 "operation, make sure there is no important data there.");
3755
3756 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3757 error_report(
3758 "Use the --shrink option to perform a shrink operation.");
3759 ret = -1;
3760 goto out;
3761 } else {
3762 warn_report("Using the --shrink option will suppress this message. "
3763 "Note that future versions of qemu-img may refuse to "
3764 "shrink images without this option.");
3765 }
3766 }
3767
Max Reitzdc5f6902017-06-13 22:20:55 +02003768 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003769 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003770 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003771 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003772 }
Max Reitz5279b302018-04-21 18:39:57 +02003773
3774 new_size = blk_getlength(blk);
3775 if (new_size < 0) {
3776 error_report("Failed to verify truncated image length: %s",
3777 strerror(-new_size));
3778 ret = -1;
3779 goto out;
3780 }
3781
3782 /* Some block drivers implement a truncation method, but only so
3783 * the user can cause qemu to refresh the image's size from disk.
3784 * The idea is that the user resizes the image outside of qemu and
3785 * then invokes block_resize to inform qemu about it.
3786 * (This includes iscsi and file-posix for device files.)
3787 * Of course, that is not the behavior someone invoking
3788 * qemu-img resize would find useful, so we catch that behavior
3789 * here and tell the user. */
3790 if (new_size != total_size && new_size == current_size) {
3791 error_report("Image was not resized; resizing may not be supported "
3792 "for this image");
3793 ret = -1;
3794 goto out;
3795 }
3796
3797 if (new_size != total_size) {
3798 warn_report("Image should have been resized to %" PRIi64
3799 " bytes, but was resized to %" PRIi64 " bytes",
3800 total_size, new_size);
3801 }
3802
3803 qprintf(quiet, "Image resized.\n");
3804
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003805out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003806 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003807 if (ret) {
3808 return 1;
3809 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003810 return 0;
3811}
3812
Max Reitz76a3a342014-10-27 11:12:51 +01003813static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003814 int64_t offset, int64_t total_work_size,
3815 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003816{
3817 qemu_progress_print(100.f * offset / total_work_size, 0);
3818}
3819
Max Reitz51641352018-05-09 23:00:20 +02003820static int print_amend_option_help(const char *format)
3821{
3822 BlockDriver *drv;
3823
3824 /* Find driver and parse its options */
3825 drv = bdrv_find_format(format);
3826 if (!drv) {
3827 error_report("Unknown file format '%s'", format);
3828 return 1;
3829 }
3830
3831 if (!drv->bdrv_amend_options) {
3832 error_report("Format driver '%s' does not support option amendment",
3833 format);
3834 return 1;
3835 }
3836
3837 /* Every driver supporting amendment must have create_opts */
3838 assert(drv->create_opts);
3839
3840 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003841 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003842 printf("\nNote that not all of these options may be amendable.\n");
3843 return 0;
3844}
3845
Max Reitz6f176b42013-09-03 10:09:50 +02003846static int img_amend(int argc, char **argv)
3847{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003848 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003849 int c, ret = 0;
3850 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003851 QemuOptsList *create_opts = NULL;
3852 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003853 const char *fmt = NULL, *filename, *cache;
3854 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003855 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003856 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003857 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003858 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003859 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003860
Max Reitzbd39e6e2014-07-22 22:58:43 +02003861 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003862 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003863 static const struct option long_options[] = {
3864 {"help", no_argument, 0, 'h'},
3865 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003866 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003867 {0, 0, 0, 0}
3868 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003869 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003870 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003871 if (c == -1) {
3872 break;
3873 }
3874
3875 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003876 case ':':
3877 missing_argument(argv[optind - 1]);
3878 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003879 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003880 unrecognized_option(argv[optind - 1]);
3881 break;
3882 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003883 help();
3884 break;
3885 case 'o':
3886 if (!is_valid_option_list(optarg)) {
3887 error_report("Invalid option list: %s", optarg);
3888 ret = -1;
3889 goto out_no_progress;
3890 }
3891 if (!options) {
3892 options = g_strdup(optarg);
3893 } else {
3894 char *old_options = options;
3895 options = g_strdup_printf("%s,%s", options, optarg);
3896 g_free(old_options);
3897 }
3898 break;
3899 case 'f':
3900 fmt = optarg;
3901 break;
3902 case 't':
3903 cache = optarg;
3904 break;
3905 case 'p':
3906 progress = true;
3907 break;
3908 case 'q':
3909 quiet = true;
3910 break;
3911 case OPTION_OBJECT:
3912 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3913 optarg, true);
3914 if (!opts) {
3915 ret = -1;
3916 goto out_no_progress;
3917 }
3918 break;
3919 case OPTION_IMAGE_OPTS:
3920 image_opts = true;
3921 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003922 }
3923 }
3924
Max Reitz6f176b42013-09-03 10:09:50 +02003925 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003926 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003927 }
3928
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003929 if (qemu_opts_foreach(&qemu_object_opts,
3930 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003931 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003932 ret = -1;
3933 goto out_no_progress;
3934 }
3935
Max Reitz76a3a342014-10-27 11:12:51 +01003936 if (quiet) {
3937 progress = false;
3938 }
3939 qemu_progress_init(progress, 1.0);
3940
Kevin Wolfa283cb62014-02-21 16:24:07 +01003941 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3942 if (fmt && has_help_option(options)) {
3943 /* If a format is explicitly specified (and possibly no filename is
3944 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003945 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003946 goto out;
3947 }
3948
3949 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003950 error_report("Expecting one image file name");
3951 ret = -1;
3952 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003953 }
Max Reitz6f176b42013-09-03 10:09:50 +02003954
Kevin Wolfce099542016-03-15 13:01:04 +01003955 flags = BDRV_O_RDWR;
3956 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003957 if (ret < 0) {
3958 error_report("Invalid cache option: %s", cache);
3959 goto out;
3960 }
3961
Fam Zheng335e9932017-05-03 00:35:39 +08003962 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3963 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003964 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003965 ret = -1;
3966 goto out;
3967 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003968 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003969
3970 fmt = bs->drv->format_name;
3971
Kevin Wolf626f84f2014-02-21 16:24:06 +01003972 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003973 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003974 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003975 goto out;
3976 }
3977
Max Reitz1f996682018-05-09 23:00:17 +02003978 if (!bs->drv->bdrv_amend_options) {
3979 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003980 fmt);
3981 ret = -1;
3982 goto out;
3983 }
3984
Max Reitz1f996682018-05-09 23:00:17 +02003985 /* Every driver supporting amendment must have create_opts */
3986 assert(bs->drv->create_opts);
3987
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003988 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003989 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003990 qemu_opts_do_parse(opts, options, NULL, &err);
3991 if (err) {
3992 error_report_err(err);
3993 ret = -1;
3994 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003995 }
3996
Max Reitz76a3a342014-10-27 11:12:51 +01003997 /* In case the driver does not call amend_status_cb() */
3998 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003999 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004000 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004001 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004002 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004003 goto out;
4004 }
4005
4006out:
Max Reitz76a3a342014-10-27 11:12:51 +01004007 qemu_progress_end();
4008
Max Reitze814dff2015-08-20 16:00:38 -07004009out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004010 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004011 qemu_opts_del(opts);
4012 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004013 g_free(options);
4014
Max Reitz6f176b42013-09-03 10:09:50 +02004015 if (ret) {
4016 return 1;
4017 }
4018 return 0;
4019}
4020
Kevin Wolfb6133b82014-08-05 14:17:13 +02004021typedef struct BenchData {
4022 BlockBackend *blk;
4023 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004024 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004025 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004026 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004027 int nrreq;
4028 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004029 int flush_interval;
4030 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004031 uint8_t *buf;
4032 QEMUIOVector *qiov;
4033
4034 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004035 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004036 uint64_t offset;
4037} BenchData;
4038
Kevin Wolf55d539c2016-06-03 13:59:41 +02004039static void bench_undrained_flush_cb(void *opaque, int ret)
4040{
4041 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004042 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004043 exit(EXIT_FAILURE);
4044 }
4045}
4046
Kevin Wolfb6133b82014-08-05 14:17:13 +02004047static void bench_cb(void *opaque, int ret)
4048{
4049 BenchData *b = opaque;
4050 BlockAIOCB *acb;
4051
4052 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004053 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004054 exit(EXIT_FAILURE);
4055 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004056
4057 if (b->in_flush) {
4058 /* Just finished a flush with drained queue: Start next requests */
4059 assert(b->in_flight == 0);
4060 b->in_flush = false;
4061 } else if (b->in_flight > 0) {
4062 int remaining = b->n - b->in_flight;
4063
Kevin Wolfb6133b82014-08-05 14:17:13 +02004064 b->n--;
4065 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004066
4067 /* Time for flush? Drain queue if requested, then flush */
4068 if (b->flush_interval && remaining % b->flush_interval == 0) {
4069 if (!b->in_flight || !b->drain_on_flush) {
4070 BlockCompletionFunc *cb;
4071
4072 if (b->drain_on_flush) {
4073 b->in_flush = true;
4074 cb = bench_cb;
4075 } else {
4076 cb = bench_undrained_flush_cb;
4077 }
4078
4079 acb = blk_aio_flush(b->blk, cb, b);
4080 if (!acb) {
4081 error_report("Failed to issue flush request");
4082 exit(EXIT_FAILURE);
4083 }
4084 }
4085 if (b->drain_on_flush) {
4086 return;
4087 }
4088 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004089 }
4090
4091 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004092 int64_t offset = b->offset;
4093 /* blk_aio_* might look for completed I/Os and kick bench_cb
4094 * again, so make sure this operation is counted by in_flight
4095 * and b->offset is ready for the next submission.
4096 */
4097 b->in_flight++;
4098 b->offset += b->step;
4099 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004100 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004101 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004102 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004103 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004104 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004105 if (!acb) {
4106 error_report("Failed to issue request");
4107 exit(EXIT_FAILURE);
4108 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004109 }
4110}
4111
4112static int img_bench(int argc, char **argv)
4113{
4114 int c, ret = 0;
4115 const char *fmt = NULL, *filename;
4116 bool quiet = false;
4117 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004118 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004119 int count = 75000;
4120 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004121 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004122 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004123 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004124 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004125 int flush_interval = 0;
4126 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004127 int64_t image_size;
4128 BlockBackend *blk = NULL;
4129 BenchData data = {};
4130 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004131 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004132 struct timeval t1, t2;
4133 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004134 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004135 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004136
4137 for (;;) {
4138 static const struct option long_options[] = {
4139 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004140 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004141 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004142 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004143 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004144 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004145 {0, 0, 0, 0}
4146 };
Fam Zheng335e9932017-05-03 00:35:39 +08004147 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004148 if (c == -1) {
4149 break;
4150 }
4151
4152 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004153 case ':':
4154 missing_argument(argv[optind - 1]);
4155 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004156 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004157 unrecognized_option(argv[optind - 1]);
4158 break;
4159 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004160 help();
4161 break;
4162 case 'c':
4163 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004164 unsigned long res;
4165
4166 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004167 error_report("Invalid request count specified");
4168 return 1;
4169 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004170 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004171 break;
4172 }
4173 case 'd':
4174 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004175 unsigned long res;
4176
4177 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004178 error_report("Invalid queue depth specified");
4179 return 1;
4180 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004181 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004182 break;
4183 }
4184 case 'f':
4185 fmt = optarg;
4186 break;
4187 case 'n':
4188 flags |= BDRV_O_NATIVE_AIO;
4189 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004190 case 'o':
4191 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004192 offset = cvtnum(optarg);
4193 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004194 error_report("Invalid offset specified");
4195 return 1;
4196 }
4197 break;
4198 }
4199 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004200 case 'q':
4201 quiet = true;
4202 break;
4203 case 's':
4204 {
4205 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004206
Markus Armbruster606caa02017-02-21 21:14:04 +01004207 sval = cvtnum(optarg);
4208 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004209 error_report("Invalid buffer size specified");
4210 return 1;
4211 }
4212
4213 bufsize = sval;
4214 break;
4215 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004216 case 'S':
4217 {
4218 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004219
Markus Armbruster606caa02017-02-21 21:14:04 +01004220 sval = cvtnum(optarg);
4221 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004222 error_report("Invalid step size specified");
4223 return 1;
4224 }
4225
4226 step = sval;
4227 break;
4228 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004229 case 't':
4230 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4231 if (ret < 0) {
4232 error_report("Invalid cache mode");
4233 ret = -1;
4234 goto out;
4235 }
4236 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004237 case 'w':
4238 flags |= BDRV_O_RDWR;
4239 is_write = true;
4240 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004241 case 'U':
4242 force_share = true;
4243 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004244 case OPTION_PATTERN:
4245 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004246 unsigned long res;
4247
4248 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004249 error_report("Invalid pattern byte specified");
4250 return 1;
4251 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004252 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004253 break;
4254 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004255 case OPTION_FLUSH_INTERVAL:
4256 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004257 unsigned long res;
4258
4259 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004260 error_report("Invalid flush interval specified");
4261 return 1;
4262 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004263 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004264 break;
4265 }
4266 case OPTION_NO_DRAIN:
4267 drain_on_flush = false;
4268 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004269 case OPTION_IMAGE_OPTS:
4270 image_opts = true;
4271 break;
4272 }
4273 }
4274
4275 if (optind != argc - 1) {
4276 error_exit("Expecting one image file name");
4277 }
4278 filename = argv[argc - 1];
4279
Kevin Wolf55d539c2016-06-03 13:59:41 +02004280 if (!is_write && flush_interval) {
4281 error_report("--flush-interval is only available in write tests");
4282 ret = -1;
4283 goto out;
4284 }
4285 if (flush_interval && flush_interval < depth) {
4286 error_report("Flush interval can't be smaller than depth");
4287 ret = -1;
4288 goto out;
4289 }
4290
Fam Zheng335e9932017-05-03 00:35:39 +08004291 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4292 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004293 if (!blk) {
4294 ret = -1;
4295 goto out;
4296 }
4297
4298 image_size = blk_getlength(blk);
4299 if (image_size < 0) {
4300 ret = image_size;
4301 goto out;
4302 }
4303
4304 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004305 .blk = blk,
4306 .image_size = image_size,
4307 .bufsize = bufsize,
4308 .step = step ?: bufsize,
4309 .nrreq = depth,
4310 .n = count,
4311 .offset = offset,
4312 .write = is_write,
4313 .flush_interval = flush_interval,
4314 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004315 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004316 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004317 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004318 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004319 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004320 if (flush_interval) {
4321 printf("Sending flush every %d requests\n", flush_interval);
4322 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004323
Fam Zheng79d46582018-01-16 14:08:58 +08004324 buf_size = data.nrreq * data.bufsize;
4325 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004326 memset(data.buf, pattern, data.nrreq * data.bufsize);
4327
Fam Zheng79d46582018-01-16 14:08:58 +08004328 blk_register_buf(blk, data.buf, buf_size);
4329
Kevin Wolfb6133b82014-08-05 14:17:13 +02004330 data.qiov = g_new(QEMUIOVector, data.nrreq);
4331 for (i = 0; i < data.nrreq; i++) {
4332 qemu_iovec_init(&data.qiov[i], 1);
4333 qemu_iovec_add(&data.qiov[i],
4334 data.buf + i * data.bufsize, data.bufsize);
4335 }
4336
4337 gettimeofday(&t1, NULL);
4338 bench_cb(&data, 0);
4339
4340 while (data.n > 0) {
4341 main_loop_wait(false);
4342 }
4343 gettimeofday(&t2, NULL);
4344
4345 printf("Run completed in %3.3f seconds.\n",
4346 (t2.tv_sec - t1.tv_sec)
4347 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4348
4349out:
Fam Zheng79d46582018-01-16 14:08:58 +08004350 if (data.buf) {
4351 blk_unregister_buf(blk, data.buf);
4352 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004353 qemu_vfree(data.buf);
4354 blk_unref(blk);
4355
4356 if (ret) {
4357 return 1;
4358 }
4359 return 0;
4360}
4361
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004362#define C_BS 01
4363#define C_COUNT 02
4364#define C_IF 04
4365#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004366#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004367
4368struct DdInfo {
4369 unsigned int flags;
4370 int64_t count;
4371};
4372
4373struct DdIo {
4374 int bsz; /* Block size */
4375 char *filename;
4376 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004377 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004378};
4379
4380struct DdOpts {
4381 const char *name;
4382 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4383 unsigned int flag;
4384};
4385
4386static int img_dd_bs(const char *arg,
4387 struct DdIo *in, struct DdIo *out,
4388 struct DdInfo *dd)
4389{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004390 int64_t res;
4391
Markus Armbruster606caa02017-02-21 21:14:04 +01004392 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004393
Markus Armbruster606caa02017-02-21 21:14:04 +01004394 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004395 error_report("invalid number: '%s'", arg);
4396 return 1;
4397 }
4398 in->bsz = out->bsz = res;
4399
4400 return 0;
4401}
4402
4403static int img_dd_count(const char *arg,
4404 struct DdIo *in, struct DdIo *out,
4405 struct DdInfo *dd)
4406{
Markus Armbruster606caa02017-02-21 21:14:04 +01004407 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004408
Markus Armbruster606caa02017-02-21 21:14:04 +01004409 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004410 error_report("invalid number: '%s'", arg);
4411 return 1;
4412 }
4413
4414 return 0;
4415}
4416
4417static int img_dd_if(const char *arg,
4418 struct DdIo *in, struct DdIo *out,
4419 struct DdInfo *dd)
4420{
4421 in->filename = g_strdup(arg);
4422
4423 return 0;
4424}
4425
4426static int img_dd_of(const char *arg,
4427 struct DdIo *in, struct DdIo *out,
4428 struct DdInfo *dd)
4429{
4430 out->filename = g_strdup(arg);
4431
4432 return 0;
4433}
4434
Reda Sallahif7c15532016-08-10 16:16:09 +02004435static int img_dd_skip(const char *arg,
4436 struct DdIo *in, struct DdIo *out,
4437 struct DdInfo *dd)
4438{
Markus Armbruster606caa02017-02-21 21:14:04 +01004439 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004440
Markus Armbruster606caa02017-02-21 21:14:04 +01004441 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004442 error_report("invalid number: '%s'", arg);
4443 return 1;
4444 }
4445
4446 return 0;
4447}
4448
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004449static int img_dd(int argc, char **argv)
4450{
4451 int ret = 0;
4452 char *arg = NULL;
4453 char *tmp;
4454 BlockDriver *drv = NULL, *proto_drv = NULL;
4455 BlockBackend *blk1 = NULL, *blk2 = NULL;
4456 QemuOpts *opts = NULL;
4457 QemuOptsList *create_opts = NULL;
4458 Error *local_err = NULL;
4459 bool image_opts = false;
4460 int c, i;
4461 const char *out_fmt = "raw";
4462 const char *fmt = NULL;
4463 int64_t size = 0;
4464 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004465 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004466 struct DdInfo dd = {
4467 .flags = 0,
4468 .count = 0,
4469 };
4470 struct DdIo in = {
4471 .bsz = 512, /* Block size is by default 512 bytes */
4472 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004473 .buf = NULL,
4474 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004475 };
4476 struct DdIo out = {
4477 .bsz = 512,
4478 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004479 .buf = NULL,
4480 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004481 };
4482
4483 const struct DdOpts options[] = {
4484 { "bs", img_dd_bs, C_BS },
4485 { "count", img_dd_count, C_COUNT },
4486 { "if", img_dd_if, C_IF },
4487 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004488 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004489 { NULL, NULL, 0 }
4490 };
4491 const struct option long_options[] = {
4492 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004493 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004494 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004495 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004496 { 0, 0, 0, 0 }
4497 };
4498
Fam Zheng335e9932017-05-03 00:35:39 +08004499 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004500 if (c == EOF) {
4501 break;
4502 }
4503 switch (c) {
4504 case 'O':
4505 out_fmt = optarg;
4506 break;
4507 case 'f':
4508 fmt = optarg;
4509 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004510 case ':':
4511 missing_argument(argv[optind - 1]);
4512 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004513 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004514 unrecognized_option(argv[optind - 1]);
4515 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004516 case 'h':
4517 help();
4518 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004519 case 'U':
4520 force_share = true;
4521 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004522 case OPTION_OBJECT:
4523 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004524 ret = -1;
4525 goto out;
4526 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004527 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004528 case OPTION_IMAGE_OPTS:
4529 image_opts = true;
4530 break;
4531 }
4532 }
4533
4534 for (i = optind; i < argc; i++) {
4535 int j;
4536 arg = g_strdup(argv[i]);
4537
4538 tmp = strchr(arg, '=');
4539 if (tmp == NULL) {
4540 error_report("unrecognized operand %s", arg);
4541 ret = -1;
4542 goto out;
4543 }
4544
4545 *tmp++ = '\0';
4546
4547 for (j = 0; options[j].name != NULL; j++) {
4548 if (!strcmp(arg, options[j].name)) {
4549 break;
4550 }
4551 }
4552 if (options[j].name == NULL) {
4553 error_report("unrecognized operand %s", arg);
4554 ret = -1;
4555 goto out;
4556 }
4557
4558 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4559 ret = -1;
4560 goto out;
4561 }
4562 dd.flags |= options[j].flag;
4563 g_free(arg);
4564 arg = NULL;
4565 }
4566
4567 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4568 error_report("Must specify both input and output files");
4569 ret = -1;
4570 goto out;
4571 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004572
4573 if (qemu_opts_foreach(&qemu_object_opts,
4574 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004575 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004576 ret = -1;
4577 goto out;
4578 }
4579
Fam Zheng335e9932017-05-03 00:35:39 +08004580 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4581 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004582
4583 if (!blk1) {
4584 ret = -1;
4585 goto out;
4586 }
4587
4588 drv = bdrv_find_format(out_fmt);
4589 if (!drv) {
4590 error_report("Unknown file format");
4591 ret = -1;
4592 goto out;
4593 }
4594 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4595
4596 if (!proto_drv) {
4597 error_report_err(local_err);
4598 ret = -1;
4599 goto out;
4600 }
4601 if (!drv->create_opts) {
4602 error_report("Format driver '%s' does not support image creation",
4603 drv->format_name);
4604 ret = -1;
4605 goto out;
4606 }
4607 if (!proto_drv->create_opts) {
4608 error_report("Protocol driver '%s' does not support image creation",
4609 proto_drv->format_name);
4610 ret = -1;
4611 goto out;
4612 }
4613 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4614 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4615
4616 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4617
4618 size = blk_getlength(blk1);
4619 if (size < 0) {
4620 error_report("Failed to get size for '%s'", in.filename);
4621 ret = -1;
4622 goto out;
4623 }
4624
4625 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4626 dd.count * in.bsz < size) {
4627 size = dd.count * in.bsz;
4628 }
4629
Reda Sallahif7c15532016-08-10 16:16:09 +02004630 /* Overflow means the specified offset is beyond input image's size */
4631 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4632 size < in.bsz * in.offset)) {
4633 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4634 } else {
4635 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4636 size - in.bsz * in.offset, &error_abort);
4637 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004638
4639 ret = bdrv_create(drv, out.filename, opts, &local_err);
4640 if (ret < 0) {
4641 error_reportf_err(local_err,
4642 "%s: error while creating output image: ",
4643 out.filename);
4644 ret = -1;
4645 goto out;
4646 }
4647
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004648 /* TODO, we can't honour --image-opts for the target,
4649 * since it needs to be given in a format compatible
4650 * with the bdrv_create() call above which does not
4651 * support image-opts style.
4652 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004653 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004654 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004655
4656 if (!blk2) {
4657 ret = -1;
4658 goto out;
4659 }
4660
Reda Sallahif7c15532016-08-10 16:16:09 +02004661 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4662 size < in.offset * in.bsz)) {
4663 /* We give a warning if the skip option is bigger than the input
4664 * size and create an empty output disk image (i.e. like dd(1)).
4665 */
4666 error_report("%s: cannot skip to specified offset", in.filename);
4667 in_pos = size;
4668 } else {
4669 in_pos = in.offset * in.bsz;
4670 }
4671
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004672 in.buf = g_new(uint8_t, in.bsz);
4673
Reda Sallahif7c15532016-08-10 16:16:09 +02004674 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004675 int in_ret, out_ret;
4676
4677 if (in_pos + in.bsz > size) {
4678 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4679 } else {
4680 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4681 }
4682 if (in_ret < 0) {
4683 error_report("error while reading from input image file: %s",
4684 strerror(-in_ret));
4685 ret = -1;
4686 goto out;
4687 }
4688 in_pos += in_ret;
4689
4690 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4691
4692 if (out_ret < 0) {
4693 error_report("error while writing to output image file: %s",
4694 strerror(-out_ret));
4695 ret = -1;
4696 goto out;
4697 }
4698 out_pos += out_ret;
4699 }
4700
4701out:
4702 g_free(arg);
4703 qemu_opts_del(opts);
4704 qemu_opts_free(create_opts);
4705 blk_unref(blk1);
4706 blk_unref(blk2);
4707 g_free(in.filename);
4708 g_free(out.filename);
4709 g_free(in.buf);
4710 g_free(out.buf);
4711
4712 if (ret) {
4713 return 1;
4714 }
4715 return 0;
4716}
4717
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004718static void dump_json_block_measure_info(BlockMeasureInfo *info)
4719{
4720 QString *str;
4721 QObject *obj;
4722 Visitor *v = qobject_output_visitor_new(&obj);
4723
4724 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4725 visit_complete(v, &obj);
4726 str = qobject_to_json_pretty(obj);
4727 assert(str != NULL);
4728 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004729 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004730 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004731 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004732}
4733
4734static int img_measure(int argc, char **argv)
4735{
4736 static const struct option long_options[] = {
4737 {"help", no_argument, 0, 'h'},
4738 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4739 {"object", required_argument, 0, OPTION_OBJECT},
4740 {"output", required_argument, 0, OPTION_OUTPUT},
4741 {"size", required_argument, 0, OPTION_SIZE},
4742 {"force-share", no_argument, 0, 'U'},
4743 {0, 0, 0, 0}
4744 };
4745 OutputFormat output_format = OFORMAT_HUMAN;
4746 BlockBackend *in_blk = NULL;
4747 BlockDriver *drv;
4748 const char *filename = NULL;
4749 const char *fmt = NULL;
4750 const char *out_fmt = "raw";
4751 char *options = NULL;
4752 char *snapshot_name = NULL;
4753 bool force_share = false;
4754 QemuOpts *opts = NULL;
4755 QemuOpts *object_opts = NULL;
4756 QemuOpts *sn_opts = NULL;
4757 QemuOptsList *create_opts = NULL;
4758 bool image_opts = false;
4759 uint64_t img_size = UINT64_MAX;
4760 BlockMeasureInfo *info = NULL;
4761 Error *local_err = NULL;
4762 int ret = 1;
4763 int c;
4764
4765 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4766 long_options, NULL)) != -1) {
4767 switch (c) {
4768 case '?':
4769 case 'h':
4770 help();
4771 break;
4772 case 'f':
4773 fmt = optarg;
4774 break;
4775 case 'O':
4776 out_fmt = optarg;
4777 break;
4778 case 'o':
4779 if (!is_valid_option_list(optarg)) {
4780 error_report("Invalid option list: %s", optarg);
4781 goto out;
4782 }
4783 if (!options) {
4784 options = g_strdup(optarg);
4785 } else {
4786 char *old_options = options;
4787 options = g_strdup_printf("%s,%s", options, optarg);
4788 g_free(old_options);
4789 }
4790 break;
4791 case 'l':
4792 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4793 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4794 optarg, false);
4795 if (!sn_opts) {
4796 error_report("Failed in parsing snapshot param '%s'",
4797 optarg);
4798 goto out;
4799 }
4800 } else {
4801 snapshot_name = optarg;
4802 }
4803 break;
4804 case 'U':
4805 force_share = true;
4806 break;
4807 case OPTION_OBJECT:
4808 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4809 optarg, true);
4810 if (!object_opts) {
4811 goto out;
4812 }
4813 break;
4814 case OPTION_IMAGE_OPTS:
4815 image_opts = true;
4816 break;
4817 case OPTION_OUTPUT:
4818 if (!strcmp(optarg, "json")) {
4819 output_format = OFORMAT_JSON;
4820 } else if (!strcmp(optarg, "human")) {
4821 output_format = OFORMAT_HUMAN;
4822 } else {
4823 error_report("--output must be used with human or json "
4824 "as argument.");
4825 goto out;
4826 }
4827 break;
4828 case OPTION_SIZE:
4829 {
4830 int64_t sval;
4831
4832 sval = cvtnum(optarg);
4833 if (sval < 0) {
4834 if (sval == -ERANGE) {
4835 error_report("Image size must be less than 8 EiB!");
4836 } else {
4837 error_report("Invalid image size specified! You may use "
4838 "k, M, G, T, P or E suffixes for ");
4839 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4840 "petabytes and exabytes.");
4841 }
4842 goto out;
4843 }
4844 img_size = (uint64_t)sval;
4845 }
4846 break;
4847 }
4848 }
4849
4850 if (qemu_opts_foreach(&qemu_object_opts,
4851 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004852 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004853 goto out;
4854 }
4855
4856 if (argc - optind > 1) {
4857 error_report("At most one filename argument is allowed.");
4858 goto out;
4859 } else if (argc - optind == 1) {
4860 filename = argv[optind];
4861 }
4862
4863 if (!filename &&
4864 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4865 error_report("--object, --image-opts, -f, and -l "
4866 "require a filename argument.");
4867 goto out;
4868 }
4869 if (filename && img_size != UINT64_MAX) {
4870 error_report("--size N cannot be used together with a filename.");
4871 goto out;
4872 }
4873 if (!filename && img_size == UINT64_MAX) {
4874 error_report("Either --size N or one filename must be specified.");
4875 goto out;
4876 }
4877
4878 if (filename) {
4879 in_blk = img_open(image_opts, filename, fmt, 0,
4880 false, false, force_share);
4881 if (!in_blk) {
4882 goto out;
4883 }
4884
4885 if (sn_opts) {
4886 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4887 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4888 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4889 &local_err);
4890 } else if (snapshot_name != NULL) {
4891 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4892 snapshot_name, &local_err);
4893 }
4894 if (local_err) {
4895 error_reportf_err(local_err, "Failed to load snapshot: ");
4896 goto out;
4897 }
4898 }
4899
4900 drv = bdrv_find_format(out_fmt);
4901 if (!drv) {
4902 error_report("Unknown file format '%s'", out_fmt);
4903 goto out;
4904 }
4905 if (!drv->create_opts) {
4906 error_report("Format driver '%s' does not support image creation",
4907 drv->format_name);
4908 goto out;
4909 }
4910
4911 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4912 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4913 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4914 if (options) {
4915 qemu_opts_do_parse(opts, options, NULL, &local_err);
4916 if (local_err) {
4917 error_report_err(local_err);
4918 error_report("Invalid options for file format '%s'", out_fmt);
4919 goto out;
4920 }
4921 }
4922 if (img_size != UINT64_MAX) {
4923 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4924 }
4925
4926 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4927 if (local_err) {
4928 error_report_err(local_err);
4929 goto out;
4930 }
4931
4932 if (output_format == OFORMAT_HUMAN) {
4933 printf("required size: %" PRIu64 "\n", info->required);
4934 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4935 } else {
4936 dump_json_block_measure_info(info);
4937 }
4938
4939 ret = 0;
4940
4941out:
4942 qapi_free_BlockMeasureInfo(info);
4943 qemu_opts_del(object_opts);
4944 qemu_opts_del(opts);
4945 qemu_opts_del(sn_opts);
4946 qemu_opts_free(create_opts);
4947 g_free(options);
4948 blk_unref(in_blk);
4949 return ret;
4950}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004951
Anthony Liguoric227f092009-10-01 16:12:16 -05004952static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004953#define DEF(option, callback, arg_string) \
4954 { option, callback },
4955#include "qemu-img-cmds.h"
4956#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004957 { NULL, NULL, },
4958};
4959
bellardea2384d2004-08-01 21:59:26 +00004960int main(int argc, char **argv)
4961{
Anthony Liguoric227f092009-10-01 16:12:16 -05004962 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004963 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004964 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004965 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004966 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004967 static const struct option long_options[] = {
4968 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004969 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004970 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004971 {0, 0, 0, 0}
4972 };
bellardea2384d2004-08-01 21:59:26 +00004973
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004974#ifdef CONFIG_POSIX
4975 signal(SIGPIPE, SIG_IGN);
4976#endif
4977
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01004978 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004979 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004980 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004981
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004982 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004983 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004984 exit(EXIT_FAILURE);
4985 }
4986
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004987 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004988
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004989 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004990 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004991 if (argc < 2) {
4992 error_exit("Not enough arguments");
4993 }
Stuart Brady153859b2009-06-07 00:42:17 +01004994
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004995 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004996 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004997 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004998
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004999 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005000 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005001 case ':':
5002 missing_argument(argv[optind - 1]);
5003 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005004 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005005 unrecognized_option(argv[optind - 1]);
5006 return 0;
5007 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005008 help();
5009 return 0;
5010 case 'V':
5011 printf(QEMU_IMG_VERSION);
5012 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005013 case 'T':
5014 g_free(trace_file);
5015 trace_file = trace_opt_parse(optarg);
5016 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005017 }
bellardea2384d2004-08-01 21:59:26 +00005018 }
Stuart Brady153859b2009-06-07 00:42:17 +01005019
Denis V. Lunev10985132016-06-17 17:44:13 +03005020 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005021
Denis V. Lunev10985132016-06-17 17:44:13 +03005022 /* reset getopt_long scanning */
5023 argc -= optind;
5024 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005025 return 0;
5026 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005027 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005028 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005029
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005030 if (!trace_init_backends()) {
5031 exit(1);
5032 }
5033 trace_init_file(trace_file);
5034 qemu_set_log(LOG_TRACE);
5035
Denis V. Lunev10985132016-06-17 17:44:13 +03005036 /* find the command */
5037 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5038 if (!strcmp(cmdname, cmd->name)) {
5039 return cmd->handler(argc, argv);
5040 }
5041 }
Jeff Cody7db16892014-04-25 17:02:32 -04005042
Stuart Brady153859b2009-06-07 00:42:17 +01005043 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005044 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005045}