blob: bdb95a4a3ff2772fe7d137b5bde70cff8708a8f8 [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 */
Benoît Canetc054b3f2012-09-05 13:09:02 +020024#include "qapi-visit.h"
25#include "qapi/qmp-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010026#include "qapi/qmp/qjson.h"
pbrookfaf07962007-11-11 02:51:17 +000027#include "qemu-common.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010028#include "qemu/option.h"
29#include "qemu/error-report.h"
30#include "qemu/osdep.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010031#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020032#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010033#include "block/block_int.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080034#include "block/qapi.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020035#include <getopt.h>
bellarde8445332006-06-14 15:32:10 +000036
Jeff Cody5f6979c2014-04-28 14:37:18 -040037#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION \
38 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
39
Anthony Liguoric227f092009-10-01 16:12:16 -050040typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010041 const char *name;
42 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050043} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010044
Federico Simoncelli8599ea42013-01-28 06:59:47 -050045enum {
46 OPTION_OUTPUT = 256,
47 OPTION_BACKING_CHAIN = 257,
48};
49
50typedef enum OutputFormat {
51 OFORMAT_JSON,
52 OFORMAT_HUMAN,
53} OutputFormat;
54
aurel32137519c2008-11-30 19:12:49 +000055/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
Stefan Hajnocziadfe0782010-04-13 10:29:35 +010056#define BDRV_O_FLAGS BDRV_O_CACHE_WB
Federico Simoncelli661a0f72011-06-20 12:48:19 -040057#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000058
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010059static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000060{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010061 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000062}
63
Fam Zhengac1307a2014-04-22 13:36:11 +080064static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
65{
66 va_list ap;
67
68 error_printf("qemu-img: ");
69
70 va_start(ap, fmt);
71 error_vprintf(fmt, ap);
72 va_end(ap);
73
74 error_printf("\nTry 'qemu-img --help' for more information\n");
75 exit(EXIT_FAILURE);
76}
77
blueswir1d2c639d2009-01-24 18:19:25 +000078/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +080079static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +000080{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010081 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -040082 QEMU_IMG_VERSION
malc3f020d72010-02-08 12:04:56 +030083 "usage: qemu-img command [command options]\n"
84 "QEMU disk image utility\n"
85 "\n"
86 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +010087#define DEF(option, callback, arg_string) \
88 " " arg_string "\n"
89#include "qemu-img-cmds.h"
90#undef DEF
91#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +030092 "\n"
93 "Command parameters:\n"
94 " 'filename' is a disk image filename\n"
95 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -040096 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +080097 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
98 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +010099 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
100 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300101 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200102 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
103 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
104 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300105 " 'output_filename' is the destination disk image filename\n"
106 " 'output_fmt' is the destination format\n"
107 " 'options' is a comma separated list of format specific options in a\n"
108 " name=value format. Use -o ? for an overview of the options supported by the\n"
109 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800110 " 'snapshot_param' is param used for internal snapshot, format\n"
111 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
112 " '[ID_OR_NAME]'\n"
113 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
114 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300115 " '-c' indicates that target image must be compressed (qcow format only)\n"
116 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
117 " match exactly. The image doesn't need a working backing file before\n"
118 " rebasing in this case (useful for renaming the backing file)\n"
119 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200120 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100121 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200122 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
123 " contain only zeros for qemu-img to create a sparse image during\n"
124 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
125 " unallocated or zero sectors, and the destination image will always be\n"
126 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200127 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100128 " '-n' skips the target volume creation (useful if the volume is created\n"
129 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300130 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200131 "Parameters to check subcommand:\n"
132 " '-r' tries to repair any inconsistencies that are found during the check.\n"
133 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
134 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200135 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200136 "\n"
malc3f020d72010-02-08 12:04:56 +0300137 "Parameters to snapshot subcommand:\n"
138 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
139 " '-a' applies a snapshot (revert disk to saved state)\n"
140 " '-c' creates a snapshot\n"
141 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100142 " '-l' lists all snapshots in the given image\n"
143 "\n"
144 "Parameters to compare subcommand:\n"
145 " '-f' first image format\n"
146 " '-F' second image format\n"
147 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100148
149 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100150 bdrv_iterate_format(format_print, NULL);
bellardea2384d2004-08-01 21:59:26 +0000151 printf("\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800152 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000153}
154
Stefan Weil7c30f652013-06-16 17:01:05 +0200155static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100156{
157 int ret = 0;
158 if (!quiet) {
159 va_list args;
160 va_start(args, fmt);
161 ret = vprintf(fmt, args);
162 va_end(args);
163 }
164 return ret;
165}
166
bellardea2384d2004-08-01 21:59:26 +0000167#if defined(WIN32)
168/* XXX: put correct support for win32 */
169static int read_password(char *buf, int buf_size)
170{
171 int c, i;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800172
bellardea2384d2004-08-01 21:59:26 +0000173 printf("Password: ");
174 fflush(stdout);
175 i = 0;
176 for(;;) {
177 c = getchar();
Chen Gangfdcf6e62014-07-06 16:43:33 +0800178 if (c < 0) {
179 buf[i] = '\0';
180 return -1;
181 } else if (c == '\n') {
bellardea2384d2004-08-01 21:59:26 +0000182 break;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800183 } else if (i < (buf_size - 1)) {
bellardea2384d2004-08-01 21:59:26 +0000184 buf[i++] = c;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800185 }
bellardea2384d2004-08-01 21:59:26 +0000186 }
187 buf[i] = '\0';
188 return 0;
189}
190
191#else
192
193#include <termios.h>
194
195static struct termios oldtty;
196
197static void term_exit(void)
198{
199 tcsetattr (0, TCSANOW, &oldtty);
200}
201
202static void term_init(void)
203{
204 struct termios tty;
205
206 tcgetattr (0, &tty);
207 oldtty = tty;
208
209 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
210 |INLCR|IGNCR|ICRNL|IXON);
211 tty.c_oflag |= OPOST;
212 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
213 tty.c_cflag &= ~(CSIZE|PARENB);
214 tty.c_cflag |= CS8;
215 tty.c_cc[VMIN] = 1;
216 tty.c_cc[VTIME] = 0;
ths3b46e622007-09-17 08:09:54 +0000217
bellardea2384d2004-08-01 21:59:26 +0000218 tcsetattr (0, TCSANOW, &tty);
219
220 atexit(term_exit);
221}
222
pbrook3f379ab2007-11-11 03:33:13 +0000223static int read_password(char *buf, int buf_size)
bellardea2384d2004-08-01 21:59:26 +0000224{
225 uint8_t ch;
226 int i, ret;
227
228 printf("password: ");
229 fflush(stdout);
230 term_init();
231 i = 0;
232 for(;;) {
233 ret = read(0, &ch, 1);
234 if (ret == -1) {
235 if (errno == EAGAIN || errno == EINTR) {
236 continue;
237 } else {
bellardea2384d2004-08-01 21:59:26 +0000238 break;
239 }
240 } else if (ret == 0) {
241 ret = -1;
242 break;
243 } else {
244 if (ch == '\r') {
245 ret = 0;
246 break;
247 }
248 if (i < (buf_size - 1))
249 buf[i++] = ch;
250 }
251 }
252 term_exit();
253 buf[i] = '\0';
254 printf("\n");
255 return ret;
256}
257#endif
258
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100259static int print_block_option_help(const char *filename, const char *fmt)
260{
261 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800262 QemuOptsList *create_opts = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100263
264 /* Find driver and parse its options */
265 drv = bdrv_find_format(fmt);
266 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100267 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100268 return 1;
269 }
270
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800271 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100272 if (filename) {
273 proto_drv = bdrv_find_protocol(filename, true);
274 if (!proto_drv) {
275 error_report("Unknown protocol '%s'", filename);
Chunyan Liu83d05212014-06-05 17:20:51 +0800276 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100277 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
Chunyan Liu83d05212014-06-05 17:20:51 +0800282 qemu_opts_print_help(create_opts);
283 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100284 return 0;
285}
286
Kevin Wolf9ffe3332014-04-17 16:57:13 +0200287static BlockDriverState *bdrv_new_open(const char *id,
288 const char *filename,
Sheng Yang9bc378c2010-01-29 10:15:06 +0800289 const char *fmt,
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100290 int flags,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100291 bool require_io,
292 bool quiet)
bellard75c23802004-08-27 21:28:58 +0000293{
294 BlockDriverState *bs;
295 BlockDriver *drv;
296 char password[256];
Max Reitz34b5d2c2013-09-05 14:45:29 +0200297 Error *local_err = NULL;
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100298 int ret;
bellard75c23802004-08-27 21:28:58 +0000299
Markus Armbrustere4e99862014-10-07 13:59:03 +0200300 bs = bdrv_new_root(id, &error_abort);
Kevin Wolfad717132010-12-16 15:37:41 +0100301
bellard75c23802004-08-27 21:28:58 +0000302 if (fmt) {
303 drv = bdrv_find_format(fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900304 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100305 error_report("Unknown file format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900306 goto fail;
307 }
bellard75c23802004-08-27 21:28:58 +0000308 } else {
309 drv = NULL;
310 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100311
Max Reitzddf56362014-02-18 18:33:06 +0100312 ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100313 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200314 error_report("Could not open '%s': %s", filename,
315 error_get_pretty(local_err));
316 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900317 goto fail;
bellard75c23802004-08-27 21:28:58 +0000318 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100319
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100320 if (bdrv_is_encrypted(bs) && require_io) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100321 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900322 if (read_password(password, sizeof(password)) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100323 error_report("No password given");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900324 goto fail;
325 }
326 if (bdrv_set_key(bs, password) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100327 error_report("invalid password");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900328 goto fail;
329 }
bellard75c23802004-08-27 21:28:58 +0000330 }
331 return bs;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900332fail:
Max Reitzf67503e2014-02-18 18:33:05 +0100333 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900334 return NULL;
bellard75c23802004-08-27 21:28:58 +0000335}
336
Chunyan Liu83d05212014-06-05 17:20:51 +0800337static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100338 const char *base_filename,
339 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200340{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200341 if (base_filename) {
Chunyan Liu83d05212014-06-05 17:20:51 +0800342 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100343 error_report("Backing file not supported for file format '%s'",
344 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900345 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200346 }
347 }
348 if (base_fmt) {
Chunyan Liu83d05212014-06-05 17:20:51 +0800349 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100350 error_report("Backing file format not supported for file "
351 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900352 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200353 }
354 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900355 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200356}
357
bellardea2384d2004-08-01 21:59:26 +0000358static int img_create(int argc, char **argv)
359{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200360 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100361 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000362 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000363 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000364 const char *filename;
365 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200366 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200367 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100368 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000369
bellardea2384d2004-08-01 21:59:26 +0000370 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100371 c = getopt(argc, argv, "F:b:f:he6o:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100372 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000373 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100374 }
bellardea2384d2004-08-01 21:59:26 +0000375 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100376 case '?':
bellardea2384d2004-08-01 21:59:26 +0000377 case 'h':
378 help();
379 break;
aliguori9230eaf2009-03-28 17:55:19 +0000380 case 'F':
381 base_fmt = optarg;
382 break;
bellardea2384d2004-08-01 21:59:26 +0000383 case 'b':
384 base_filename = optarg;
385 break;
386 case 'f':
387 fmt = optarg;
388 break;
389 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200390 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100391 "encryption\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100392 goto fail;
thsd8871c52007-10-24 16:11:42 +0000393 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200394 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100395 "compat6\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100396 goto fail;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200397 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100398 if (!is_valid_option_list(optarg)) {
399 error_report("Invalid option list: %s", optarg);
400 goto fail;
401 }
402 if (!options) {
403 options = g_strdup(optarg);
404 } else {
405 char *old_options = options;
406 options = g_strdup_printf("%s,%s", options, optarg);
407 g_free(old_options);
408 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200409 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100410 case 'q':
411 quiet = true;
412 break;
bellardea2384d2004-08-01 21:59:26 +0000413 }
414 }
aliguori9230eaf2009-03-28 17:55:19 +0000415
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900416 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100417 filename = (optind < argc) ? argv[optind] : NULL;
418 if (options && has_help_option(options)) {
419 g_free(options);
420 return print_block_option_help(filename, fmt);
421 }
422
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100423 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800424 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100425 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100426 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900427
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100428 /* Get image size, if specified */
429 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100430 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100431 char *end;
432 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
433 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800434 if (sval == -ERANGE) {
435 error_report("Image size must be less than 8 EiB!");
436 } else {
437 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200438 "G, T, P or E suffixes for ");
439 error_report("kilobytes, megabytes, gigabytes, terabytes, "
440 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800441 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100442 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100443 }
444 img_size = (uint64_t)sval;
445 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200446 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800447 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200448 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100449
Luiz Capitulino9b375252012-11-30 10:52:05 -0200450 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100451 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100452 if (local_err) {
Max Reitzb70d8c22013-09-06 16:51:03 +0200453 error_report("%s: %s", filename, error_get_pretty(local_err));
Luiz Capitulino9b375252012-11-30 10:52:05 -0200454 error_free(local_err);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100455 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900456 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200457
Kevin Wolf77386bf2014-02-21 16:24:04 +0100458 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000459 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100460
461fail:
462 g_free(options);
463 return 1;
bellardea2384d2004-08-01 21:59:26 +0000464}
465
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100466static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500467{
Markus Armbruster4399c432014-04-25 16:50:32 +0200468 Error *local_err = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500469 QString *str;
470 QmpOutputVisitor *ov = qmp_output_visitor_new();
471 QObject *obj;
472 visit_type_ImageCheck(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +0200473 &check, NULL, &local_err);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500474 obj = qmp_output_get_qobject(ov);
475 str = qobject_to_json_pretty(obj);
476 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100477 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500478 qobject_decref(obj);
479 qmp_output_visitor_cleanup(ov);
480 QDECREF(str);
481}
482
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100483static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500484{
485 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100486 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500487 } else {
488 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100489 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
490 "Data may be corrupted, or further writes to the image "
491 "may corrupt it.\n",
492 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500493 }
494
495 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100496 qprintf(quiet,
497 "\n%" PRId64 " leaked clusters were found on the image.\n"
498 "This means waste of disk space, but no harm to data.\n",
499 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500500 }
501
502 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100503 qprintf(quiet,
504 "\n%" PRId64
505 " internal errors have occurred during the check.\n",
506 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500507 }
508 }
509
510 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100511 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
512 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
513 check->allocated_clusters, check->total_clusters,
514 check->allocated_clusters * 100.0 / check->total_clusters,
515 check->fragmented_clusters * 100.0 / check->allocated_clusters,
516 check->compressed_clusters * 100.0 /
517 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500518 }
519
520 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100521 qprintf(quiet,
522 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500523 }
524}
525
526static int collect_image_check(BlockDriverState *bs,
527 ImageCheck *check,
528 const char *filename,
529 const char *fmt,
530 int fix)
531{
532 int ret;
533 BdrvCheckResult result;
534
535 ret = bdrv_check(bs, &result, fix);
536 if (ret < 0) {
537 return ret;
538 }
539
540 check->filename = g_strdup(filename);
541 check->format = g_strdup(bdrv_get_format_name(bs));
542 check->check_errors = result.check_errors;
543 check->corruptions = result.corruptions;
544 check->has_corruptions = result.corruptions != 0;
545 check->leaks = result.leaks;
546 check->has_leaks = result.leaks != 0;
547 check->corruptions_fixed = result.corruptions_fixed;
548 check->has_corruptions_fixed = result.corruptions != 0;
549 check->leaks_fixed = result.leaks_fixed;
550 check->has_leaks_fixed = result.leaks != 0;
551 check->image_end_offset = result.image_end_offset;
552 check->has_image_end_offset = result.image_end_offset != 0;
553 check->total_clusters = result.bfi.total_clusters;
554 check->has_total_clusters = result.bfi.total_clusters != 0;
555 check->allocated_clusters = result.bfi.allocated_clusters;
556 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
557 check->fragmented_clusters = result.bfi.fragmented_clusters;
558 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100559 check->compressed_clusters = result.bfi.compressed_clusters;
560 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500561
562 return 0;
563}
564
Kevin Wolfe076f332010-06-29 11:43:13 +0200565/*
566 * Checks an image for consistency. Exit codes:
567 *
Max Reitzd6635c42014-06-02 22:15:21 +0200568 * 0 - Check completed, image is good
569 * 1 - Check not completed because of internal errors
570 * 2 - Check completed, image is corrupted
571 * 3 - Check completed, image has leaked clusters, but is good otherwise
572 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200573 */
aliguori15859692009-04-21 23:11:53 +0000574static int img_check(int argc, char **argv)
575{
576 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500577 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200578 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200579 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000580 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200581 int fix = 0;
Stefan Hajnoczi058f8f12012-08-09 13:05:56 +0100582 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200583 ImageCheck *check = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100584 bool quiet = false;
aliguori15859692009-04-21 23:11:53 +0000585
586 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500587 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200588 cache = BDRV_DEFAULT_CACHE;
aliguori15859692009-04-21 23:11:53 +0000589 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500590 int option_index = 0;
591 static const struct option long_options[] = {
592 {"help", no_argument, 0, 'h'},
593 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530594 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500595 {"output", required_argument, 0, OPTION_OUTPUT},
596 {0, 0, 0, 0}
597 };
Max Reitz40055952014-07-22 22:58:42 +0200598 c = getopt_long(argc, argv, "hf:r:T:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500599 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100600 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000601 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100602 }
aliguori15859692009-04-21 23:11:53 +0000603 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100604 case '?':
aliguori15859692009-04-21 23:11:53 +0000605 case 'h':
606 help();
607 break;
608 case 'f':
609 fmt = optarg;
610 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200611 case 'r':
612 flags |= BDRV_O_RDWR;
613
614 if (!strcmp(optarg, "leaks")) {
615 fix = BDRV_FIX_LEAKS;
616 } else if (!strcmp(optarg, "all")) {
617 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
618 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800619 error_exit("Unknown option value for -r "
620 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200621 }
622 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500623 case OPTION_OUTPUT:
624 output = optarg;
625 break;
Max Reitz40055952014-07-22 22:58:42 +0200626 case 'T':
627 cache = optarg;
628 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100629 case 'q':
630 quiet = true;
631 break;
aliguori15859692009-04-21 23:11:53 +0000632 }
633 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200634 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800635 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100636 }
aliguori15859692009-04-21 23:11:53 +0000637 filename = argv[optind++];
638
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500639 if (output && !strcmp(output, "json")) {
640 output_format = OFORMAT_JSON;
641 } else if (output && !strcmp(output, "human")) {
642 output_format = OFORMAT_HUMAN;
643 } else if (output) {
644 error_report("--output must be used with human or json as argument.");
645 return 1;
646 }
647
Max Reitz40055952014-07-22 22:58:42 +0200648 ret = bdrv_parse_cache_flags(cache, &flags);
649 if (ret < 0) {
650 error_report("Invalid source cache option: %s", cache);
651 return 1;
652 }
653
Markus Armbruster26f54e92014-10-07 13:59:04 +0200654 blk = blk_new("image", &error_abort);
Kevin Wolf9ffe3332014-04-17 16:57:13 +0200655 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900656 if (!bs) {
Markus Armbruster26f54e92014-10-07 13:59:04 +0200657 ret = 1;
658 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900659 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500660
661 check = g_new0(ImageCheck, 1);
662 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200663
664 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200665 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200666 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500667 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200668 }
669
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500670 if (check->corruptions_fixed || check->leaks_fixed) {
671 int corruptions_fixed, leaks_fixed;
672
673 leaks_fixed = check->leaks_fixed;
674 corruptions_fixed = check->corruptions_fixed;
675
676 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100677 qprintf(quiet,
678 "The following inconsistencies were found and repaired:\n\n"
679 " %" PRId64 " leaked clusters\n"
680 " %" PRId64 " corruptions\n\n"
681 "Double checking the fixed image now...\n",
682 check->leaks_fixed,
683 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 }
685
686 ret = collect_image_check(bs, check, filename, fmt, 0);
687
688 check->leaks_fixed = leaks_fixed;
689 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200690 }
691
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500692 switch (output_format) {
693 case OFORMAT_HUMAN:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100694 dump_human_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500695 break;
696 case OFORMAT_JSON:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100697 dump_json_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500698 break;
699 }
700
701 if (ret || check->check_errors) {
702 ret = 1;
703 goto fail;
704 }
705
706 if (check->corruptions) {
707 ret = 2;
708 } else if (check->leaks) {
709 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200710 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500711 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000712 }
713
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500714fail:
715 qapi_free_ImageCheck(check);
Fam Zheng4f6fd342013-08-23 09:14:47 +0800716 bdrv_unref(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200717 blk_unref(blk);
Kevin Wolfe076f332010-06-29 11:43:13 +0200718
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500719 return ret;
aliguori15859692009-04-21 23:11:53 +0000720}
721
bellardea2384d2004-08-01 21:59:26 +0000722static int img_commit(int argc, char **argv)
723{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400724 int c, ret, flags;
725 const char *filename, *fmt, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200726 BlockBackend *blk;
bellardea2384d2004-08-01 21:59:26 +0000727 BlockDriverState *bs;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100728 bool quiet = false;
bellardea2384d2004-08-01 21:59:26 +0000729
730 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400731 cache = BDRV_DEFAULT_CACHE;
bellardea2384d2004-08-01 21:59:26 +0000732 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100733 c = getopt(argc, argv, "f:ht:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100734 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000735 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100736 }
bellardea2384d2004-08-01 21:59:26 +0000737 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100738 case '?':
bellardea2384d2004-08-01 21:59:26 +0000739 case 'h':
740 help();
741 break;
742 case 'f':
743 fmt = optarg;
744 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400745 case 't':
746 cache = optarg;
747 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100748 case 'q':
749 quiet = true;
750 break;
bellardea2384d2004-08-01 21:59:26 +0000751 }
752 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200753 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800754 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100755 }
bellardea2384d2004-08-01 21:59:26 +0000756 filename = argv[optind++];
757
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400758 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100759 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400760 if (ret < 0) {
761 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100762 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400763 }
764
Markus Armbruster26f54e92014-10-07 13:59:04 +0200765 blk = blk_new("image", &error_abort);
Kevin Wolf9ffe3332014-04-17 16:57:13 +0200766 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900767 if (!bs) {
Markus Armbruster26f54e92014-10-07 13:59:04 +0200768 ret = -1;
769 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900770 }
bellardea2384d2004-08-01 21:59:26 +0000771 ret = bdrv_commit(bs);
772 switch(ret) {
773 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100774 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000775 break;
776 case -ENOENT:
Jes Sorensen15654a62010-12-16 14:31:53 +0100777 error_report("No disk inserted");
bellardea2384d2004-08-01 21:59:26 +0000778 break;
779 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +0100780 error_report("Image is read-only");
bellardea2384d2004-08-01 21:59:26 +0000781 break;
782 case -ENOTSUP:
Jes Sorensen15654a62010-12-16 14:31:53 +0100783 error_report("Image is already committed");
bellardea2384d2004-08-01 21:59:26 +0000784 break;
785 default:
Jes Sorensen15654a62010-12-16 14:31:53 +0100786 error_report("Error while committing image");
bellardea2384d2004-08-01 21:59:26 +0000787 break;
788 }
789
Markus Armbruster26f54e92014-10-07 13:59:04 +0200790out:
Fam Zheng4f6fd342013-08-23 09:14:47 +0800791 bdrv_unref(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200792 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900793 if (ret) {
794 return 1;
795 }
bellardea2384d2004-08-01 21:59:26 +0000796 return 0;
797}
798
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400799/*
thsf58c7b32008-06-05 21:53:49 +0000800 * Returns true iff the first sector pointed to by 'buf' contains at least
801 * a non-NUL byte.
802 *
803 * 'pnum' is set to the number of sectors (including and immediately following
804 * the first one) that are known to be in the same allocated/unallocated state.
805 */
bellardea2384d2004-08-01 21:59:26 +0000806static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
807{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000808 bool is_zero;
809 int i;
bellardea2384d2004-08-01 21:59:26 +0000810
811 if (n <= 0) {
812 *pnum = 0;
813 return 0;
814 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000815 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +0000816 for(i = 1; i < n; i++) {
817 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000818 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +0000819 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000820 }
bellardea2384d2004-08-01 21:59:26 +0000821 }
822 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000823 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +0000824}
825
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100826/*
Kevin Wolfa22f1232011-08-26 15:27:13 +0200827 * Like is_allocated_sectors, but if the buffer starts with a used sector,
828 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
829 * breaking up write requests for only small sparse areas.
830 */
831static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
832 int min)
833{
834 int ret;
835 int num_checked, num_used;
836
837 if (n < min) {
838 min = n;
839 }
840
841 ret = is_allocated_sectors(buf, n, pnum);
842 if (!ret) {
843 return ret;
844 }
845
846 num_used = *pnum;
847 buf += BDRV_SECTOR_SIZE * *pnum;
848 n -= *pnum;
849 num_checked = num_used;
850
851 while (n > 0) {
852 ret = is_allocated_sectors(buf, n, pnum);
853
854 buf += BDRV_SECTOR_SIZE * *pnum;
855 n -= *pnum;
856 num_checked += *pnum;
857 if (ret) {
858 num_used = num_checked;
859 } else if (*pnum >= min) {
860 break;
861 }
862 }
863
864 *pnum = num_used;
865 return 1;
866}
867
868/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100869 * Compares two buffers sector by sector. Returns 0 if the first sector of both
870 * buffers matches, non-zero otherwise.
871 *
872 * pnum is set to the number of sectors (including and immediately following
873 * the first one) that are known to have the same comparison result
874 */
875static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
876 int *pnum)
877{
878 int res, i;
879
880 if (n <= 0) {
881 *pnum = 0;
882 return 0;
883 }
884
885 res = !!memcmp(buf1, buf2, 512);
886 for(i = 1; i < n; i++) {
887 buf1 += 512;
888 buf2 += 512;
889
890 if (!!memcmp(buf1, buf2, 512) != res) {
891 break;
892 }
893 }
894
895 *pnum = i;
896 return res;
897}
898
Kevin Wolf80ee15a2009-09-15 12:30:43 +0200899#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +0000900
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100901static int64_t sectors_to_bytes(int64_t sectors)
902{
903 return sectors << BDRV_SECTOR_BITS;
904}
905
906static int64_t sectors_to_process(int64_t total, int64_t from)
907{
908 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
909}
910
911/*
912 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
913 *
914 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
915 * data and negative value on error.
916 *
917 * @param bs: Driver used for accessing file
918 * @param sect_num: Number of first sector to check
919 * @param sect_count: Number of sectors to check
920 * @param filename: Name of disk file we are checking (logging purpose)
921 * @param buffer: Allocated buffer for storing read data
922 * @param quiet: Flag for quiet mode
923 */
924static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
925 int sect_count, const char *filename,
926 uint8_t *buffer, bool quiet)
927{
928 int pnum, ret = 0;
929 ret = bdrv_read(bs, sect_num, buffer, sect_count);
930 if (ret < 0) {
931 error_report("Error while reading offset %" PRId64 " of %s: %s",
932 sectors_to_bytes(sect_num), filename, strerror(-ret));
933 return ret;
934 }
935 ret = is_allocated_sectors(buffer, sect_count, &pnum);
936 if (ret || pnum != sect_count) {
937 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
938 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
939 return 1;
940 }
941
942 return 0;
943}
944
945/*
946 * Compares two images. Exit codes:
947 *
948 * 0 - Images are identical
949 * 1 - Images differ
950 * >1 - Error occurred
951 */
952static int img_compare(int argc, char **argv)
953{
Max Reitz40055952014-07-22 22:58:42 +0200954 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200955 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100956 BlockDriverState *bs1, *bs2;
957 int64_t total_sectors1, total_sectors2;
958 uint8_t *buf1 = NULL, *buf2 = NULL;
959 int pnum1, pnum2;
960 int allocated1, allocated2;
961 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
962 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +0200963 int flags;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100964 int64_t total_sectors;
965 int64_t sector_num = 0;
966 int64_t nb_sectors;
967 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100968 uint64_t progress_base;
969
Max Reitz40055952014-07-22 22:58:42 +0200970 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100971 for (;;) {
Max Reitz40055952014-07-22 22:58:42 +0200972 c = getopt(argc, argv, "hf:F:T:pqs");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100973 if (c == -1) {
974 break;
975 }
976 switch (c) {
977 case '?':
978 case 'h':
979 help();
980 break;
981 case 'f':
982 fmt1 = optarg;
983 break;
984 case 'F':
985 fmt2 = optarg;
986 break;
Max Reitz40055952014-07-22 22:58:42 +0200987 case 'T':
988 cache = optarg;
989 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100990 case 'p':
991 progress = true;
992 break;
993 case 'q':
994 quiet = true;
995 break;
996 case 's':
997 strict = true;
998 break;
999 }
1000 }
1001
1002 /* Progress is not shown in Quiet mode */
1003 if (quiet) {
1004 progress = false;
1005 }
1006
1007
Kevin Wolffc11eb22013-08-05 10:53:04 +02001008 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001009 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001010 }
1011 filename1 = argv[optind++];
1012 filename2 = argv[optind++];
1013
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001014 /* Initialize before goto out */
1015 qemu_progress_init(progress, 2.0);
1016
Max Reitz40055952014-07-22 22:58:42 +02001017 flags = BDRV_O_FLAGS;
1018 ret = bdrv_parse_cache_flags(cache, &flags);
1019 if (ret < 0) {
1020 error_report("Invalid source cache option: %s", cache);
1021 ret = 2;
1022 goto out3;
1023 }
1024
Markus Armbruster26f54e92014-10-07 13:59:04 +02001025 blk1 = blk_new("image_1", &error_abort);
Kevin Wolf9aebf3b2014-09-25 09:54:02 +02001026 bs1 = bdrv_new_open("image_1", filename1, fmt1, flags, true, quiet);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001027 if (!bs1) {
1028 error_report("Can't open file %s", filename1);
1029 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001030 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001031 }
1032
Markus Armbruster26f54e92014-10-07 13:59:04 +02001033 blk2 = blk_new("image_2", &error_abort);
Kevin Wolf9aebf3b2014-09-25 09:54:02 +02001034 bs2 = bdrv_new_open("image_2", filename2, fmt2, flags, true, quiet);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001035 if (!bs2) {
1036 error_report("Can't open file %s", filename2);
1037 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001038 goto out1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001039 }
1040
1041 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
1042 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001043 total_sectors1 = bdrv_nb_sectors(bs1);
1044 if (total_sectors1 < 0) {
1045 error_report("Can't get size of %s: %s",
1046 filename1, strerror(-total_sectors1));
1047 ret = 4;
1048 goto out;
1049 }
1050 total_sectors2 = bdrv_nb_sectors(bs2);
1051 if (total_sectors2 < 0) {
1052 error_report("Can't get size of %s: %s",
1053 filename2, strerror(-total_sectors2));
1054 ret = 4;
1055 goto out;
1056 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001057 total_sectors = MIN(total_sectors1, total_sectors2);
1058 progress_base = MAX(total_sectors1, total_sectors2);
1059
1060 qemu_progress_print(0, 100);
1061
1062 if (strict && total_sectors1 != total_sectors2) {
1063 ret = 1;
1064 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1065 goto out;
1066 }
1067
1068 for (;;) {
1069 nb_sectors = sectors_to_process(total_sectors, sector_num);
1070 if (nb_sectors <= 0) {
1071 break;
1072 }
1073 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
1074 &pnum1);
1075 if (allocated1 < 0) {
1076 ret = 3;
1077 error_report("Sector allocation test failed for %s", filename1);
1078 goto out;
1079 }
1080
1081 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1082 &pnum2);
1083 if (allocated2 < 0) {
1084 ret = 3;
1085 error_report("Sector allocation test failed for %s", filename2);
1086 goto out;
1087 }
1088 nb_sectors = MIN(pnum1, pnum2);
1089
1090 if (allocated1 == allocated2) {
1091 if (allocated1) {
1092 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1093 if (ret < 0) {
1094 error_report("Error while reading offset %" PRId64 " of %s:"
1095 " %s", sectors_to_bytes(sector_num), filename1,
1096 strerror(-ret));
1097 ret = 4;
1098 goto out;
1099 }
1100 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1101 if (ret < 0) {
1102 error_report("Error while reading offset %" PRId64
1103 " of %s: %s", sectors_to_bytes(sector_num),
1104 filename2, strerror(-ret));
1105 ret = 4;
1106 goto out;
1107 }
1108 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1109 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001110 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1111 sectors_to_bytes(
1112 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001113 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001114 goto out;
1115 }
1116 }
1117 } else {
1118 if (strict) {
1119 ret = 1;
1120 qprintf(quiet, "Strict mode: Offset %" PRId64
1121 " allocation mismatch!\n",
1122 sectors_to_bytes(sector_num));
1123 goto out;
1124 }
1125
1126 if (allocated1) {
1127 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1128 filename1, buf1, quiet);
1129 } else {
1130 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1131 filename2, buf1, quiet);
1132 }
1133 if (ret) {
1134 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001135 error_report("Error while reading offset %" PRId64 ": %s",
1136 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001137 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001138 }
1139 goto out;
1140 }
1141 }
1142 sector_num += nb_sectors;
1143 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1144 }
1145
1146 if (total_sectors1 != total_sectors2) {
1147 BlockDriverState *bs_over;
1148 int64_t total_sectors_over;
1149 const char *filename_over;
1150
1151 qprintf(quiet, "Warning: Image size mismatch!\n");
1152 if (total_sectors1 > total_sectors2) {
1153 total_sectors_over = total_sectors1;
1154 bs_over = bs1;
1155 filename_over = filename1;
1156 } else {
1157 total_sectors_over = total_sectors2;
1158 bs_over = bs2;
1159 filename_over = filename2;
1160 }
1161
1162 for (;;) {
1163 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1164 if (nb_sectors <= 0) {
1165 break;
1166 }
1167 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1168 nb_sectors, &pnum);
1169 if (ret < 0) {
1170 ret = 3;
1171 error_report("Sector allocation test failed for %s",
1172 filename_over);
1173 goto out;
1174
1175 }
1176 nb_sectors = pnum;
1177 if (ret) {
1178 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1179 filename_over, buf1, quiet);
1180 if (ret) {
1181 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001182 error_report("Error while reading offset %" PRId64
1183 " of %s: %s", sectors_to_bytes(sector_num),
1184 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001185 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001186 }
1187 goto out;
1188 }
1189 }
1190 sector_num += nb_sectors;
1191 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1192 }
1193 }
1194
1195 qprintf(quiet, "Images are identical.\n");
1196 ret = 0;
1197
1198out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001199 qemu_vfree(buf1);
1200 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001201out1:
1202 bdrv_unref(bs2);
1203 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001204out2:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001205 bdrv_unref(bs1);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001206 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001207out3:
1208 qemu_progress_end();
1209 return ret;
1210}
1211
bellardea2384d2004-08-01 21:59:26 +00001212static int img_convert(int argc, char **argv)
1213{
Peter Lieven24f833c2013-11-27 11:07:07 +01001214 int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001215 int64_t ret = 0;
Max Reitz40055952014-07-22 22:58:42 +02001216 int progress = 0, flags, src_flags;
1217 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001218 BlockDriver *drv, *proto_drv;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001219 BlockBackend **blk = NULL, *out_blk = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001220 BlockDriverState **bs = NULL, *out_bs = NULL;
Peter Lieven802c3d42013-12-05 15:54:53 +01001221 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001222 int64_t *bs_sectors = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001223 uint8_t * buf = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001224 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardea2384d2004-08-01 21:59:26 +00001225 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +00001226 BlockDriverInfo bdi;
Chunyan Liu83d05212014-06-05 17:20:51 +08001227 QemuOpts *opts = NULL;
1228 QemuOptsList *create_opts = NULL;
1229 const char *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001230 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001231 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001232 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001233 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001234 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001235 QemuOpts *sn_opts = NULL;
bellardea2384d2004-08-01 21:59:26 +00001236
1237 fmt = NULL;
1238 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001239 cache = "unsafe";
Max Reitz40055952014-07-22 22:58:42 +02001240 src_cache = BDRV_DEFAULT_CACHE;
thsf58c7b32008-06-05 21:53:49 +00001241 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001242 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001243 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001244 for(;;) {
Max Reitz40055952014-07-22 22:58:42 +02001245 c = getopt(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001246 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001247 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001248 }
bellardea2384d2004-08-01 21:59:26 +00001249 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001250 case '?':
bellardea2384d2004-08-01 21:59:26 +00001251 case 'h':
1252 help();
1253 break;
1254 case 'f':
1255 fmt = optarg;
1256 break;
1257 case 'O':
1258 out_fmt = optarg;
1259 break;
thsf58c7b32008-06-05 21:53:49 +00001260 case 'B':
1261 out_baseimg = optarg;
1262 break;
bellardea2384d2004-08-01 21:59:26 +00001263 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001264 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001265 break;
1266 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001267 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001268 "encryption\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001269 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001270 goto fail_getopt;
thsec36ba12007-09-16 21:59:02 +00001271 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001272 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001273 "compat6\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001274 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001275 goto fail_getopt;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001276 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001277 if (!is_valid_option_list(optarg)) {
1278 error_report("Invalid option list: %s", optarg);
1279 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001280 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001281 }
1282 if (!options) {
1283 options = g_strdup(optarg);
1284 } else {
1285 char *old_options = options;
1286 options = g_strdup_printf("%s,%s", options, optarg);
1287 g_free(old_options);
1288 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001289 break;
edison51ef6722010-09-21 19:58:41 -07001290 case 's':
1291 snapshot_name = optarg;
1292 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001293 case 'l':
1294 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1295 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1296 if (!sn_opts) {
1297 error_report("Failed in parsing snapshot param '%s'",
1298 optarg);
Kevin Wolf2dc83282014-02-21 16:24:05 +01001299 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001300 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08001301 }
1302 } else {
1303 snapshot_name = optarg;
1304 }
1305 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001306 case 'S':
1307 {
1308 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001309 char *end;
1310 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1311 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001312 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001313 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001314 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001315 }
1316
1317 min_sparse = sval / BDRV_SECTOR_SIZE;
1318 break;
1319 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001320 case 'p':
1321 progress = 1;
1322 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001323 case 't':
1324 cache = optarg;
1325 break;
Max Reitz40055952014-07-22 22:58:42 +02001326 case 'T':
1327 src_cache = optarg;
1328 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001329 case 'q':
1330 quiet = true;
1331 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001332 case 'n':
1333 skip_create = 1;
1334 break;
bellardea2384d2004-08-01 21:59:26 +00001335 }
1336 }
ths3b46e622007-09-17 08:09:54 +00001337
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001338 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001339 if (quiet) {
1340 progress = 0;
1341 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001342 qemu_progress_init(progress, 1.0);
1343
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001344
balrog926c2d22007-10-31 01:11:44 +00001345 bs_n = argc - optind - 1;
Kevin Wolfa283cb62014-02-21 16:24:07 +01001346 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
thsf58c7b32008-06-05 21:53:49 +00001347
Kevin Wolf2dc83282014-02-21 16:24:05 +01001348 if (options && has_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001349 ret = print_block_option_help(out_filename, out_fmt);
1350 goto out;
1351 }
1352
bellardea2384d2004-08-01 21:59:26 +00001353 if (bs_n < 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001354 error_exit("Must specify image file name");
ths5fafdf22007-09-16 21:08:06 +00001355 }
bellardea2384d2004-08-01 21:59:26 +00001356
thsf58c7b32008-06-05 21:53:49 +00001357
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001358 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001359 error_report("-B makes no sense when concatenating multiple input "
1360 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001361 ret = -1;
1362 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001363 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001364
Max Reitz40055952014-07-22 22:58:42 +02001365 src_flags = BDRV_O_FLAGS;
1366 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1367 if (ret < 0) {
1368 error_report("Invalid source cache option: %s", src_cache);
1369 goto out;
1370 }
1371
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001372 qemu_progress_print(0, 100);
1373
Markus Armbruster26f54e92014-10-07 13:59:04 +02001374 blk = g_new0(BlockBackend *, bs_n);
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001375 bs = g_new0(BlockDriverState *, bs_n);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001376 bs_sectors = g_new(int64_t, bs_n);
balrog926c2d22007-10-31 01:11:44 +00001377
1378 total_sectors = 0;
1379 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Kevin Wolf9aebf3b2014-09-25 09:54:02 +02001380 char *id = bs_n > 1 ? g_strdup_printf("source_%d", bs_i)
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001381 : g_strdup("source");
Markus Armbruster26f54e92014-10-07 13:59:04 +02001382 blk[bs_i] = blk_new(id, &error_abort);
Max Reitz40055952014-07-22 22:58:42 +02001383 bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001384 true, quiet);
1385 g_free(id);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001386 if (!bs[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001387 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001388 ret = -1;
1389 goto out;
1390 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001391 bs_sectors[bs_i] = bdrv_nb_sectors(bs[bs_i]);
1392 if (bs_sectors[bs_i] < 0) {
1393 error_report("Could not get size of %s: %s",
1394 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1395 ret = -1;
1396 goto out;
1397 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001398 total_sectors += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001399 }
bellardea2384d2004-08-01 21:59:26 +00001400
Wenchao Xiaef806542013-12-04 17:10:57 +08001401 if (sn_opts) {
1402 ret = bdrv_snapshot_load_tmp(bs[0],
1403 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1404 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1405 &local_err);
1406 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001407 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001408 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001409 ret = -1;
1410 goto out;
1411 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001412
1413 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001414 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001415 if (local_err) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001416 error_report("Failed to load snapshot: %s",
1417 error_get_pretty(local_err));
1418 error_free(local_err);
1419 ret = -1;
1420 goto out;
edison51ef6722010-09-21 19:58:41 -07001421 }
1422
Kevin Wolfefa84d42009-05-18 16:42:12 +02001423 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001424 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001425 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001426 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001427 ret = -1;
1428 goto out;
1429 }
balrog926c2d22007-10-31 01:11:44 +00001430
Kevin Wolf98289622013-07-10 15:47:39 +02001431 proto_drv = bdrv_find_protocol(out_filename, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001432 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001433 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001434 ret = -1;
1435 goto out;
1436 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001437
Chunyan Liuc282e1f2014-06-05 17:21:11 +08001438 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1439 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02001440
Chunyan Liu83d05212014-06-05 17:20:51 +08001441 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1442 if (options && qemu_opts_do_parse(opts, options, NULL)) {
1443 error_report("Invalid options for file format '%s'", out_fmt);
1444 ret = -1;
1445 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001446 }
1447
Chunyan Liu83d05212014-06-05 17:20:51 +08001448 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512);
1449 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001450 if (ret < 0) {
1451 goto out;
1452 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001453
Kevin Wolfa18953f2010-10-14 15:46:04 +02001454 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08001455 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02001456 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08001457 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02001458 }
1459
Kevin Wolfefa84d42009-05-18 16:42:12 +02001460 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01001461 if (compress) {
Chunyan Liu83d05212014-06-05 17:20:51 +08001462 bool encryption =
1463 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1464 const char *preallocation =
1465 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001466
1467 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001468 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001469 ret = -1;
1470 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001471 }
1472
Chunyan Liu83d05212014-06-05 17:20:51 +08001473 if (encryption) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001474 error_report("Compression and encryption not supported at "
1475 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001476 ret = -1;
1477 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001478 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02001479
Chunyan Liu83d05212014-06-05 17:20:51 +08001480 if (preallocation
1481 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02001482 {
1483 error_report("Compression and preallocation not supported at "
1484 "the same time");
1485 ret = -1;
1486 goto out;
1487 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001488 }
1489
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001490 if (!skip_create) {
1491 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08001492 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001493 if (ret < 0) {
Max Reitzcc84d902013-09-06 17:14:26 +02001494 error_report("%s: error while converting %s: %s",
1495 out_filename, out_fmt, error_get_pretty(local_err));
1496 error_free(local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001497 goto out;
bellardea2384d2004-08-01 21:59:26 +00001498 }
1499 }
ths3b46e622007-09-17 08:09:54 +00001500
Peter Lieven5a37b602013-10-24 12:07:06 +02001501 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001502 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001503 if (ret < 0) {
1504 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02001505 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001506 }
1507
Markus Armbruster26f54e92014-10-07 13:59:04 +02001508 out_blk = blk_new("target", &error_abort);
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001509 out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001510 if (!out_bs) {
1511 ret = -1;
1512 goto out;
1513 }
bellardea2384d2004-08-01 21:59:26 +00001514
balrog926c2d22007-10-31 01:11:44 +00001515 bs_i = 0;
1516 bs_offset = 0;
Peter Lievenf2521c92013-11-27 11:07:06 +01001517
1518 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1519 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1520 * as maximum. */
1521 bufsectors = MIN(32768,
1522 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1523 out_bs->bl.discard_alignment))
1524 );
1525
1526 buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001527
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001528 if (skip_create) {
Markus Armbruster43716fa2014-06-26 13:23:21 +02001529 int64_t output_sectors = bdrv_nb_sectors(out_bs);
1530 if (output_sectors < 0) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001531 error_report("unable to get output image length: %s\n",
Markus Armbruster43716fa2014-06-26 13:23:21 +02001532 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001533 ret = -1;
1534 goto out;
Markus Armbruster43716fa2014-06-26 13:23:21 +02001535 } else if (output_sectors < total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001536 error_report("output file is smaller than input file");
1537 ret = -1;
1538 goto out;
1539 }
1540 }
1541
Peter Lieven24f833c2013-11-27 11:07:07 +01001542 cluster_sectors = 0;
1543 ret = bdrv_get_info(out_bs, &bdi);
1544 if (ret < 0) {
1545 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001546 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001547 goto out;
1548 }
Peter Lieven24f833c2013-11-27 11:07:07 +01001549 } else {
Fam Zheng85f49ca2014-05-06 21:08:43 +08001550 compress = compress || bdi.needs_compressed_writes;
Peter Lieven24f833c2013-11-27 11:07:07 +01001551 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
1552 }
1553
1554 if (compress) {
1555 if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001556 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001557 ret = -1;
1558 goto out;
1559 }
bellardea2384d2004-08-01 21:59:26 +00001560 sector_num = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001561
1562 nb_sectors = total_sectors;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001563
bellardea2384d2004-08-01 21:59:26 +00001564 for(;;) {
balrog926c2d22007-10-31 01:11:44 +00001565 int64_t bs_num;
1566 int remainder;
1567 uint8_t *buf2;
1568
bellardea2384d2004-08-01 21:59:26 +00001569 nb_sectors = total_sectors - sector_num;
1570 if (nb_sectors <= 0)
1571 break;
1572 if (nb_sectors >= cluster_sectors)
1573 n = cluster_sectors;
1574 else
1575 n = nb_sectors;
balrog926c2d22007-10-31 01:11:44 +00001576
1577 bs_num = sector_num - bs_offset;
1578 assert (bs_num >= 0);
1579 remainder = n;
1580 buf2 = buf;
1581 while (remainder > 0) {
1582 int nlow;
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001583 while (bs_num == bs_sectors[bs_i]) {
1584 bs_offset += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001585 bs_i++;
1586 assert (bs_i < bs_n);
balrog926c2d22007-10-31 01:11:44 +00001587 bs_num = 0;
Blue Swirl0bfcd592010-05-22 08:02:12 +00001588 /* printf("changing part: sector_num=%" PRId64 ", "
1589 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001590 "\n", sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
balrog926c2d22007-10-31 01:11:44 +00001591 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001592 assert (bs_num < bs_sectors[bs_i]);
balrog926c2d22007-10-31 01:11:44 +00001593
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001594 nlow = remainder > bs_sectors[bs_i] - bs_num
1595 ? bs_sectors[bs_i] - bs_num : remainder;
balrog926c2d22007-10-31 01:11:44 +00001596
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001597 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1598 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001599 error_report("error while reading sector %" PRId64 ": %s",
1600 bs_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001601 goto out;
1602 }
balrog926c2d22007-10-31 01:11:44 +00001603
1604 buf2 += nlow * 512;
1605 bs_num += nlow;
1606
1607 remainder -= nlow;
1608 }
1609 assert (remainder == 0);
1610
Stefan Hajnoczi54f106d2013-04-15 17:17:33 +02001611 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1612 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001613 if (ret != 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001614 error_report("error while compressing sector %" PRId64
1615 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001616 goto out;
1617 }
bellardea2384d2004-08-01 21:59:26 +00001618 }
1619 sector_num += n;
Peter Lieven13c28af2013-11-27 11:07:01 +01001620 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
bellardea2384d2004-08-01 21:59:26 +00001621 }
bellardfaea38e2006-08-05 21:31:00 +00001622 /* signal EOF to align */
1623 bdrv_write_compressed(out_bs, 0, NULL, 0);
bellardea2384d2004-08-01 21:59:26 +00001624 } else {
Peter Lieven802c3d42013-12-05 15:54:53 +01001625 int64_t sectors_to_read, sectors_read, sector_num_next_status;
1626 bool count_allocated_sectors;
Peter Lieven11b66992013-10-24 12:07:05 +02001627 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02001628
Peter Lieven5a37b602013-10-24 12:07:06 +02001629 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1630 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1631 if (ret < 0) {
1632 goto out;
1633 }
1634 has_zero_init = 1;
1635 }
1636
Peter Lieven802c3d42013-12-05 15:54:53 +01001637 sectors_to_read = total_sectors;
1638 count_allocated_sectors = progress && (out_baseimg || has_zero_init);
1639restart:
thsf58c7b32008-06-05 21:53:49 +00001640 sector_num = 0; // total number of sectors converted so far
Peter Lieven802c3d42013-12-05 15:54:53 +01001641 sectors_read = 0;
1642 sector_num_next_status = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001643
bellardea2384d2004-08-01 21:59:26 +00001644 for(;;) {
1645 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001646 if (nb_sectors <= 0) {
Peter Lieven802c3d42013-12-05 15:54:53 +01001647 if (count_allocated_sectors) {
1648 sectors_to_read = sectors_read;
1649 count_allocated_sectors = false;
1650 goto restart;
1651 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001652 ret = 0;
bellardea2384d2004-08-01 21:59:26 +00001653 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001654 }
balrog926c2d22007-10-31 01:11:44 +00001655
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001656 while (sector_num - bs_offset >= bs_sectors[bs_i]) {
1657 bs_offset += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001658 bs_i ++;
1659 assert (bs_i < bs_n);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001660 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1661 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001662 sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
balrog926c2d22007-10-31 01:11:44 +00001663 }
1664
Peter Lieven13c28af2013-11-27 11:07:01 +01001665 if ((out_baseimg || has_zero_init) &&
1666 sector_num >= sector_num_next_status) {
1667 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1668 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1669 n, &n1);
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001670 if (ret < 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001671 error_report("error while reading block status of sector %"
1672 PRId64 ": %s", sector_num - bs_offset,
1673 strerror(-ret));
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001674 goto out;
aliguori93c65b42009-04-05 17:40:43 +00001675 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001676 /* If the output image is zero initialized, we are not working
1677 * on a shared base and the input is zero we can skip the next
1678 * n1 sectors */
1679 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001680 sector_num += n1;
1681 continue;
1682 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001683 /* If the output image is being created as a copy on write
1684 * image, assume that sectors which are unallocated in the
1685 * input image are present in both the output's and input's
1686 * base images (no need to copy them). */
1687 if (out_baseimg) {
1688 if (!(ret & BDRV_BLOCK_DATA)) {
1689 sector_num += n1;
1690 continue;
1691 }
1692 /* The next 'n1' sectors are allocated in the input image.
1693 * Copy only those as they may be followed by unallocated
1694 * sectors. */
1695 nb_sectors = n1;
1696 }
1697 /* avoid redundant callouts to get_block_status */
1698 sector_num_next_status = sector_num + n1;
thsf58c7b32008-06-05 21:53:49 +00001699 }
1700
Peter Lievenf2521c92013-11-27 11:07:06 +01001701 n = MIN(nb_sectors, bufsectors);
Peter Lieven24f833c2013-11-27 11:07:07 +01001702
1703 /* round down request length to an aligned sector, but
1704 * do not bother doing this on short requests. They happen
1705 * when we found an all-zero area, and the next sector to
1706 * write will not be sector_num + n. */
1707 if (cluster_sectors > 0 && n >= cluster_sectors) {
1708 int64_t next_aligned_sector = (sector_num + n);
1709 next_aligned_sector -= next_aligned_sector % cluster_sectors;
1710 if (sector_num + n > next_aligned_sector) {
1711 n = next_aligned_sector - sector_num;
1712 }
1713 }
1714
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001715 n = MIN(n, bs_sectors[bs_i] - (sector_num - bs_offset));
Peter Lieven13c28af2013-11-27 11:07:01 +01001716
Peter Lieven802c3d42013-12-05 15:54:53 +01001717 sectors_read += n;
1718 if (count_allocated_sectors) {
1719 sector_num += n;
1720 continue;
1721 }
1722
1723 n1 = n;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001724 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1725 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001726 error_report("error while reading sector %" PRId64 ": %s",
1727 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001728 goto out;
1729 }
bellardea2384d2004-08-01 21:59:26 +00001730 /* NOTE: at the same time we convert, we do not write zero
1731 sectors to have a chance to compress the image. Ideally, we
1732 should add a specific call to have the info to go faster */
1733 buf1 = buf;
1734 while (n > 0) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02001735 if (!has_zero_init ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001736 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001737 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1738 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001739 error_report("error while writing sector %" PRId64
1740 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001741 goto out;
1742 }
bellardea2384d2004-08-01 21:59:26 +00001743 }
1744 sector_num += n1;
1745 n -= n1;
1746 buf1 += n1 * 512;
1747 }
Peter Lieven802c3d42013-12-05 15:54:53 +01001748 qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
bellardea2384d2004-08-01 21:59:26 +00001749 }
1750 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001751out:
Peter Lieven13c28af2013-11-27 11:07:01 +01001752 if (!ret) {
1753 qemu_progress_print(100, 0);
1754 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001755 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08001756 qemu_opts_del(opts);
1757 qemu_opts_free(create_opts);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001758 qemu_vfree(buf);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02001759 qemu_opts_del(sn_opts);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001760 if (out_bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001761 bdrv_unref(out_bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001762 }
Markus Armbruster26f54e92014-10-07 13:59:04 +02001763 blk_unref(out_blk);
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001764 if (bs) {
1765 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1766 if (bs[bs_i]) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001767 bdrv_unref(bs[bs_i]);
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001768 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001769 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001770 g_free(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001771 }
Markus Armbruster26f54e92014-10-07 13:59:04 +02001772 if (blk) {
1773 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1774 blk_unref(blk[bs_i]);
1775 }
1776 g_free(blk);
1777 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001778 g_free(bs_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001779fail_getopt:
1780 g_free(options);
1781
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001782 if (ret) {
1783 return 1;
1784 }
bellardea2384d2004-08-01 21:59:26 +00001785 return 0;
1786}
1787
bellard57d1a2b2004-08-03 21:15:11 +00001788
bellardfaea38e2006-08-05 21:31:00 +00001789static void dump_snapshots(BlockDriverState *bs)
1790{
1791 QEMUSnapshotInfo *sn_tab, *sn;
1792 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00001793
1794 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1795 if (nb_sns <= 0)
1796 return;
1797 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08001798 bdrv_snapshot_dump(fprintf, stdout, NULL);
1799 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001800 for(i = 0; i < nb_sns; i++) {
1801 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08001802 bdrv_snapshot_dump(fprintf, stdout, sn);
1803 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001804 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001805 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001806}
1807
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001808static void dump_json_image_info_list(ImageInfoList *list)
1809{
Markus Armbruster4399c432014-04-25 16:50:32 +02001810 Error *local_err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001811 QString *str;
1812 QmpOutputVisitor *ov = qmp_output_visitor_new();
1813 QObject *obj;
1814 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +02001815 &list, NULL, &local_err);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001816 obj = qmp_output_get_qobject(ov);
1817 str = qobject_to_json_pretty(obj);
1818 assert(str != NULL);
1819 printf("%s\n", qstring_get_str(str));
1820 qobject_decref(obj);
1821 qmp_output_visitor_cleanup(ov);
1822 QDECREF(str);
1823}
1824
Benoît Canetc054b3f2012-09-05 13:09:02 +02001825static void dump_json_image_info(ImageInfo *info)
1826{
Markus Armbruster4399c432014-04-25 16:50:32 +02001827 Error *local_err = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001828 QString *str;
1829 QmpOutputVisitor *ov = qmp_output_visitor_new();
1830 QObject *obj;
1831 visit_type_ImageInfo(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +02001832 &info, NULL, &local_err);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001833 obj = qmp_output_get_qobject(ov);
1834 str = qobject_to_json_pretty(obj);
1835 assert(str != NULL);
1836 printf("%s\n", qstring_get_str(str));
1837 qobject_decref(obj);
1838 qmp_output_visitor_cleanup(ov);
1839 QDECREF(str);
1840}
1841
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001842static void dump_human_image_info_list(ImageInfoList *list)
1843{
1844 ImageInfoList *elem;
1845 bool delim = false;
1846
1847 for (elem = list; elem; elem = elem->next) {
1848 if (delim) {
1849 printf("\n");
1850 }
1851 delim = true;
1852
Wenchao Xia5b917042013-05-25 11:09:45 +08001853 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001854 }
1855}
1856
1857static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1858{
1859 return strcmp(a, b) == 0;
1860}
1861
1862/**
1863 * Open an image file chain and return an ImageInfoList
1864 *
1865 * @filename: topmost image filename
1866 * @fmt: topmost image format (may be NULL to autodetect)
1867 * @chain: true - enumerate entire backing file chain
1868 * false - only topmost image file
1869 *
1870 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1871 * image file. If there was an error a message will have been printed to
1872 * stderr.
1873 */
1874static ImageInfoList *collect_image_info_list(const char *filename,
1875 const char *fmt,
1876 bool chain)
1877{
1878 ImageInfoList *head = NULL;
1879 ImageInfoList **last = &head;
1880 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08001881 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001882
1883 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1884
1885 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02001886 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001887 BlockDriverState *bs;
1888 ImageInfo *info;
1889 ImageInfoList *elem;
1890
1891 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1892 error_report("Backing file '%s' creates an infinite loop.",
1893 filename);
1894 goto err;
1895 }
1896 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1897
Markus Armbruster26f54e92014-10-07 13:59:04 +02001898 blk = blk_new("image", &error_abort);
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001899 bs = bdrv_new_open("image", filename, fmt,
1900 BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001901 if (!bs) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02001902 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001903 goto err;
1904 }
1905
Wenchao Xia43526ec2013-06-06 12:27:58 +08001906 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001907 if (err) {
Wenchao Xia43526ec2013-06-06 12:27:58 +08001908 error_report("%s", error_get_pretty(err));
1909 error_free(err);
Prasad Joshibdf866f2014-03-26 01:55:53 +05301910 bdrv_unref(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001911 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08001912 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08001913 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001914
1915 elem = g_new0(ImageInfoList, 1);
1916 elem->value = info;
1917 *last = elem;
1918 last = &elem->next;
1919
Fam Zheng4f6fd342013-08-23 09:14:47 +08001920 bdrv_unref(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001921 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001922
1923 filename = fmt = NULL;
1924 if (chain) {
1925 if (info->has_full_backing_filename) {
1926 filename = info->full_backing_filename;
1927 } else if (info->has_backing_filename) {
1928 filename = info->backing_filename;
1929 }
1930 if (info->has_backing_filename_format) {
1931 fmt = info->backing_filename_format;
1932 }
1933 }
1934 }
1935 g_hash_table_destroy(filenames);
1936 return head;
1937
1938err:
1939 qapi_free_ImageInfoList(head);
1940 g_hash_table_destroy(filenames);
1941 return NULL;
1942}
1943
Benoît Canetc054b3f2012-09-05 13:09:02 +02001944static int img_info(int argc, char **argv)
1945{
1946 int c;
1947 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001948 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001949 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001950 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001951
bellardea2384d2004-08-01 21:59:26 +00001952 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001953 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001954 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001955 int option_index = 0;
1956 static const struct option long_options[] = {
1957 {"help", no_argument, 0, 'h'},
1958 {"format", required_argument, 0, 'f'},
1959 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001960 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001961 {0, 0, 0, 0}
1962 };
1963 c = getopt_long(argc, argv, "f:h",
1964 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001965 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001966 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001967 }
bellardea2384d2004-08-01 21:59:26 +00001968 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001969 case '?':
bellardea2384d2004-08-01 21:59:26 +00001970 case 'h':
1971 help();
1972 break;
1973 case 'f':
1974 fmt = optarg;
1975 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001976 case OPTION_OUTPUT:
1977 output = optarg;
1978 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001979 case OPTION_BACKING_CHAIN:
1980 chain = true;
1981 break;
bellardea2384d2004-08-01 21:59:26 +00001982 }
1983 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02001984 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001985 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001986 }
bellardea2384d2004-08-01 21:59:26 +00001987 filename = argv[optind++];
1988
Benoît Canetc054b3f2012-09-05 13:09:02 +02001989 if (output && !strcmp(output, "json")) {
1990 output_format = OFORMAT_JSON;
1991 } else if (output && !strcmp(output, "human")) {
1992 output_format = OFORMAT_HUMAN;
1993 } else if (output) {
1994 error_report("--output must be used with human or json as argument.");
1995 return 1;
1996 }
1997
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001998 list = collect_image_info_list(filename, fmt, chain);
1999 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002000 return 1;
2001 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002002
Benoît Canetc054b3f2012-09-05 13:09:02 +02002003 switch (output_format) {
2004 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002005 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002006 break;
2007 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002008 if (chain) {
2009 dump_json_image_info_list(list);
2010 } else {
2011 dump_json_image_info(list->value);
2012 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002013 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002014 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002015
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002016 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002017 return 0;
2018}
2019
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002020
2021typedef struct MapEntry {
2022 int flags;
2023 int depth;
2024 int64_t start;
2025 int64_t length;
2026 int64_t offset;
2027 BlockDriverState *bs;
2028} MapEntry;
2029
2030static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2031 MapEntry *next)
2032{
2033 switch (output_format) {
2034 case OFORMAT_HUMAN:
2035 if ((e->flags & BDRV_BLOCK_DATA) &&
2036 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
2037 error_report("File contains external, encrypted or compressed clusters.");
2038 exit(1);
2039 }
2040 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
2041 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2042 e->start, e->length, e->offset, e->bs->filename);
2043 }
2044 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2045 * Modify the flags here to allow more coalescing.
2046 */
2047 if (next &&
2048 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
2049 next->flags &= ~BDRV_BLOCK_DATA;
2050 next->flags |= BDRV_BLOCK_ZERO;
2051 }
2052 break;
2053 case OFORMAT_JSON:
2054 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
2055 " \"zero\": %s, \"data\": %s",
2056 (e->start == 0 ? "[" : ",\n"),
2057 e->start, e->length, e->depth,
2058 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
2059 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
2060 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002061 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002062 }
2063 putchar('}');
2064
2065 if (!next) {
2066 printf("]\n");
2067 }
2068 break;
2069 }
2070}
2071
2072static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2073 int nb_sectors, MapEntry *e)
2074{
2075 int64_t ret;
2076 int depth;
2077
2078 /* As an optimization, we could cache the current range of unallocated
2079 * clusters in each file of the chain, and avoid querying the same
2080 * range repeatedly.
2081 */
2082
2083 depth = 0;
2084 for (;;) {
2085 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
2086 if (ret < 0) {
2087 return ret;
2088 }
2089 assert(nb_sectors);
2090 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2091 break;
2092 }
2093 bs = bs->backing_hd;
2094 if (bs == NULL) {
2095 ret = 0;
2096 break;
2097 }
2098
2099 depth++;
2100 }
2101
2102 e->start = sector_num * BDRV_SECTOR_SIZE;
2103 e->length = nb_sectors * BDRV_SECTOR_SIZE;
2104 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
2105 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
2106 e->depth = depth;
2107 e->bs = bs;
2108 return 0;
2109}
2110
2111static int img_map(int argc, char **argv)
2112{
2113 int c;
2114 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002115 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002116 BlockDriverState *bs;
2117 const char *filename, *fmt, *output;
2118 int64_t length;
2119 MapEntry curr = { .length = 0 }, next;
2120 int ret = 0;
2121
2122 fmt = NULL;
2123 output = NULL;
2124 for (;;) {
2125 int option_index = 0;
2126 static const struct option long_options[] = {
2127 {"help", no_argument, 0, 'h'},
2128 {"format", required_argument, 0, 'f'},
2129 {"output", required_argument, 0, OPTION_OUTPUT},
2130 {0, 0, 0, 0}
2131 };
2132 c = getopt_long(argc, argv, "f:h",
2133 long_options, &option_index);
2134 if (c == -1) {
2135 break;
2136 }
2137 switch (c) {
2138 case '?':
2139 case 'h':
2140 help();
2141 break;
2142 case 'f':
2143 fmt = optarg;
2144 break;
2145 case OPTION_OUTPUT:
2146 output = optarg;
2147 break;
2148 }
2149 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002150 if (optind != argc - 1) {
2151 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002152 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002153 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002154
2155 if (output && !strcmp(output, "json")) {
2156 output_format = OFORMAT_JSON;
2157 } else if (output && !strcmp(output, "human")) {
2158 output_format = OFORMAT_HUMAN;
2159 } else if (output) {
2160 error_report("--output must be used with human or json as argument.");
2161 return 1;
2162 }
2163
Markus Armbruster26f54e92014-10-07 13:59:04 +02002164 blk = blk_new("image", &error_abort);
Kevin Wolf9ffe3332014-04-17 16:57:13 +02002165 bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002166 if (!bs) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002167 ret = -1;
2168 goto out;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002169 }
2170
2171 if (output_format == OFORMAT_HUMAN) {
2172 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2173 }
2174
2175 length = bdrv_getlength(bs);
2176 while (curr.start + curr.length < length) {
2177 int64_t nsectors_left;
2178 int64_t sector_num;
2179 int n;
2180
2181 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2182
2183 /* Probe up to 1 GiB at a time. */
2184 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2185 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2186 ret = get_block_status(bs, sector_num, n, &next);
2187
2188 if (ret < 0) {
2189 error_report("Could not read file metadata: %s", strerror(-ret));
2190 goto out;
2191 }
2192
2193 if (curr.length != 0 && curr.flags == next.flags &&
2194 curr.depth == next.depth &&
2195 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2196 curr.offset + curr.length == next.offset)) {
2197 curr.length += next.length;
2198 continue;
2199 }
2200
2201 if (curr.length > 0) {
2202 dump_map_entry(output_format, &curr, &next);
2203 }
2204 curr = next;
2205 }
2206
2207 dump_map_entry(output_format, &curr, NULL);
2208
2209out:
2210 bdrv_unref(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002211 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002212 return ret < 0;
2213}
2214
aliguorif7b4a942009-01-07 17:40:15 +00002215#define SNAPSHOT_LIST 1
2216#define SNAPSHOT_CREATE 2
2217#define SNAPSHOT_APPLY 3
2218#define SNAPSHOT_DELETE 4
2219
Stuart Brady153859b2009-06-07 00:42:17 +01002220static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002221{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002222 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002223 BlockDriverState *bs;
2224 QEMUSnapshotInfo sn;
2225 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002226 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002227 int action = 0;
2228 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002229 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002230 Error *err = NULL;
aliguorif7b4a942009-01-07 17:40:15 +00002231
Kevin Wolf710da702011-01-10 12:33:02 +01002232 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002233 /* Parse commandline parameters */
2234 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002235 c = getopt(argc, argv, "la:c:d:hq");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002236 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002237 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002238 }
aliguorif7b4a942009-01-07 17:40:15 +00002239 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002240 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002241 case 'h':
2242 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002243 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002244 case 'l':
2245 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002246 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002247 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002248 }
2249 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002250 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002251 break;
2252 case 'a':
2253 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002254 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002255 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002256 }
2257 action = SNAPSHOT_APPLY;
2258 snapshot_name = optarg;
2259 break;
2260 case 'c':
2261 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002262 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002263 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002264 }
2265 action = SNAPSHOT_CREATE;
2266 snapshot_name = optarg;
2267 break;
2268 case 'd':
2269 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002270 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002271 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002272 }
2273 action = SNAPSHOT_DELETE;
2274 snapshot_name = optarg;
2275 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002276 case 'q':
2277 quiet = true;
2278 break;
aliguorif7b4a942009-01-07 17:40:15 +00002279 }
2280 }
2281
Kevin Wolffc11eb22013-08-05 10:53:04 +02002282 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002283 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002284 }
aliguorif7b4a942009-01-07 17:40:15 +00002285 filename = argv[optind++];
2286
2287 /* Open the image */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002288 blk = blk_new("image", &error_abort);
Kevin Wolf9ffe3332014-04-17 16:57:13 +02002289 bs = bdrv_new_open("image", filename, NULL, bdrv_oflags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002290 if (!bs) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002291 ret = -1;
2292 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002293 }
aliguorif7b4a942009-01-07 17:40:15 +00002294
2295 /* Perform the requested action */
2296 switch(action) {
2297 case SNAPSHOT_LIST:
2298 dump_snapshots(bs);
2299 break;
2300
2301 case SNAPSHOT_CREATE:
2302 memset(&sn, 0, sizeof(sn));
2303 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2304
2305 qemu_gettimeofday(&tv);
2306 sn.date_sec = tv.tv_sec;
2307 sn.date_nsec = tv.tv_usec * 1000;
2308
2309 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002310 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002311 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002312 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002313 }
aliguorif7b4a942009-01-07 17:40:15 +00002314 break;
2315
2316 case SNAPSHOT_APPLY:
2317 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002318 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002319 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002320 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002321 }
aliguorif7b4a942009-01-07 17:40:15 +00002322 break;
2323
2324 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002325 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002326 if (err) {
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002327 error_report("Could not delete snapshot '%s': (%s)",
2328 snapshot_name, error_get_pretty(err));
2329 error_free(err);
2330 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002331 }
aliguorif7b4a942009-01-07 17:40:15 +00002332 break;
2333 }
2334
2335 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002336out:
Fam Zheng4f6fd342013-08-23 09:14:47 +08002337 bdrv_unref(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002338 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002339 if (ret) {
2340 return 1;
2341 }
Stuart Brady153859b2009-06-07 00:42:17 +01002342 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002343}
2344
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002345static int img_rebase(int argc, char **argv)
2346{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002347 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002348 BlockDriverState *bs = NULL, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01002349 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002350 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02002351 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2352 int c, flags, src_flags, ret;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002353 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002354 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002355 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002356 Error *local_err = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002357
2358 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002359 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002360 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02002361 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002362 out_baseimg = NULL;
2363 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002364 for(;;) {
Max Reitz40055952014-07-22 22:58:42 +02002365 c = getopt(argc, argv, "hf:F:b:upt:T:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002366 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002367 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002368 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002369 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002370 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002371 case 'h':
2372 help();
2373 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002374 case 'f':
2375 fmt = optarg;
2376 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002377 case 'F':
2378 out_basefmt = optarg;
2379 break;
2380 case 'b':
2381 out_baseimg = optarg;
2382 break;
2383 case 'u':
2384 unsafe = 1;
2385 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002386 case 'p':
2387 progress = 1;
2388 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002389 case 't':
2390 cache = optarg;
2391 break;
Max Reitz40055952014-07-22 22:58:42 +02002392 case 'T':
2393 src_cache = optarg;
2394 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002395 case 'q':
2396 quiet = true;
2397 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002398 }
2399 }
2400
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002401 if (quiet) {
2402 progress = 0;
2403 }
2404
Fam Zhengac1307a2014-04-22 13:36:11 +08002405 if (optind != argc - 1) {
2406 error_exit("Expecting one image file name");
2407 }
2408 if (!unsafe && !out_baseimg) {
2409 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002410 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002411 filename = argv[optind++];
2412
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002413 qemu_progress_init(progress, 2.0);
2414 qemu_progress_print(0, 100);
2415
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002416 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01002417 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002418 if (ret < 0) {
2419 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002420 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002421 }
2422
Max Reitz40055952014-07-22 22:58:42 +02002423 src_flags = BDRV_O_FLAGS;
2424 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2425 if (ret < 0) {
2426 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002427 goto out;
Max Reitz40055952014-07-22 22:58:42 +02002428 }
2429
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002430 /*
2431 * Open the images.
2432 *
2433 * Ignore the old backing file for unsafe rebase in case we want to correct
2434 * the reference to a renamed or moved backing file.
2435 */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002436 blk = blk_new("image", &error_abort);
Kevin Wolf9ffe3332014-04-17 16:57:13 +02002437 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002438 if (!bs) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002439 ret = -1;
2440 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002441 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002442
2443 /* Find the right drivers for the backing files */
2444 old_backing_drv = NULL;
2445 new_backing_drv = NULL;
2446
2447 if (!unsafe && bs->backing_format[0] != '\0') {
2448 old_backing_drv = bdrv_find_format(bs->backing_format);
2449 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002450 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002451 ret = -1;
2452 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002453 }
2454 }
2455
2456 if (out_basefmt != NULL) {
2457 new_backing_drv = bdrv_find_format(out_basefmt);
2458 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002459 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002460 ret = -1;
2461 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002462 }
2463 }
2464
2465 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002466 if (!unsafe) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002467 char backing_name[1024];
2468
Markus Armbruster26f54e92014-10-07 13:59:04 +02002469 blk_old_backing = blk_new("old_backing", &error_abort);
Markus Armbrustere4e99862014-10-07 13:59:03 +02002470 bs_old_backing = bdrv_new_root("old_backing", &error_abort);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002471 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitz40055952014-07-22 22:58:42 +02002472 ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002473 old_backing_drv, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002474 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002475 error_report("Could not open old backing file '%s': %s",
2476 backing_name, error_get_pretty(local_err));
2477 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002478 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002479 }
Alex Bligha6166732012-10-16 13:46:18 +01002480 if (out_baseimg[0]) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002481 blk_new_backing = blk_new("new_backing", &error_abort);
Markus Armbrustere4e99862014-10-07 13:59:03 +02002482 bs_new_backing = bdrv_new_root("new_backing", &error_abort);
Max Reitz40055952014-07-22 22:58:42 +02002483 ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
2484 new_backing_drv, &local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002485 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002486 error_report("Could not open new backing file '%s': %s",
2487 out_baseimg, error_get_pretty(local_err));
2488 error_free(local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002489 goto out;
2490 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002491 }
2492 }
2493
2494 /*
2495 * Check each unallocated cluster in the COW file. If it is unallocated,
2496 * accesses go to the backing file. We must therefore compare this cluster
2497 * in the old and new backing file, and if they differ we need to copy it
2498 * from the old backing file into the COW file.
2499 *
2500 * If qemu-img crashes during this step, no harm is done. The content of
2501 * the image is the same as the original one at any time.
2502 */
2503 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002504 int64_t num_sectors;
2505 int64_t old_backing_num_sectors;
2506 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002507 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02002508 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08002509 uint8_t * buf_old;
2510 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02002511 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08002512
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002513 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2514 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002515
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002516 num_sectors = bdrv_nb_sectors(bs);
2517 if (num_sectors < 0) {
2518 error_report("Could not get size of '%s': %s",
2519 filename, strerror(-num_sectors));
2520 ret = -1;
2521 goto out;
2522 }
2523 old_backing_num_sectors = bdrv_nb_sectors(bs_old_backing);
2524 if (old_backing_num_sectors < 0) {
2525 char backing_name[1024];
2526
2527 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2528 error_report("Could not get size of '%s': %s",
2529 backing_name, strerror(-old_backing_num_sectors));
2530 ret = -1;
2531 goto out;
2532 }
Alex Bligha6166732012-10-16 13:46:18 +01002533 if (bs_new_backing) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002534 new_backing_num_sectors = bdrv_nb_sectors(bs_new_backing);
2535 if (new_backing_num_sectors < 0) {
2536 error_report("Could not get size of '%s': %s",
2537 out_baseimg, strerror(-new_backing_num_sectors));
2538 ret = -1;
2539 goto out;
2540 }
Alex Bligha6166732012-10-16 13:46:18 +01002541 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002542
Kevin Wolf1f710492012-10-12 14:29:18 +02002543 if (num_sectors != 0) {
2544 local_progress = (float)100 /
2545 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2546 }
2547
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002548 for (sector = 0; sector < num_sectors; sector += n) {
2549
2550 /* How many sectors can we handle with the next read? */
2551 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2552 n = (IO_BUF_SIZE / 512);
2553 } else {
2554 n = num_sectors - sector;
2555 }
2556
2557 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02002558 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02002559 if (ret < 0) {
2560 error_report("error while reading image metadata: %s",
2561 strerror(-ret));
2562 goto out;
2563 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02002564 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002565 continue;
2566 }
2567
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002568 /*
2569 * Read old and new backing file and take into consideration that
2570 * backing files may be smaller than the COW image.
2571 */
2572 if (sector >= old_backing_num_sectors) {
2573 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2574 } else {
2575 if (sector + n > old_backing_num_sectors) {
2576 n = old_backing_num_sectors - sector;
2577 }
2578
2579 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2580 if (ret < 0) {
2581 error_report("error while reading from old backing file");
2582 goto out;
2583 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002584 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002585
Alex Bligha6166732012-10-16 13:46:18 +01002586 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002587 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2588 } else {
2589 if (sector + n > new_backing_num_sectors) {
2590 n = new_backing_num_sectors - sector;
2591 }
2592
2593 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2594 if (ret < 0) {
2595 error_report("error while reading from new backing file");
2596 goto out;
2597 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002598 }
2599
2600 /* If they differ, we need to write to the COW file */
2601 uint64_t written = 0;
2602
2603 while (written < n) {
2604 int pnum;
2605
2606 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01002607 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002608 {
2609 ret = bdrv_write(bs, sector + written,
2610 buf_old + written * 512, pnum);
2611 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002612 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002613 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002614 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002615 }
2616 }
2617
2618 written += pnum;
2619 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002620 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002621 }
TeLeMand6771bf2010-02-08 16:20:00 +08002622
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002623 qemu_vfree(buf_old);
2624 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002625 }
2626
2627 /*
2628 * Change the backing file. All clusters that are different from the old
2629 * backing file are overwritten in the COW file now, so the visible content
2630 * doesn't change when we switch the backing file.
2631 */
Alex Bligha6166732012-10-16 13:46:18 +01002632 if (out_baseimg && *out_baseimg) {
2633 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2634 } else {
2635 ret = bdrv_change_backing_file(bs, NULL, NULL);
2636 }
2637
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002638 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002639 error_report("Could not change the backing file to '%s': No "
2640 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002641 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002642 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002643 out_baseimg, strerror(-ret));
2644 }
2645
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002646 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002647 /*
2648 * TODO At this point it is possible to check if any clusters that are
2649 * allocated in the COW file are the same in the backing file. If so, they
2650 * could be dropped from the COW file. Don't do this before switching the
2651 * backing file, in case of a crash this would lead to corruption.
2652 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002653out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002654 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002655 /* Cleanup */
2656 if (!unsafe) {
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002657 if (bs_old_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002658 bdrv_unref(bs_old_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002659 }
Markus Armbruster26f54e92014-10-07 13:59:04 +02002660 blk_unref(blk_old_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002661 if (bs_new_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002662 bdrv_unref(bs_new_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002663 }
Markus Armbruster26f54e92014-10-07 13:59:04 +02002664 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002665 }
2666
Fam Zheng4f6fd342013-08-23 09:14:47 +08002667 bdrv_unref(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002668 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002669 if (ret) {
2670 return 1;
2671 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002672 return 0;
2673}
2674
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002675static int img_resize(int argc, char **argv)
2676{
2677 int c, ret, relative;
2678 const char *filename, *fmt, *size;
2679 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002680 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002681 BlockBackend *blk = NULL;
Jes Sorensen2a819982010-12-06 17:08:31 +01002682 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002683 QemuOpts *param;
2684 static QemuOptsList resize_options = {
2685 .name = "resize_options",
2686 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2687 .desc = {
2688 {
2689 .name = BLOCK_OPT_SIZE,
2690 .type = QEMU_OPT_SIZE,
2691 .help = "Virtual disk size"
2692 }, {
2693 /* end of list */
2694 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002695 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002696 };
2697
Kevin Wolfe80fec72011-04-29 10:58:12 +02002698 /* Remove size from argv manually so that negative numbers are not treated
2699 * as options by getopt. */
2700 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002701 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02002702 return 1;
2703 }
2704
2705 size = argv[--argc];
2706
2707 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002708 fmt = NULL;
2709 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002710 c = getopt(argc, argv, "f:hq");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002711 if (c == -1) {
2712 break;
2713 }
2714 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002715 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002716 case 'h':
2717 help();
2718 break;
2719 case 'f':
2720 fmt = optarg;
2721 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002722 case 'q':
2723 quiet = true;
2724 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002725 }
2726 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002727 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002728 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002729 }
2730 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002731
2732 /* Choose grow, shrink, or absolute resize mode */
2733 switch (size[0]) {
2734 case '+':
2735 relative = 1;
2736 size++;
2737 break;
2738 case '-':
2739 relative = -1;
2740 size++;
2741 break;
2742 default:
2743 relative = 0;
2744 break;
2745 }
2746
2747 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08002748 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002749 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002750 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002751 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002752 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002753 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002754 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002755 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2756 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002757
Markus Armbruster26f54e92014-10-07 13:59:04 +02002758 blk = blk_new("image", &error_abort);
Kevin Wolf9ffe3332014-04-17 16:57:13 +02002759 bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
2760 true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002761 if (!bs) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002762 ret = -1;
2763 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002764 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002765
2766 if (relative) {
2767 total_size = bdrv_getlength(bs) + n * relative;
2768 } else {
2769 total_size = n;
2770 }
2771 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002772 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002773 ret = -1;
2774 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002775 }
2776
2777 ret = bdrv_truncate(bs, total_size);
2778 switch (ret) {
2779 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002780 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002781 break;
2782 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002783 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002784 break;
2785 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002786 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002787 break;
2788 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002789 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002790 break;
2791 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002792out:
Jes Sorensen2a819982010-12-06 17:08:31 +01002793 if (bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002794 bdrv_unref(bs);
Jes Sorensen2a819982010-12-06 17:08:31 +01002795 }
Markus Armbruster26f54e92014-10-07 13:59:04 +02002796 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002797 if (ret) {
2798 return 1;
2799 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002800 return 0;
2801}
2802
Max Reitz6f176b42013-09-03 10:09:50 +02002803static int img_amend(int argc, char **argv)
2804{
2805 int c, ret = 0;
2806 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002807 QemuOptsList *create_opts = NULL;
2808 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02002809 const char *fmt = NULL, *filename, *cache;
2810 int flags;
Max Reitz6f176b42013-09-03 10:09:50 +02002811 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002812 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02002813 BlockDriverState *bs = NULL;
2814
Max Reitzbd39e6e2014-07-22 22:58:43 +02002815 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02002816 for (;;) {
Max Reitzbd39e6e2014-07-22 22:58:43 +02002817 c = getopt(argc, argv, "ho:f:t:q");
Max Reitz6f176b42013-09-03 10:09:50 +02002818 if (c == -1) {
2819 break;
2820 }
2821
2822 switch (c) {
2823 case 'h':
2824 case '?':
2825 help();
2826 break;
2827 case 'o':
Kevin Wolf626f84f2014-02-21 16:24:06 +01002828 if (!is_valid_option_list(optarg)) {
2829 error_report("Invalid option list: %s", optarg);
2830 ret = -1;
2831 goto out;
2832 }
2833 if (!options) {
2834 options = g_strdup(optarg);
2835 } else {
2836 char *old_options = options;
2837 options = g_strdup_printf("%s,%s", options, optarg);
2838 g_free(old_options);
2839 }
Max Reitz6f176b42013-09-03 10:09:50 +02002840 break;
2841 case 'f':
2842 fmt = optarg;
2843 break;
Max Reitzbd39e6e2014-07-22 22:58:43 +02002844 case 't':
2845 cache = optarg;
2846 break;
Max Reitz6f176b42013-09-03 10:09:50 +02002847 case 'q':
2848 quiet = true;
2849 break;
2850 }
2851 }
2852
Max Reitz6f176b42013-09-03 10:09:50 +02002853 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002854 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02002855 }
2856
Kevin Wolfa283cb62014-02-21 16:24:07 +01002857 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
2858 if (fmt && has_help_option(options)) {
2859 /* If a format is explicitly specified (and possibly no filename is
2860 * given), print option help here */
2861 ret = print_block_option_help(filename, fmt);
2862 goto out;
2863 }
2864
2865 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002866 error_exit("Expecting one image file name");
Kevin Wolfa283cb62014-02-21 16:24:07 +01002867 }
Max Reitz6f176b42013-09-03 10:09:50 +02002868
Max Reitzbd39e6e2014-07-22 22:58:43 +02002869 flags = BDRV_O_FLAGS | BDRV_O_RDWR;
2870 ret = bdrv_parse_cache_flags(cache, &flags);
2871 if (ret < 0) {
2872 error_report("Invalid cache option: %s", cache);
2873 goto out;
2874 }
2875
Markus Armbruster26f54e92014-10-07 13:59:04 +02002876 blk = blk_new("image", &error_abort);
Max Reitzbd39e6e2014-07-22 22:58:43 +02002877 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
Max Reitz6f176b42013-09-03 10:09:50 +02002878 if (!bs) {
2879 error_report("Could not open image '%s'", filename);
2880 ret = -1;
2881 goto out;
2882 }
2883
2884 fmt = bs->drv->format_name;
2885
Kevin Wolf626f84f2014-02-21 16:24:06 +01002886 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01002887 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02002888 ret = print_block_option_help(filename, fmt);
2889 goto out;
2890 }
2891
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002892 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08002893 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2894 if (options && qemu_opts_do_parse(opts, options, NULL)) {
Max Reitz6f176b42013-09-03 10:09:50 +02002895 error_report("Invalid options for file format '%s'", fmt);
2896 ret = -1;
2897 goto out;
2898 }
2899
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002900 ret = bdrv_amend_options(bs, opts);
Max Reitz6f176b42013-09-03 10:09:50 +02002901 if (ret < 0) {
2902 error_report("Error while amending options: %s", strerror(-ret));
2903 goto out;
2904 }
2905
2906out:
2907 if (bs) {
2908 bdrv_unref(bs);
2909 }
Markus Armbruster26f54e92014-10-07 13:59:04 +02002910 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08002911 qemu_opts_del(opts);
2912 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01002913 g_free(options);
2914
Max Reitz6f176b42013-09-03 10:09:50 +02002915 if (ret) {
2916 return 1;
2917 }
2918 return 0;
2919}
2920
Anthony Liguoric227f092009-10-01 16:12:16 -05002921static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002922#define DEF(option, callback, arg_string) \
2923 { option, callback },
2924#include "qemu-img-cmds.h"
2925#undef DEF
2926#undef GEN_DOCS
2927 { NULL, NULL, },
2928};
2929
bellardea2384d2004-08-01 21:59:26 +00002930int main(int argc, char **argv)
2931{
Anthony Liguoric227f092009-10-01 16:12:16 -05002932 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002933 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03002934 Error *local_error = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04002935 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04002936 static const struct option long_options[] = {
2937 {"help", no_argument, 0, 'h'},
Jeff Cody5f6979c2014-04-28 14:37:18 -04002938 {"version", no_argument, 0, 'v'},
Jeff Cody7db16892014-04-25 17:02:32 -04002939 {0, 0, 0, 0}
2940 };
bellardea2384d2004-08-01 21:59:26 +00002941
MORITA Kazutaka526eda12013-07-23 17:30:11 +09002942#ifdef CONFIG_POSIX
2943 signal(SIGPIPE, SIG_IGN);
2944#endif
2945
Kevin Wolf53f76e52010-12-16 15:10:32 +01002946 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08002947 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01002948
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03002949 if (qemu_init_main_loop(&local_error)) {
2950 error_report("%s", error_get_pretty(local_error));
2951 error_free(local_error);
2952 exit(EXIT_FAILURE);
2953 }
2954
bellardea2384d2004-08-01 21:59:26 +00002955 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08002956 if (argc < 2) {
2957 error_exit("Not enough arguments");
2958 }
Stuart Brady153859b2009-06-07 00:42:17 +01002959 cmdname = argv[1];
Stuart Brady153859b2009-06-07 00:42:17 +01002960
2961 /* find the command */
Jeff Cody5f6979c2014-04-28 14:37:18 -04002962 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
Stuart Brady153859b2009-06-07 00:42:17 +01002963 if (!strcmp(cmdname, cmd->name)) {
Jeff Cody7db16892014-04-25 17:02:32 -04002964 return cmd->handler(argc - 1, argv + 1);
Stuart Brady153859b2009-06-07 00:42:17 +01002965 }
bellardea2384d2004-08-01 21:59:26 +00002966 }
Stuart Brady153859b2009-06-07 00:42:17 +01002967
Jeff Cody5f6979c2014-04-28 14:37:18 -04002968 c = getopt_long(argc, argv, "h", long_options, NULL);
Jeff Cody7db16892014-04-25 17:02:32 -04002969
2970 if (c == 'h') {
2971 help();
2972 }
Jeff Cody5f6979c2014-04-28 14:37:18 -04002973 if (c == 'v') {
2974 printf(QEMU_IMG_VERSION);
2975 return 0;
2976 }
Jeff Cody7db16892014-04-25 17:02:32 -04002977
Stuart Brady153859b2009-06-07 00:42:17 +01002978 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08002979 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00002980}