blob: 54ae9849790922f3a5034b93fcd098855ce2dc2f [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"
Paolo Bonzini737e1502012-12-17 18:19:44 +010032#include "block/block_int.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080033#include "block/qapi.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020034#include <getopt.h>
aliguori9230eaf2009-03-28 17:55:19 +000035#include <stdio.h>
Miroslav Rezaninaf382d432013-02-13 09:09:40 +010036#include <stdarg.h>
bellardea2384d2004-08-01 21:59:26 +000037
bellarde8445332006-06-14 15:32:10 +000038#ifdef _WIN32
39#include <windows.h>
40#endif
41
Anthony Liguoric227f092009-10-01 16:12:16 -050042typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010043 const char *name;
44 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050045} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010046
Federico Simoncelli8599ea42013-01-28 06:59:47 -050047enum {
48 OPTION_OUTPUT = 256,
49 OPTION_BACKING_CHAIN = 257,
50};
51
52typedef enum OutputFormat {
53 OFORMAT_JSON,
54 OFORMAT_HUMAN,
55} OutputFormat;
56
aurel32137519c2008-11-30 19:12:49 +000057/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
Stefan Hajnocziadfe0782010-04-13 10:29:35 +010058#define BDRV_O_FLAGS BDRV_O_CACHE_WB
Federico Simoncelli661a0f72011-06-20 12:48:19 -040059#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000060
bellardea2384d2004-08-01 21:59:26 +000061static void format_print(void *opaque, const char *name)
62{
63 printf(" %s", name);
64}
65
blueswir1d2c639d2009-01-24 18:19:25 +000066/* Please keep in synch with qemu-img.texi */
pbrook3f379ab2007-11-11 03:33:13 +000067static void help(void)
bellardea2384d2004-08-01 21:59:26 +000068{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010069 const char *help_msg =
70 "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
malc3f020d72010-02-08 12:04:56 +030071 "usage: qemu-img command [command options]\n"
72 "QEMU disk image utility\n"
73 "\n"
74 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +010075#define DEF(option, callback, arg_string) \
76 " " arg_string "\n"
77#include "qemu-img-cmds.h"
78#undef DEF
79#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +030080 "\n"
81 "Command parameters:\n"
82 " 'filename' is a disk image filename\n"
83 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -040084 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +080085 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
86 " 'directsync' and 'unsafe' (default for convert)\n"
malc3f020d72010-02-08 12:04:56 +030087 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +020088 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
89 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
90 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +030091 " 'output_filename' is the destination disk image filename\n"
92 " 'output_fmt' is the destination format\n"
93 " 'options' is a comma separated list of format specific options in a\n"
94 " name=value format. Use -o ? for an overview of the options supported by the\n"
95 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +080096 " 'snapshot_param' is param used for internal snapshot, format\n"
97 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
98 " '[ID_OR_NAME]'\n"
99 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
100 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300101 " '-c' indicates that target image must be compressed (qcow format only)\n"
102 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
103 " match exactly. The image doesn't need a working backing file before\n"
104 " rebasing in this case (useful for renaming the backing file)\n"
105 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200106 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100107 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200108 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
109 " contain only zeros for qemu-img to create a sparse image during\n"
110 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
111 " unallocated or zero sectors, and the destination image will always be\n"
112 " fully allocated\n"
113 " images will always be fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200114 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100115 " '-n' skips the target volume creation (useful if the volume is created\n"
116 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300117 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200118 "Parameters to check subcommand:\n"
119 " '-r' tries to repair any inconsistencies that are found during the check.\n"
120 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
121 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200122 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200123 "\n"
malc3f020d72010-02-08 12:04:56 +0300124 "Parameters to snapshot subcommand:\n"
125 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
126 " '-a' applies a snapshot (revert disk to saved state)\n"
127 " '-c' creates a snapshot\n"
128 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100129 " '-l' lists all snapshots in the given image\n"
130 "\n"
131 "Parameters to compare subcommand:\n"
132 " '-f' first image format\n"
133 " '-F' second image format\n"
134 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100135
136 printf("%s\nSupported formats:", help_msg);
bellardea2384d2004-08-01 21:59:26 +0000137 bdrv_iterate_format(format_print, NULL);
138 printf("\n");
139 exit(1);
140}
141
Stefan Weil7c30f652013-06-16 17:01:05 +0200142static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100143{
144 int ret = 0;
145 if (!quiet) {
146 va_list args;
147 va_start(args, fmt);
148 ret = vprintf(fmt, args);
149 va_end(args);
150 }
151 return ret;
152}
153
bellardea2384d2004-08-01 21:59:26 +0000154#if defined(WIN32)
155/* XXX: put correct support for win32 */
156static int read_password(char *buf, int buf_size)
157{
158 int c, i;
159 printf("Password: ");
160 fflush(stdout);
161 i = 0;
162 for(;;) {
163 c = getchar();
164 if (c == '\n')
165 break;
166 if (i < (buf_size - 1))
167 buf[i++] = c;
168 }
169 buf[i] = '\0';
170 return 0;
171}
172
173#else
174
175#include <termios.h>
176
177static struct termios oldtty;
178
179static void term_exit(void)
180{
181 tcsetattr (0, TCSANOW, &oldtty);
182}
183
184static void term_init(void)
185{
186 struct termios tty;
187
188 tcgetattr (0, &tty);
189 oldtty = tty;
190
191 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
192 |INLCR|IGNCR|ICRNL|IXON);
193 tty.c_oflag |= OPOST;
194 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
195 tty.c_cflag &= ~(CSIZE|PARENB);
196 tty.c_cflag |= CS8;
197 tty.c_cc[VMIN] = 1;
198 tty.c_cc[VTIME] = 0;
ths3b46e622007-09-17 08:09:54 +0000199
bellardea2384d2004-08-01 21:59:26 +0000200 tcsetattr (0, TCSANOW, &tty);
201
202 atexit(term_exit);
203}
204
pbrook3f379ab2007-11-11 03:33:13 +0000205static int read_password(char *buf, int buf_size)
bellardea2384d2004-08-01 21:59:26 +0000206{
207 uint8_t ch;
208 int i, ret;
209
210 printf("password: ");
211 fflush(stdout);
212 term_init();
213 i = 0;
214 for(;;) {
215 ret = read(0, &ch, 1);
216 if (ret == -1) {
217 if (errno == EAGAIN || errno == EINTR) {
218 continue;
219 } else {
220 ret = -1;
221 break;
222 }
223 } else if (ret == 0) {
224 ret = -1;
225 break;
226 } else {
227 if (ch == '\r') {
228 ret = 0;
229 break;
230 }
231 if (i < (buf_size - 1))
232 buf[i++] = ch;
233 }
234 }
235 term_exit();
236 buf[i] = '\0';
237 printf("\n");
238 return ret;
239}
240#endif
241
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100242static int print_block_option_help(const char *filename, const char *fmt)
243{
244 BlockDriver *drv, *proto_drv;
245 QEMUOptionParameter *create_options = NULL;
246
247 /* Find driver and parse its options */
248 drv = bdrv_find_format(fmt);
249 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100250 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100251 return 1;
252 }
253
Kevin Wolf98289622013-07-10 15:47:39 +0200254 proto_drv = bdrv_find_protocol(filename, true);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100255 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100256 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100257 return 1;
258 }
259
260 create_options = append_option_parameters(create_options,
261 drv->create_options);
262 create_options = append_option_parameters(create_options,
263 proto_drv->create_options);
264 print_option_help(create_options);
265 free_option_parameters(create_options);
266 return 0;
267}
268
bellard75c23802004-08-27 21:28:58 +0000269static BlockDriverState *bdrv_new_open(const char *filename,
Sheng Yang9bc378c2010-01-29 10:15:06 +0800270 const char *fmt,
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100271 int flags,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100272 bool require_io,
273 bool quiet)
bellard75c23802004-08-27 21:28:58 +0000274{
275 BlockDriverState *bs;
276 BlockDriver *drv;
277 char password[256];
Max Reitz34b5d2c2013-09-05 14:45:29 +0200278 Error *local_err = NULL;
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100279 int ret;
bellard75c23802004-08-27 21:28:58 +0000280
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100281 bs = bdrv_new("image");
Kevin Wolfad717132010-12-16 15:37:41 +0100282
bellard75c23802004-08-27 21:28:58 +0000283 if (fmt) {
284 drv = bdrv_find_format(fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900285 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100286 error_report("Unknown file format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900287 goto fail;
288 }
bellard75c23802004-08-27 21:28:58 +0000289 } else {
290 drv = NULL;
291 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100292
Max Reitz34b5d2c2013-09-05 14:45:29 +0200293 ret = bdrv_open(bs, filename, NULL, flags, drv, &local_err);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100294 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200295 error_report("Could not open '%s': %s", filename,
296 error_get_pretty(local_err));
297 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900298 goto fail;
bellard75c23802004-08-27 21:28:58 +0000299 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100300
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100301 if (bdrv_is_encrypted(bs) && require_io) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100302 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900303 if (read_password(password, sizeof(password)) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100304 error_report("No password given");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900305 goto fail;
306 }
307 if (bdrv_set_key(bs, password) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100308 error_report("invalid password");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900309 goto fail;
310 }
bellard75c23802004-08-27 21:28:58 +0000311 }
312 return bs;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900313fail:
314 if (bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +0800315 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900316 }
317 return NULL;
bellard75c23802004-08-27 21:28:58 +0000318}
319
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900320static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100321 const char *base_filename,
322 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200323{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200324 if (base_filename) {
325 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100326 error_report("Backing file not supported for file format '%s'",
327 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900328 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200329 }
330 }
331 if (base_fmt) {
332 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100333 error_report("Backing file format not supported for file "
334 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900335 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200336 }
337 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900338 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200339}
340
bellardea2384d2004-08-01 21:59:26 +0000341static int img_create(int argc, char **argv)
342{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200343 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100344 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000345 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000346 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000347 const char *filename;
348 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200349 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200350 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100351 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000352
bellardea2384d2004-08-01 21:59:26 +0000353 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100354 c = getopt(argc, argv, "F:b:f:he6o:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100355 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000356 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100357 }
bellardea2384d2004-08-01 21:59:26 +0000358 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100359 case '?':
bellardea2384d2004-08-01 21:59:26 +0000360 case 'h':
361 help();
362 break;
aliguori9230eaf2009-03-28 17:55:19 +0000363 case 'F':
364 base_fmt = optarg;
365 break;
bellardea2384d2004-08-01 21:59:26 +0000366 case 'b':
367 base_filename = optarg;
368 break;
369 case 'f':
370 fmt = optarg;
371 break;
372 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200373 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100374 "encryption\' instead!");
375 return 1;
thsd8871c52007-10-24 16:11:42 +0000376 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200377 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100378 "compat6\' instead!");
379 return 1;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200380 case 'o':
381 options = optarg;
382 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100383 case 'q':
384 quiet = true;
385 break;
bellardea2384d2004-08-01 21:59:26 +0000386 }
387 }
aliguori9230eaf2009-03-28 17:55:19 +0000388
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900389 /* Get the filename */
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100390 if (optind >= argc) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900391 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100392 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900393 filename = argv[optind++];
394
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100395 /* Get image size, if specified */
396 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100397 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100398 char *end;
399 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
400 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800401 if (sval == -ERANGE) {
402 error_report("Image size must be less than 8 EiB!");
403 } else {
404 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200405 "G, T, P or E suffixes for ");
406 error_report("kilobytes, megabytes, gigabytes, terabytes, "
407 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800408 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200409 return 1;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100410 }
411 img_size = (uint64_t)sval;
412 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200413 if (optind != argc) {
414 help();
415 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100416
Peter Maydellc8057f92012-08-02 13:45:54 +0100417 if (options && is_help_option(options)) {
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200418 return print_block_option_help(filename, fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100419 }
420
Luiz Capitulino9b375252012-11-30 10:52:05 -0200421 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100422 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
Luiz Capitulino9b375252012-11-30 10:52:05 -0200423 if (error_is_set(&local_err)) {
Max Reitzb70d8c22013-09-06 16:51:03 +0200424 error_report("%s: %s", filename, error_get_pretty(local_err));
Luiz Capitulino9b375252012-11-30 10:52:05 -0200425 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900426 return 1;
427 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200428
bellardea2384d2004-08-01 21:59:26 +0000429 return 0;
430}
431
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100432static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500433{
434 Error *errp = NULL;
435 QString *str;
436 QmpOutputVisitor *ov = qmp_output_visitor_new();
437 QObject *obj;
438 visit_type_ImageCheck(qmp_output_get_visitor(ov),
439 &check, NULL, &errp);
440 obj = qmp_output_get_qobject(ov);
441 str = qobject_to_json_pretty(obj);
442 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100443 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500444 qobject_decref(obj);
445 qmp_output_visitor_cleanup(ov);
446 QDECREF(str);
447}
448
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100449static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500450{
451 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100452 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500453 } else {
454 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100455 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
456 "Data may be corrupted, or further writes to the image "
457 "may corrupt it.\n",
458 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500459 }
460
461 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100462 qprintf(quiet,
463 "\n%" PRId64 " leaked clusters were found on the image.\n"
464 "This means waste of disk space, but no harm to data.\n",
465 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500466 }
467
468 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100469 qprintf(quiet,
470 "\n%" PRId64
471 " internal errors have occurred during the check.\n",
472 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500473 }
474 }
475
476 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100477 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
478 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
479 check->allocated_clusters, check->total_clusters,
480 check->allocated_clusters * 100.0 / check->total_clusters,
481 check->fragmented_clusters * 100.0 / check->allocated_clusters,
482 check->compressed_clusters * 100.0 /
483 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500484 }
485
486 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100487 qprintf(quiet,
488 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500489 }
490}
491
492static int collect_image_check(BlockDriverState *bs,
493 ImageCheck *check,
494 const char *filename,
495 const char *fmt,
496 int fix)
497{
498 int ret;
499 BdrvCheckResult result;
500
501 ret = bdrv_check(bs, &result, fix);
502 if (ret < 0) {
503 return ret;
504 }
505
506 check->filename = g_strdup(filename);
507 check->format = g_strdup(bdrv_get_format_name(bs));
508 check->check_errors = result.check_errors;
509 check->corruptions = result.corruptions;
510 check->has_corruptions = result.corruptions != 0;
511 check->leaks = result.leaks;
512 check->has_leaks = result.leaks != 0;
513 check->corruptions_fixed = result.corruptions_fixed;
514 check->has_corruptions_fixed = result.corruptions != 0;
515 check->leaks_fixed = result.leaks_fixed;
516 check->has_leaks_fixed = result.leaks != 0;
517 check->image_end_offset = result.image_end_offset;
518 check->has_image_end_offset = result.image_end_offset != 0;
519 check->total_clusters = result.bfi.total_clusters;
520 check->has_total_clusters = result.bfi.total_clusters != 0;
521 check->allocated_clusters = result.bfi.allocated_clusters;
522 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
523 check->fragmented_clusters = result.bfi.fragmented_clusters;
524 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100525 check->compressed_clusters = result.bfi.compressed_clusters;
526 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500527
528 return 0;
529}
530
Kevin Wolfe076f332010-06-29 11:43:13 +0200531/*
532 * Checks an image for consistency. Exit codes:
533 *
534 * 0 - Check completed, image is good
535 * 1 - Check not completed because of internal errors
536 * 2 - Check completed, image is corrupted
537 * 3 - Check completed, image has leaked clusters, but is good otherwise
538 */
aliguori15859692009-04-21 23:11:53 +0000539static int img_check(int argc, char **argv)
540{
541 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500542 OutputFormat output_format = OFORMAT_HUMAN;
543 const char *filename, *fmt, *output;
aliguori15859692009-04-21 23:11:53 +0000544 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200545 int fix = 0;
Stefan Hajnoczi058f8f12012-08-09 13:05:56 +0100546 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500547 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100548 bool quiet = false;
aliguori15859692009-04-21 23:11:53 +0000549
550 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500551 output = NULL;
aliguori15859692009-04-21 23:11:53 +0000552 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500553 int option_index = 0;
554 static const struct option long_options[] = {
555 {"help", no_argument, 0, 'h'},
556 {"format", required_argument, 0, 'f'},
557 {"repair", no_argument, 0, 'r'},
558 {"output", required_argument, 0, OPTION_OUTPUT},
559 {0, 0, 0, 0}
560 };
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100561 c = getopt_long(argc, argv, "f:hr:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500562 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100563 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000564 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100565 }
aliguori15859692009-04-21 23:11:53 +0000566 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100567 case '?':
aliguori15859692009-04-21 23:11:53 +0000568 case 'h':
569 help();
570 break;
571 case 'f':
572 fmt = optarg;
573 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200574 case 'r':
575 flags |= BDRV_O_RDWR;
576
577 if (!strcmp(optarg, "leaks")) {
578 fix = BDRV_FIX_LEAKS;
579 } else if (!strcmp(optarg, "all")) {
580 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
581 } else {
582 help();
583 }
584 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500585 case OPTION_OUTPUT:
586 output = optarg;
587 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100588 case 'q':
589 quiet = true;
590 break;
aliguori15859692009-04-21 23:11:53 +0000591 }
592 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200593 if (optind != argc - 1) {
aliguori15859692009-04-21 23:11:53 +0000594 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100595 }
aliguori15859692009-04-21 23:11:53 +0000596 filename = argv[optind++];
597
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500598 if (output && !strcmp(output, "json")) {
599 output_format = OFORMAT_JSON;
600 } else if (output && !strcmp(output, "human")) {
601 output_format = OFORMAT_HUMAN;
602 } else if (output) {
603 error_report("--output must be used with human or json as argument.");
604 return 1;
605 }
606
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100607 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900608 if (!bs) {
609 return 1;
610 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500611
612 check = g_new0(ImageCheck, 1);
613 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200614
615 if (ret == -ENOTSUP) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500616 if (output_format == OFORMAT_HUMAN) {
617 error_report("This image format does not support checks");
618 }
Peter Lievenfefddf92013-10-24 08:53:34 +0200619 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500620 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200621 }
622
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500623 if (check->corruptions_fixed || check->leaks_fixed) {
624 int corruptions_fixed, leaks_fixed;
625
626 leaks_fixed = check->leaks_fixed;
627 corruptions_fixed = check->corruptions_fixed;
628
629 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100630 qprintf(quiet,
631 "The following inconsistencies were found and repaired:\n\n"
632 " %" PRId64 " leaked clusters\n"
633 " %" PRId64 " corruptions\n\n"
634 "Double checking the fixed image now...\n",
635 check->leaks_fixed,
636 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500637 }
638
639 ret = collect_image_check(bs, check, filename, fmt, 0);
640
641 check->leaks_fixed = leaks_fixed;
642 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200643 }
644
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500645 switch (output_format) {
646 case OFORMAT_HUMAN:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100647 dump_human_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500648 break;
649 case OFORMAT_JSON:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100650 dump_json_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500651 break;
652 }
653
654 if (ret || check->check_errors) {
655 ret = 1;
656 goto fail;
657 }
658
659 if (check->corruptions) {
660 ret = 2;
661 } else if (check->leaks) {
662 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200663 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500664 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000665 }
666
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500667fail:
668 qapi_free_ImageCheck(check);
Fam Zheng4f6fd342013-08-23 09:14:47 +0800669 bdrv_unref(bs);
Kevin Wolfe076f332010-06-29 11:43:13 +0200670
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500671 return ret;
aliguori15859692009-04-21 23:11:53 +0000672}
673
bellardea2384d2004-08-01 21:59:26 +0000674static int img_commit(int argc, char **argv)
675{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400676 int c, ret, flags;
677 const char *filename, *fmt, *cache;
bellardea2384d2004-08-01 21:59:26 +0000678 BlockDriverState *bs;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100679 bool quiet = false;
bellardea2384d2004-08-01 21:59:26 +0000680
681 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400682 cache = BDRV_DEFAULT_CACHE;
bellardea2384d2004-08-01 21:59:26 +0000683 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100684 c = getopt(argc, argv, "f:ht:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100685 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000686 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100687 }
bellardea2384d2004-08-01 21:59:26 +0000688 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100689 case '?':
bellardea2384d2004-08-01 21:59:26 +0000690 case 'h':
691 help();
692 break;
693 case 'f':
694 fmt = optarg;
695 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400696 case 't':
697 cache = optarg;
698 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100699 case 'q':
700 quiet = true;
701 break;
bellardea2384d2004-08-01 21:59:26 +0000702 }
703 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200704 if (optind != argc - 1) {
bellardea2384d2004-08-01 21:59:26 +0000705 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100706 }
bellardea2384d2004-08-01 21:59:26 +0000707 filename = argv[optind++];
708
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400709 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100710 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400711 if (ret < 0) {
712 error_report("Invalid cache option: %s", cache);
713 return -1;
714 }
715
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100716 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900717 if (!bs) {
718 return 1;
719 }
bellardea2384d2004-08-01 21:59:26 +0000720 ret = bdrv_commit(bs);
721 switch(ret) {
722 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100723 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000724 break;
725 case -ENOENT:
Jes Sorensen15654a62010-12-16 14:31:53 +0100726 error_report("No disk inserted");
bellardea2384d2004-08-01 21:59:26 +0000727 break;
728 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +0100729 error_report("Image is read-only");
bellardea2384d2004-08-01 21:59:26 +0000730 break;
731 case -ENOTSUP:
Jes Sorensen15654a62010-12-16 14:31:53 +0100732 error_report("Image is already committed");
bellardea2384d2004-08-01 21:59:26 +0000733 break;
734 default:
Jes Sorensen15654a62010-12-16 14:31:53 +0100735 error_report("Error while committing image");
bellardea2384d2004-08-01 21:59:26 +0000736 break;
737 }
738
Fam Zheng4f6fd342013-08-23 09:14:47 +0800739 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900740 if (ret) {
741 return 1;
742 }
bellardea2384d2004-08-01 21:59:26 +0000743 return 0;
744}
745
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400746/*
thsf58c7b32008-06-05 21:53:49 +0000747 * Returns true iff the first sector pointed to by 'buf' contains at least
748 * a non-NUL byte.
749 *
750 * 'pnum' is set to the number of sectors (including and immediately following
751 * the first one) that are known to be in the same allocated/unallocated state.
752 */
bellardea2384d2004-08-01 21:59:26 +0000753static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
754{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000755 bool is_zero;
756 int i;
bellardea2384d2004-08-01 21:59:26 +0000757
758 if (n <= 0) {
759 *pnum = 0;
760 return 0;
761 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000762 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +0000763 for(i = 1; i < n; i++) {
764 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000765 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +0000766 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000767 }
bellardea2384d2004-08-01 21:59:26 +0000768 }
769 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000770 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +0000771}
772
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100773/*
Kevin Wolfa22f1232011-08-26 15:27:13 +0200774 * Like is_allocated_sectors, but if the buffer starts with a used sector,
775 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
776 * breaking up write requests for only small sparse areas.
777 */
778static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
779 int min)
780{
781 int ret;
782 int num_checked, num_used;
783
784 if (n < min) {
785 min = n;
786 }
787
788 ret = is_allocated_sectors(buf, n, pnum);
789 if (!ret) {
790 return ret;
791 }
792
793 num_used = *pnum;
794 buf += BDRV_SECTOR_SIZE * *pnum;
795 n -= *pnum;
796 num_checked = num_used;
797
798 while (n > 0) {
799 ret = is_allocated_sectors(buf, n, pnum);
800
801 buf += BDRV_SECTOR_SIZE * *pnum;
802 n -= *pnum;
803 num_checked += *pnum;
804 if (ret) {
805 num_used = num_checked;
806 } else if (*pnum >= min) {
807 break;
808 }
809 }
810
811 *pnum = num_used;
812 return 1;
813}
814
815/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100816 * Compares two buffers sector by sector. Returns 0 if the first sector of both
817 * buffers matches, non-zero otherwise.
818 *
819 * pnum is set to the number of sectors (including and immediately following
820 * the first one) that are known to have the same comparison result
821 */
822static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
823 int *pnum)
824{
825 int res, i;
826
827 if (n <= 0) {
828 *pnum = 0;
829 return 0;
830 }
831
832 res = !!memcmp(buf1, buf2, 512);
833 for(i = 1; i < n; i++) {
834 buf1 += 512;
835 buf2 += 512;
836
837 if (!!memcmp(buf1, buf2, 512) != res) {
838 break;
839 }
840 }
841
842 *pnum = i;
843 return res;
844}
845
Kevin Wolf80ee15a2009-09-15 12:30:43 +0200846#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +0000847
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100848static int64_t sectors_to_bytes(int64_t sectors)
849{
850 return sectors << BDRV_SECTOR_BITS;
851}
852
853static int64_t sectors_to_process(int64_t total, int64_t from)
854{
855 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
856}
857
858/*
859 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
860 *
861 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
862 * data and negative value on error.
863 *
864 * @param bs: Driver used for accessing file
865 * @param sect_num: Number of first sector to check
866 * @param sect_count: Number of sectors to check
867 * @param filename: Name of disk file we are checking (logging purpose)
868 * @param buffer: Allocated buffer for storing read data
869 * @param quiet: Flag for quiet mode
870 */
871static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
872 int sect_count, const char *filename,
873 uint8_t *buffer, bool quiet)
874{
875 int pnum, ret = 0;
876 ret = bdrv_read(bs, sect_num, buffer, sect_count);
877 if (ret < 0) {
878 error_report("Error while reading offset %" PRId64 " of %s: %s",
879 sectors_to_bytes(sect_num), filename, strerror(-ret));
880 return ret;
881 }
882 ret = is_allocated_sectors(buffer, sect_count, &pnum);
883 if (ret || pnum != sect_count) {
884 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
885 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
886 return 1;
887 }
888
889 return 0;
890}
891
892/*
893 * Compares two images. Exit codes:
894 *
895 * 0 - Images are identical
896 * 1 - Images differ
897 * >1 - Error occurred
898 */
899static int img_compare(int argc, char **argv)
900{
901 const char *fmt1 = NULL, *fmt2 = NULL, *filename1, *filename2;
902 BlockDriverState *bs1, *bs2;
903 int64_t total_sectors1, total_sectors2;
904 uint8_t *buf1 = NULL, *buf2 = NULL;
905 int pnum1, pnum2;
906 int allocated1, allocated2;
907 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
908 bool progress = false, quiet = false, strict = false;
909 int64_t total_sectors;
910 int64_t sector_num = 0;
911 int64_t nb_sectors;
912 int c, pnum;
913 uint64_t bs_sectors;
914 uint64_t progress_base;
915
916 for (;;) {
917 c = getopt(argc, argv, "hpf:F:sq");
918 if (c == -1) {
919 break;
920 }
921 switch (c) {
922 case '?':
923 case 'h':
924 help();
925 break;
926 case 'f':
927 fmt1 = optarg;
928 break;
929 case 'F':
930 fmt2 = optarg;
931 break;
932 case 'p':
933 progress = true;
934 break;
935 case 'q':
936 quiet = true;
937 break;
938 case 's':
939 strict = true;
940 break;
941 }
942 }
943
944 /* Progress is not shown in Quiet mode */
945 if (quiet) {
946 progress = false;
947 }
948
949
Kevin Wolffc11eb22013-08-05 10:53:04 +0200950 if (optind != argc - 2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100951 help();
952 }
953 filename1 = argv[optind++];
954 filename2 = argv[optind++];
955
956 /* Initialize before goto out */
957 qemu_progress_init(progress, 2.0);
958
959 bs1 = bdrv_new_open(filename1, fmt1, BDRV_O_FLAGS, true, quiet);
960 if (!bs1) {
961 error_report("Can't open file %s", filename1);
962 ret = 2;
963 goto out3;
964 }
965
966 bs2 = bdrv_new_open(filename2, fmt2, BDRV_O_FLAGS, true, quiet);
967 if (!bs2) {
968 error_report("Can't open file %s", filename2);
969 ret = 2;
970 goto out2;
971 }
972
973 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
974 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
975 bdrv_get_geometry(bs1, &bs_sectors);
976 total_sectors1 = bs_sectors;
977 bdrv_get_geometry(bs2, &bs_sectors);
978 total_sectors2 = bs_sectors;
979 total_sectors = MIN(total_sectors1, total_sectors2);
980 progress_base = MAX(total_sectors1, total_sectors2);
981
982 qemu_progress_print(0, 100);
983
984 if (strict && total_sectors1 != total_sectors2) {
985 ret = 1;
986 qprintf(quiet, "Strict mode: Image size mismatch!\n");
987 goto out;
988 }
989
990 for (;;) {
991 nb_sectors = sectors_to_process(total_sectors, sector_num);
992 if (nb_sectors <= 0) {
993 break;
994 }
995 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
996 &pnum1);
997 if (allocated1 < 0) {
998 ret = 3;
999 error_report("Sector allocation test failed for %s", filename1);
1000 goto out;
1001 }
1002
1003 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1004 &pnum2);
1005 if (allocated2 < 0) {
1006 ret = 3;
1007 error_report("Sector allocation test failed for %s", filename2);
1008 goto out;
1009 }
1010 nb_sectors = MIN(pnum1, pnum2);
1011
1012 if (allocated1 == allocated2) {
1013 if (allocated1) {
1014 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1015 if (ret < 0) {
1016 error_report("Error while reading offset %" PRId64 " of %s:"
1017 " %s", sectors_to_bytes(sector_num), filename1,
1018 strerror(-ret));
1019 ret = 4;
1020 goto out;
1021 }
1022 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1023 if (ret < 0) {
1024 error_report("Error while reading offset %" PRId64
1025 " of %s: %s", sectors_to_bytes(sector_num),
1026 filename2, strerror(-ret));
1027 ret = 4;
1028 goto out;
1029 }
1030 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1031 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001032 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1033 sectors_to_bytes(
1034 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001035 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001036 goto out;
1037 }
1038 }
1039 } else {
1040 if (strict) {
1041 ret = 1;
1042 qprintf(quiet, "Strict mode: Offset %" PRId64
1043 " allocation mismatch!\n",
1044 sectors_to_bytes(sector_num));
1045 goto out;
1046 }
1047
1048 if (allocated1) {
1049 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1050 filename1, buf1, quiet);
1051 } else {
1052 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1053 filename2, buf1, quiet);
1054 }
1055 if (ret) {
1056 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001057 error_report("Error while reading offset %" PRId64 ": %s",
1058 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001059 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001060 }
1061 goto out;
1062 }
1063 }
1064 sector_num += nb_sectors;
1065 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1066 }
1067
1068 if (total_sectors1 != total_sectors2) {
1069 BlockDriverState *bs_over;
1070 int64_t total_sectors_over;
1071 const char *filename_over;
1072
1073 qprintf(quiet, "Warning: Image size mismatch!\n");
1074 if (total_sectors1 > total_sectors2) {
1075 total_sectors_over = total_sectors1;
1076 bs_over = bs1;
1077 filename_over = filename1;
1078 } else {
1079 total_sectors_over = total_sectors2;
1080 bs_over = bs2;
1081 filename_over = filename2;
1082 }
1083
1084 for (;;) {
1085 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1086 if (nb_sectors <= 0) {
1087 break;
1088 }
1089 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1090 nb_sectors, &pnum);
1091 if (ret < 0) {
1092 ret = 3;
1093 error_report("Sector allocation test failed for %s",
1094 filename_over);
1095 goto out;
1096
1097 }
1098 nb_sectors = pnum;
1099 if (ret) {
1100 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1101 filename_over, buf1, quiet);
1102 if (ret) {
1103 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001104 error_report("Error while reading offset %" PRId64
1105 " of %s: %s", sectors_to_bytes(sector_num),
1106 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001107 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001108 }
1109 goto out;
1110 }
1111 }
1112 sector_num += nb_sectors;
1113 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1114 }
1115 }
1116
1117 qprintf(quiet, "Images are identical.\n");
1118 ret = 0;
1119
1120out:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001121 bdrv_unref(bs2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001122 qemu_vfree(buf1);
1123 qemu_vfree(buf2);
1124out2:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001125 bdrv_unref(bs1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001126out3:
1127 qemu_progress_end();
1128 return ret;
1129}
1130
bellardea2384d2004-08-01 21:59:26 +00001131static int img_convert(int argc, char **argv)
1132{
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001133 int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size,
1134 cluster_sectors, skip_create;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001135 int progress = 0, flags;
1136 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001137 BlockDriver *drv, *proto_drv;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001138 BlockDriverState **bs = NULL, *out_bs = NULL;
ths96b8f132007-12-17 01:35:20 +00001139 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
1140 uint64_t bs_sectors;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001141 uint8_t * buf = NULL;
bellardea2384d2004-08-01 21:59:26 +00001142 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +00001143 BlockDriverInfo bdi;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001144 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfa18953f2010-10-14 15:46:04 +02001145 QEMUOptionParameter *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001146 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001147 const char *snapshot_name = NULL;
Kevin Wolf1f710492012-10-12 14:29:18 +02001148 float local_progress = 0;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001149 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001150 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001151 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001152 QemuOpts *sn_opts = NULL;
bellardea2384d2004-08-01 21:59:26 +00001153
1154 fmt = NULL;
1155 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001156 cache = "unsafe";
thsf58c7b32008-06-05 21:53:49 +00001157 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001158 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001159 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001160 for(;;) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001161 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:qnl:");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001162 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001163 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001164 }
bellardea2384d2004-08-01 21:59:26 +00001165 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001166 case '?':
bellardea2384d2004-08-01 21:59:26 +00001167 case 'h':
1168 help();
1169 break;
1170 case 'f':
1171 fmt = optarg;
1172 break;
1173 case 'O':
1174 out_fmt = optarg;
1175 break;
thsf58c7b32008-06-05 21:53:49 +00001176 case 'B':
1177 out_baseimg = optarg;
1178 break;
bellardea2384d2004-08-01 21:59:26 +00001179 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001180 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001181 break;
1182 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001183 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001184 "encryption\' instead!");
1185 return 1;
thsec36ba12007-09-16 21:59:02 +00001186 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001187 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001188 "compat6\' instead!");
1189 return 1;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001190 case 'o':
1191 options = optarg;
1192 break;
edison51ef6722010-09-21 19:58:41 -07001193 case 's':
1194 snapshot_name = optarg;
1195 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001196 case 'l':
1197 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1198 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1199 if (!sn_opts) {
1200 error_report("Failed in parsing snapshot param '%s'",
1201 optarg);
1202 return 1;
1203 }
1204 } else {
1205 snapshot_name = optarg;
1206 }
1207 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001208 case 'S':
1209 {
1210 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001211 char *end;
1212 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1213 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001214 error_report("Invalid minimum zero buffer size for sparse output specified");
1215 return 1;
1216 }
1217
1218 min_sparse = sval / BDRV_SECTOR_SIZE;
1219 break;
1220 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001221 case 'p':
1222 progress = 1;
1223 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001224 case 't':
1225 cache = optarg;
1226 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001227 case 'q':
1228 quiet = true;
1229 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001230 case 'n':
1231 skip_create = 1;
1232 break;
bellardea2384d2004-08-01 21:59:26 +00001233 }
1234 }
ths3b46e622007-09-17 08:09:54 +00001235
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001236 if (quiet) {
1237 progress = 0;
1238 }
1239
balrog926c2d22007-10-31 01:11:44 +00001240 bs_n = argc - optind - 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001241 if (bs_n < 1) {
1242 help();
1243 }
balrog926c2d22007-10-31 01:11:44 +00001244
1245 out_filename = argv[argc - 1];
thsf58c7b32008-06-05 21:53:49 +00001246
Charles Arnoldfa170c12012-05-11 10:57:54 -06001247 /* Initialize before goto out */
1248 qemu_progress_init(progress, 2.0);
1249
Peter Maydellc8057f92012-08-02 13:45:54 +01001250 if (options && is_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001251 ret = print_block_option_help(out_filename, out_fmt);
1252 goto out;
1253 }
1254
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001255 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001256 error_report("-B makes no sense when concatenating multiple input "
1257 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001258 ret = -1;
1259 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001260 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001261
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001262 qemu_progress_print(0, 100);
1263
Anthony Liguori7267c092011-08-20 22:09:37 -05001264 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
balrog926c2d22007-10-31 01:11:44 +00001265
1266 total_sectors = 0;
1267 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001268 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
1269 quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001270 if (!bs[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001271 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001272 ret = -1;
1273 goto out;
1274 }
balrog926c2d22007-10-31 01:11:44 +00001275 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1276 total_sectors += bs_sectors;
1277 }
bellardea2384d2004-08-01 21:59:26 +00001278
Wenchao Xiaef806542013-12-04 17:10:57 +08001279 if (sn_opts) {
1280 ret = bdrv_snapshot_load_tmp(bs[0],
1281 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1282 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1283 &local_err);
1284 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001285 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001286 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001287 ret = -1;
1288 goto out;
1289 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001290
1291 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001292 }
1293 if (error_is_set(&local_err)) {
1294 error_report("Failed to load snapshot: %s",
1295 error_get_pretty(local_err));
1296 error_free(local_err);
1297 ret = -1;
1298 goto out;
edison51ef6722010-09-21 19:58:41 -07001299 }
1300
Kevin Wolfefa84d42009-05-18 16:42:12 +02001301 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001302 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001303 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001304 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001305 ret = -1;
1306 goto out;
1307 }
balrog926c2d22007-10-31 01:11:44 +00001308
Kevin Wolf98289622013-07-10 15:47:39 +02001309 proto_drv = bdrv_find_protocol(out_filename, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001310 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001311 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001312 ret = -1;
1313 goto out;
1314 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001315
1316 create_options = append_option_parameters(create_options,
1317 drv->create_options);
1318 create_options = append_option_parameters(create_options,
1319 proto_drv->create_options);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02001320
Kevin Wolfefa84d42009-05-18 16:42:12 +02001321 if (options) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001322 param = parse_option_parameters(options, create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001323 if (param == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001324 error_report("Invalid options for file format '%s'.", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001325 ret = -1;
1326 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001327 }
1328 } else {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001329 param = parse_option_parameters("", create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001330 }
1331
1332 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
Jes Sorenseneec77d92010-12-07 17:44:34 +01001333 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001334 if (ret < 0) {
1335 goto out;
1336 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001337
Kevin Wolfa18953f2010-10-14 15:46:04 +02001338 /* Get backing file name if -o backing_file was used */
1339 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
1340 if (out_baseimg_param) {
1341 out_baseimg = out_baseimg_param->value.s;
1342 }
1343
Kevin Wolfefa84d42009-05-18 16:42:12 +02001344 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01001345 if (compress) {
Kevin Wolfefa84d42009-05-18 16:42:12 +02001346 QEMUOptionParameter *encryption =
1347 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
Kevin Wolf41521fa2011-10-18 16:19:42 +02001348 QEMUOptionParameter *preallocation =
1349 get_option_parameter(param, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001350
1351 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001352 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001353 ret = -1;
1354 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001355 }
1356
1357 if (encryption && encryption->value.n) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001358 error_report("Compression and encryption not supported at "
1359 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001360 ret = -1;
1361 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001362 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02001363
1364 if (preallocation && preallocation->value.s
1365 && strcmp(preallocation->value.s, "off"))
1366 {
1367 error_report("Compression and preallocation not supported at "
1368 "the same time");
1369 ret = -1;
1370 goto out;
1371 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001372 }
1373
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001374 if (!skip_create) {
1375 /* Create the new image */
Max Reitzcc84d902013-09-06 17:14:26 +02001376 ret = bdrv_create(drv, out_filename, param, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001377 if (ret < 0) {
Max Reitzcc84d902013-09-06 17:14:26 +02001378 error_report("%s: error while converting %s: %s",
1379 out_filename, out_fmt, error_get_pretty(local_err));
1380 error_free(local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001381 goto out;
bellardea2384d2004-08-01 21:59:26 +00001382 }
1383 }
ths3b46e622007-09-17 08:09:54 +00001384
Peter Lieven5a37b602013-10-24 12:07:06 +02001385 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001386 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001387 if (ret < 0) {
1388 error_report("Invalid cache option: %s", cache);
1389 return -1;
1390 }
1391
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001392 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001393 if (!out_bs) {
1394 ret = -1;
1395 goto out;
1396 }
bellardea2384d2004-08-01 21:59:26 +00001397
balrog926c2d22007-10-31 01:11:44 +00001398 bs_i = 0;
1399 bs_offset = 0;
1400 bdrv_get_geometry(bs[0], &bs_sectors);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001401 buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001402
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001403 if (skip_create) {
1404 int64_t output_length = bdrv_getlength(out_bs);
1405 if (output_length < 0) {
1406 error_report("unable to get output image length: %s\n",
1407 strerror(-output_length));
1408 ret = -1;
1409 goto out;
1410 } else if (output_length < total_sectors << BDRV_SECTOR_BITS) {
1411 error_report("output file is smaller than input file");
1412 ret = -1;
1413 goto out;
1414 }
1415 }
1416
Jes Sorenseneec77d92010-12-07 17:44:34 +01001417 if (compress) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001418 ret = bdrv_get_info(out_bs, &bdi);
1419 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001420 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001421 goto out;
1422 }
bellardfaea38e2006-08-05 21:31:00 +00001423 cluster_size = bdi.cluster_size;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001424 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001425 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001426 ret = -1;
1427 goto out;
1428 }
bellardea2384d2004-08-01 21:59:26 +00001429 cluster_sectors = cluster_size >> 9;
1430 sector_num = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001431
1432 nb_sectors = total_sectors;
Kevin Wolf1f710492012-10-12 14:29:18 +02001433 if (nb_sectors != 0) {
1434 local_progress = (float)100 /
1435 (nb_sectors / MIN(nb_sectors, cluster_sectors));
1436 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001437
bellardea2384d2004-08-01 21:59:26 +00001438 for(;;) {
balrog926c2d22007-10-31 01:11:44 +00001439 int64_t bs_num;
1440 int remainder;
1441 uint8_t *buf2;
1442
bellardea2384d2004-08-01 21:59:26 +00001443 nb_sectors = total_sectors - sector_num;
1444 if (nb_sectors <= 0)
1445 break;
1446 if (nb_sectors >= cluster_sectors)
1447 n = cluster_sectors;
1448 else
1449 n = nb_sectors;
balrog926c2d22007-10-31 01:11:44 +00001450
1451 bs_num = sector_num - bs_offset;
1452 assert (bs_num >= 0);
1453 remainder = n;
1454 buf2 = buf;
1455 while (remainder > 0) {
1456 int nlow;
1457 while (bs_num == bs_sectors) {
1458 bs_i++;
1459 assert (bs_i < bs_n);
1460 bs_offset += bs_sectors;
1461 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1462 bs_num = 0;
Blue Swirl0bfcd592010-05-22 08:02:12 +00001463 /* printf("changing part: sector_num=%" PRId64 ", "
1464 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1465 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
balrog926c2d22007-10-31 01:11:44 +00001466 }
1467 assert (bs_num < bs_sectors);
1468
1469 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1470
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001471 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1472 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001473 error_report("error while reading sector %" PRId64 ": %s",
1474 bs_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001475 goto out;
1476 }
balrog926c2d22007-10-31 01:11:44 +00001477
1478 buf2 += nlow * 512;
1479 bs_num += nlow;
1480
1481 remainder -= nlow;
1482 }
1483 assert (remainder == 0);
1484
Stefan Hajnoczi54f106d2013-04-15 17:17:33 +02001485 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1486 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001487 if (ret != 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001488 error_report("error while compressing sector %" PRId64
1489 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001490 goto out;
1491 }
bellardea2384d2004-08-01 21:59:26 +00001492 }
1493 sector_num += n;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001494 qemu_progress_print(local_progress, 100);
bellardea2384d2004-08-01 21:59:26 +00001495 }
bellardfaea38e2006-08-05 21:31:00 +00001496 /* signal EOF to align */
1497 bdrv_write_compressed(out_bs, 0, NULL, 0);
bellardea2384d2004-08-01 21:59:26 +00001498 } else {
Peter Lieven11b66992013-10-24 12:07:05 +02001499 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02001500
Peter Lieven5a37b602013-10-24 12:07:06 +02001501 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1502 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1503 if (ret < 0) {
1504 goto out;
1505 }
1506 has_zero_init = 1;
1507 }
1508
thsf58c7b32008-06-05 21:53:49 +00001509 sector_num = 0; // total number of sectors converted so far
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001510 nb_sectors = total_sectors - sector_num;
Kevin Wolf1f710492012-10-12 14:29:18 +02001511 if (nb_sectors != 0) {
1512 local_progress = (float)100 /
1513 (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
1514 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001515
bellardea2384d2004-08-01 21:59:26 +00001516 for(;;) {
1517 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001518 if (nb_sectors <= 0) {
bellardea2384d2004-08-01 21:59:26 +00001519 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001520 }
1521 if (nb_sectors >= (IO_BUF_SIZE / 512)) {
bellardea2384d2004-08-01 21:59:26 +00001522 n = (IO_BUF_SIZE / 512);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001523 } else {
bellardea2384d2004-08-01 21:59:26 +00001524 n = nb_sectors;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001525 }
balrog926c2d22007-10-31 01:11:44 +00001526
1527 while (sector_num - bs_offset >= bs_sectors) {
1528 bs_i ++;
1529 assert (bs_i < bs_n);
1530 bs_offset += bs_sectors;
1531 bdrv_get_geometry(bs[bs_i], &bs_sectors);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001532 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1533 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
balrog926c2d22007-10-31 01:11:44 +00001534 sector_num, bs_i, bs_offset, bs_sectors); */
1535 }
1536
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001537 if (n > bs_offset + bs_sectors - sector_num) {
balrog926c2d22007-10-31 01:11:44 +00001538 n = bs_offset + bs_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001539 }
balrog926c2d22007-10-31 01:11:44 +00001540
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001541 /* If the output image is being created as a copy on write image,
1542 assume that sectors which are unallocated in the input image
1543 are present in both the output's and input's base images (no
1544 need to copy them). */
1545 if (out_baseimg) {
1546 ret = bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
1547 n, &n1);
1548 if (ret < 0) {
1549 error_report("error while reading metadata for sector "
1550 "%" PRId64 ": %s",
1551 sector_num - bs_offset, strerror(-ret));
1552 goto out;
aliguori93c65b42009-04-05 17:40:43 +00001553 }
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001554 if (!ret) {
1555 sector_num += n1;
1556 continue;
1557 }
1558 /* The next 'n1' sectors are allocated in the input image. Copy
1559 only those as they may be followed by unallocated sectors. */
1560 n = n1;
aliguori93c65b42009-04-05 17:40:43 +00001561 } else {
1562 n1 = n;
thsf58c7b32008-06-05 21:53:49 +00001563 }
1564
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001565 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1566 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001567 error_report("error while reading sector %" PRId64 ": %s",
1568 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001569 goto out;
1570 }
bellardea2384d2004-08-01 21:59:26 +00001571 /* NOTE: at the same time we convert, we do not write zero
1572 sectors to have a chance to compress the image. Ideally, we
1573 should add a specific call to have the info to go faster */
1574 buf1 = buf;
1575 while (n > 0) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02001576 if (!has_zero_init ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001577 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001578 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1579 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001580 error_report("error while writing sector %" PRId64
1581 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001582 goto out;
1583 }
bellardea2384d2004-08-01 21:59:26 +00001584 }
1585 sector_num += n1;
1586 n -= n1;
1587 buf1 += n1 * 512;
1588 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001589 qemu_progress_print(local_progress, 100);
bellardea2384d2004-08-01 21:59:26 +00001590 }
1591 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001592out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001593 qemu_progress_end();
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001594 free_option_parameters(create_options);
1595 free_option_parameters(param);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001596 qemu_vfree(buf);
Wenchao Xiaef806542013-12-04 17:10:57 +08001597 if (sn_opts) {
1598 qemu_opts_del(sn_opts);
1599 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001600 if (out_bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001601 bdrv_unref(out_bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001602 }
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001603 if (bs) {
1604 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1605 if (bs[bs_i]) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001606 bdrv_unref(bs[bs_i]);
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001607 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001608 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001609 g_free(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001610 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001611 if (ret) {
1612 return 1;
1613 }
bellardea2384d2004-08-01 21:59:26 +00001614 return 0;
1615}
1616
bellard57d1a2b2004-08-03 21:15:11 +00001617
bellardfaea38e2006-08-05 21:31:00 +00001618static void dump_snapshots(BlockDriverState *bs)
1619{
1620 QEMUSnapshotInfo *sn_tab, *sn;
1621 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00001622
1623 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1624 if (nb_sns <= 0)
1625 return;
1626 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08001627 bdrv_snapshot_dump(fprintf, stdout, NULL);
1628 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001629 for(i = 0; i < nb_sns; i++) {
1630 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08001631 bdrv_snapshot_dump(fprintf, stdout, sn);
1632 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001633 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001634 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001635}
1636
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001637static void dump_json_image_info_list(ImageInfoList *list)
1638{
1639 Error *errp = NULL;
1640 QString *str;
1641 QmpOutputVisitor *ov = qmp_output_visitor_new();
1642 QObject *obj;
1643 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1644 &list, NULL, &errp);
1645 obj = qmp_output_get_qobject(ov);
1646 str = qobject_to_json_pretty(obj);
1647 assert(str != NULL);
1648 printf("%s\n", qstring_get_str(str));
1649 qobject_decref(obj);
1650 qmp_output_visitor_cleanup(ov);
1651 QDECREF(str);
1652}
1653
Benoît Canetc054b3f2012-09-05 13:09:02 +02001654static void dump_json_image_info(ImageInfo *info)
1655{
1656 Error *errp = NULL;
1657 QString *str;
1658 QmpOutputVisitor *ov = qmp_output_visitor_new();
1659 QObject *obj;
1660 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1661 &info, NULL, &errp);
1662 obj = qmp_output_get_qobject(ov);
1663 str = qobject_to_json_pretty(obj);
1664 assert(str != NULL);
1665 printf("%s\n", qstring_get_str(str));
1666 qobject_decref(obj);
1667 qmp_output_visitor_cleanup(ov);
1668 QDECREF(str);
1669}
1670
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001671static void dump_human_image_info_list(ImageInfoList *list)
1672{
1673 ImageInfoList *elem;
1674 bool delim = false;
1675
1676 for (elem = list; elem; elem = elem->next) {
1677 if (delim) {
1678 printf("\n");
1679 }
1680 delim = true;
1681
Wenchao Xia5b917042013-05-25 11:09:45 +08001682 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001683 }
1684}
1685
1686static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1687{
1688 return strcmp(a, b) == 0;
1689}
1690
1691/**
1692 * Open an image file chain and return an ImageInfoList
1693 *
1694 * @filename: topmost image filename
1695 * @fmt: topmost image format (may be NULL to autodetect)
1696 * @chain: true - enumerate entire backing file chain
1697 * false - only topmost image file
1698 *
1699 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1700 * image file. If there was an error a message will have been printed to
1701 * stderr.
1702 */
1703static ImageInfoList *collect_image_info_list(const char *filename,
1704 const char *fmt,
1705 bool chain)
1706{
1707 ImageInfoList *head = NULL;
1708 ImageInfoList **last = &head;
1709 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08001710 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001711
1712 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1713
1714 while (filename) {
1715 BlockDriverState *bs;
1716 ImageInfo *info;
1717 ImageInfoList *elem;
1718
1719 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1720 error_report("Backing file '%s' creates an infinite loop.",
1721 filename);
1722 goto err;
1723 }
1724 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1725
1726 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001727 false, false);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001728 if (!bs) {
1729 goto err;
1730 }
1731
Wenchao Xia43526ec2013-06-06 12:27:58 +08001732 bdrv_query_image_info(bs, &info, &err);
1733 if (error_is_set(&err)) {
1734 error_report("%s", error_get_pretty(err));
1735 error_free(err);
1736 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08001737 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001738
1739 elem = g_new0(ImageInfoList, 1);
1740 elem->value = info;
1741 *last = elem;
1742 last = &elem->next;
1743
Fam Zheng4f6fd342013-08-23 09:14:47 +08001744 bdrv_unref(bs);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001745
1746 filename = fmt = NULL;
1747 if (chain) {
1748 if (info->has_full_backing_filename) {
1749 filename = info->full_backing_filename;
1750 } else if (info->has_backing_filename) {
1751 filename = info->backing_filename;
1752 }
1753 if (info->has_backing_filename_format) {
1754 fmt = info->backing_filename_format;
1755 }
1756 }
1757 }
1758 g_hash_table_destroy(filenames);
1759 return head;
1760
1761err:
1762 qapi_free_ImageInfoList(head);
1763 g_hash_table_destroy(filenames);
1764 return NULL;
1765}
1766
Benoît Canetc054b3f2012-09-05 13:09:02 +02001767static int img_info(int argc, char **argv)
1768{
1769 int c;
1770 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001771 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001772 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001773 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001774
bellardea2384d2004-08-01 21:59:26 +00001775 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001776 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001777 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001778 int option_index = 0;
1779 static const struct option long_options[] = {
1780 {"help", no_argument, 0, 'h'},
1781 {"format", required_argument, 0, 'f'},
1782 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001783 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001784 {0, 0, 0, 0}
1785 };
1786 c = getopt_long(argc, argv, "f:h",
1787 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001788 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001789 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001790 }
bellardea2384d2004-08-01 21:59:26 +00001791 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001792 case '?':
bellardea2384d2004-08-01 21:59:26 +00001793 case 'h':
1794 help();
1795 break;
1796 case 'f':
1797 fmt = optarg;
1798 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001799 case OPTION_OUTPUT:
1800 output = optarg;
1801 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001802 case OPTION_BACKING_CHAIN:
1803 chain = true;
1804 break;
bellardea2384d2004-08-01 21:59:26 +00001805 }
1806 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02001807 if (optind != argc - 1) {
bellardea2384d2004-08-01 21:59:26 +00001808 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001809 }
bellardea2384d2004-08-01 21:59:26 +00001810 filename = argv[optind++];
1811
Benoît Canetc054b3f2012-09-05 13:09:02 +02001812 if (output && !strcmp(output, "json")) {
1813 output_format = OFORMAT_JSON;
1814 } else if (output && !strcmp(output, "human")) {
1815 output_format = OFORMAT_HUMAN;
1816 } else if (output) {
1817 error_report("--output must be used with human or json as argument.");
1818 return 1;
1819 }
1820
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001821 list = collect_image_info_list(filename, fmt, chain);
1822 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001823 return 1;
1824 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001825
Benoît Canetc054b3f2012-09-05 13:09:02 +02001826 switch (output_format) {
1827 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001828 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001829 break;
1830 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001831 if (chain) {
1832 dump_json_image_info_list(list);
1833 } else {
1834 dump_json_image_info(list->value);
1835 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001836 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001837 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001838
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001839 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00001840 return 0;
1841}
1842
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001843
1844typedef struct MapEntry {
1845 int flags;
1846 int depth;
1847 int64_t start;
1848 int64_t length;
1849 int64_t offset;
1850 BlockDriverState *bs;
1851} MapEntry;
1852
1853static void dump_map_entry(OutputFormat output_format, MapEntry *e,
1854 MapEntry *next)
1855{
1856 switch (output_format) {
1857 case OFORMAT_HUMAN:
1858 if ((e->flags & BDRV_BLOCK_DATA) &&
1859 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
1860 error_report("File contains external, encrypted or compressed clusters.");
1861 exit(1);
1862 }
1863 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
1864 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
1865 e->start, e->length, e->offset, e->bs->filename);
1866 }
1867 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
1868 * Modify the flags here to allow more coalescing.
1869 */
1870 if (next &&
1871 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
1872 next->flags &= ~BDRV_BLOCK_DATA;
1873 next->flags |= BDRV_BLOCK_ZERO;
1874 }
1875 break;
1876 case OFORMAT_JSON:
1877 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
1878 " \"zero\": %s, \"data\": %s",
1879 (e->start == 0 ? "[" : ",\n"),
1880 e->start, e->length, e->depth,
1881 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
1882 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
1883 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02001884 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001885 }
1886 putchar('}');
1887
1888 if (!next) {
1889 printf("]\n");
1890 }
1891 break;
1892 }
1893}
1894
1895static int get_block_status(BlockDriverState *bs, int64_t sector_num,
1896 int nb_sectors, MapEntry *e)
1897{
1898 int64_t ret;
1899 int depth;
1900
1901 /* As an optimization, we could cache the current range of unallocated
1902 * clusters in each file of the chain, and avoid querying the same
1903 * range repeatedly.
1904 */
1905
1906 depth = 0;
1907 for (;;) {
1908 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
1909 if (ret < 0) {
1910 return ret;
1911 }
1912 assert(nb_sectors);
1913 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
1914 break;
1915 }
1916 bs = bs->backing_hd;
1917 if (bs == NULL) {
1918 ret = 0;
1919 break;
1920 }
1921
1922 depth++;
1923 }
1924
1925 e->start = sector_num * BDRV_SECTOR_SIZE;
1926 e->length = nb_sectors * BDRV_SECTOR_SIZE;
1927 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
1928 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
1929 e->depth = depth;
1930 e->bs = bs;
1931 return 0;
1932}
1933
1934static int img_map(int argc, char **argv)
1935{
1936 int c;
1937 OutputFormat output_format = OFORMAT_HUMAN;
1938 BlockDriverState *bs;
1939 const char *filename, *fmt, *output;
1940 int64_t length;
1941 MapEntry curr = { .length = 0 }, next;
1942 int ret = 0;
1943
1944 fmt = NULL;
1945 output = NULL;
1946 for (;;) {
1947 int option_index = 0;
1948 static const struct option long_options[] = {
1949 {"help", no_argument, 0, 'h'},
1950 {"format", required_argument, 0, 'f'},
1951 {"output", required_argument, 0, OPTION_OUTPUT},
1952 {0, 0, 0, 0}
1953 };
1954 c = getopt_long(argc, argv, "f:h",
1955 long_options, &option_index);
1956 if (c == -1) {
1957 break;
1958 }
1959 switch (c) {
1960 case '?':
1961 case 'h':
1962 help();
1963 break;
1964 case 'f':
1965 fmt = optarg;
1966 break;
1967 case OPTION_OUTPUT:
1968 output = optarg;
1969 break;
1970 }
1971 }
1972 if (optind >= argc) {
1973 help();
1974 }
1975 filename = argv[optind++];
1976
1977 if (output && !strcmp(output, "json")) {
1978 output_format = OFORMAT_JSON;
1979 } else if (output && !strcmp(output, "human")) {
1980 output_format = OFORMAT_HUMAN;
1981 } else if (output) {
1982 error_report("--output must be used with human or json as argument.");
1983 return 1;
1984 }
1985
1986 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS, true, false);
1987 if (!bs) {
1988 return 1;
1989 }
1990
1991 if (output_format == OFORMAT_HUMAN) {
1992 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
1993 }
1994
1995 length = bdrv_getlength(bs);
1996 while (curr.start + curr.length < length) {
1997 int64_t nsectors_left;
1998 int64_t sector_num;
1999 int n;
2000
2001 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2002
2003 /* Probe up to 1 GiB at a time. */
2004 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2005 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2006 ret = get_block_status(bs, sector_num, n, &next);
2007
2008 if (ret < 0) {
2009 error_report("Could not read file metadata: %s", strerror(-ret));
2010 goto out;
2011 }
2012
2013 if (curr.length != 0 && curr.flags == next.flags &&
2014 curr.depth == next.depth &&
2015 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2016 curr.offset + curr.length == next.offset)) {
2017 curr.length += next.length;
2018 continue;
2019 }
2020
2021 if (curr.length > 0) {
2022 dump_map_entry(output_format, &curr, &next);
2023 }
2024 curr = next;
2025 }
2026
2027 dump_map_entry(output_format, &curr, NULL);
2028
2029out:
2030 bdrv_unref(bs);
2031 return ret < 0;
2032}
2033
aliguorif7b4a942009-01-07 17:40:15 +00002034#define SNAPSHOT_LIST 1
2035#define SNAPSHOT_CREATE 2
2036#define SNAPSHOT_APPLY 3
2037#define SNAPSHOT_DELETE 4
2038
Stuart Brady153859b2009-06-07 00:42:17 +01002039static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002040{
2041 BlockDriverState *bs;
2042 QEMUSnapshotInfo sn;
2043 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002044 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002045 int action = 0;
2046 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002047 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002048 Error *err = NULL;
aliguorif7b4a942009-01-07 17:40:15 +00002049
Kevin Wolf710da702011-01-10 12:33:02 +01002050 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002051 /* Parse commandline parameters */
2052 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002053 c = getopt(argc, argv, "la:c:d:hq");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002054 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002055 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002056 }
aliguorif7b4a942009-01-07 17:40:15 +00002057 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002058 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002059 case 'h':
2060 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002061 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002062 case 'l':
2063 if (action) {
2064 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002065 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002066 }
2067 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002068 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002069 break;
2070 case 'a':
2071 if (action) {
2072 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002073 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002074 }
2075 action = SNAPSHOT_APPLY;
2076 snapshot_name = optarg;
2077 break;
2078 case 'c':
2079 if (action) {
2080 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002081 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002082 }
2083 action = SNAPSHOT_CREATE;
2084 snapshot_name = optarg;
2085 break;
2086 case 'd':
2087 if (action) {
2088 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002089 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002090 }
2091 action = SNAPSHOT_DELETE;
2092 snapshot_name = optarg;
2093 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002094 case 'q':
2095 quiet = true;
2096 break;
aliguorif7b4a942009-01-07 17:40:15 +00002097 }
2098 }
2099
Kevin Wolffc11eb22013-08-05 10:53:04 +02002100 if (optind != argc - 1) {
aliguorif7b4a942009-01-07 17:40:15 +00002101 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002102 }
aliguorif7b4a942009-01-07 17:40:15 +00002103 filename = argv[optind++];
2104
2105 /* Open the image */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002106 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002107 if (!bs) {
2108 return 1;
2109 }
aliguorif7b4a942009-01-07 17:40:15 +00002110
2111 /* Perform the requested action */
2112 switch(action) {
2113 case SNAPSHOT_LIST:
2114 dump_snapshots(bs);
2115 break;
2116
2117 case SNAPSHOT_CREATE:
2118 memset(&sn, 0, sizeof(sn));
2119 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2120
2121 qemu_gettimeofday(&tv);
2122 sn.date_sec = tv.tv_sec;
2123 sn.date_nsec = tv.tv_usec * 1000;
2124
2125 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002126 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002127 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002128 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002129 }
aliguorif7b4a942009-01-07 17:40:15 +00002130 break;
2131
2132 case SNAPSHOT_APPLY:
2133 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002134 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002135 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002136 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002137 }
aliguorif7b4a942009-01-07 17:40:15 +00002138 break;
2139
2140 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002141 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2142 if (error_is_set(&err)) {
2143 error_report("Could not delete snapshot '%s': (%s)",
2144 snapshot_name, error_get_pretty(err));
2145 error_free(err);
2146 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002147 }
aliguorif7b4a942009-01-07 17:40:15 +00002148 break;
2149 }
2150
2151 /* Cleanup */
Fam Zheng4f6fd342013-08-23 09:14:47 +08002152 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002153 if (ret) {
2154 return 1;
2155 }
Stuart Brady153859b2009-06-07 00:42:17 +01002156 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002157}
2158
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002159static int img_rebase(int argc, char **argv)
2160{
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002161 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01002162 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002163 char *filename;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002164 const char *fmt, *cache, *out_basefmt, *out_baseimg;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002165 int c, flags, ret;
2166 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002167 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002168 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002169 Error *local_err = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002170
2171 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002172 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002173 cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002174 out_baseimg = NULL;
2175 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002176 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002177 c = getopt(argc, argv, "uhf:F:b:pt:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002178 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002179 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002180 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002181 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002182 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002183 case 'h':
2184 help();
2185 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002186 case 'f':
2187 fmt = optarg;
2188 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002189 case 'F':
2190 out_basefmt = optarg;
2191 break;
2192 case 'b':
2193 out_baseimg = optarg;
2194 break;
2195 case 'u':
2196 unsafe = 1;
2197 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002198 case 'p':
2199 progress = 1;
2200 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002201 case 't':
2202 cache = optarg;
2203 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002204 case 'q':
2205 quiet = true;
2206 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002207 }
2208 }
2209
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002210 if (quiet) {
2211 progress = 0;
2212 }
2213
Kevin Wolffc11eb22013-08-05 10:53:04 +02002214 if ((optind != argc - 1) || (!unsafe && !out_baseimg)) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002215 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002216 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002217 filename = argv[optind++];
2218
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002219 qemu_progress_init(progress, 2.0);
2220 qemu_progress_print(0, 100);
2221
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002222 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01002223 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002224 if (ret < 0) {
2225 error_report("Invalid cache option: %s", cache);
2226 return -1;
2227 }
2228
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002229 /*
2230 * Open the images.
2231 *
2232 * Ignore the old backing file for unsafe rebase in case we want to correct
2233 * the reference to a renamed or moved backing file.
2234 */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002235 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002236 if (!bs) {
2237 return 1;
2238 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002239
2240 /* Find the right drivers for the backing files */
2241 old_backing_drv = NULL;
2242 new_backing_drv = NULL;
2243
2244 if (!unsafe && bs->backing_format[0] != '\0') {
2245 old_backing_drv = bdrv_find_format(bs->backing_format);
2246 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002247 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002248 ret = -1;
2249 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002250 }
2251 }
2252
2253 if (out_basefmt != NULL) {
2254 new_backing_drv = bdrv_find_format(out_basefmt);
2255 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002256 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002257 ret = -1;
2258 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002259 }
2260 }
2261
2262 /* For safe rebasing we need to compare old and new backing file */
2263 if (unsafe) {
2264 /* Make the compiler happy */
2265 bs_old_backing = NULL;
2266 bs_new_backing = NULL;
2267 } else {
2268 char backing_name[1024];
2269
2270 bs_old_backing = bdrv_new("old_backing");
2271 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002272 ret = bdrv_open(bs_old_backing, backing_name, NULL, BDRV_O_FLAGS,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002273 old_backing_drv, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002274 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002275 error_report("Could not open old backing file '%s': %s",
2276 backing_name, error_get_pretty(local_err));
2277 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002278 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002279 }
Alex Bligha6166732012-10-16 13:46:18 +01002280 if (out_baseimg[0]) {
2281 bs_new_backing = bdrv_new("new_backing");
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002282 ret = bdrv_open(bs_new_backing, out_baseimg, NULL, BDRV_O_FLAGS,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002283 new_backing_drv, &local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002284 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002285 error_report("Could not open new backing file '%s': %s",
2286 out_baseimg, error_get_pretty(local_err));
2287 error_free(local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002288 goto out;
2289 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002290 }
2291 }
2292
2293 /*
2294 * Check each unallocated cluster in the COW file. If it is unallocated,
2295 * accesses go to the backing file. We must therefore compare this cluster
2296 * in the old and new backing file, and if they differ we need to copy it
2297 * from the old backing file into the COW file.
2298 *
2299 * If qemu-img crashes during this step, no harm is done. The content of
2300 * the image is the same as the original one at any time.
2301 */
2302 if (!unsafe) {
2303 uint64_t num_sectors;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002304 uint64_t old_backing_num_sectors;
Alex Bligha6166732012-10-16 13:46:18 +01002305 uint64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002306 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02002307 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08002308 uint8_t * buf_old;
2309 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02002310 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08002311
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002312 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2313 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002314
2315 bdrv_get_geometry(bs, &num_sectors);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002316 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
Alex Bligha6166732012-10-16 13:46:18 +01002317 if (bs_new_backing) {
2318 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
2319 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002320
Kevin Wolf1f710492012-10-12 14:29:18 +02002321 if (num_sectors != 0) {
2322 local_progress = (float)100 /
2323 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2324 }
2325
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002326 for (sector = 0; sector < num_sectors; sector += n) {
2327
2328 /* How many sectors can we handle with the next read? */
2329 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2330 n = (IO_BUF_SIZE / 512);
2331 } else {
2332 n = num_sectors - sector;
2333 }
2334
2335 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02002336 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02002337 if (ret < 0) {
2338 error_report("error while reading image metadata: %s",
2339 strerror(-ret));
2340 goto out;
2341 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02002342 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002343 continue;
2344 }
2345
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002346 /*
2347 * Read old and new backing file and take into consideration that
2348 * backing files may be smaller than the COW image.
2349 */
2350 if (sector >= old_backing_num_sectors) {
2351 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2352 } else {
2353 if (sector + n > old_backing_num_sectors) {
2354 n = old_backing_num_sectors - sector;
2355 }
2356
2357 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2358 if (ret < 0) {
2359 error_report("error while reading from old backing file");
2360 goto out;
2361 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002362 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002363
Alex Bligha6166732012-10-16 13:46:18 +01002364 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002365 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2366 } else {
2367 if (sector + n > new_backing_num_sectors) {
2368 n = new_backing_num_sectors - sector;
2369 }
2370
2371 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2372 if (ret < 0) {
2373 error_report("error while reading from new backing file");
2374 goto out;
2375 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002376 }
2377
2378 /* If they differ, we need to write to the COW file */
2379 uint64_t written = 0;
2380
2381 while (written < n) {
2382 int pnum;
2383
2384 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01002385 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002386 {
2387 ret = bdrv_write(bs, sector + written,
2388 buf_old + written * 512, pnum);
2389 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002390 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002391 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002392 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002393 }
2394 }
2395
2396 written += pnum;
2397 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002398 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002399 }
TeLeMand6771bf2010-02-08 16:20:00 +08002400
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002401 qemu_vfree(buf_old);
2402 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002403 }
2404
2405 /*
2406 * Change the backing file. All clusters that are different from the old
2407 * backing file are overwritten in the COW file now, so the visible content
2408 * doesn't change when we switch the backing file.
2409 */
Alex Bligha6166732012-10-16 13:46:18 +01002410 if (out_baseimg && *out_baseimg) {
2411 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2412 } else {
2413 ret = bdrv_change_backing_file(bs, NULL, NULL);
2414 }
2415
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002416 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002417 error_report("Could not change the backing file to '%s': No "
2418 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002419 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002420 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002421 out_baseimg, strerror(-ret));
2422 }
2423
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002424 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002425 /*
2426 * TODO At this point it is possible to check if any clusters that are
2427 * allocated in the COW file are the same in the backing file. If so, they
2428 * could be dropped from the COW file. Don't do this before switching the
2429 * backing file, in case of a crash this would lead to corruption.
2430 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002431out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002432 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002433 /* Cleanup */
2434 if (!unsafe) {
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002435 if (bs_old_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002436 bdrv_unref(bs_old_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002437 }
2438 if (bs_new_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002439 bdrv_unref(bs_new_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002440 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002441 }
2442
Fam Zheng4f6fd342013-08-23 09:14:47 +08002443 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002444 if (ret) {
2445 return 1;
2446 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002447 return 0;
2448}
2449
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002450static int img_resize(int argc, char **argv)
2451{
2452 int c, ret, relative;
2453 const char *filename, *fmt, *size;
2454 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002455 bool quiet = false;
Jes Sorensen2a819982010-12-06 17:08:31 +01002456 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002457 QemuOpts *param;
2458 static QemuOptsList resize_options = {
2459 .name = "resize_options",
2460 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2461 .desc = {
2462 {
2463 .name = BLOCK_OPT_SIZE,
2464 .type = QEMU_OPT_SIZE,
2465 .help = "Virtual disk size"
2466 }, {
2467 /* end of list */
2468 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002469 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002470 };
2471
Kevin Wolfe80fec72011-04-29 10:58:12 +02002472 /* Remove size from argv manually so that negative numbers are not treated
2473 * as options by getopt. */
2474 if (argc < 3) {
2475 help();
2476 return 1;
2477 }
2478
2479 size = argv[--argc];
2480
2481 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002482 fmt = NULL;
2483 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002484 c = getopt(argc, argv, "f:hq");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002485 if (c == -1) {
2486 break;
2487 }
2488 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002489 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002490 case 'h':
2491 help();
2492 break;
2493 case 'f':
2494 fmt = optarg;
2495 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002496 case 'q':
2497 quiet = true;
2498 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002499 }
2500 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002501 if (optind != argc - 1) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002502 help();
2503 }
2504 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002505
2506 /* Choose grow, shrink, or absolute resize mode */
2507 switch (size[0]) {
2508 case '+':
2509 relative = 1;
2510 size++;
2511 break;
2512 case '-':
2513 relative = -1;
2514 size++;
2515 break;
2516 default:
2517 relative = 0;
2518 break;
2519 }
2520
2521 /* Parse size */
Dong Xu Wange478b442012-12-06 14:47:22 +08002522 param = qemu_opts_create_nofail(&resize_options);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002523 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002524 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002525 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002526 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002527 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002528 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002529 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2530 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002531
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002532 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002533 if (!bs) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002534 ret = -1;
2535 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002536 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002537
2538 if (relative) {
2539 total_size = bdrv_getlength(bs) + n * relative;
2540 } else {
2541 total_size = n;
2542 }
2543 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002544 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002545 ret = -1;
2546 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002547 }
2548
2549 ret = bdrv_truncate(bs, total_size);
2550 switch (ret) {
2551 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002552 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002553 break;
2554 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002555 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002556 break;
2557 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002558 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002559 break;
2560 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002561 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002562 break;
2563 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002564out:
Jes Sorensen2a819982010-12-06 17:08:31 +01002565 if (bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002566 bdrv_unref(bs);
Jes Sorensen2a819982010-12-06 17:08:31 +01002567 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002568 if (ret) {
2569 return 1;
2570 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002571 return 0;
2572}
2573
Max Reitz6f176b42013-09-03 10:09:50 +02002574static int img_amend(int argc, char **argv)
2575{
2576 int c, ret = 0;
2577 char *options = NULL;
2578 QEMUOptionParameter *create_options = NULL, *options_param = NULL;
2579 const char *fmt = NULL, *filename;
2580 bool quiet = false;
2581 BlockDriverState *bs = NULL;
2582
2583 for (;;) {
2584 c = getopt(argc, argv, "hqf:o:");
2585 if (c == -1) {
2586 break;
2587 }
2588
2589 switch (c) {
2590 case 'h':
2591 case '?':
2592 help();
2593 break;
2594 case 'o':
2595 options = optarg;
2596 break;
2597 case 'f':
2598 fmt = optarg;
2599 break;
2600 case 'q':
2601 quiet = true;
2602 break;
2603 }
2604 }
2605
2606 if (optind != argc - 1) {
2607 help();
2608 }
2609
2610 if (!options) {
2611 help();
2612 }
2613
2614 filename = argv[argc - 1];
2615
2616 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
2617 if (!bs) {
2618 error_report("Could not open image '%s'", filename);
2619 ret = -1;
2620 goto out;
2621 }
2622
2623 fmt = bs->drv->format_name;
2624
2625 if (is_help_option(options)) {
2626 ret = print_block_option_help(filename, fmt);
2627 goto out;
2628 }
2629
2630 create_options = append_option_parameters(create_options,
2631 bs->drv->create_options);
2632 options_param = parse_option_parameters(options, create_options,
2633 options_param);
2634 if (options_param == NULL) {
2635 error_report("Invalid options for file format '%s'", fmt);
2636 ret = -1;
2637 goto out;
2638 }
2639
2640 ret = bdrv_amend_options(bs, options_param);
2641 if (ret < 0) {
2642 error_report("Error while amending options: %s", strerror(-ret));
2643 goto out;
2644 }
2645
2646out:
2647 if (bs) {
2648 bdrv_unref(bs);
2649 }
2650 free_option_parameters(create_options);
2651 free_option_parameters(options_param);
2652 if (ret) {
2653 return 1;
2654 }
2655 return 0;
2656}
2657
Anthony Liguoric227f092009-10-01 16:12:16 -05002658static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002659#define DEF(option, callback, arg_string) \
2660 { option, callback },
2661#include "qemu-img-cmds.h"
2662#undef DEF
2663#undef GEN_DOCS
2664 { NULL, NULL, },
2665};
2666
bellardea2384d2004-08-01 21:59:26 +00002667int main(int argc, char **argv)
2668{
Anthony Liguoric227f092009-10-01 16:12:16 -05002669 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002670 const char *cmdname;
bellardea2384d2004-08-01 21:59:26 +00002671
MORITA Kazutaka526eda12013-07-23 17:30:11 +09002672#ifdef CONFIG_POSIX
2673 signal(SIGPIPE, SIG_IGN);
2674#endif
2675
Kevin Wolf53f76e52010-12-16 15:10:32 +01002676 error_set_progname(argv[0]);
2677
Paolo Bonzini2592c592012-11-03 18:10:17 +01002678 qemu_init_main_loop();
bellardea2384d2004-08-01 21:59:26 +00002679 bdrv_init();
2680 if (argc < 2)
2681 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002682 cmdname = argv[1];
aurel328f9b1572009-02-09 18:14:31 +00002683 argc--; argv++;
Stuart Brady153859b2009-06-07 00:42:17 +01002684
2685 /* find the command */
2686 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2687 if (!strcmp(cmdname, cmd->name)) {
2688 return cmd->handler(argc, argv);
2689 }
bellardea2384d2004-08-01 21:59:26 +00002690 }
Stuart Brady153859b2009-06-07 00:42:17 +01002691
2692 /* not found */
2693 help();
bellardea2384d2004-08-01 21:59:26 +00002694 return 0;
2695}