blob: 6233b8ca5682afd2f98bf33a6cb17997b5f1193e [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 Armbrusterdb725812019-08-12 07:23:50 +020041#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020042#include "qemu/module.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020043#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000044#include "qom/object_interfaces.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,
Max Reitz8eaac022019-05-07 22:35:03 +020072 OPTION_SALVAGE = 267,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050073};
74
75typedef enum OutputFormat {
76 OFORMAT_JSON,
77 OFORMAT_HUMAN,
78} OutputFormat;
79
Kevin Wolfe6996142016-03-15 13:03:11 +010080/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040081#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000082
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010083static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000084{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010085 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000086}
87
Fam Zhengac1307a2014-04-22 13:36:11 +080088static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
89{
90 va_list ap;
91
Fam Zhengac1307a2014-04-22 13:36:11 +080092 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +020093 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +080094 va_end(ap);
95
Markus Armbrustere9e1d922019-04-17 21:06:27 +020096 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +080097 exit(EXIT_FAILURE);
98}
99
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800100static void QEMU_NORETURN missing_argument(const char *option)
101{
102 error_exit("missing argument for option '%s'", option);
103}
104
105static void QEMU_NORETURN unrecognized_option(const char *option)
106{
107 error_exit("unrecognized option '%s'", option);
108}
109
blueswir1d2c639d2009-01-24 18:19:25 +0000110/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800111static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000112{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100113 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400114 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300115 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300116 "QEMU disk image utility\n"
117 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300118 " '-h', '--help' display this help and exit\n"
119 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300120 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
121 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300122 "\n"
malc3f020d72010-02-08 12:04:56 +0300123 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100124#define DEF(option, callback, arg_string) \
125 " " arg_string "\n"
126#include "qemu-img-cmds.h"
127#undef DEF
malc3f020d72010-02-08 12:04:56 +0300128 "\n"
129 "Command parameters:\n"
130 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000131 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
132 " manual page for a description of the object properties. The most common\n"
133 " object type is a 'secret', which is used to supply passwords and/or\n"
134 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300135 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400136 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800137 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
138 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100139 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
140 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300141 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200142 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
143 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
144 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300145 " 'output_filename' is the destination disk image filename\n"
146 " 'output_fmt' is the destination format\n"
147 " 'options' is a comma separated list of format specific options in a\n"
148 " name=value format. Use -o ? for an overview of the options supported by the\n"
149 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800150 " 'snapshot_param' is param used for internal snapshot, format\n"
151 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
152 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300153 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300159 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200160 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100161 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
166 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200167 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300170 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200175 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200176 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
181 "\n"
malc3f020d72010-02-08 12:04:56 +0300182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100187 " '-l' lists all snapshots in the given image\n"
188 "\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
193 "\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
196 "(default: 512)\n"
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100201
202 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300203 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500204 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800205 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000206}
207
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000208static QemuOptsList qemu_object_opts = {
209 .name = "object",
210 .implied_opt_name = "qom-type",
211 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
212 .desc = {
213 { }
214 },
215};
216
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200217static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
218{
219 if (user_creatable_print_help(type, opts)) {
220 exit(0);
221 }
222 return true;
223}
224
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000225static QemuOptsList qemu_source_opts = {
226 .name = "source",
227 .implied_opt_name = "file",
228 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
229 .desc = {
230 { }
231 },
232};
233
Stefan Weil7c30f652013-06-16 17:01:05 +0200234static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100235{
236 int ret = 0;
237 if (!quiet) {
238 va_list args;
239 va_start(args, fmt);
240 ret = vprintf(fmt, args);
241 va_end(args);
242 }
243 return ret;
244}
245
bellardea2384d2004-08-01 21:59:26 +0000246
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100247static int print_block_option_help(const char *filename, const char *fmt)
248{
249 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800250 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500251 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100252
253 /* Find driver and parse its options */
254 drv = bdrv_find_format(fmt);
255 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100256 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100257 return 1;
258 }
259
Max Reitzd402b6a2018-05-09 23:00:21 +0200260 if (!drv->create_opts) {
261 error_report("Format driver '%s' does not support image creation", fmt);
262 return 1;
263 }
264
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800265 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100266 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500267 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100268 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100269 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800270 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100271 return 1;
272 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200273 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100274 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200275 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100276 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200277 return 1;
278 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800279 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100280 }
281
Max Reitzf4619af2019-04-13 17:20:37 +0200282 if (filename) {
283 printf("Supported options:\n");
284 } else {
285 printf("Supported %s options:\n", fmt);
286 }
Max Reitz63898712018-10-19 18:49:25 +0200287 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800288 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200289
290 if (!filename) {
291 printf("\n"
292 "The protocol level may support further options.\n"
293 "Specify the target filename to include those options.\n");
294 }
295
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100296 return 0;
297}
298
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000299
Max Reitzefaa7c42016-03-16 19:54:38 +0100300static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100301 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800302 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000303{
304 QDict *options;
305 Error *local_err = NULL;
306 BlockBackend *blk;
307 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800308 if (force_share) {
309 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200310 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800311 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200312 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800313 return NULL;
314 }
Max Reitz4615f872018-05-02 22:20:50 +0200315 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800316 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100317 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000318 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100319 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000320 return NULL;
321 }
Kevin Wolfce099542016-03-15 13:01:04 +0100322 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000323
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000324 return blk;
325}
326
Max Reitzefaa7c42016-03-16 19:54:38 +0100327static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100328 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000329 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800330 bool writethrough, bool quiet,
331 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000332{
333 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200334 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100335
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100336 if (!options) {
337 options = qdict_new();
338 }
bellard75c23802004-08-27 21:28:58 +0000339 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500340 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000341 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100342
Fam Zheng335e9932017-05-03 00:35:39 +0800343 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500344 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800345 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100346 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500347 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100348 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000349 return NULL;
bellard75c23802004-08-27 21:28:58 +0000350 }
Kevin Wolfce099542016-03-15 13:01:04 +0100351 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100352
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200353 return blk;
bellard75c23802004-08-27 21:28:58 +0000354}
355
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000356
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100357static int img_add_key_secrets(void *opaque,
358 const char *name, const char *value,
359 Error **errp)
360{
361 QDict *options = opaque;
362
363 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600364 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100365 }
366
367 return 0;
368}
369
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100370
Max Reitzefaa7c42016-03-16 19:54:38 +0100371static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000372 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100373 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800374 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000375{
376 BlockBackend *blk;
377 if (image_opts) {
378 QemuOpts *opts;
379 if (fmt) {
380 error_report("--image-opts and --format are mutually exclusive");
381 return NULL;
382 }
383 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
384 filename, true);
385 if (!opts) {
386 return NULL;
387 }
Fam Zheng335e9932017-05-03 00:35:39 +0800388 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
389 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000390 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100391 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800392 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000393 }
394 return blk;
395}
396
397
Chunyan Liu83d05212014-06-05 17:20:51 +0800398static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100399 const char *base_filename,
400 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200401{
Markus Armbruster6750e792015-02-12 17:43:08 +0100402 Error *err = NULL;
403
Kevin Wolfefa84d42009-05-18 16:42:12 +0200404 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100405 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100406 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100407 error_report("Backing file not supported for file format '%s'",
408 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 }
413 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100414 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100415 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100416 error_report("Backing file format not supported for file "
417 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100418 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900419 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200420 }
421 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900422 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200423}
424
Markus Armbruster606caa02017-02-21 21:14:04 +0100425static int64_t cvtnum(const char *s)
426{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100427 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100428 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100429
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100430 err = qemu_strtosz(s, NULL, &value);
431 if (err < 0) {
432 return err;
433 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100434 if (value > INT64_MAX) {
435 return -ERANGE;
436 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100437 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100438}
439
bellardea2384d2004-08-01 21:59:26 +0000440static int img_create(int argc, char **argv)
441{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200442 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100443 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000444 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000445 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000446 const char *filename;
447 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200448 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200449 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100450 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400451 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000452
bellardea2384d2004-08-01 21:59:26 +0000453 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000454 static const struct option long_options[] = {
455 {"help", no_argument, 0, 'h'},
456 {"object", required_argument, 0, OPTION_OBJECT},
457 {0, 0, 0, 0}
458 };
John Snow6e6e55f2017-07-17 20:34:22 -0400459 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000460 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100461 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000462 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100463 }
bellardea2384d2004-08-01 21:59:26 +0000464 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800465 case ':':
466 missing_argument(argv[optind - 1]);
467 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100468 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800469 unrecognized_option(argv[optind - 1]);
470 break;
bellardea2384d2004-08-01 21:59:26 +0000471 case 'h':
472 help();
473 break;
aliguori9230eaf2009-03-28 17:55:19 +0000474 case 'F':
475 base_fmt = optarg;
476 break;
bellardea2384d2004-08-01 21:59:26 +0000477 case 'b':
478 base_filename = optarg;
479 break;
480 case 'f':
481 fmt = optarg;
482 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200483 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100484 if (!is_valid_option_list(optarg)) {
485 error_report("Invalid option list: %s", optarg);
486 goto fail;
487 }
488 if (!options) {
489 options = g_strdup(optarg);
490 } else {
491 char *old_options = options;
492 options = g_strdup_printf("%s,%s", options, optarg);
493 g_free(old_options);
494 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200495 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100496 case 'q':
497 quiet = true;
498 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400499 case 'u':
500 flags |= BDRV_O_NO_BACKING;
501 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000502 case OPTION_OBJECT: {
503 QemuOpts *opts;
504 opts = qemu_opts_parse_noisily(&qemu_object_opts,
505 optarg, true);
506 if (!opts) {
507 goto fail;
508 }
509 } break;
bellardea2384d2004-08-01 21:59:26 +0000510 }
511 }
aliguori9230eaf2009-03-28 17:55:19 +0000512
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900513 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100514 filename = (optind < argc) ? argv[optind] : NULL;
515 if (options && has_help_option(options)) {
516 g_free(options);
517 return print_block_option_help(filename, fmt);
518 }
519
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100520 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800521 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100522 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100523 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900524
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000525 if (qemu_opts_foreach(&qemu_object_opts,
526 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200527 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000528 goto fail;
529 }
530
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100531 /* Get image size, if specified */
532 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100533 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100534
535 sval = cvtnum(argv[optind++]);
536 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800537 if (sval == -ERANGE) {
538 error_report("Image size must be less than 8 EiB!");
539 } else {
540 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200541 "G, T, P or E suffixes for ");
542 error_report("kilobytes, megabytes, gigabytes, terabytes, "
543 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800544 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100545 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100546 }
547 img_size = (uint64_t)sval;
548 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200549 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800550 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200551 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100552
Luiz Capitulino9b375252012-11-30 10:52:05 -0200553 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400554 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100555 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100556 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100557 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900558 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200559
Kevin Wolf77386bf2014-02-21 16:24:04 +0100560 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000561 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100562
563fail:
564 g_free(options);
565 return 1;
bellardea2384d2004-08-01 21:59:26 +0000566}
567
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100568static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500569{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500570 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500571 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100572 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600573
574 visit_type_ImageCheck(v, NULL, &check, &error_abort);
575 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500576 str = qobject_to_json_pretty(obj);
577 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100578 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200579 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600580 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200581 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500582}
583
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100584static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500585{
586 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100587 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500588 } else {
589 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100590 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
591 "Data may be corrupted, or further writes to the image "
592 "may corrupt it.\n",
593 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500594 }
595
596 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100597 qprintf(quiet,
598 "\n%" PRId64 " leaked clusters were found on the image.\n"
599 "This means waste of disk space, but no harm to data.\n",
600 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500601 }
602
603 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100604 qprintf(quiet,
605 "\n%" PRId64
606 " internal errors have occurred during the check.\n",
607 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608 }
609 }
610
611 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100612 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
613 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
614 check->allocated_clusters, check->total_clusters,
615 check->allocated_clusters * 100.0 / check->total_clusters,
616 check->fragmented_clusters * 100.0 / check->allocated_clusters,
617 check->compressed_clusters * 100.0 /
618 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500619 }
620
621 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100622 qprintf(quiet,
623 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500624 }
625}
626
627static int collect_image_check(BlockDriverState *bs,
628 ImageCheck *check,
629 const char *filename,
630 const char *fmt,
631 int fix)
632{
633 int ret;
634 BdrvCheckResult result;
635
636 ret = bdrv_check(bs, &result, fix);
637 if (ret < 0) {
638 return ret;
639 }
640
641 check->filename = g_strdup(filename);
642 check->format = g_strdup(bdrv_get_format_name(bs));
643 check->check_errors = result.check_errors;
644 check->corruptions = result.corruptions;
645 check->has_corruptions = result.corruptions != 0;
646 check->leaks = result.leaks;
647 check->has_leaks = result.leaks != 0;
648 check->corruptions_fixed = result.corruptions_fixed;
649 check->has_corruptions_fixed = result.corruptions != 0;
650 check->leaks_fixed = result.leaks_fixed;
651 check->has_leaks_fixed = result.leaks != 0;
652 check->image_end_offset = result.image_end_offset;
653 check->has_image_end_offset = result.image_end_offset != 0;
654 check->total_clusters = result.bfi.total_clusters;
655 check->has_total_clusters = result.bfi.total_clusters != 0;
656 check->allocated_clusters = result.bfi.allocated_clusters;
657 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
658 check->fragmented_clusters = result.bfi.fragmented_clusters;
659 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100660 check->compressed_clusters = result.bfi.compressed_clusters;
661 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500662
663 return 0;
664}
665
Kevin Wolfe076f332010-06-29 11:43:13 +0200666/*
667 * Checks an image for consistency. Exit codes:
668 *
Max Reitzd6635c42014-06-02 22:15:21 +0200669 * 0 - Check completed, image is good
670 * 1 - Check not completed because of internal errors
671 * 2 - Check completed, image is corrupted
672 * 3 - Check completed, image has leaked clusters, but is good otherwise
673 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200674 */
aliguori15859692009-04-21 23:11:53 +0000675static int img_check(int argc, char **argv)
676{
677 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500678 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200679 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200680 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000681 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200682 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100683 int flags = BDRV_O_CHECK;
684 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200685 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100686 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000687 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800688 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000689
690 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500691 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200692 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100693
aliguori15859692009-04-21 23:11:53 +0000694 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500695 int option_index = 0;
696 static const struct option long_options[] = {
697 {"help", no_argument, 0, 'h'},
698 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530699 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500700 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000701 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000702 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800703 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500704 {0, 0, 0, 0}
705 };
Fam Zheng335e9932017-05-03 00:35:39 +0800706 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500707 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100708 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000709 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100710 }
aliguori15859692009-04-21 23:11:53 +0000711 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800712 case ':':
713 missing_argument(argv[optind - 1]);
714 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100715 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800716 unrecognized_option(argv[optind - 1]);
717 break;
aliguori15859692009-04-21 23:11:53 +0000718 case 'h':
719 help();
720 break;
721 case 'f':
722 fmt = optarg;
723 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200724 case 'r':
725 flags |= BDRV_O_RDWR;
726
727 if (!strcmp(optarg, "leaks")) {
728 fix = BDRV_FIX_LEAKS;
729 } else if (!strcmp(optarg, "all")) {
730 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
731 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800732 error_exit("Unknown option value for -r "
733 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200734 }
735 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500736 case OPTION_OUTPUT:
737 output = optarg;
738 break;
Max Reitz40055952014-07-22 22:58:42 +0200739 case 'T':
740 cache = optarg;
741 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100742 case 'q':
743 quiet = true;
744 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800745 case 'U':
746 force_share = true;
747 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000748 case OPTION_OBJECT: {
749 QemuOpts *opts;
750 opts = qemu_opts_parse_noisily(&qemu_object_opts,
751 optarg, true);
752 if (!opts) {
753 return 1;
754 }
755 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000756 case OPTION_IMAGE_OPTS:
757 image_opts = true;
758 break;
aliguori15859692009-04-21 23:11:53 +0000759 }
760 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200761 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800762 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100763 }
aliguori15859692009-04-21 23:11:53 +0000764 filename = argv[optind++];
765
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500766 if (output && !strcmp(output, "json")) {
767 output_format = OFORMAT_JSON;
768 } else if (output && !strcmp(output, "human")) {
769 output_format = OFORMAT_HUMAN;
770 } else if (output) {
771 error_report("--output must be used with human or json as argument.");
772 return 1;
773 }
774
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000775 if (qemu_opts_foreach(&qemu_object_opts,
776 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200777 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000778 return 1;
779 }
780
Kevin Wolfce099542016-03-15 13:01:04 +0100781 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200782 if (ret < 0) {
783 error_report("Invalid source cache option: %s", cache);
784 return 1;
785 }
786
Fam Zheng335e9932017-05-03 00:35:39 +0800787 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
788 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200789 if (!blk) {
790 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900791 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200792 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500793
794 check = g_new0(ImageCheck, 1);
795 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200796
797 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200798 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200799 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500800 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200801 }
802
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500803 if (check->corruptions_fixed || check->leaks_fixed) {
804 int corruptions_fixed, leaks_fixed;
805
806 leaks_fixed = check->leaks_fixed;
807 corruptions_fixed = check->corruptions_fixed;
808
809 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100810 qprintf(quiet,
811 "The following inconsistencies were found and repaired:\n\n"
812 " %" PRId64 " leaked clusters\n"
813 " %" PRId64 " corruptions\n\n"
814 "Double checking the fixed image now...\n",
815 check->leaks_fixed,
816 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500817 }
818
819 ret = collect_image_check(bs, check, filename, fmt, 0);
820
821 check->leaks_fixed = leaks_fixed;
822 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200823 }
824
Max Reitz832390a2014-10-23 15:29:12 +0200825 if (!ret) {
826 switch (output_format) {
827 case OFORMAT_HUMAN:
828 dump_human_image_check(check, quiet);
829 break;
830 case OFORMAT_JSON:
831 dump_json_image_check(check, quiet);
832 break;
833 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500834 }
835
836 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200837 if (ret) {
838 error_report("Check failed: %s", strerror(-ret));
839 } else {
840 error_report("Check failed");
841 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500842 ret = 1;
843 goto fail;
844 }
845
846 if (check->corruptions) {
847 ret = 2;
848 } else if (check->leaks) {
849 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200850 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500851 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000852 }
853
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500854fail:
855 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200856 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500857 return ret;
aliguori15859692009-04-21 23:11:53 +0000858}
859
Max Reitzd4a32382014-10-24 15:57:37 +0200860typedef struct CommonBlockJobCBInfo {
861 BlockDriverState *bs;
862 Error **errp;
863} CommonBlockJobCBInfo;
864
865static void common_block_job_cb(void *opaque, int ret)
866{
867 CommonBlockJobCBInfo *cbi = opaque;
868
869 if (ret < 0) {
870 error_setg_errno(cbi->errp, -ret, "Block job failed");
871 }
Max Reitzd4a32382014-10-24 15:57:37 +0200872}
873
874static void run_block_job(BlockJob *job, Error **errp)
875{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200876 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800877 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200878
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200879 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200880 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200881 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200882 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200883 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200884 if (job->job.progress_total) {
885 progress = (float)job->job.progress_current /
886 job->job.progress_total * 100.f;
887 }
888 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200889 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200890
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200891 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200892 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800893 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200894 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800895 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200896 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200897 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200898
sochin.jiang4172a002017-06-15 14:47:33 +0800899 /* publish completion progress only when success */
900 if (!ret) {
901 qemu_progress_print(100.f, 0);
902 }
Max Reitzd4a32382014-10-24 15:57:37 +0200903}
904
bellardea2384d2004-08-01 21:59:26 +0000905static int img_commit(int argc, char **argv)
906{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400907 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200908 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200909 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200910 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100911 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200912 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100913 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200914 Error *local_err = NULL;
915 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000916 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200917 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000918
919 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400920 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200921 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000922 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000923 static const struct option long_options[] = {
924 {"help", no_argument, 0, 'h'},
925 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000926 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000927 {0, 0, 0, 0}
928 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800929 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000930 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100931 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000932 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100933 }
bellardea2384d2004-08-01 21:59:26 +0000934 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800935 case ':':
936 missing_argument(argv[optind - 1]);
937 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100938 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800939 unrecognized_option(argv[optind - 1]);
940 break;
bellardea2384d2004-08-01 21:59:26 +0000941 case 'h':
942 help();
943 break;
944 case 'f':
945 fmt = optarg;
946 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400947 case 't':
948 cache = optarg;
949 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200950 case 'b':
951 base = optarg;
952 /* -b implies -d */
953 drop = true;
954 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200955 case 'd':
956 drop = true;
957 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200958 case 'p':
959 progress = true;
960 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100961 case 'q':
962 quiet = true;
963 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000964 case OPTION_OBJECT: {
965 QemuOpts *opts;
966 opts = qemu_opts_parse_noisily(&qemu_object_opts,
967 optarg, true);
968 if (!opts) {
969 return 1;
970 }
971 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000972 case OPTION_IMAGE_OPTS:
973 image_opts = true;
974 break;
bellardea2384d2004-08-01 21:59:26 +0000975 }
976 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200977
978 /* Progress is not shown in Quiet mode */
979 if (quiet) {
980 progress = false;
981 }
982
Kevin Wolffc11eb22013-08-05 10:53:04 +0200983 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800984 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100985 }
bellardea2384d2004-08-01 21:59:26 +0000986 filename = argv[optind++];
987
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000988 if (qemu_opts_foreach(&qemu_object_opts,
989 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200990 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000991 return 1;
992 }
993
Max Reitz9a86fe42014-10-24 15:57:38 +0200994 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100995 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400996 if (ret < 0) {
997 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100998 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400999 }
1000
Fam Zheng335e9932017-05-03 00:35:39 +08001001 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1002 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001003 if (!blk) {
1004 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001005 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001006 bs = blk_bs(blk);
1007
Max Reitz687fa1d2014-10-24 15:57:39 +02001008 qemu_progress_init(progress, 1.f);
1009 qemu_progress_print(0.f, 100);
1010
Max Reitz1b22bff2014-10-24 15:57:40 +02001011 if (base) {
1012 base_bs = bdrv_find_backing_image(bs, base);
1013 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001014 error_setg(&local_err,
1015 "Did not find '%s' in the backing chain of '%s'",
1016 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001017 goto done;
1018 }
1019 } else {
1020 /* This is different from QMP, which by default uses the deepest file in
1021 * the backing chain (i.e., the very base); however, the traditional
1022 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001023 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001024 if (!base_bs) {
1025 error_setg(&local_err, "Image does not have a backing file");
1026 goto done;
1027 }
bellardea2384d2004-08-01 21:59:26 +00001028 }
1029
Max Reitzd4a32382014-10-24 15:57:37 +02001030 cbi = (CommonBlockJobCBInfo){
1031 .errp = &local_err,
1032 .bs = bs,
1033 };
1034
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001035 aio_context = bdrv_get_aio_context(bs);
1036 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001037 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001038 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001039 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001040 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001041 if (local_err) {
1042 goto done;
1043 }
1044
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001045 /* When the block job completes, the BlockBackend reference will point to
1046 * the old backing file. In order to avoid that the top image is already
1047 * deleted, so we can still empty it afterwards, increment the reference
1048 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001049 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001050 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001051 }
1052
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001053 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001054 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001055 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001056 if (local_err) {
1057 goto unref_backing;
1058 }
1059
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001060 if (!drop && bs->drv->bdrv_make_empty) {
1061 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001062 if (ret) {
1063 error_setg_errno(&local_err, -ret, "Could not empty %s",
1064 filename);
1065 goto unref_backing;
1066 }
1067 }
1068
1069unref_backing:
1070 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001071 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001072 }
Max Reitzd4a32382014-10-24 15:57:37 +02001073
1074done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001075 qemu_progress_end();
1076
Markus Armbruster26f54e92014-10-07 13:59:04 +02001077 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001078
1079 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001080 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001081 return 1;
1082 }
Max Reitzd4a32382014-10-24 15:57:37 +02001083
1084 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001085 return 0;
1086}
1087
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001088/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001089 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1090 * of the first sector boundary within buf where the sector contains a
1091 * non-zero byte. This function is robust to a buffer that is not
1092 * sector-aligned.
1093 */
1094static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1095{
1096 int64_t i;
1097 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1098
1099 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1100 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1101 return i;
1102 }
1103 }
1104 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1105 return i;
1106 }
1107 return -1;
1108}
1109
1110/*
thsf58c7b32008-06-05 21:53:49 +00001111 * Returns true iff the first sector pointed to by 'buf' contains at least
1112 * a non-NUL byte.
1113 *
1114 * 'pnum' is set to the number of sectors (including and immediately following
1115 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001116 * The function will try to align the end offset to alignment boundaries so
1117 * that the request will at least end aligned and consequtive requests will
1118 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001119 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001120static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1121 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001122{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001123 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001124 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001125
1126 if (n <= 0) {
1127 *pnum = 0;
1128 return 0;
1129 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001130 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001131 for(i = 1; i < n; i++) {
1132 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001133 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001134 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001135 }
bellardea2384d2004-08-01 21:59:26 +00001136 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001137
1138 tail = (sector_num + i) & (alignment - 1);
1139 if (tail) {
1140 if (is_zero && i <= tail) {
1141 /* treat unallocated areas which only consist
1142 * of a small tail as allocated. */
1143 is_zero = false;
1144 }
1145 if (!is_zero) {
1146 /* align up end offset of allocated areas. */
1147 i += alignment - tail;
1148 i = MIN(i, n);
1149 } else {
1150 /* align down end offset of zero areas. */
1151 i -= tail;
1152 }
1153 }
bellardea2384d2004-08-01 21:59:26 +00001154 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001155 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001156}
1157
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001158/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001159 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1160 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1161 * breaking up write requests for only small sparse areas.
1162 */
1163static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001164 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001165{
1166 int ret;
1167 int num_checked, num_used;
1168
1169 if (n < min) {
1170 min = n;
1171 }
1172
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001173 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001174 if (!ret) {
1175 return ret;
1176 }
1177
1178 num_used = *pnum;
1179 buf += BDRV_SECTOR_SIZE * *pnum;
1180 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001181 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001182 num_checked = num_used;
1183
1184 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001185 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001186
1187 buf += BDRV_SECTOR_SIZE * *pnum;
1188 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001189 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001190 num_checked += *pnum;
1191 if (ret) {
1192 num_used = num_checked;
1193 } else if (*pnum >= min) {
1194 break;
1195 }
1196 }
1197
1198 *pnum = num_used;
1199 return 1;
1200}
1201
1202/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001203 * Compares two buffers sector by sector. Returns 0 if the first
1204 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001205 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001206 * pnum is set to the sector-aligned size of the buffer prefix that
1207 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001208 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001209static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1210 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001211{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001212 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001213 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001214
Eric Blakedc61cd32017-10-11 22:47:14 -05001215 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001216
Eric Blakedc61cd32017-10-11 22:47:14 -05001217 res = !!memcmp(buf1, buf2, i);
1218 while (i < bytes) {
1219 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001220
Eric Blakedc61cd32017-10-11 22:47:14 -05001221 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001222 break;
1223 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001224 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001225 }
1226
1227 *pnum = i;
1228 return res;
1229}
1230
Stefano Garzarella97ede572019-05-08 12:43:24 +02001231#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001232
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001233/*
1234 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1235 *
Eric Blake0608e402017-10-11 22:47:12 -05001236 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1237 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1238 * failure), and 4 on error (the exit status for read errors), after emitting
1239 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001240 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001241 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001242 * @param offset: Starting offset to check
1243 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001244 * @param filename: Name of disk file we are checking (logging purpose)
1245 * @param buffer: Allocated buffer for storing read data
1246 * @param quiet: Flag for quiet mode
1247 */
Eric Blakec41508e2017-10-11 22:47:13 -05001248static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1249 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001250 uint8_t *buffer, bool quiet)
1251{
Eric Blakedebb38a2017-10-11 22:47:11 -05001252 int ret = 0;
1253 int64_t idx;
1254
Eric Blakec41508e2017-10-11 22:47:13 -05001255 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001256 if (ret < 0) {
1257 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001258 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001259 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001260 }
Eric Blakec41508e2017-10-11 22:47:13 -05001261 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001262 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001263 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001264 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001265 return 1;
1266 }
1267
1268 return 0;
1269}
1270
1271/*
1272 * Compares two images. Exit codes:
1273 *
1274 * 0 - Images are identical
1275 * 1 - Images differ
1276 * >1 - Error occurred
1277 */
1278static int img_compare(int argc, char **argv)
1279{
Max Reitz40055952014-07-22 22:58:42 +02001280 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001281 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001282 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001283 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001284 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001285 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001286 int allocated1, allocated2;
1287 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1288 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001289 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001290 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001291 int64_t total_size;
1292 int64_t offset = 0;
1293 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001294 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001295 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001296 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001297 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001298
Max Reitz40055952014-07-22 22:58:42 +02001299 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001300 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001301 static const struct option long_options[] = {
1302 {"help", no_argument, 0, 'h'},
1303 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001304 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001305 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001306 {0, 0, 0, 0}
1307 };
Fam Zheng335e9932017-05-03 00:35:39 +08001308 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001309 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001310 if (c == -1) {
1311 break;
1312 }
1313 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001314 case ':':
1315 missing_argument(argv[optind - 1]);
1316 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001317 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001318 unrecognized_option(argv[optind - 1]);
1319 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001320 case 'h':
1321 help();
1322 break;
1323 case 'f':
1324 fmt1 = optarg;
1325 break;
1326 case 'F':
1327 fmt2 = optarg;
1328 break;
Max Reitz40055952014-07-22 22:58:42 +02001329 case 'T':
1330 cache = optarg;
1331 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001332 case 'p':
1333 progress = true;
1334 break;
1335 case 'q':
1336 quiet = true;
1337 break;
1338 case 's':
1339 strict = true;
1340 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001341 case 'U':
1342 force_share = true;
1343 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001344 case OPTION_OBJECT: {
1345 QemuOpts *opts;
1346 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1347 optarg, true);
1348 if (!opts) {
1349 ret = 2;
1350 goto out4;
1351 }
1352 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001353 case OPTION_IMAGE_OPTS:
1354 image_opts = true;
1355 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001356 }
1357 }
1358
1359 /* Progress is not shown in Quiet mode */
1360 if (quiet) {
1361 progress = false;
1362 }
1363
1364
Kevin Wolffc11eb22013-08-05 10:53:04 +02001365 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001366 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001367 }
1368 filename1 = argv[optind++];
1369 filename2 = argv[optind++];
1370
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001371 if (qemu_opts_foreach(&qemu_object_opts,
1372 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001373 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001374 ret = 2;
1375 goto out4;
1376 }
1377
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001378 /* Initialize before goto out */
1379 qemu_progress_init(progress, 2.0);
1380
Kevin Wolfce099542016-03-15 13:01:04 +01001381 flags = 0;
1382 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001383 if (ret < 0) {
1384 error_report("Invalid source cache option: %s", cache);
1385 ret = 2;
1386 goto out3;
1387 }
1388
Fam Zheng335e9932017-05-03 00:35:39 +08001389 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1390 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001391 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001393 goto out3;
1394 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001395
Fam Zheng335e9932017-05-03 00:35:39 +08001396 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1397 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001398 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001399 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001400 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001401 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001402 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001403 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001404
Max Reitzf1d3cd72015-02-05 13:58:18 -05001405 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1406 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001407 total_size1 = blk_getlength(blk1);
1408 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001409 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001410 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001411 ret = 4;
1412 goto out;
1413 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001414 total_size2 = blk_getlength(blk2);
1415 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001416 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001417 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001418 ret = 4;
1419 goto out;
1420 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001421 total_size = MIN(total_size1, total_size2);
1422 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001423
1424 qemu_progress_print(0, 100);
1425
Eric Blake033d9fc2017-10-11 22:47:16 -05001426 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001427 ret = 1;
1428 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1429 goto out;
1430 }
1431
Eric Blake033d9fc2017-10-11 22:47:16 -05001432 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001433 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001434
Eric Blake033d9fc2017-10-11 22:47:16 -05001435 status1 = bdrv_block_status_above(bs1, NULL, offset,
1436 total_size1 - offset, &pnum1, NULL,
1437 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001438 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001439 ret = 3;
1440 error_report("Sector allocation test failed for %s", filename1);
1441 goto out;
1442 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001443 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001444
Eric Blake033d9fc2017-10-11 22:47:16 -05001445 status2 = bdrv_block_status_above(bs2, NULL, offset,
1446 total_size2 - offset, &pnum2, NULL,
1447 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001448 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001449 ret = 3;
1450 error_report("Sector allocation test failed for %s", filename2);
1451 goto out;
1452 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001453 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001454
1455 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001456 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001457
Fam Zheng25ad8e62016-01-13 16:37:41 +08001458 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001459 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001460 ret = 1;
1461 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001462 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001463 goto out;
1464 }
1465 }
1466 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001467 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001468 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001469 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001470 int64_t pnum;
1471
Eric Blake033d9fc2017-10-11 22:47:16 -05001472 chunk = MIN(chunk, IO_BUF_SIZE);
1473 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001474 if (ret < 0) {
1475 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001476 " of %s: %s",
1477 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001478 ret = 4;
1479 goto out;
1480 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001481 ret = blk_pread(blk2, offset, buf2, chunk);
1482 if (ret < 0) {
1483 error_report("Error while reading offset %" PRId64
1484 " of %s: %s",
1485 offset, filename2, strerror(-ret));
1486 ret = 4;
1487 goto out;
1488 }
1489 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1490 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001493 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001494 goto out;
1495 }
1496 }
1497 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001498 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001500 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001501 filename1, buf1, quiet);
1502 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001503 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001504 filename2, buf1, quiet);
1505 }
1506 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001507 goto out;
1508 }
1509 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001510 offset += chunk;
1511 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001512 }
1513
Eric Blake033d9fc2017-10-11 22:47:16 -05001514 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001515 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001516 const char *filename_over;
1517
1518 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001519 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001520 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001521 filename_over = filename1;
1522 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001523 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001524 filename_over = filename2;
1525 }
1526
Eric Blake033d9fc2017-10-11 22:47:16 -05001527 while (offset < progress_base) {
1528 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1529 progress_base - offset, &chunk,
1530 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001531 if (ret < 0) {
1532 ret = 3;
1533 error_report("Sector allocation test failed for %s",
1534 filename_over);
1535 goto out;
1536
1537 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001538 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001539 chunk = MIN(chunk, IO_BUF_SIZE);
1540 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001541 filename_over, buf1, quiet);
1542 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001543 goto out;
1544 }
1545 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001546 offset += chunk;
1547 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001548 }
1549 }
1550
1551 qprintf(quiet, "Images are identical.\n");
1552 ret = 0;
1553
1554out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001555 qemu_vfree(buf1);
1556 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001557 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001558out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001559 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001560out3:
1561 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001562out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001563 return ret;
1564}
1565
Kevin Wolf690c7302015-03-19 13:33:32 +01001566enum ImgConvertBlockStatus {
1567 BLK_DATA,
1568 BLK_ZERO,
1569 BLK_BACKING_FILE,
1570};
1571
Peter Lieven2d9187b2017-02-28 13:40:07 +01001572#define MAX_COROUTINES 16
1573
Kevin Wolf690c7302015-03-19 13:33:32 +01001574typedef struct ImgConvertState {
1575 BlockBackend **src;
1576 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001577 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001578 int64_t total_sectors;
1579 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001580 int64_t allocated_done;
1581 int64_t sector_num;
1582 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001583 enum ImgConvertBlockStatus status;
1584 int64_t sector_next_status;
1585 BlockBackend *target;
1586 bool has_zero_init;
1587 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001588 bool unallocated_blocks_are_zero;
Max Reitz4d7c4872019-07-24 19:12:29 +02001589 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001590 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001591 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001592 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001593 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001594 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001595 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001596 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001597 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001598 size_t cluster_sectors;
1599 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001600 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001601 int running_coroutines;
1602 Coroutine *co[MAX_COROUTINES];
1603 int64_t wait_sector_num[MAX_COROUTINES];
1604 CoMutex lock;
1605 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001606} ImgConvertState;
1607
Peter Lieven2d9187b2017-02-28 13:40:07 +01001608static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1609 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001610{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001611 *src_cur = 0;
1612 *src_cur_offset = 0;
1613 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1614 *src_cur_offset += s->src_sectors[*src_cur];
1615 (*src_cur)++;
1616 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001617 }
1618}
1619
1620static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1621{
Eric Blake31826642017-10-11 22:47:08 -05001622 int64_t src_cur_offset;
1623 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001624 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001625
Peter Lieven2d9187b2017-02-28 13:40:07 +01001626 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001627
1628 assert(s->total_sectors > sector_num);
1629 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1630
Max Reitz351c8ef2018-05-01 18:57:49 +02001631 if (s->target_backing_sectors >= 0) {
1632 if (sector_num >= s->target_backing_sectors) {
1633 post_backing_zero = s->unallocated_blocks_are_zero;
1634 } else if (sector_num + n > s->target_backing_sectors) {
1635 /* Split requests around target_backing_sectors (because
1636 * starting from there, zeros are handled differently) */
1637 n = s->target_backing_sectors - sector_num;
1638 }
1639 }
1640
Kevin Wolf690c7302015-03-19 13:33:32 +01001641 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001642 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1643 int64_t count;
Eric Blake31826642017-10-11 22:47:08 -05001644
Max Reitz8eaac022019-05-07 22:35:03 +02001645 do {
1646 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001647
Max Reitz8eaac022019-05-07 22:35:03 +02001648 if (s->target_has_backing) {
1649 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1650 count, &count, NULL, NULL);
1651 } else {
1652 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1653 offset, count, &count, NULL,
1654 NULL);
1655 }
1656
1657 if (ret < 0) {
1658 if (s->salvage) {
1659 if (n == 1) {
1660 if (!s->quiet) {
1661 warn_report("error while reading block status at "
1662 "offset %" PRIu64 ": %s", offset,
1663 strerror(-ret));
1664 }
1665 /* Just try to read the data, then */
1666 ret = BDRV_BLOCK_DATA;
1667 count = BDRV_SECTOR_SIZE;
1668 } else {
1669 /* Retry on a shorter range */
1670 n = DIV_ROUND_UP(n, 4);
1671 }
1672 } else {
1673 error_report("error while reading block status at offset "
1674 "%" PRIu64 ": %s", offset, strerror(-ret));
1675 return ret;
1676 }
1677 }
1678 } while (ret < 0);
1679
Eric Blake31826642017-10-11 22:47:08 -05001680 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001681
1682 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001683 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001684 } else if (ret & BDRV_BLOCK_DATA) {
1685 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001686 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001687 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001688 }
1689
1690 s->sector_next_status = sector_num + n;
1691 }
1692
1693 n = MIN(n, s->sector_next_status - sector_num);
1694 if (s->status == BLK_DATA) {
1695 n = MIN(n, s->buf_sectors);
1696 }
1697
1698 /* We need to write complete clusters for compressed images, so if an
1699 * unallocated area is shorter than that, we must consider the whole
1700 * cluster allocated. */
1701 if (s->compressed) {
1702 if (n < s->cluster_sectors) {
1703 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1704 s->status = BLK_DATA;
1705 } else {
1706 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1707 }
1708 }
1709
1710 return n;
1711}
1712
Peter Lieven2d9187b2017-02-28 13:40:07 +01001713static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1714 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001715{
Max Reitz8eaac022019-05-07 22:35:03 +02001716 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001717 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001718
Kevin Wolf690c7302015-03-19 13:33:32 +01001719 assert(nb_sectors <= s->buf_sectors);
1720 while (nb_sectors > 0) {
1721 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001722 int src_cur;
1723 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001724 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001725
1726 /* In the case of compression with multiple source files, we can get a
1727 * nb_sectors that spreads into the next part. So we must be able to
1728 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001729 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1730 blk = s->src[src_cur];
1731 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001732
Max Reitz8eaac022019-05-07 22:35:03 +02001733 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001734
Max Reitz8eaac022019-05-07 22:35:03 +02001735 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1736 if (single_read_until > offset) {
1737 n = 1;
1738 }
1739
1740 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001741 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001742 if (s->salvage) {
1743 if (n > 1) {
1744 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1745 continue;
1746 } else {
1747 if (!s->quiet) {
1748 warn_report("error while reading offset %" PRIu64
1749 ": %s", offset, strerror(-ret));
1750 }
1751 memset(buf, 0, BDRV_SECTOR_SIZE);
1752 }
1753 } else {
1754 return ret;
1755 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001756 }
1757
1758 sector_num += n;
1759 nb_sectors -= n;
1760 buf += n * BDRV_SECTOR_SIZE;
1761 }
1762
1763 return 0;
1764}
1765
Peter Lieven2d9187b2017-02-28 13:40:07 +01001766
1767static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1768 int nb_sectors, uint8_t *buf,
1769 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001770{
1771 int ret;
1772
1773 while (nb_sectors > 0) {
1774 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001775 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1776
Peter Lieven2d9187b2017-02-28 13:40:07 +01001777 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001778 case BLK_BACKING_FILE:
1779 /* If we have a backing file, leave clusters unallocated that are
1780 * unallocated in the source image, so that the backing file is
1781 * visible at the respective offset. */
1782 assert(s->target_has_backing);
1783 break;
1784
1785 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001786 /* If we're told to keep the target fully allocated (-S 0) or there
1787 * is real non-zero data, we must write it. Otherwise we can treat
1788 * it as zero sectors.
1789 * Compressed clusters need to be written as a whole, so in that
1790 * case we can only save the write if the buffer is completely
1791 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001792 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001793 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001794 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1795 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001796 (s->compressed &&
1797 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001798 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001799 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1800 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001801 if (ret < 0) {
1802 return ret;
1803 }
1804 break;
1805 }
1806 /* fall-through */
1807
1808 case BLK_ZERO:
1809 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001810 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001811 break;
1812 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001813 ret = blk_co_pwrite_zeroes(s->target,
1814 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001815 n << BDRV_SECTOR_BITS,
1816 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001817 if (ret < 0) {
1818 return ret;
1819 }
1820 break;
1821 }
1822
1823 sector_num += n;
1824 nb_sectors -= n;
1825 buf += n * BDRV_SECTOR_SIZE;
1826 }
1827
1828 return 0;
1829}
1830
Fam Zhengee5306d2018-06-01 17:26:48 +08001831static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1832 int nb_sectors)
1833{
1834 int n, ret;
1835
1836 while (nb_sectors > 0) {
1837 BlockBackend *blk;
1838 int src_cur;
1839 int64_t bs_sectors, src_cur_offset;
1840 int64_t offset;
1841
1842 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1843 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1844 blk = s->src[src_cur];
1845 bs_sectors = s->src_sectors[src_cur];
1846
1847 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1848
1849 ret = blk_co_copy_range(blk, offset, s->target,
1850 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001851 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001852 if (ret < 0) {
1853 return ret;
1854 }
1855
1856 sector_num += n;
1857 nb_sectors -= n;
1858 }
1859 return 0;
1860}
1861
Peter Lieven2d9187b2017-02-28 13:40:07 +01001862static void coroutine_fn convert_co_do_copy(void *opaque)
1863{
1864 ImgConvertState *s = opaque;
1865 uint8_t *buf = NULL;
1866 int ret, i;
1867 int index = -1;
1868
1869 for (i = 0; i < s->num_coroutines; i++) {
1870 if (s->co[i] == qemu_coroutine_self()) {
1871 index = i;
1872 break;
1873 }
1874 }
1875 assert(index >= 0);
1876
1877 s->running_coroutines++;
1878 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1879
1880 while (1) {
1881 int n;
1882 int64_t sector_num;
1883 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001884 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001885
1886 qemu_co_mutex_lock(&s->lock);
1887 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1888 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001889 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001890 }
1891 n = convert_iteration_sectors(s, s->sector_num);
1892 if (n < 0) {
1893 qemu_co_mutex_unlock(&s->lock);
1894 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001895 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001896 }
1897 /* save current sector and allocation status to local variables */
1898 sector_num = s->sector_num;
1899 status = s->status;
1900 if (!s->min_sparse && s->status == BLK_ZERO) {
1901 n = MIN(n, s->buf_sectors);
1902 }
1903 /* increment global sector counter so that other coroutines can
1904 * already continue reading beyond this request */
1905 s->sector_num += n;
1906 qemu_co_mutex_unlock(&s->lock);
1907
1908 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1909 s->allocated_done += n;
1910 qemu_progress_print(100.0 * s->allocated_done /
1911 s->allocated_sectors, 0);
1912 }
1913
Fam Zhengee5306d2018-06-01 17:26:48 +08001914retry:
1915 copy_range = s->copy_range && s->status == BLK_DATA;
1916 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001917 ret = convert_co_read(s, sector_num, n, buf);
1918 if (ret < 0) {
1919 error_report("error while reading sector %" PRId64
1920 ": %s", sector_num, strerror(-ret));
1921 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001922 }
1923 } else if (!s->min_sparse && status == BLK_ZERO) {
1924 status = BLK_DATA;
1925 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1926 }
1927
1928 if (s->wr_in_order) {
1929 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001930 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001931 s->wait_sector_num[index] = sector_num;
1932 qemu_coroutine_yield();
1933 }
1934 s->wait_sector_num[index] = -1;
1935 }
1936
Anton Nefedovb91127e2017-04-26 11:33:15 +03001937 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001938 if (copy_range) {
1939 ret = convert_co_copy_range(s, sector_num, n);
1940 if (ret) {
1941 s->copy_range = false;
1942 goto retry;
1943 }
1944 } else {
1945 ret = convert_co_write(s, sector_num, n, buf, status);
1946 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001947 if (ret < 0) {
1948 error_report("error while writing sector %" PRId64
1949 ": %s", sector_num, strerror(-ret));
1950 s->ret = ret;
1951 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001952 }
1953
1954 if (s->wr_in_order) {
1955 /* reenter the coroutine that might have waited
1956 * for this write to complete */
1957 s->wr_offs = sector_num + n;
1958 for (i = 0; i < s->num_coroutines; i++) {
1959 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1960 /*
1961 * A -> B -> A cannot occur because A has
1962 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1963 * B will never enter A during this time window.
1964 */
1965 qemu_coroutine_enter(s->co[i]);
1966 break;
1967 }
1968 }
1969 }
1970 }
1971
Peter Lieven2d9187b2017-02-28 13:40:07 +01001972 qemu_vfree(buf);
1973 s->co[index] = NULL;
1974 s->running_coroutines--;
1975 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1976 /* the convert job finished successfully */
1977 s->ret = 0;
1978 }
1979}
1980
Kevin Wolf690c7302015-03-19 13:33:32 +01001981static int convert_do_copy(ImgConvertState *s)
1982{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001983 int ret, i, n;
1984 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001985
1986 /* Check whether we have zero initialisation or can get it efficiently */
Max Reitz4d7c4872019-07-24 19:12:29 +02001987 if (s->target_is_new && s->min_sparse && !s->target_has_backing) {
1988 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
1989 } else {
1990 s->has_zero_init = false;
1991 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001992
1993 if (!s->has_zero_init && !s->target_has_backing &&
1994 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1995 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001996 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001997 if (ret == 0) {
1998 s->has_zero_init = true;
1999 }
2000 }
2001
2002 /* Allocate buffer for copied data. For compressed images, only one cluster
2003 * can be copied at a time. */
2004 if (s->compressed) {
2005 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2006 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002007 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002008 }
2009 s->buf_sectors = s->cluster_sectors;
2010 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002011
Kevin Wolf690c7302015-03-19 13:33:32 +01002012 while (sector_num < s->total_sectors) {
2013 n = convert_iteration_sectors(s, sector_num);
2014 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002015 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002016 }
Max Reitzaad15de2016-03-24 23:33:57 +01002017 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2018 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002019 s->allocated_sectors += n;
2020 }
2021 sector_num += n;
2022 }
2023
2024 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002025 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002026 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002027
Peter Lieven2d9187b2017-02-28 13:40:07 +01002028 qemu_co_mutex_init(&s->lock);
2029 for (i = 0; i < s->num_coroutines; i++) {
2030 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2031 s->wait_sector_num[i] = -1;
2032 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002033 }
2034
Anton Nefedovb91127e2017-04-26 11:33:15 +03002035 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002036 main_loop_wait(false);
2037 }
2038
2039 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002040 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002041 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002042 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002043 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002044 }
2045 }
2046
Peter Lieven2d9187b2017-02-28 13:40:07 +01002047 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002048}
2049
Peter Lieven6360ab22018-07-13 09:15:39 +02002050#define MAX_BUF_SECTORS 32768
2051
bellardea2384d2004-08-01 21:59:26 +00002052static int img_convert(int argc, char **argv)
2053{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002054 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002055 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002056 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2057 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002058 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002059 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002060 BlockDriverState *out_bs;
2061 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002062 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002063 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002064 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002065 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002066 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002067 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002068 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002069 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002070 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002071
Peter Lieven9fd77f92017-04-21 11:11:55 +02002072 ImgConvertState s = (ImgConvertState) {
2073 /* Need at least 4k of zeros for sparse detection */
2074 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002075 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002076 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2077 .wr_in_order = true,
2078 .num_coroutines = 8,
2079 };
2080
bellardea2384d2004-08-01 21:59:26 +00002081 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002082 static const struct option long_options[] = {
2083 {"help", no_argument, 0, 'h'},
2084 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002085 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002086 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002087 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002088 {"salvage", no_argument, 0, OPTION_SALVAGE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002089 {0, 0, 0, 0}
2090 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002091 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002092 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002093 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002094 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002095 }
bellardea2384d2004-08-01 21:59:26 +00002096 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002097 case ':':
2098 missing_argument(argv[optind - 1]);
2099 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002100 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002101 unrecognized_option(argv[optind - 1]);
2102 break;
bellardea2384d2004-08-01 21:59:26 +00002103 case 'h':
2104 help();
2105 break;
2106 case 'f':
2107 fmt = optarg;
2108 break;
2109 case 'O':
2110 out_fmt = optarg;
2111 break;
thsf58c7b32008-06-05 21:53:49 +00002112 case 'B':
2113 out_baseimg = optarg;
2114 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002115 case 'C':
2116 s.copy_range = true;
2117 break;
bellardea2384d2004-08-01 21:59:26 +00002118 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002119 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002120 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002121 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002122 if (!is_valid_option_list(optarg)) {
2123 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002124 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002125 }
2126 if (!options) {
2127 options = g_strdup(optarg);
2128 } else {
2129 char *old_options = options;
2130 options = g_strdup_printf("%s,%s", options, optarg);
2131 g_free(old_options);
2132 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002133 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002134 case 'l':
2135 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002136 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2137 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002138 if (!sn_opts) {
2139 error_report("Failed in parsing snapshot param '%s'",
2140 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002141 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002142 }
2143 } else {
2144 snapshot_name = optarg;
2145 }
2146 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002147 case 'S':
2148 {
2149 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002150
2151 sval = cvtnum(optarg);
Nir Soffer1bbbf322019-08-27 21:59:12 +03002152 if (sval < 0 || !QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002153 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2154 error_report("Invalid buffer size for sparse output specified. "
2155 "Valid sizes are multiples of %llu up to %llu. Select "
2156 "0 to disable sparse detection (fully allocates output).",
2157 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002158 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002159 }
2160
Peter Lieven9fd77f92017-04-21 11:11:55 +02002161 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002162 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002163 break;
2164 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002165 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002166 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002167 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002168 case 't':
2169 cache = optarg;
2170 break;
Max Reitz40055952014-07-22 22:58:42 +02002171 case 'T':
2172 src_cache = optarg;
2173 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002174 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002175 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002176 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002177 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002178 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002179 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002180 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002181 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2182 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002183 error_report("Invalid number of coroutines. Allowed number of"
2184 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002185 goto fail_getopt;
2186 }
2187 break;
2188 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002189 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002190 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002191 case 'U':
2192 force_share = true;
2193 break;
Max Reitz3258b912017-04-26 15:46:47 +02002194 case OPTION_OBJECT: {
2195 QemuOpts *object_opts;
2196 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2197 optarg, true);
2198 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002199 goto fail_getopt;
2200 }
2201 break;
Max Reitz3258b912017-04-26 15:46:47 +02002202 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002203 case OPTION_IMAGE_OPTS:
2204 image_opts = true;
2205 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002206 case OPTION_SALVAGE:
2207 s.salvage = true;
2208 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002209 case OPTION_TARGET_IMAGE_OPTS:
2210 tgt_image_opts = true;
2211 break;
bellardea2384d2004-08-01 21:59:26 +00002212 }
2213 }
ths3b46e622007-09-17 08:09:54 +00002214
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002215 if (!out_fmt && !tgt_image_opts) {
2216 out_fmt = "raw";
2217 }
2218
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002219 if (qemu_opts_foreach(&qemu_object_opts,
2220 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002221 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002222 goto fail_getopt;
2223 }
2224
Fam Zhenge11ce122018-07-27 11:34:01 +08002225 if (s.compressed && s.copy_range) {
2226 error_report("Cannot enable copy offloading when -c is used");
2227 goto fail_getopt;
2228 }
2229
2230 if (explict_min_sparse && s.copy_range) {
2231 error_report("Cannot enable copy offloading when -S is used");
2232 goto fail_getopt;
2233 }
2234
Max Reitz8eaac022019-05-07 22:35:03 +02002235 if (s.copy_range && s.salvage) {
2236 error_report("Cannot use copy offloading in salvaging mode");
2237 goto fail_getopt;
2238 }
2239
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002240 if (tgt_image_opts && !skip_create) {
2241 error_report("--target-image-opts requires use of -n flag");
2242 goto fail_getopt;
2243 }
2244
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002245 if (skip_create && options) {
2246 warn_report("-o has no effect when skipping image creation");
2247 warn_report("This will become an error in future QEMU versions.");
2248 }
2249
Peter Lieven9fd77f92017-04-21 11:11:55 +02002250 s.src_num = argc - optind - 1;
2251 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2252
2253 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002254 if (out_fmt) {
2255 ret = print_block_option_help(out_filename, out_fmt);
2256 goto fail_getopt;
2257 } else {
2258 error_report("Option help requires a format be specified");
2259 goto fail_getopt;
2260 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002261 }
2262
2263 if (s.src_num < 1) {
2264 error_report("Must specify image file name");
2265 goto fail_getopt;
2266 }
2267
2268
Peter Lieven9fd77f92017-04-21 11:11:55 +02002269 /* ret is still -EINVAL until here */
2270 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2271 if (ret < 0) {
2272 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002273 goto fail_getopt;
2274 }
2275
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002276 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002277 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002278 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002279 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002280 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002281 qemu_progress_print(0, 100);
2282
Peter Lieven9fd77f92017-04-21 11:11:55 +02002283 s.src = g_new0(BlockBackend *, s.src_num);
2284 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002285
Peter Lieven9fd77f92017-04-21 11:11:55 +02002286 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2287 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002288 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002289 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002290 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002291 ret = -1;
2292 goto out;
2293 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002294 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2295 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002296 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002297 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002298 ret = -1;
2299 goto out;
2300 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002301 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002302 }
bellardea2384d2004-08-01 21:59:26 +00002303
Wenchao Xiaef806542013-12-04 17:10:57 +08002304 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002305 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002306 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2307 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2308 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002309 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002310 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002311 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002312 ret = -1;
2313 goto out;
2314 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002315
Peter Lieven9fd77f92017-04-21 11:11:55 +02002316 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2317 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002318 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002319 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002320 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002321 ret = -1;
2322 goto out;
edison51ef6722010-09-21 19:58:41 -07002323 }
2324
Max Reitz2e024cd2015-02-11 09:58:46 -05002325 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002326 /* Find driver and parse its options */
2327 drv = bdrv_find_format(out_fmt);
2328 if (!drv) {
2329 error_report("Unknown file format '%s'", out_fmt);
2330 ret = -1;
2331 goto out;
2332 }
2333
2334 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2335 if (!proto_drv) {
2336 error_report_err(local_err);
2337 ret = -1;
2338 goto out;
2339 }
2340
Max Reitz2e024cd2015-02-11 09:58:46 -05002341 if (!drv->create_opts) {
2342 error_report("Format driver '%s' does not support image creation",
2343 drv->format_name);
2344 ret = -1;
2345 goto out;
2346 }
Max Reitzf75613c2014-12-02 18:32:46 +01002347
Max Reitz2e024cd2015-02-11 09:58:46 -05002348 if (!proto_drv->create_opts) {
2349 error_report("Protocol driver '%s' does not support image creation",
2350 proto_drv->format_name);
2351 ret = -1;
2352 goto out;
2353 }
Max Reitzf75613c2014-12-02 18:32:46 +01002354
Max Reitz2e024cd2015-02-11 09:58:46 -05002355 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2356 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002357
Max Reitz2e024cd2015-02-11 09:58:46 -05002358 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002359 if (options) {
2360 qemu_opts_do_parse(opts, options, NULL, &local_err);
2361 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002362 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002363 ret = -1;
2364 goto out;
2365 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002366 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002367
Peter Lieven9fd77f92017-04-21 11:11:55 +02002368 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002369 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002370 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2371 if (ret < 0) {
2372 goto out;
2373 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002374 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002375
Kevin Wolfa18953f2010-10-14 15:46:04 +02002376 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002377 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002378 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002379 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002380 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002381 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002382
Max Reitz48758a82017-04-26 15:46:48 +02002383 if (s.src_num > 1 && out_baseimg) {
2384 error_report("Having a backing file for the target makes no sense when "
2385 "concatenating multiple input images");
2386 ret = -1;
2387 goto out;
2388 }
2389
Kevin Wolfefa84d42009-05-18 16:42:12 +02002390 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002391 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002392 bool encryption =
2393 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002394 const char *encryptfmt =
2395 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002396 const char *preallocation =
2397 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002398
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002399 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002400 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002401 ret = -1;
2402 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002403 }
2404
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002405 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002406 error_report("Compression and encryption not supported at "
2407 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002408 ret = -1;
2409 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002410 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002411
Chunyan Liu83d05212014-06-05 17:20:51 +08002412 if (preallocation
2413 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002414 {
2415 error_report("Compression and preallocation not supported at "
2416 "the same time");
2417 ret = -1;
2418 goto out;
2419 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002420 }
2421
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002422 /*
2423 * The later open call will need any decryption secrets, and
2424 * bdrv_create() will purge "opts", so extract them now before
2425 * they are lost.
2426 */
2427 if (!skip_create) {
2428 open_opts = qdict_new();
2429 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2430 }
2431
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002432 if (!skip_create) {
2433 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002434 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002435 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002436 error_reportf_err(local_err, "%s: error while converting %s: ",
2437 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002438 goto out;
bellardea2384d2004-08-01 21:59:26 +00002439 }
2440 }
ths3b46e622007-09-17 08:09:54 +00002441
Max Reitz4d7c4872019-07-24 19:12:29 +02002442 s.target_is_new = !skip_create;
2443
Peter Lieven9fd77f92017-04-21 11:11:55 +02002444 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002445 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002446 if (ret < 0) {
2447 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002448 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002449 }
2450
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002451 if (skip_create) {
2452 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002453 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002454 } else {
2455 /* TODO ultimately we should allow --target-image-opts
2456 * to be used even when -n is not given.
2457 * That has to wait for bdrv_create to be improved
2458 * to allow filenames in option syntax
2459 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002460 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002461 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002462 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002463 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002464 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002465 ret = -1;
2466 goto out;
2467 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002468 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002469
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002470 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002471 error_report("Compression not supported for this file format");
2472 ret = -1;
2473 goto out;
2474 }
2475
Eric Blake5def6b82016-06-23 16:37:19 -06002476 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002477 * or discard_alignment of the out_bs is greater. Limit to
2478 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2479 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002480 MAX(s.buf_sectors,
2481 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2482 out_bs->bl.pdiscard_alignment >>
2483 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002484
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002485 /* try to align the write requests to the destination to avoid unnecessary
2486 * RMW cycles. */
2487 s.alignment = MAX(pow2floor(s.min_sparse),
2488 DIV_ROUND_UP(out_bs->bl.request_alignment,
2489 BDRV_SECTOR_SIZE));
2490 assert(is_power_of_2(s.alignment));
2491
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002492 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002493 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002494 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002495 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002496 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002497 ret = -1;
2498 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002499 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002500 error_report("output file is smaller than input file");
2501 ret = -1;
2502 goto out;
2503 }
2504 }
2505
Max Reitz351c8ef2018-05-01 18:57:49 +02002506 if (s.target_has_backing) {
2507 /* Errors are treated as "backing length unknown" (which means
2508 * s.target_backing_sectors has to be negative, which it will
2509 * be automatically). The backing file length is used only
2510 * for optimizations, so such a case is not fatal. */
2511 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2512 } else {
2513 s.target_backing_sectors = -1;
2514 }
2515
Peter Lieven24f833c2013-11-27 11:07:07 +01002516 ret = bdrv_get_info(out_bs, &bdi);
2517 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002518 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002519 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002520 goto out;
2521 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002522 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002523 s.compressed = s.compressed || bdi.needs_compressed_writes;
2524 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002525 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002526 }
2527
Peter Lieven9fd77f92017-04-21 11:11:55 +02002528 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002529out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002530 if (!ret) {
2531 qemu_progress_print(100, 0);
2532 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002533 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002534 qemu_opts_del(opts);
2535 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002536 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002537 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002538 blk_unref(s.target);
2539 if (s.src) {
2540 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2541 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002542 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002543 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002544 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002545 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002546fail_getopt:
2547 g_free(options);
2548
Peter Lieven9fd77f92017-04-21 11:11:55 +02002549 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002550}
2551
bellard57d1a2b2004-08-03 21:15:11 +00002552
bellardfaea38e2006-08-05 21:31:00 +00002553static void dump_snapshots(BlockDriverState *bs)
2554{
2555 QEMUSnapshotInfo *sn_tab, *sn;
2556 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002557
2558 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2559 if (nb_sns <= 0)
2560 return;
2561 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002562 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002563 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002564 for(i = 0; i < nb_sns; i++) {
2565 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002566 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002567 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002568 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002569 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002570}
2571
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002572static void dump_json_image_info_list(ImageInfoList *list)
2573{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002574 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002575 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002576 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002577
2578 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2579 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002580 str = qobject_to_json_pretty(obj);
2581 assert(str != NULL);
2582 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002583 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002584 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002585 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002586}
2587
Benoît Canetc054b3f2012-09-05 13:09:02 +02002588static void dump_json_image_info(ImageInfo *info)
2589{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002590 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002591 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002592 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002593
2594 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2595 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002596 str = qobject_to_json_pretty(obj);
2597 assert(str != NULL);
2598 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002599 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002600 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002601 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002602}
2603
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002604static void dump_human_image_info_list(ImageInfoList *list)
2605{
2606 ImageInfoList *elem;
2607 bool delim = false;
2608
2609 for (elem = list; elem; elem = elem->next) {
2610 if (delim) {
2611 printf("\n");
2612 }
2613 delim = true;
2614
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002615 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002616 }
2617}
2618
2619static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2620{
2621 return strcmp(a, b) == 0;
2622}
2623
2624/**
2625 * Open an image file chain and return an ImageInfoList
2626 *
2627 * @filename: topmost image filename
2628 * @fmt: topmost image format (may be NULL to autodetect)
2629 * @chain: true - enumerate entire backing file chain
2630 * false - only topmost image file
2631 *
2632 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2633 * image file. If there was an error a message will have been printed to
2634 * stderr.
2635 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002636static ImageInfoList *collect_image_info_list(bool image_opts,
2637 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002638 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002639 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002640{
2641 ImageInfoList *head = NULL;
2642 ImageInfoList **last = &head;
2643 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002644 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002645
2646 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2647
2648 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002649 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002650 BlockDriverState *bs;
2651 ImageInfo *info;
2652 ImageInfoList *elem;
2653
2654 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2655 error_report("Backing file '%s' creates an infinite loop.",
2656 filename);
2657 goto err;
2658 }
2659 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2660
Max Reitzefaa7c42016-03-16 19:54:38 +01002661 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002662 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2663 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002664 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002665 goto err;
2666 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002667 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002668
Wenchao Xia43526ec2013-06-06 12:27:58 +08002669 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002670 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002671 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002672 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002673 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002674 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002675
2676 elem = g_new0(ImageInfoList, 1);
2677 elem->value = info;
2678 *last = elem;
2679 last = &elem->next;
2680
Markus Armbruster26f54e92014-10-07 13:59:04 +02002681 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002682
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002683 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002684 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002685 image_opts = false;
2686
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002687 if (chain) {
2688 if (info->has_full_backing_filename) {
2689 filename = info->full_backing_filename;
2690 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002691 error_report("Could not determine absolute backing filename,"
2692 " but backing filename '%s' present",
2693 info->backing_filename);
2694 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002695 }
2696 if (info->has_backing_filename_format) {
2697 fmt = info->backing_filename_format;
2698 }
2699 }
2700 }
2701 g_hash_table_destroy(filenames);
2702 return head;
2703
2704err:
2705 qapi_free_ImageInfoList(head);
2706 g_hash_table_destroy(filenames);
2707 return NULL;
2708}
2709
Benoît Canetc054b3f2012-09-05 13:09:02 +02002710static int img_info(int argc, char **argv)
2711{
2712 int c;
2713 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002714 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002715 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002716 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002717 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002718 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002719
bellardea2384d2004-08-01 21:59:26 +00002720 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002721 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002722 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002723 int option_index = 0;
2724 static const struct option long_options[] = {
2725 {"help", no_argument, 0, 'h'},
2726 {"format", required_argument, 0, 'f'},
2727 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002728 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002729 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002730 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002731 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002732 {0, 0, 0, 0}
2733 };
Fam Zheng335e9932017-05-03 00:35:39 +08002734 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002735 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002736 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002737 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002738 }
bellardea2384d2004-08-01 21:59:26 +00002739 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002740 case ':':
2741 missing_argument(argv[optind - 1]);
2742 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002743 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002744 unrecognized_option(argv[optind - 1]);
2745 break;
bellardea2384d2004-08-01 21:59:26 +00002746 case 'h':
2747 help();
2748 break;
2749 case 'f':
2750 fmt = optarg;
2751 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002752 case 'U':
2753 force_share = true;
2754 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002755 case OPTION_OUTPUT:
2756 output = optarg;
2757 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002758 case OPTION_BACKING_CHAIN:
2759 chain = true;
2760 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002761 case OPTION_OBJECT: {
2762 QemuOpts *opts;
2763 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2764 optarg, true);
2765 if (!opts) {
2766 return 1;
2767 }
2768 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002769 case OPTION_IMAGE_OPTS:
2770 image_opts = true;
2771 break;
bellardea2384d2004-08-01 21:59:26 +00002772 }
2773 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002774 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002775 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002776 }
bellardea2384d2004-08-01 21:59:26 +00002777 filename = argv[optind++];
2778
Benoît Canetc054b3f2012-09-05 13:09:02 +02002779 if (output && !strcmp(output, "json")) {
2780 output_format = OFORMAT_JSON;
2781 } else if (output && !strcmp(output, "human")) {
2782 output_format = OFORMAT_HUMAN;
2783 } else if (output) {
2784 error_report("--output must be used with human or json as argument.");
2785 return 1;
2786 }
2787
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002788 if (qemu_opts_foreach(&qemu_object_opts,
2789 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002790 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002791 return 1;
2792 }
2793
Fam Zheng335e9932017-05-03 00:35:39 +08002794 list = collect_image_info_list(image_opts, filename, fmt, chain,
2795 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002796 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002797 return 1;
2798 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002799
Benoît Canetc054b3f2012-09-05 13:09:02 +02002800 switch (output_format) {
2801 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002802 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002803 break;
2804 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002805 if (chain) {
2806 dump_json_image_info_list(list);
2807 } else {
2808 dump_json_image_info(list->value);
2809 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002810 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002811 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002812
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002813 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002814 return 0;
2815}
2816
Eric Blake30065d12019-03-26 13:40:43 -05002817static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2818 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002819{
2820 switch (output_format) {
2821 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002822 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002823 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002824 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002825 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002826 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002827 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002828 e->start, e->length,
2829 e->has_offset ? e->offset : 0,
2830 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002831 }
2832 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2833 * Modify the flags here to allow more coalescing.
2834 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002835 if (next && (!next->data || next->zero)) {
2836 next->data = false;
2837 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002838 }
2839 break;
2840 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002841 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2842 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002843 (e->start == 0 ? "[" : ",\n"),
2844 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002845 e->zero ? "true" : "false",
2846 e->data ? "true" : "false");
2847 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002848 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002849 }
2850 putchar('}');
2851
2852 if (!next) {
2853 printf("]\n");
2854 }
2855 break;
2856 }
Eric Blake30065d12019-03-26 13:40:43 -05002857 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002858}
2859
Eric Blake5e344dd2017-10-11 22:47:02 -05002860static int get_block_status(BlockDriverState *bs, int64_t offset,
2861 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002862{
Eric Blake237d78f2017-10-11 22:47:03 -05002863 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002864 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002865 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002866 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002867 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002868 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002869
2870 /* As an optimization, we could cache the current range of unallocated
2871 * clusters in each file of the chain, and avoid querying the same
2872 * range repeatedly.
2873 */
2874
2875 depth = 0;
2876 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002877 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002878 if (ret < 0) {
2879 return ret;
2880 }
Eric Blake237d78f2017-10-11 22:47:03 -05002881 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002882 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2883 break;
2884 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002885 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002886 if (bs == NULL) {
2887 ret = 0;
2888 break;
2889 }
2890
2891 depth++;
2892 }
2893
John Snow28756452016-02-05 13:12:33 -05002894 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2895
Max Reitzf30c66b2019-02-01 20:29:05 +01002896 if (file && has_offset) {
2897 bdrv_refresh_filename(file);
2898 filename = file->filename;
2899 }
2900
John Snow28756452016-02-05 13:12:33 -05002901 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002902 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002903 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002904 .data = !!(ret & BDRV_BLOCK_DATA),
2905 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002906 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002907 .has_offset = has_offset,
2908 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002909 .has_filename = filename,
2910 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002911 };
2912
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002913 return 0;
2914}
2915
Fam Zheng16b0d552016-01-26 11:59:02 +08002916static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2917{
2918 if (curr->length == 0) {
2919 return false;
2920 }
2921 if (curr->zero != next->zero ||
2922 curr->data != next->data ||
2923 curr->depth != next->depth ||
2924 curr->has_filename != next->has_filename ||
2925 curr->has_offset != next->has_offset) {
2926 return false;
2927 }
2928 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2929 return false;
2930 }
2931 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2932 return false;
2933 }
2934 return true;
2935}
2936
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002937static int img_map(int argc, char **argv)
2938{
2939 int c;
2940 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002941 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002942 BlockDriverState *bs;
2943 const char *filename, *fmt, *output;
2944 int64_t length;
2945 MapEntry curr = { .length = 0 }, next;
2946 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002947 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002948 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002949
2950 fmt = NULL;
2951 output = NULL;
2952 for (;;) {
2953 int option_index = 0;
2954 static const struct option long_options[] = {
2955 {"help", no_argument, 0, 'h'},
2956 {"format", required_argument, 0, 'f'},
2957 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002958 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002959 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002960 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002961 {0, 0, 0, 0}
2962 };
Fam Zheng335e9932017-05-03 00:35:39 +08002963 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002964 long_options, &option_index);
2965 if (c == -1) {
2966 break;
2967 }
2968 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002969 case ':':
2970 missing_argument(argv[optind - 1]);
2971 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002972 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002973 unrecognized_option(argv[optind - 1]);
2974 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002975 case 'h':
2976 help();
2977 break;
2978 case 'f':
2979 fmt = optarg;
2980 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002981 case 'U':
2982 force_share = true;
2983 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002984 case OPTION_OUTPUT:
2985 output = optarg;
2986 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002987 case OPTION_OBJECT: {
2988 QemuOpts *opts;
2989 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2990 optarg, true);
2991 if (!opts) {
2992 return 1;
2993 }
2994 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002995 case OPTION_IMAGE_OPTS:
2996 image_opts = true;
2997 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002998 }
2999 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003000 if (optind != argc - 1) {
3001 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003002 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003003 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003004
3005 if (output && !strcmp(output, "json")) {
3006 output_format = OFORMAT_JSON;
3007 } else if (output && !strcmp(output, "human")) {
3008 output_format = OFORMAT_HUMAN;
3009 } else if (output) {
3010 error_report("--output must be used with human or json as argument.");
3011 return 1;
3012 }
3013
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003014 if (qemu_opts_foreach(&qemu_object_opts,
3015 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003016 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003017 return 1;
3018 }
3019
Fam Zheng335e9932017-05-03 00:35:39 +08003020 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003021 if (!blk) {
3022 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003023 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003024 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003025
3026 if (output_format == OFORMAT_HUMAN) {
3027 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3028 }
3029
Max Reitzf1d3cd72015-02-05 13:58:18 -05003030 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003031 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003032 int64_t offset = curr.start + curr.length;
3033 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003034
3035 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02003036 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05003037 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003038
3039 if (ret < 0) {
3040 error_report("Could not read file metadata: %s", strerror(-ret));
3041 goto out;
3042 }
3043
Fam Zheng16b0d552016-01-26 11:59:02 +08003044 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003045 curr.length += next.length;
3046 continue;
3047 }
3048
3049 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003050 ret = dump_map_entry(output_format, &curr, &next);
3051 if (ret < 0) {
3052 goto out;
3053 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003054 }
3055 curr = next;
3056 }
3057
Eric Blake30065d12019-03-26 13:40:43 -05003058 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003059
3060out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003061 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003062 return ret < 0;
3063}
3064
aliguorif7b4a942009-01-07 17:40:15 +00003065#define SNAPSHOT_LIST 1
3066#define SNAPSHOT_CREATE 2
3067#define SNAPSHOT_APPLY 3
3068#define SNAPSHOT_DELETE 4
3069
Stuart Brady153859b2009-06-07 00:42:17 +01003070static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003071{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003072 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003073 BlockDriverState *bs;
3074 QEMUSnapshotInfo sn;
3075 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003076 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003077 int action = 0;
3078 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003079 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003080 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003081 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003082 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003083
Kevin Wolfce099542016-03-15 13:01:04 +01003084 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003085 /* Parse commandline parameters */
3086 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003087 static const struct option long_options[] = {
3088 {"help", no_argument, 0, 'h'},
3089 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003090 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003091 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003092 {0, 0, 0, 0}
3093 };
Fam Zheng335e9932017-05-03 00:35:39 +08003094 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003095 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003096 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003097 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003098 }
aliguorif7b4a942009-01-07 17:40:15 +00003099 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003100 case ':':
3101 missing_argument(argv[optind - 1]);
3102 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003103 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003104 unrecognized_option(argv[optind - 1]);
3105 break;
aliguorif7b4a942009-01-07 17:40:15 +00003106 case 'h':
3107 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003108 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003109 case 'l':
3110 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003111 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003112 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003113 }
3114 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003115 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003116 break;
3117 case 'a':
3118 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003119 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003120 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003121 }
3122 action = SNAPSHOT_APPLY;
3123 snapshot_name = optarg;
3124 break;
3125 case 'c':
3126 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003127 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003128 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003129 }
3130 action = SNAPSHOT_CREATE;
3131 snapshot_name = optarg;
3132 break;
3133 case 'd':
3134 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003135 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003136 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003137 }
3138 action = SNAPSHOT_DELETE;
3139 snapshot_name = optarg;
3140 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003141 case 'q':
3142 quiet = true;
3143 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003144 case 'U':
3145 force_share = true;
3146 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003147 case OPTION_OBJECT: {
3148 QemuOpts *opts;
3149 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3150 optarg, true);
3151 if (!opts) {
3152 return 1;
3153 }
3154 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003155 case OPTION_IMAGE_OPTS:
3156 image_opts = true;
3157 break;
aliguorif7b4a942009-01-07 17:40:15 +00003158 }
3159 }
3160
Kevin Wolffc11eb22013-08-05 10:53:04 +02003161 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003162 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003163 }
aliguorif7b4a942009-01-07 17:40:15 +00003164 filename = argv[optind++];
3165
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003166 if (qemu_opts_foreach(&qemu_object_opts,
3167 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003168 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003169 return 1;
3170 }
3171
aliguorif7b4a942009-01-07 17:40:15 +00003172 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003173 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3174 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003175 if (!blk) {
3176 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003177 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003178 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003179
3180 /* Perform the requested action */
3181 switch(action) {
3182 case SNAPSHOT_LIST:
3183 dump_snapshots(bs);
3184 break;
3185
3186 case SNAPSHOT_CREATE:
3187 memset(&sn, 0, sizeof(sn));
3188 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3189
3190 qemu_gettimeofday(&tv);
3191 sn.date_sec = tv.tv_sec;
3192 sn.date_nsec = tv.tv_usec * 1000;
3193
3194 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003195 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003196 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003197 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003198 }
aliguorif7b4a942009-01-07 17:40:15 +00003199 break;
3200
3201 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003202 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003203 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003204 error_reportf_err(err, "Could not apply snapshot '%s': ",
3205 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003206 }
aliguorif7b4a942009-01-07 17:40:15 +00003207 break;
3208
3209 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003210 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3211 if (ret < 0) {
3212 error_report("Could not delete snapshot '%s': snapshot not "
3213 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003214 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003215 } else {
3216 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3217 if (ret < 0) {
3218 error_reportf_err(err, "Could not delete snapshot '%s': ",
3219 snapshot_name);
3220 ret = 1;
3221 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003222 }
aliguorif7b4a942009-01-07 17:40:15 +00003223 break;
3224 }
3225
3226 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003227 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003228 if (ret) {
3229 return 1;
3230 }
Stuart Brady153859b2009-06-07 00:42:17 +01003231 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003232}
3233
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003234static int img_rebase(int argc, char **argv)
3235{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003236 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003237 uint8_t *buf_old = NULL;
3238 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003239 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003240 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003241 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3242 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003243 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003244 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003245 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003246 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003247 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003248 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003249 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003250
3251 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003252 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003253 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003254 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003255 out_baseimg = NULL;
3256 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003257 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003258 static const struct option long_options[] = {
3259 {"help", no_argument, 0, 'h'},
3260 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003261 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003262 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003263 {0, 0, 0, 0}
3264 };
Fam Zheng335e9932017-05-03 00:35:39 +08003265 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003266 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003267 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003268 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003269 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003270 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003271 case ':':
3272 missing_argument(argv[optind - 1]);
3273 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003274 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003275 unrecognized_option(argv[optind - 1]);
3276 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003277 case 'h':
3278 help();
3279 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003280 case 'f':
3281 fmt = optarg;
3282 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003283 case 'F':
3284 out_basefmt = optarg;
3285 break;
3286 case 'b':
3287 out_baseimg = optarg;
3288 break;
3289 case 'u':
3290 unsafe = 1;
3291 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003292 case 'p':
3293 progress = 1;
3294 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003295 case 't':
3296 cache = optarg;
3297 break;
Max Reitz40055952014-07-22 22:58:42 +02003298 case 'T':
3299 src_cache = optarg;
3300 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003301 case 'q':
3302 quiet = true;
3303 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003304 case OPTION_OBJECT: {
3305 QemuOpts *opts;
3306 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3307 optarg, true);
3308 if (!opts) {
3309 return 1;
3310 }
3311 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003312 case OPTION_IMAGE_OPTS:
3313 image_opts = true;
3314 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003315 case 'U':
3316 force_share = true;
3317 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003318 }
3319 }
3320
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003321 if (quiet) {
3322 progress = 0;
3323 }
3324
Fam Zhengac1307a2014-04-22 13:36:11 +08003325 if (optind != argc - 1) {
3326 error_exit("Expecting one image file name");
3327 }
3328 if (!unsafe && !out_baseimg) {
3329 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003330 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003331 filename = argv[optind++];
3332
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003333 if (qemu_opts_foreach(&qemu_object_opts,
3334 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003335 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003336 return 1;
3337 }
3338
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003339 qemu_progress_init(progress, 2.0);
3340 qemu_progress_print(0, 100);
3341
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003342 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003343 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003344 if (ret < 0) {
3345 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003346 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003347 }
3348
Kevin Wolfce099542016-03-15 13:01:04 +01003349 src_flags = 0;
3350 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003351 if (ret < 0) {
3352 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003353 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003354 }
3355
Kevin Wolfce099542016-03-15 13:01:04 +01003356 /* The source files are opened read-only, don't care about WCE */
3357 assert((src_flags & BDRV_O_RDWR) == 0);
3358 (void) src_writethrough;
3359
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003360 /*
3361 * Open the images.
3362 *
3363 * Ignore the old backing file for unsafe rebase in case we want to correct
3364 * the reference to a renamed or moved backing file.
3365 */
Fam Zheng335e9932017-05-03 00:35:39 +08003366 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3367 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003368 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003369 ret = -1;
3370 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003371 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003372 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003373
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003374 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003375 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003376 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003377 ret = -1;
3378 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003379 }
3380 }
3381
3382 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003383 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003384 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003385 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003386
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003387 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003388 blk_old_backing = blk_new(qemu_get_aio_context(),
3389 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003390 BLK_PERM_ALL);
3391 ret = blk_insert_bs(blk_old_backing, base_bs,
3392 &local_err);
3393 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003394 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003395 "Could not reuse old backing file '%s': ",
3396 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003397 goto out;
3398 }
3399 } else {
3400 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003401 }
Max Reitz644483d2015-02-05 13:58:17 -05003402
Alex Bligha6166732012-10-16 13:46:18 +01003403 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003404 const char *overlay_filename;
3405 char *out_real_path;
3406
Fam Zheng335e9932017-05-03 00:35:39 +08003407 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003408 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003409 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003410 }
3411 if (force_share) {
3412 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003413 }
3414
Max Reitzf30c66b2019-02-01 20:29:05 +01003415 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003416 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3417 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003418 out_real_path =
3419 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3420 out_baseimg,
3421 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003422 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003423 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003424 error_reportf_err(local_err,
3425 "Could not resolve backing filename: ");
3426 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003427 goto out;
3428 }
3429
Sam Eiderman863cc782019-05-23 19:33:36 +03003430 /*
3431 * Find out whether we rebase an image on top of a previous image
3432 * in its chain.
3433 */
3434 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003435 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003436 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003437 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003438
Kevin Wolfd861ab32019-04-25 14:25:10 +02003439 blk_new_backing = blk_new(qemu_get_aio_context(),
3440 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003441 BLK_PERM_ALL);
3442 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3443 &local_err);
3444 if (ret < 0) {
3445 error_reportf_err(local_err,
3446 "Could not reuse backing file '%s': ",
3447 out_baseimg);
3448 goto out;
3449 }
3450 } else {
3451 blk_new_backing = blk_new_open(out_real_path, NULL,
3452 options, src_flags, &local_err);
3453 g_free(out_real_path);
3454 if (!blk_new_backing) {
3455 error_reportf_err(local_err,
3456 "Could not open new backing file '%s': ",
3457 out_baseimg);
3458 ret = -1;
3459 goto out;
3460 }
Alex Bligha6166732012-10-16 13:46:18 +01003461 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003462 }
3463 }
3464
3465 /*
3466 * Check each unallocated cluster in the COW file. If it is unallocated,
3467 * accesses go to the backing file. We must therefore compare this cluster
3468 * in the old and new backing file, and if they differ we need to copy it
3469 * from the old backing file into the COW file.
3470 *
3471 * If qemu-img crashes during this step, no harm is done. The content of
3472 * the image is the same as the original one at any time.
3473 */
3474 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003475 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003476 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003477 int64_t new_backing_size = 0;
3478 uint64_t offset;
3479 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003480 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003481
Max Reitzf1d3cd72015-02-05 13:58:18 -05003482 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3483 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003484
Eric Blake41536282017-10-11 22:47:15 -05003485 size = blk_getlength(blk);
3486 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003487 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003488 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003489 ret = -1;
3490 goto out;
3491 }
Max Reitz35ddd932019-05-09 19:52:35 +02003492 if (blk_old_backing) {
3493 old_backing_size = blk_getlength(blk_old_backing);
3494 if (old_backing_size < 0) {
3495 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003496
Max Reitz35ddd932019-05-09 19:52:35 +02003497 bdrv_get_backing_filename(bs, backing_name,
3498 sizeof(backing_name));
3499 error_report("Could not get size of '%s': %s",
3500 backing_name, strerror(-old_backing_size));
3501 ret = -1;
3502 goto out;
3503 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003504 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003505 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003506 new_backing_size = blk_getlength(blk_new_backing);
3507 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003508 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003509 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003510 ret = -1;
3511 goto out;
3512 }
Alex Bligha6166732012-10-16 13:46:18 +01003513 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003514
Eric Blake41536282017-10-11 22:47:15 -05003515 if (size != 0) {
3516 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003517 }
3518
Eric Blake41536282017-10-11 22:47:15 -05003519 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003520 bool buf_old_is_zero = false;
3521
Eric Blake41536282017-10-11 22:47:15 -05003522 /* How many bytes can we handle with the next read? */
3523 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003524
3525 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003526 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003527 if (ret < 0) {
3528 error_report("error while reading image metadata: %s",
3529 strerror(-ret));
3530 goto out;
3531 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003532 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003533 continue;
3534 }
3535
Sam Eiderman863cc782019-05-23 19:33:36 +03003536 if (prefix_chain_bs) {
3537 /*
3538 * If cluster wasn't changed since prefix_chain, we don't need
3539 * to take action
3540 */
3541 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
Andrey Shinkevich170d3bd2019-05-29 20:56:14 +03003542 false, offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003543 if (ret < 0) {
3544 error_report("error while reading image metadata: %s",
3545 strerror(-ret));
3546 goto out;
3547 }
3548 if (!ret) {
3549 continue;
3550 }
3551 }
3552
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003553 /*
3554 * Read old and new backing file and take into consideration that
3555 * backing files may be smaller than the COW image.
3556 */
Eric Blake41536282017-10-11 22:47:15 -05003557 if (offset >= old_backing_size) {
3558 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003559 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003560 } else {
Eric Blake41536282017-10-11 22:47:15 -05003561 if (offset + n > old_backing_size) {
3562 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003563 }
3564
Eric Blake41536282017-10-11 22:47:15 -05003565 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003566 if (ret < 0) {
3567 error_report("error while reading from old backing file");
3568 goto out;
3569 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003570 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003571
Eric Blake41536282017-10-11 22:47:15 -05003572 if (offset >= new_backing_size || !blk_new_backing) {
3573 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003574 } else {
Eric Blake41536282017-10-11 22:47:15 -05003575 if (offset + n > new_backing_size) {
3576 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003577 }
3578
Eric Blake41536282017-10-11 22:47:15 -05003579 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003580 if (ret < 0) {
3581 error_report("error while reading from new backing file");
3582 goto out;
3583 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003584 }
3585
3586 /* If they differ, we need to write to the COW file */
3587 uint64_t written = 0;
3588
Eric Blake41536282017-10-11 22:47:15 -05003589 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003590 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003591
Eric Blake41536282017-10-11 22:47:15 -05003592 if (compare_buffers(buf_old + written, buf_new + written,
3593 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003594 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003595 if (buf_old_is_zero) {
3596 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3597 } else {
3598 ret = blk_pwrite(blk, offset + written,
3599 buf_old + written, pnum, 0);
3600 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003601 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003602 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003603 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003604 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003605 }
3606 }
3607
3608 written += pnum;
3609 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003610 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003611 }
3612 }
3613
3614 /*
3615 * Change the backing file. All clusters that are different from the old
3616 * backing file are overwritten in the COW file now, so the visible content
3617 * doesn't change when we switch the backing file.
3618 */
Alex Bligha6166732012-10-16 13:46:18 +01003619 if (out_baseimg && *out_baseimg) {
3620 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3621 } else {
3622 ret = bdrv_change_backing_file(bs, NULL, NULL);
3623 }
3624
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003625 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003626 error_report("Could not change the backing file to '%s': No "
3627 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003628 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003629 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003630 out_baseimg, strerror(-ret));
3631 }
3632
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003633 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003634 /*
3635 * TODO At this point it is possible to check if any clusters that are
3636 * allocated in the COW file are the same in the backing file. If so, they
3637 * could be dropped from the COW file. Don't do this before switching the
3638 * backing file, in case of a crash this would lead to corruption.
3639 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003640out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003641 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003642 /* Cleanup */
3643 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003644 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003645 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003646 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003647 qemu_vfree(buf_old);
3648 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003649
Markus Armbruster26f54e92014-10-07 13:59:04 +02003650 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003651 if (ret) {
3652 return 1;
3653 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003654 return 0;
3655}
3656
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003657static int img_resize(int argc, char **argv)
3658{
Markus Armbruster6750e792015-02-12 17:43:08 +01003659 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003660 int c, ret, relative;
3661 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003662 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003663 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003664 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003665 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003666 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003667
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003668 static QemuOptsList resize_options = {
3669 .name = "resize_options",
3670 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3671 .desc = {
3672 {
3673 .name = BLOCK_OPT_SIZE,
3674 .type = QEMU_OPT_SIZE,
3675 .help = "Virtual disk size"
3676 }, {
3677 /* end of list */
3678 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003679 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003680 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003681 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003682 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003683
Kevin Wolfe80fec72011-04-29 10:58:12 +02003684 /* Remove size from argv manually so that negative numbers are not treated
3685 * as options by getopt. */
3686 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003687 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003688 return 1;
3689 }
3690
3691 size = argv[--argc];
3692
3693 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003694 fmt = NULL;
3695 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003696 static const struct option long_options[] = {
3697 {"help", no_argument, 0, 'h'},
3698 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003699 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003700 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003701 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003702 {0, 0, 0, 0}
3703 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003704 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003705 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003706 if (c == -1) {
3707 break;
3708 }
3709 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003710 case ':':
3711 missing_argument(argv[optind - 1]);
3712 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003713 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003714 unrecognized_option(argv[optind - 1]);
3715 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003716 case 'h':
3717 help();
3718 break;
3719 case 'f':
3720 fmt = optarg;
3721 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003722 case 'q':
3723 quiet = true;
3724 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003725 case OPTION_OBJECT: {
3726 QemuOpts *opts;
3727 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3728 optarg, true);
3729 if (!opts) {
3730 return 1;
3731 }
3732 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003733 case OPTION_IMAGE_OPTS:
3734 image_opts = true;
3735 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003736 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003737 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003738 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003739 if (prealloc == PREALLOC_MODE__MAX) {
3740 error_report("Invalid preallocation mode '%s'", optarg);
3741 return 1;
3742 }
3743 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003744 case OPTION_SHRINK:
3745 shrink = true;
3746 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003747 }
3748 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003749 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003750 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003751 }
3752 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003753
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003754 if (qemu_opts_foreach(&qemu_object_opts,
3755 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003756 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003757 return 1;
3758 }
3759
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003760 /* Choose grow, shrink, or absolute resize mode */
3761 switch (size[0]) {
3762 case '+':
3763 relative = 1;
3764 size++;
3765 break;
3766 case '-':
3767 relative = -1;
3768 size++;
3769 break;
3770 default:
3771 relative = 0;
3772 break;
3773 }
3774
3775 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003776 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003777 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003778 if (err) {
3779 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003780 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003781 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003782 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003783 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003784 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3785 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003786
Max Reitzefaa7c42016-03-16 19:54:38 +01003787 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003788 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3789 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003790 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003791 ret = -1;
3792 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003793 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003794
Max Reitzdc5f6902017-06-13 22:20:55 +02003795 current_size = blk_getlength(blk);
3796 if (current_size < 0) {
3797 error_report("Failed to inquire current image length: %s",
3798 strerror(-current_size));
3799 ret = -1;
3800 goto out;
3801 }
3802
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003803 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003804 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003805 } else {
3806 total_size = n;
3807 }
3808 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003809 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003810 ret = -1;
3811 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003812 }
3813
Max Reitzdc5f6902017-06-13 22:20:55 +02003814 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3815 error_report("Preallocation can only be used for growing images");
3816 ret = -1;
3817 goto out;
3818 }
3819
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003820 if (total_size < current_size && !shrink) {
3821 warn_report("Shrinking an image will delete all data beyond the "
3822 "shrunken image's end. Before performing such an "
3823 "operation, make sure there is no important data there.");
3824
3825 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3826 error_report(
3827 "Use the --shrink option to perform a shrink operation.");
3828 ret = -1;
3829 goto out;
3830 } else {
3831 warn_report("Using the --shrink option will suppress this message. "
3832 "Note that future versions of qemu-img may refuse to "
3833 "shrink images without this option.");
3834 }
3835 }
3836
Max Reitze8d04f92019-09-18 11:51:43 +02003837 /*
3838 * The user expects the image to have the desired size after
3839 * resizing, so pass @exact=true. It is of no use to report
3840 * success when the image has not actually been resized.
3841 */
3842 ret = blk_truncate(blk, total_size, true, prealloc, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02003843 if (!ret) {
3844 qprintf(quiet, "Image resized.\n");
3845 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003846 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003847 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003848out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003849 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003850 if (ret) {
3851 return 1;
3852 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003853 return 0;
3854}
3855
Max Reitz76a3a342014-10-27 11:12:51 +01003856static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003857 int64_t offset, int64_t total_work_size,
3858 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003859{
3860 qemu_progress_print(100.f * offset / total_work_size, 0);
3861}
3862
Max Reitz51641352018-05-09 23:00:20 +02003863static int print_amend_option_help(const char *format)
3864{
3865 BlockDriver *drv;
3866
3867 /* Find driver and parse its options */
3868 drv = bdrv_find_format(format);
3869 if (!drv) {
3870 error_report("Unknown file format '%s'", format);
3871 return 1;
3872 }
3873
3874 if (!drv->bdrv_amend_options) {
3875 error_report("Format driver '%s' does not support option amendment",
3876 format);
3877 return 1;
3878 }
3879
3880 /* Every driver supporting amendment must have create_opts */
3881 assert(drv->create_opts);
3882
3883 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003884 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003885 printf("\nNote that not all of these options may be amendable.\n");
3886 return 0;
3887}
3888
Max Reitz6f176b42013-09-03 10:09:50 +02003889static int img_amend(int argc, char **argv)
3890{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003891 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003892 int c, ret = 0;
3893 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003894 QemuOptsList *create_opts = NULL;
3895 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003896 const char *fmt = NULL, *filename, *cache;
3897 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003898 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003899 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003900 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003901 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003902 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003903
Max Reitzbd39e6e2014-07-22 22:58:43 +02003904 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003905 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003906 static const struct option long_options[] = {
3907 {"help", no_argument, 0, 'h'},
3908 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003909 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003910 {0, 0, 0, 0}
3911 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003912 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003913 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003914 if (c == -1) {
3915 break;
3916 }
3917
3918 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003919 case ':':
3920 missing_argument(argv[optind - 1]);
3921 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003922 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003923 unrecognized_option(argv[optind - 1]);
3924 break;
3925 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003926 help();
3927 break;
3928 case 'o':
3929 if (!is_valid_option_list(optarg)) {
3930 error_report("Invalid option list: %s", optarg);
3931 ret = -1;
3932 goto out_no_progress;
3933 }
3934 if (!options) {
3935 options = g_strdup(optarg);
3936 } else {
3937 char *old_options = options;
3938 options = g_strdup_printf("%s,%s", options, optarg);
3939 g_free(old_options);
3940 }
3941 break;
3942 case 'f':
3943 fmt = optarg;
3944 break;
3945 case 't':
3946 cache = optarg;
3947 break;
3948 case 'p':
3949 progress = true;
3950 break;
3951 case 'q':
3952 quiet = true;
3953 break;
3954 case OPTION_OBJECT:
3955 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3956 optarg, true);
3957 if (!opts) {
3958 ret = -1;
3959 goto out_no_progress;
3960 }
3961 break;
3962 case OPTION_IMAGE_OPTS:
3963 image_opts = true;
3964 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003965 }
3966 }
3967
Max Reitz6f176b42013-09-03 10:09:50 +02003968 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003969 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003970 }
3971
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003972 if (qemu_opts_foreach(&qemu_object_opts,
3973 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003974 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003975 ret = -1;
3976 goto out_no_progress;
3977 }
3978
Max Reitz76a3a342014-10-27 11:12:51 +01003979 if (quiet) {
3980 progress = false;
3981 }
3982 qemu_progress_init(progress, 1.0);
3983
Kevin Wolfa283cb62014-02-21 16:24:07 +01003984 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3985 if (fmt && has_help_option(options)) {
3986 /* If a format is explicitly specified (and possibly no filename is
3987 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003988 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003989 goto out;
3990 }
3991
3992 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003993 error_report("Expecting one image file name");
3994 ret = -1;
3995 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003996 }
Max Reitz6f176b42013-09-03 10:09:50 +02003997
Kevin Wolfce099542016-03-15 13:01:04 +01003998 flags = BDRV_O_RDWR;
3999 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004000 if (ret < 0) {
4001 error_report("Invalid cache option: %s", cache);
4002 goto out;
4003 }
4004
Fam Zheng335e9932017-05-03 00:35:39 +08004005 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4006 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004007 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004008 ret = -1;
4009 goto out;
4010 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004011 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004012
4013 fmt = bs->drv->format_name;
4014
Kevin Wolf626f84f2014-02-21 16:24:06 +01004015 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004016 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004017 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004018 goto out;
4019 }
4020
Max Reitz1f996682018-05-09 23:00:17 +02004021 if (!bs->drv->bdrv_amend_options) {
4022 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004023 fmt);
4024 ret = -1;
4025 goto out;
4026 }
4027
Max Reitz1f996682018-05-09 23:00:17 +02004028 /* Every driver supporting amendment must have create_opts */
4029 assert(bs->drv->create_opts);
4030
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004031 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08004032 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01004033 qemu_opts_do_parse(opts, options, NULL, &err);
4034 if (err) {
4035 error_report_err(err);
4036 ret = -1;
4037 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004038 }
4039
Max Reitz76a3a342014-10-27 11:12:51 +01004040 /* In case the driver does not call amend_status_cb() */
4041 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02004042 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004043 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004044 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004045 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004046 goto out;
4047 }
4048
4049out:
Max Reitz76a3a342014-10-27 11:12:51 +01004050 qemu_progress_end();
4051
Max Reitze814dff2015-08-20 16:00:38 -07004052out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004053 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004054 qemu_opts_del(opts);
4055 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004056 g_free(options);
4057
Max Reitz6f176b42013-09-03 10:09:50 +02004058 if (ret) {
4059 return 1;
4060 }
4061 return 0;
4062}
4063
Kevin Wolfb6133b82014-08-05 14:17:13 +02004064typedef struct BenchData {
4065 BlockBackend *blk;
4066 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004067 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004068 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004069 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004070 int nrreq;
4071 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004072 int flush_interval;
4073 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004074 uint8_t *buf;
4075 QEMUIOVector *qiov;
4076
4077 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004078 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004079 uint64_t offset;
4080} BenchData;
4081
Kevin Wolf55d539c2016-06-03 13:59:41 +02004082static void bench_undrained_flush_cb(void *opaque, int ret)
4083{
4084 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004085 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004086 exit(EXIT_FAILURE);
4087 }
4088}
4089
Kevin Wolfb6133b82014-08-05 14:17:13 +02004090static void bench_cb(void *opaque, int ret)
4091{
4092 BenchData *b = opaque;
4093 BlockAIOCB *acb;
4094
4095 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004096 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004097 exit(EXIT_FAILURE);
4098 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004099
4100 if (b->in_flush) {
4101 /* Just finished a flush with drained queue: Start next requests */
4102 assert(b->in_flight == 0);
4103 b->in_flush = false;
4104 } else if (b->in_flight > 0) {
4105 int remaining = b->n - b->in_flight;
4106
Kevin Wolfb6133b82014-08-05 14:17:13 +02004107 b->n--;
4108 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004109
4110 /* Time for flush? Drain queue if requested, then flush */
4111 if (b->flush_interval && remaining % b->flush_interval == 0) {
4112 if (!b->in_flight || !b->drain_on_flush) {
4113 BlockCompletionFunc *cb;
4114
4115 if (b->drain_on_flush) {
4116 b->in_flush = true;
4117 cb = bench_cb;
4118 } else {
4119 cb = bench_undrained_flush_cb;
4120 }
4121
4122 acb = blk_aio_flush(b->blk, cb, b);
4123 if (!acb) {
4124 error_report("Failed to issue flush request");
4125 exit(EXIT_FAILURE);
4126 }
4127 }
4128 if (b->drain_on_flush) {
4129 return;
4130 }
4131 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004132 }
4133
4134 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004135 int64_t offset = b->offset;
4136 /* blk_aio_* might look for completed I/Os and kick bench_cb
4137 * again, so make sure this operation is counted by in_flight
4138 * and b->offset is ready for the next submission.
4139 */
4140 b->in_flight++;
4141 b->offset += b->step;
4142 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004143 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004144 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004145 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004146 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004147 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004148 if (!acb) {
4149 error_report("Failed to issue request");
4150 exit(EXIT_FAILURE);
4151 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004152 }
4153}
4154
4155static int img_bench(int argc, char **argv)
4156{
4157 int c, ret = 0;
4158 const char *fmt = NULL, *filename;
4159 bool quiet = false;
4160 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004161 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004162 int count = 75000;
4163 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004164 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004165 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004166 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004167 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004168 int flush_interval = 0;
4169 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004170 int64_t image_size;
4171 BlockBackend *blk = NULL;
4172 BenchData data = {};
4173 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004174 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004175 struct timeval t1, t2;
4176 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004177 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004178 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004179
4180 for (;;) {
4181 static const struct option long_options[] = {
4182 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004183 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004184 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004185 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004186 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004187 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004188 {0, 0, 0, 0}
4189 };
Fam Zheng335e9932017-05-03 00:35:39 +08004190 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004191 if (c == -1) {
4192 break;
4193 }
4194
4195 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004196 case ':':
4197 missing_argument(argv[optind - 1]);
4198 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004199 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004200 unrecognized_option(argv[optind - 1]);
4201 break;
4202 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004203 help();
4204 break;
4205 case 'c':
4206 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004207 unsigned long res;
4208
4209 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004210 error_report("Invalid request count specified");
4211 return 1;
4212 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004213 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004214 break;
4215 }
4216 case 'd':
4217 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004218 unsigned long res;
4219
4220 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004221 error_report("Invalid queue depth specified");
4222 return 1;
4223 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004224 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004225 break;
4226 }
4227 case 'f':
4228 fmt = optarg;
4229 break;
4230 case 'n':
4231 flags |= BDRV_O_NATIVE_AIO;
4232 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004233 case 'o':
4234 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004235 offset = cvtnum(optarg);
4236 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004237 error_report("Invalid offset specified");
4238 return 1;
4239 }
4240 break;
4241 }
4242 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004243 case 'q':
4244 quiet = true;
4245 break;
4246 case 's':
4247 {
4248 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004249
Markus Armbruster606caa02017-02-21 21:14:04 +01004250 sval = cvtnum(optarg);
4251 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004252 error_report("Invalid buffer size specified");
4253 return 1;
4254 }
4255
4256 bufsize = sval;
4257 break;
4258 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004259 case 'S':
4260 {
4261 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004262
Markus Armbruster606caa02017-02-21 21:14:04 +01004263 sval = cvtnum(optarg);
4264 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004265 error_report("Invalid step size specified");
4266 return 1;
4267 }
4268
4269 step = sval;
4270 break;
4271 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004272 case 't':
4273 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4274 if (ret < 0) {
4275 error_report("Invalid cache mode");
4276 ret = -1;
4277 goto out;
4278 }
4279 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004280 case 'w':
4281 flags |= BDRV_O_RDWR;
4282 is_write = true;
4283 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004284 case 'U':
4285 force_share = true;
4286 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004287 case OPTION_PATTERN:
4288 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004289 unsigned long res;
4290
4291 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004292 error_report("Invalid pattern byte specified");
4293 return 1;
4294 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004295 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004296 break;
4297 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004298 case OPTION_FLUSH_INTERVAL:
4299 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004300 unsigned long res;
4301
4302 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004303 error_report("Invalid flush interval specified");
4304 return 1;
4305 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004306 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004307 break;
4308 }
4309 case OPTION_NO_DRAIN:
4310 drain_on_flush = false;
4311 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004312 case OPTION_IMAGE_OPTS:
4313 image_opts = true;
4314 break;
4315 }
4316 }
4317
4318 if (optind != argc - 1) {
4319 error_exit("Expecting one image file name");
4320 }
4321 filename = argv[argc - 1];
4322
Kevin Wolf55d539c2016-06-03 13:59:41 +02004323 if (!is_write && flush_interval) {
4324 error_report("--flush-interval is only available in write tests");
4325 ret = -1;
4326 goto out;
4327 }
4328 if (flush_interval && flush_interval < depth) {
4329 error_report("Flush interval can't be smaller than depth");
4330 ret = -1;
4331 goto out;
4332 }
4333
Fam Zheng335e9932017-05-03 00:35:39 +08004334 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4335 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004336 if (!blk) {
4337 ret = -1;
4338 goto out;
4339 }
4340
4341 image_size = blk_getlength(blk);
4342 if (image_size < 0) {
4343 ret = image_size;
4344 goto out;
4345 }
4346
4347 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004348 .blk = blk,
4349 .image_size = image_size,
4350 .bufsize = bufsize,
4351 .step = step ?: bufsize,
4352 .nrreq = depth,
4353 .n = count,
4354 .offset = offset,
4355 .write = is_write,
4356 .flush_interval = flush_interval,
4357 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004358 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004359 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004360 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004361 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004362 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004363 if (flush_interval) {
4364 printf("Sending flush every %d requests\n", flush_interval);
4365 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004366
Fam Zheng79d46582018-01-16 14:08:58 +08004367 buf_size = data.nrreq * data.bufsize;
4368 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004369 memset(data.buf, pattern, data.nrreq * data.bufsize);
4370
Fam Zheng79d46582018-01-16 14:08:58 +08004371 blk_register_buf(blk, data.buf, buf_size);
4372
Kevin Wolfb6133b82014-08-05 14:17:13 +02004373 data.qiov = g_new(QEMUIOVector, data.nrreq);
4374 for (i = 0; i < data.nrreq; i++) {
4375 qemu_iovec_init(&data.qiov[i], 1);
4376 qemu_iovec_add(&data.qiov[i],
4377 data.buf + i * data.bufsize, data.bufsize);
4378 }
4379
4380 gettimeofday(&t1, NULL);
4381 bench_cb(&data, 0);
4382
4383 while (data.n > 0) {
4384 main_loop_wait(false);
4385 }
4386 gettimeofday(&t2, NULL);
4387
4388 printf("Run completed in %3.3f seconds.\n",
4389 (t2.tv_sec - t1.tv_sec)
4390 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4391
4392out:
Fam Zheng79d46582018-01-16 14:08:58 +08004393 if (data.buf) {
4394 blk_unregister_buf(blk, data.buf);
4395 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004396 qemu_vfree(data.buf);
4397 blk_unref(blk);
4398
4399 if (ret) {
4400 return 1;
4401 }
4402 return 0;
4403}
4404
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004405#define C_BS 01
4406#define C_COUNT 02
4407#define C_IF 04
4408#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004409#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004410
4411struct DdInfo {
4412 unsigned int flags;
4413 int64_t count;
4414};
4415
4416struct DdIo {
4417 int bsz; /* Block size */
4418 char *filename;
4419 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004420 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004421};
4422
4423struct DdOpts {
4424 const char *name;
4425 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4426 unsigned int flag;
4427};
4428
4429static int img_dd_bs(const char *arg,
4430 struct DdIo *in, struct DdIo *out,
4431 struct DdInfo *dd)
4432{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004433 int64_t res;
4434
Markus Armbruster606caa02017-02-21 21:14:04 +01004435 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004436
Markus Armbruster606caa02017-02-21 21:14:04 +01004437 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004438 error_report("invalid number: '%s'", arg);
4439 return 1;
4440 }
4441 in->bsz = out->bsz = res;
4442
4443 return 0;
4444}
4445
4446static int img_dd_count(const char *arg,
4447 struct DdIo *in, struct DdIo *out,
4448 struct DdInfo *dd)
4449{
Markus Armbruster606caa02017-02-21 21:14:04 +01004450 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004451
Markus Armbruster606caa02017-02-21 21:14:04 +01004452 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004453 error_report("invalid number: '%s'", arg);
4454 return 1;
4455 }
4456
4457 return 0;
4458}
4459
4460static int img_dd_if(const char *arg,
4461 struct DdIo *in, struct DdIo *out,
4462 struct DdInfo *dd)
4463{
4464 in->filename = g_strdup(arg);
4465
4466 return 0;
4467}
4468
4469static int img_dd_of(const char *arg,
4470 struct DdIo *in, struct DdIo *out,
4471 struct DdInfo *dd)
4472{
4473 out->filename = g_strdup(arg);
4474
4475 return 0;
4476}
4477
Reda Sallahif7c15532016-08-10 16:16:09 +02004478static int img_dd_skip(const char *arg,
4479 struct DdIo *in, struct DdIo *out,
4480 struct DdInfo *dd)
4481{
Markus Armbruster606caa02017-02-21 21:14:04 +01004482 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004483
Markus Armbruster606caa02017-02-21 21:14:04 +01004484 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004485 error_report("invalid number: '%s'", arg);
4486 return 1;
4487 }
4488
4489 return 0;
4490}
4491
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004492static int img_dd(int argc, char **argv)
4493{
4494 int ret = 0;
4495 char *arg = NULL;
4496 char *tmp;
4497 BlockDriver *drv = NULL, *proto_drv = NULL;
4498 BlockBackend *blk1 = NULL, *blk2 = NULL;
4499 QemuOpts *opts = NULL;
4500 QemuOptsList *create_opts = NULL;
4501 Error *local_err = NULL;
4502 bool image_opts = false;
4503 int c, i;
4504 const char *out_fmt = "raw";
4505 const char *fmt = NULL;
4506 int64_t size = 0;
4507 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004508 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004509 struct DdInfo dd = {
4510 .flags = 0,
4511 .count = 0,
4512 };
4513 struct DdIo in = {
4514 .bsz = 512, /* Block size is by default 512 bytes */
4515 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004516 .buf = NULL,
4517 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004518 };
4519 struct DdIo out = {
4520 .bsz = 512,
4521 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004522 .buf = NULL,
4523 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004524 };
4525
4526 const struct DdOpts options[] = {
4527 { "bs", img_dd_bs, C_BS },
4528 { "count", img_dd_count, C_COUNT },
4529 { "if", img_dd_if, C_IF },
4530 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004531 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004532 { NULL, NULL, 0 }
4533 };
4534 const struct option long_options[] = {
4535 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004536 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004537 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004538 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004539 { 0, 0, 0, 0 }
4540 };
4541
Fam Zheng335e9932017-05-03 00:35:39 +08004542 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004543 if (c == EOF) {
4544 break;
4545 }
4546 switch (c) {
4547 case 'O':
4548 out_fmt = optarg;
4549 break;
4550 case 'f':
4551 fmt = optarg;
4552 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004553 case ':':
4554 missing_argument(argv[optind - 1]);
4555 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004556 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004557 unrecognized_option(argv[optind - 1]);
4558 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004559 case 'h':
4560 help();
4561 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004562 case 'U':
4563 force_share = true;
4564 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004565 case OPTION_OBJECT:
4566 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004567 ret = -1;
4568 goto out;
4569 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004570 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004571 case OPTION_IMAGE_OPTS:
4572 image_opts = true;
4573 break;
4574 }
4575 }
4576
4577 for (i = optind; i < argc; i++) {
4578 int j;
4579 arg = g_strdup(argv[i]);
4580
4581 tmp = strchr(arg, '=');
4582 if (tmp == NULL) {
4583 error_report("unrecognized operand %s", arg);
4584 ret = -1;
4585 goto out;
4586 }
4587
4588 *tmp++ = '\0';
4589
4590 for (j = 0; options[j].name != NULL; j++) {
4591 if (!strcmp(arg, options[j].name)) {
4592 break;
4593 }
4594 }
4595 if (options[j].name == NULL) {
4596 error_report("unrecognized operand %s", arg);
4597 ret = -1;
4598 goto out;
4599 }
4600
4601 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4602 ret = -1;
4603 goto out;
4604 }
4605 dd.flags |= options[j].flag;
4606 g_free(arg);
4607 arg = NULL;
4608 }
4609
4610 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4611 error_report("Must specify both input and output files");
4612 ret = -1;
4613 goto out;
4614 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004615
4616 if (qemu_opts_foreach(&qemu_object_opts,
4617 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004618 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004619 ret = -1;
4620 goto out;
4621 }
4622
Fam Zheng335e9932017-05-03 00:35:39 +08004623 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4624 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004625
4626 if (!blk1) {
4627 ret = -1;
4628 goto out;
4629 }
4630
4631 drv = bdrv_find_format(out_fmt);
4632 if (!drv) {
4633 error_report("Unknown file format");
4634 ret = -1;
4635 goto out;
4636 }
4637 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4638
4639 if (!proto_drv) {
4640 error_report_err(local_err);
4641 ret = -1;
4642 goto out;
4643 }
4644 if (!drv->create_opts) {
4645 error_report("Format driver '%s' does not support image creation",
4646 drv->format_name);
4647 ret = -1;
4648 goto out;
4649 }
4650 if (!proto_drv->create_opts) {
4651 error_report("Protocol driver '%s' does not support image creation",
4652 proto_drv->format_name);
4653 ret = -1;
4654 goto out;
4655 }
4656 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4657 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4658
4659 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4660
4661 size = blk_getlength(blk1);
4662 if (size < 0) {
4663 error_report("Failed to get size for '%s'", in.filename);
4664 ret = -1;
4665 goto out;
4666 }
4667
4668 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4669 dd.count * in.bsz < size) {
4670 size = dd.count * in.bsz;
4671 }
4672
Reda Sallahif7c15532016-08-10 16:16:09 +02004673 /* Overflow means the specified offset is beyond input image's size */
4674 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4675 size < in.bsz * in.offset)) {
4676 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4677 } else {
4678 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4679 size - in.bsz * in.offset, &error_abort);
4680 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004681
4682 ret = bdrv_create(drv, out.filename, opts, &local_err);
4683 if (ret < 0) {
4684 error_reportf_err(local_err,
4685 "%s: error while creating output image: ",
4686 out.filename);
4687 ret = -1;
4688 goto out;
4689 }
4690
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004691 /* TODO, we can't honour --image-opts for the target,
4692 * since it needs to be given in a format compatible
4693 * with the bdrv_create() call above which does not
4694 * support image-opts style.
4695 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004696 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004697 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004698
4699 if (!blk2) {
4700 ret = -1;
4701 goto out;
4702 }
4703
Reda Sallahif7c15532016-08-10 16:16:09 +02004704 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4705 size < in.offset * in.bsz)) {
4706 /* We give a warning if the skip option is bigger than the input
4707 * size and create an empty output disk image (i.e. like dd(1)).
4708 */
4709 error_report("%s: cannot skip to specified offset", in.filename);
4710 in_pos = size;
4711 } else {
4712 in_pos = in.offset * in.bsz;
4713 }
4714
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004715 in.buf = g_new(uint8_t, in.bsz);
4716
Reda Sallahif7c15532016-08-10 16:16:09 +02004717 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004718 int in_ret, out_ret;
4719
4720 if (in_pos + in.bsz > size) {
4721 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4722 } else {
4723 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4724 }
4725 if (in_ret < 0) {
4726 error_report("error while reading from input image file: %s",
4727 strerror(-in_ret));
4728 ret = -1;
4729 goto out;
4730 }
4731 in_pos += in_ret;
4732
4733 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4734
4735 if (out_ret < 0) {
4736 error_report("error while writing to output image file: %s",
4737 strerror(-out_ret));
4738 ret = -1;
4739 goto out;
4740 }
4741 out_pos += out_ret;
4742 }
4743
4744out:
4745 g_free(arg);
4746 qemu_opts_del(opts);
4747 qemu_opts_free(create_opts);
4748 blk_unref(blk1);
4749 blk_unref(blk2);
4750 g_free(in.filename);
4751 g_free(out.filename);
4752 g_free(in.buf);
4753 g_free(out.buf);
4754
4755 if (ret) {
4756 return 1;
4757 }
4758 return 0;
4759}
4760
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004761static void dump_json_block_measure_info(BlockMeasureInfo *info)
4762{
4763 QString *str;
4764 QObject *obj;
4765 Visitor *v = qobject_output_visitor_new(&obj);
4766
4767 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4768 visit_complete(v, &obj);
4769 str = qobject_to_json_pretty(obj);
4770 assert(str != NULL);
4771 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004772 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004773 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004774 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004775}
4776
4777static int img_measure(int argc, char **argv)
4778{
4779 static const struct option long_options[] = {
4780 {"help", no_argument, 0, 'h'},
4781 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4782 {"object", required_argument, 0, OPTION_OBJECT},
4783 {"output", required_argument, 0, OPTION_OUTPUT},
4784 {"size", required_argument, 0, OPTION_SIZE},
4785 {"force-share", no_argument, 0, 'U'},
4786 {0, 0, 0, 0}
4787 };
4788 OutputFormat output_format = OFORMAT_HUMAN;
4789 BlockBackend *in_blk = NULL;
4790 BlockDriver *drv;
4791 const char *filename = NULL;
4792 const char *fmt = NULL;
4793 const char *out_fmt = "raw";
4794 char *options = NULL;
4795 char *snapshot_name = NULL;
4796 bool force_share = false;
4797 QemuOpts *opts = NULL;
4798 QemuOpts *object_opts = NULL;
4799 QemuOpts *sn_opts = NULL;
4800 QemuOptsList *create_opts = NULL;
4801 bool image_opts = false;
4802 uint64_t img_size = UINT64_MAX;
4803 BlockMeasureInfo *info = NULL;
4804 Error *local_err = NULL;
4805 int ret = 1;
4806 int c;
4807
4808 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4809 long_options, NULL)) != -1) {
4810 switch (c) {
4811 case '?':
4812 case 'h':
4813 help();
4814 break;
4815 case 'f':
4816 fmt = optarg;
4817 break;
4818 case 'O':
4819 out_fmt = optarg;
4820 break;
4821 case 'o':
4822 if (!is_valid_option_list(optarg)) {
4823 error_report("Invalid option list: %s", optarg);
4824 goto out;
4825 }
4826 if (!options) {
4827 options = g_strdup(optarg);
4828 } else {
4829 char *old_options = options;
4830 options = g_strdup_printf("%s,%s", options, optarg);
4831 g_free(old_options);
4832 }
4833 break;
4834 case 'l':
4835 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4836 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4837 optarg, false);
4838 if (!sn_opts) {
4839 error_report("Failed in parsing snapshot param '%s'",
4840 optarg);
4841 goto out;
4842 }
4843 } else {
4844 snapshot_name = optarg;
4845 }
4846 break;
4847 case 'U':
4848 force_share = true;
4849 break;
4850 case OPTION_OBJECT:
4851 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4852 optarg, true);
4853 if (!object_opts) {
4854 goto out;
4855 }
4856 break;
4857 case OPTION_IMAGE_OPTS:
4858 image_opts = true;
4859 break;
4860 case OPTION_OUTPUT:
4861 if (!strcmp(optarg, "json")) {
4862 output_format = OFORMAT_JSON;
4863 } else if (!strcmp(optarg, "human")) {
4864 output_format = OFORMAT_HUMAN;
4865 } else {
4866 error_report("--output must be used with human or json "
4867 "as argument.");
4868 goto out;
4869 }
4870 break;
4871 case OPTION_SIZE:
4872 {
4873 int64_t sval;
4874
4875 sval = cvtnum(optarg);
4876 if (sval < 0) {
4877 if (sval == -ERANGE) {
4878 error_report("Image size must be less than 8 EiB!");
4879 } else {
4880 error_report("Invalid image size specified! You may use "
4881 "k, M, G, T, P or E suffixes for ");
4882 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4883 "petabytes and exabytes.");
4884 }
4885 goto out;
4886 }
4887 img_size = (uint64_t)sval;
4888 }
4889 break;
4890 }
4891 }
4892
4893 if (qemu_opts_foreach(&qemu_object_opts,
4894 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004895 qemu_img_object_print_help, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004896 goto out;
4897 }
4898
4899 if (argc - optind > 1) {
4900 error_report("At most one filename argument is allowed.");
4901 goto out;
4902 } else if (argc - optind == 1) {
4903 filename = argv[optind];
4904 }
4905
4906 if (!filename &&
4907 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4908 error_report("--object, --image-opts, -f, and -l "
4909 "require a filename argument.");
4910 goto out;
4911 }
4912 if (filename && img_size != UINT64_MAX) {
4913 error_report("--size N cannot be used together with a filename.");
4914 goto out;
4915 }
4916 if (!filename && img_size == UINT64_MAX) {
4917 error_report("Either --size N or one filename must be specified.");
4918 goto out;
4919 }
4920
4921 if (filename) {
4922 in_blk = img_open(image_opts, filename, fmt, 0,
4923 false, false, force_share);
4924 if (!in_blk) {
4925 goto out;
4926 }
4927
4928 if (sn_opts) {
4929 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4930 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4931 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4932 &local_err);
4933 } else if (snapshot_name != NULL) {
4934 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4935 snapshot_name, &local_err);
4936 }
4937 if (local_err) {
4938 error_reportf_err(local_err, "Failed to load snapshot: ");
4939 goto out;
4940 }
4941 }
4942
4943 drv = bdrv_find_format(out_fmt);
4944 if (!drv) {
4945 error_report("Unknown file format '%s'", out_fmt);
4946 goto out;
4947 }
4948 if (!drv->create_opts) {
4949 error_report("Format driver '%s' does not support image creation",
4950 drv->format_name);
4951 goto out;
4952 }
4953
4954 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4955 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4956 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4957 if (options) {
4958 qemu_opts_do_parse(opts, options, NULL, &local_err);
4959 if (local_err) {
4960 error_report_err(local_err);
4961 error_report("Invalid options for file format '%s'", out_fmt);
4962 goto out;
4963 }
4964 }
4965 if (img_size != UINT64_MAX) {
4966 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4967 }
4968
4969 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4970 if (local_err) {
4971 error_report_err(local_err);
4972 goto out;
4973 }
4974
4975 if (output_format == OFORMAT_HUMAN) {
4976 printf("required size: %" PRIu64 "\n", info->required);
4977 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4978 } else {
4979 dump_json_block_measure_info(info);
4980 }
4981
4982 ret = 0;
4983
4984out:
4985 qapi_free_BlockMeasureInfo(info);
4986 qemu_opts_del(object_opts);
4987 qemu_opts_del(opts);
4988 qemu_opts_del(sn_opts);
4989 qemu_opts_free(create_opts);
4990 g_free(options);
4991 blk_unref(in_blk);
4992 return ret;
4993}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004994
Anthony Liguoric227f092009-10-01 16:12:16 -05004995static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004996#define DEF(option, callback, arg_string) \
4997 { option, callback },
4998#include "qemu-img-cmds.h"
4999#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005000 { NULL, NULL, },
5001};
5002
bellardea2384d2004-08-01 21:59:26 +00005003int main(int argc, char **argv)
5004{
Anthony Liguoric227f092009-10-01 16:12:16 -05005005 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005006 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005007 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005008 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005009 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005010 static const struct option long_options[] = {
5011 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005012 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005013 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005014 {0, 0, 0, 0}
5015 };
bellardea2384d2004-08-01 21:59:26 +00005016
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005017#ifdef CONFIG_POSIX
5018 signal(SIGPIPE, SIG_IGN);
5019#endif
5020
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005021 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005022 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005023 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005024
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005025 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005026 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005027 exit(EXIT_FAILURE);
5028 }
5029
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005030 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005031
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005032 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005033 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005034 if (argc < 2) {
5035 error_exit("Not enough arguments");
5036 }
Stuart Brady153859b2009-06-07 00:42:17 +01005037
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005038 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005039 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005040 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005041
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005042 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005043 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005044 case ':':
5045 missing_argument(argv[optind - 1]);
5046 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005047 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005048 unrecognized_option(argv[optind - 1]);
5049 return 0;
5050 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005051 help();
5052 return 0;
5053 case 'V':
5054 printf(QEMU_IMG_VERSION);
5055 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005056 case 'T':
5057 g_free(trace_file);
5058 trace_file = trace_opt_parse(optarg);
5059 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005060 }
bellardea2384d2004-08-01 21:59:26 +00005061 }
Stuart Brady153859b2009-06-07 00:42:17 +01005062
Denis V. Lunev10985132016-06-17 17:44:13 +03005063 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005064
Denis V. Lunev10985132016-06-17 17:44:13 +03005065 /* reset getopt_long scanning */
5066 argc -= optind;
5067 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005068 return 0;
5069 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005070 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005071 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005072
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005073 if (!trace_init_backends()) {
5074 exit(1);
5075 }
5076 trace_init_file(trace_file);
5077 qemu_set_log(LOG_TRACE);
5078
Denis V. Lunev10985132016-06-17 17:44:13 +03005079 /* find the command */
5080 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5081 if (!strcmp(cmdname, cmd->name)) {
5082 return cmd->handler(argc, argv);
5083 }
5084 }
Jeff Cody7db16892014-04-25 17:02:32 -04005085
Stuart Brady153859b2009-06-07 00:42:17 +01005086 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005087 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005088}