blob: 9d1b6b500a1a95ac20e1eb95556fc98ac22e2005 [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{
Peter Lieven13c28af2013-11-27 11:07:01 +01001133 int c, n, n1, bs_n, bs_i, compress, cluster_size,
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001134 cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001135 int64_t ret = 0;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001136 int progress = 0, flags;
1137 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001138 BlockDriver *drv, *proto_drv;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001139 BlockDriverState **bs = NULL, *out_bs = NULL;
Peter Lieven13c28af2013-11-27 11:07:01 +01001140 int64_t total_sectors, nb_sectors, sector_num, bs_offset,
1141 sector_num_next_status = 0;
ths96b8f132007-12-17 01:35:20 +00001142 uint64_t bs_sectors;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001143 uint8_t * buf = NULL;
bellardea2384d2004-08-01 21:59:26 +00001144 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +00001145 BlockDriverInfo bdi;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001146 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfa18953f2010-10-14 15:46:04 +02001147 QEMUOptionParameter *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001148 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001149 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001150 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001151 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001152 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001153 QemuOpts *sn_opts = NULL;
bellardea2384d2004-08-01 21:59:26 +00001154
1155 fmt = NULL;
1156 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001157 cache = "unsafe";
thsf58c7b32008-06-05 21:53:49 +00001158 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001159 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001160 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001161 for(;;) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001162 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:qnl:");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001163 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001164 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001165 }
bellardea2384d2004-08-01 21:59:26 +00001166 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001167 case '?':
bellardea2384d2004-08-01 21:59:26 +00001168 case 'h':
1169 help();
1170 break;
1171 case 'f':
1172 fmt = optarg;
1173 break;
1174 case 'O':
1175 out_fmt = optarg;
1176 break;
thsf58c7b32008-06-05 21:53:49 +00001177 case 'B':
1178 out_baseimg = optarg;
1179 break;
bellardea2384d2004-08-01 21:59:26 +00001180 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001181 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001182 break;
1183 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001184 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001185 "encryption\' instead!");
1186 return 1;
thsec36ba12007-09-16 21:59:02 +00001187 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001188 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001189 "compat6\' instead!");
1190 return 1;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001191 case 'o':
1192 options = optarg;
1193 break;
edison51ef6722010-09-21 19:58:41 -07001194 case 's':
1195 snapshot_name = optarg;
1196 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001197 case 'l':
1198 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1199 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1200 if (!sn_opts) {
1201 error_report("Failed in parsing snapshot param '%s'",
1202 optarg);
1203 return 1;
1204 }
1205 } else {
1206 snapshot_name = optarg;
1207 }
1208 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001209 case 'S':
1210 {
1211 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001212 char *end;
1213 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1214 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001215 error_report("Invalid minimum zero buffer size for sparse output specified");
1216 return 1;
1217 }
1218
1219 min_sparse = sval / BDRV_SECTOR_SIZE;
1220 break;
1221 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001222 case 'p':
1223 progress = 1;
1224 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001225 case 't':
1226 cache = optarg;
1227 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001228 case 'q':
1229 quiet = true;
1230 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001231 case 'n':
1232 skip_create = 1;
1233 break;
bellardea2384d2004-08-01 21:59:26 +00001234 }
1235 }
ths3b46e622007-09-17 08:09:54 +00001236
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001237 if (quiet) {
1238 progress = 0;
1239 }
1240
balrog926c2d22007-10-31 01:11:44 +00001241 bs_n = argc - optind - 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001242 if (bs_n < 1) {
1243 help();
1244 }
balrog926c2d22007-10-31 01:11:44 +00001245
1246 out_filename = argv[argc - 1];
thsf58c7b32008-06-05 21:53:49 +00001247
Charles Arnoldfa170c12012-05-11 10:57:54 -06001248 /* Initialize before goto out */
1249 qemu_progress_init(progress, 2.0);
1250
Peter Maydellc8057f92012-08-02 13:45:54 +01001251 if (options && is_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001252 ret = print_block_option_help(out_filename, out_fmt);
1253 goto out;
1254 }
1255
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001256 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001257 error_report("-B makes no sense when concatenating multiple input "
1258 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001259 ret = -1;
1260 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001261 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001262
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001263 qemu_progress_print(0, 100);
1264
Anthony Liguori7267c092011-08-20 22:09:37 -05001265 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
balrog926c2d22007-10-31 01:11:44 +00001266
1267 total_sectors = 0;
1268 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001269 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
1270 quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001271 if (!bs[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001272 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001273 ret = -1;
1274 goto out;
1275 }
balrog926c2d22007-10-31 01:11:44 +00001276 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1277 total_sectors += bs_sectors;
1278 }
bellardea2384d2004-08-01 21:59:26 +00001279
Wenchao Xiaef806542013-12-04 17:10:57 +08001280 if (sn_opts) {
1281 ret = bdrv_snapshot_load_tmp(bs[0],
1282 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1283 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1284 &local_err);
1285 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001286 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001287 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001288 ret = -1;
1289 goto out;
1290 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001291
1292 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001293 }
1294 if (error_is_set(&local_err)) {
1295 error_report("Failed to load snapshot: %s",
1296 error_get_pretty(local_err));
1297 error_free(local_err);
1298 ret = -1;
1299 goto out;
edison51ef6722010-09-21 19:58:41 -07001300 }
1301
Kevin Wolfefa84d42009-05-18 16:42:12 +02001302 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001303 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001304 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001305 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001306 ret = -1;
1307 goto out;
1308 }
balrog926c2d22007-10-31 01:11:44 +00001309
Kevin Wolf98289622013-07-10 15:47:39 +02001310 proto_drv = bdrv_find_protocol(out_filename, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001311 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001312 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001313 ret = -1;
1314 goto out;
1315 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001316
1317 create_options = append_option_parameters(create_options,
1318 drv->create_options);
1319 create_options = append_option_parameters(create_options,
1320 proto_drv->create_options);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02001321
Kevin Wolfefa84d42009-05-18 16:42:12 +02001322 if (options) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001323 param = parse_option_parameters(options, create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001324 if (param == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001325 error_report("Invalid options for file format '%s'.", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001326 ret = -1;
1327 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001328 }
1329 } else {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001330 param = parse_option_parameters("", create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001331 }
1332
1333 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
Jes Sorenseneec77d92010-12-07 17:44:34 +01001334 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001335 if (ret < 0) {
1336 goto out;
1337 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001338
Kevin Wolfa18953f2010-10-14 15:46:04 +02001339 /* Get backing file name if -o backing_file was used */
1340 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
1341 if (out_baseimg_param) {
1342 out_baseimg = out_baseimg_param->value.s;
1343 }
1344
Kevin Wolfefa84d42009-05-18 16:42:12 +02001345 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01001346 if (compress) {
Kevin Wolfefa84d42009-05-18 16:42:12 +02001347 QEMUOptionParameter *encryption =
1348 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
Kevin Wolf41521fa2011-10-18 16:19:42 +02001349 QEMUOptionParameter *preallocation =
1350 get_option_parameter(param, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001351
1352 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001353 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001354 ret = -1;
1355 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001356 }
1357
1358 if (encryption && encryption->value.n) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001359 error_report("Compression and encryption not supported at "
1360 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001361 ret = -1;
1362 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001363 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02001364
1365 if (preallocation && preallocation->value.s
1366 && strcmp(preallocation->value.s, "off"))
1367 {
1368 error_report("Compression and preallocation not supported at "
1369 "the same time");
1370 ret = -1;
1371 goto out;
1372 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001373 }
1374
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001375 if (!skip_create) {
1376 /* Create the new image */
Max Reitzcc84d902013-09-06 17:14:26 +02001377 ret = bdrv_create(drv, out_filename, param, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001378 if (ret < 0) {
Max Reitzcc84d902013-09-06 17:14:26 +02001379 error_report("%s: error while converting %s: %s",
1380 out_filename, out_fmt, error_get_pretty(local_err));
1381 error_free(local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001382 goto out;
bellardea2384d2004-08-01 21:59:26 +00001383 }
1384 }
ths3b46e622007-09-17 08:09:54 +00001385
Peter Lieven5a37b602013-10-24 12:07:06 +02001386 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001387 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001388 if (ret < 0) {
1389 error_report("Invalid cache option: %s", cache);
1390 return -1;
1391 }
1392
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001393 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001394 if (!out_bs) {
1395 ret = -1;
1396 goto out;
1397 }
bellardea2384d2004-08-01 21:59:26 +00001398
balrog926c2d22007-10-31 01:11:44 +00001399 bs_i = 0;
1400 bs_offset = 0;
1401 bdrv_get_geometry(bs[0], &bs_sectors);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001402 buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001403
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001404 if (skip_create) {
1405 int64_t output_length = bdrv_getlength(out_bs);
1406 if (output_length < 0) {
1407 error_report("unable to get output image length: %s\n",
1408 strerror(-output_length));
1409 ret = -1;
1410 goto out;
1411 } else if (output_length < total_sectors << BDRV_SECTOR_BITS) {
1412 error_report("output file is smaller than input file");
1413 ret = -1;
1414 goto out;
1415 }
1416 }
1417
Jes Sorenseneec77d92010-12-07 17:44:34 +01001418 if (compress) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001419 ret = bdrv_get_info(out_bs, &bdi);
1420 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001421 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001422 goto out;
1423 }
bellardfaea38e2006-08-05 21:31:00 +00001424 cluster_size = bdi.cluster_size;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001425 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001426 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001427 ret = -1;
1428 goto out;
1429 }
bellardea2384d2004-08-01 21:59:26 +00001430 cluster_sectors = cluster_size >> 9;
1431 sector_num = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001432
1433 nb_sectors = total_sectors;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001434
bellardea2384d2004-08-01 21:59:26 +00001435 for(;;) {
balrog926c2d22007-10-31 01:11:44 +00001436 int64_t bs_num;
1437 int remainder;
1438 uint8_t *buf2;
1439
bellardea2384d2004-08-01 21:59:26 +00001440 nb_sectors = total_sectors - sector_num;
1441 if (nb_sectors <= 0)
1442 break;
1443 if (nb_sectors >= cluster_sectors)
1444 n = cluster_sectors;
1445 else
1446 n = nb_sectors;
balrog926c2d22007-10-31 01:11:44 +00001447
1448 bs_num = sector_num - bs_offset;
1449 assert (bs_num >= 0);
1450 remainder = n;
1451 buf2 = buf;
1452 while (remainder > 0) {
1453 int nlow;
1454 while (bs_num == bs_sectors) {
1455 bs_i++;
1456 assert (bs_i < bs_n);
1457 bs_offset += bs_sectors;
1458 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1459 bs_num = 0;
Blue Swirl0bfcd592010-05-22 08:02:12 +00001460 /* printf("changing part: sector_num=%" PRId64 ", "
1461 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1462 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
balrog926c2d22007-10-31 01:11:44 +00001463 }
1464 assert (bs_num < bs_sectors);
1465
1466 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1467
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001468 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1469 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001470 error_report("error while reading sector %" PRId64 ": %s",
1471 bs_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001472 goto out;
1473 }
balrog926c2d22007-10-31 01:11:44 +00001474
1475 buf2 += nlow * 512;
1476 bs_num += nlow;
1477
1478 remainder -= nlow;
1479 }
1480 assert (remainder == 0);
1481
Stefan Hajnoczi54f106d2013-04-15 17:17:33 +02001482 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1483 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001484 if (ret != 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001485 error_report("error while compressing sector %" PRId64
1486 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001487 goto out;
1488 }
bellardea2384d2004-08-01 21:59:26 +00001489 }
1490 sector_num += n;
Peter Lieven13c28af2013-11-27 11:07:01 +01001491 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
bellardea2384d2004-08-01 21:59:26 +00001492 }
bellardfaea38e2006-08-05 21:31:00 +00001493 /* signal EOF to align */
1494 bdrv_write_compressed(out_bs, 0, NULL, 0);
bellardea2384d2004-08-01 21:59:26 +00001495 } else {
Peter Lieven11b66992013-10-24 12:07:05 +02001496 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02001497
Peter Lieven5a37b602013-10-24 12:07:06 +02001498 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1499 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1500 if (ret < 0) {
1501 goto out;
1502 }
1503 has_zero_init = 1;
1504 }
1505
thsf58c7b32008-06-05 21:53:49 +00001506 sector_num = 0; // total number of sectors converted so far
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001507 nb_sectors = total_sectors - sector_num;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001508
bellardea2384d2004-08-01 21:59:26 +00001509 for(;;) {
1510 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001511 if (nb_sectors <= 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001512 ret = 0;
bellardea2384d2004-08-01 21:59:26 +00001513 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001514 }
balrog926c2d22007-10-31 01:11:44 +00001515
1516 while (sector_num - bs_offset >= bs_sectors) {
1517 bs_i ++;
1518 assert (bs_i < bs_n);
1519 bs_offset += bs_sectors;
1520 bdrv_get_geometry(bs[bs_i], &bs_sectors);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001521 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1522 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
balrog926c2d22007-10-31 01:11:44 +00001523 sector_num, bs_i, bs_offset, bs_sectors); */
1524 }
1525
Peter Lieven13c28af2013-11-27 11:07:01 +01001526 if ((out_baseimg || has_zero_init) &&
1527 sector_num >= sector_num_next_status) {
1528 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1529 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1530 n, &n1);
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001531 if (ret < 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001532 error_report("error while reading block status of sector %"
1533 PRId64 ": %s", sector_num - bs_offset,
1534 strerror(-ret));
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001535 goto out;
aliguori93c65b42009-04-05 17:40:43 +00001536 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001537 /* If the output image is zero initialized, we are not working
1538 * on a shared base and the input is zero we can skip the next
1539 * n1 sectors */
1540 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001541 sector_num += n1;
1542 continue;
1543 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001544 /* If the output image is being created as a copy on write
1545 * image, assume that sectors which are unallocated in the
1546 * input image are present in both the output's and input's
1547 * base images (no need to copy them). */
1548 if (out_baseimg) {
1549 if (!(ret & BDRV_BLOCK_DATA)) {
1550 sector_num += n1;
1551 continue;
1552 }
1553 /* The next 'n1' sectors are allocated in the input image.
1554 * Copy only those as they may be followed by unallocated
1555 * sectors. */
1556 nb_sectors = n1;
1557 }
1558 /* avoid redundant callouts to get_block_status */
1559 sector_num_next_status = sector_num + n1;
thsf58c7b32008-06-05 21:53:49 +00001560 }
1561
Peter Lieven13c28af2013-11-27 11:07:01 +01001562 n = MIN(nb_sectors, IO_BUF_SIZE / 512);
1563 n = MIN(n, bs_sectors - (sector_num - bs_offset));
1564 n1 = n;
1565
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001566 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1567 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001568 error_report("error while reading sector %" PRId64 ": %s",
1569 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001570 goto out;
1571 }
bellardea2384d2004-08-01 21:59:26 +00001572 /* NOTE: at the same time we convert, we do not write zero
1573 sectors to have a chance to compress the image. Ideally, we
1574 should add a specific call to have the info to go faster */
1575 buf1 = buf;
1576 while (n > 0) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02001577 if (!has_zero_init ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001578 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001579 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1580 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001581 error_report("error while writing sector %" PRId64
1582 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001583 goto out;
1584 }
bellardea2384d2004-08-01 21:59:26 +00001585 }
1586 sector_num += n1;
1587 n -= n1;
1588 buf1 += n1 * 512;
1589 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001590 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
bellardea2384d2004-08-01 21:59:26 +00001591 }
1592 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001593out:
Peter Lieven13c28af2013-11-27 11:07:01 +01001594 if (!ret) {
1595 qemu_progress_print(100, 0);
1596 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001597 qemu_progress_end();
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001598 free_option_parameters(create_options);
1599 free_option_parameters(param);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001600 qemu_vfree(buf);
Wenchao Xiaef806542013-12-04 17:10:57 +08001601 if (sn_opts) {
1602 qemu_opts_del(sn_opts);
1603 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001604 if (out_bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001605 bdrv_unref(out_bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001606 }
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001607 if (bs) {
1608 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1609 if (bs[bs_i]) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001610 bdrv_unref(bs[bs_i]);
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001611 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001612 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001613 g_free(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001614 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001615 if (ret) {
1616 return 1;
1617 }
bellardea2384d2004-08-01 21:59:26 +00001618 return 0;
1619}
1620
bellard57d1a2b2004-08-03 21:15:11 +00001621
bellardfaea38e2006-08-05 21:31:00 +00001622static void dump_snapshots(BlockDriverState *bs)
1623{
1624 QEMUSnapshotInfo *sn_tab, *sn;
1625 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00001626
1627 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1628 if (nb_sns <= 0)
1629 return;
1630 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08001631 bdrv_snapshot_dump(fprintf, stdout, NULL);
1632 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001633 for(i = 0; i < nb_sns; i++) {
1634 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08001635 bdrv_snapshot_dump(fprintf, stdout, sn);
1636 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001637 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001638 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001639}
1640
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001641static void dump_json_image_info_list(ImageInfoList *list)
1642{
1643 Error *errp = NULL;
1644 QString *str;
1645 QmpOutputVisitor *ov = qmp_output_visitor_new();
1646 QObject *obj;
1647 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1648 &list, NULL, &errp);
1649 obj = qmp_output_get_qobject(ov);
1650 str = qobject_to_json_pretty(obj);
1651 assert(str != NULL);
1652 printf("%s\n", qstring_get_str(str));
1653 qobject_decref(obj);
1654 qmp_output_visitor_cleanup(ov);
1655 QDECREF(str);
1656}
1657
Benoît Canetc054b3f2012-09-05 13:09:02 +02001658static void dump_json_image_info(ImageInfo *info)
1659{
1660 Error *errp = NULL;
1661 QString *str;
1662 QmpOutputVisitor *ov = qmp_output_visitor_new();
1663 QObject *obj;
1664 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1665 &info, NULL, &errp);
1666 obj = qmp_output_get_qobject(ov);
1667 str = qobject_to_json_pretty(obj);
1668 assert(str != NULL);
1669 printf("%s\n", qstring_get_str(str));
1670 qobject_decref(obj);
1671 qmp_output_visitor_cleanup(ov);
1672 QDECREF(str);
1673}
1674
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001675static void dump_human_image_info_list(ImageInfoList *list)
1676{
1677 ImageInfoList *elem;
1678 bool delim = false;
1679
1680 for (elem = list; elem; elem = elem->next) {
1681 if (delim) {
1682 printf("\n");
1683 }
1684 delim = true;
1685
Wenchao Xia5b917042013-05-25 11:09:45 +08001686 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001687 }
1688}
1689
1690static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1691{
1692 return strcmp(a, b) == 0;
1693}
1694
1695/**
1696 * Open an image file chain and return an ImageInfoList
1697 *
1698 * @filename: topmost image filename
1699 * @fmt: topmost image format (may be NULL to autodetect)
1700 * @chain: true - enumerate entire backing file chain
1701 * false - only topmost image file
1702 *
1703 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1704 * image file. If there was an error a message will have been printed to
1705 * stderr.
1706 */
1707static ImageInfoList *collect_image_info_list(const char *filename,
1708 const char *fmt,
1709 bool chain)
1710{
1711 ImageInfoList *head = NULL;
1712 ImageInfoList **last = &head;
1713 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08001714 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001715
1716 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1717
1718 while (filename) {
1719 BlockDriverState *bs;
1720 ImageInfo *info;
1721 ImageInfoList *elem;
1722
1723 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1724 error_report("Backing file '%s' creates an infinite loop.",
1725 filename);
1726 goto err;
1727 }
1728 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1729
1730 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001731 false, false);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001732 if (!bs) {
1733 goto err;
1734 }
1735
Wenchao Xia43526ec2013-06-06 12:27:58 +08001736 bdrv_query_image_info(bs, &info, &err);
1737 if (error_is_set(&err)) {
1738 error_report("%s", error_get_pretty(err));
1739 error_free(err);
1740 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08001741 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001742
1743 elem = g_new0(ImageInfoList, 1);
1744 elem->value = info;
1745 *last = elem;
1746 last = &elem->next;
1747
Fam Zheng4f6fd342013-08-23 09:14:47 +08001748 bdrv_unref(bs);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001749
1750 filename = fmt = NULL;
1751 if (chain) {
1752 if (info->has_full_backing_filename) {
1753 filename = info->full_backing_filename;
1754 } else if (info->has_backing_filename) {
1755 filename = info->backing_filename;
1756 }
1757 if (info->has_backing_filename_format) {
1758 fmt = info->backing_filename_format;
1759 }
1760 }
1761 }
1762 g_hash_table_destroy(filenames);
1763 return head;
1764
1765err:
1766 qapi_free_ImageInfoList(head);
1767 g_hash_table_destroy(filenames);
1768 return NULL;
1769}
1770
Benoît Canetc054b3f2012-09-05 13:09:02 +02001771static int img_info(int argc, char **argv)
1772{
1773 int c;
1774 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001775 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001776 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001777 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001778
bellardea2384d2004-08-01 21:59:26 +00001779 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001780 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001781 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001782 int option_index = 0;
1783 static const struct option long_options[] = {
1784 {"help", no_argument, 0, 'h'},
1785 {"format", required_argument, 0, 'f'},
1786 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001787 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001788 {0, 0, 0, 0}
1789 };
1790 c = getopt_long(argc, argv, "f:h",
1791 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001792 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001793 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001794 }
bellardea2384d2004-08-01 21:59:26 +00001795 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001796 case '?':
bellardea2384d2004-08-01 21:59:26 +00001797 case 'h':
1798 help();
1799 break;
1800 case 'f':
1801 fmt = optarg;
1802 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001803 case OPTION_OUTPUT:
1804 output = optarg;
1805 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001806 case OPTION_BACKING_CHAIN:
1807 chain = true;
1808 break;
bellardea2384d2004-08-01 21:59:26 +00001809 }
1810 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02001811 if (optind != argc - 1) {
bellardea2384d2004-08-01 21:59:26 +00001812 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001813 }
bellardea2384d2004-08-01 21:59:26 +00001814 filename = argv[optind++];
1815
Benoît Canetc054b3f2012-09-05 13:09:02 +02001816 if (output && !strcmp(output, "json")) {
1817 output_format = OFORMAT_JSON;
1818 } else if (output && !strcmp(output, "human")) {
1819 output_format = OFORMAT_HUMAN;
1820 } else if (output) {
1821 error_report("--output must be used with human or json as argument.");
1822 return 1;
1823 }
1824
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001825 list = collect_image_info_list(filename, fmt, chain);
1826 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001827 return 1;
1828 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001829
Benoît Canetc054b3f2012-09-05 13:09:02 +02001830 switch (output_format) {
1831 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001832 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001833 break;
1834 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001835 if (chain) {
1836 dump_json_image_info_list(list);
1837 } else {
1838 dump_json_image_info(list->value);
1839 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001840 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001841 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001842
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001843 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00001844 return 0;
1845}
1846
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001847
1848typedef struct MapEntry {
1849 int flags;
1850 int depth;
1851 int64_t start;
1852 int64_t length;
1853 int64_t offset;
1854 BlockDriverState *bs;
1855} MapEntry;
1856
1857static void dump_map_entry(OutputFormat output_format, MapEntry *e,
1858 MapEntry *next)
1859{
1860 switch (output_format) {
1861 case OFORMAT_HUMAN:
1862 if ((e->flags & BDRV_BLOCK_DATA) &&
1863 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
1864 error_report("File contains external, encrypted or compressed clusters.");
1865 exit(1);
1866 }
1867 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
1868 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
1869 e->start, e->length, e->offset, e->bs->filename);
1870 }
1871 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
1872 * Modify the flags here to allow more coalescing.
1873 */
1874 if (next &&
1875 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
1876 next->flags &= ~BDRV_BLOCK_DATA;
1877 next->flags |= BDRV_BLOCK_ZERO;
1878 }
1879 break;
1880 case OFORMAT_JSON:
1881 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
1882 " \"zero\": %s, \"data\": %s",
1883 (e->start == 0 ? "[" : ",\n"),
1884 e->start, e->length, e->depth,
1885 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
1886 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
1887 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02001888 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001889 }
1890 putchar('}');
1891
1892 if (!next) {
1893 printf("]\n");
1894 }
1895 break;
1896 }
1897}
1898
1899static int get_block_status(BlockDriverState *bs, int64_t sector_num,
1900 int nb_sectors, MapEntry *e)
1901{
1902 int64_t ret;
1903 int depth;
1904
1905 /* As an optimization, we could cache the current range of unallocated
1906 * clusters in each file of the chain, and avoid querying the same
1907 * range repeatedly.
1908 */
1909
1910 depth = 0;
1911 for (;;) {
1912 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
1913 if (ret < 0) {
1914 return ret;
1915 }
1916 assert(nb_sectors);
1917 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
1918 break;
1919 }
1920 bs = bs->backing_hd;
1921 if (bs == NULL) {
1922 ret = 0;
1923 break;
1924 }
1925
1926 depth++;
1927 }
1928
1929 e->start = sector_num * BDRV_SECTOR_SIZE;
1930 e->length = nb_sectors * BDRV_SECTOR_SIZE;
1931 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
1932 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
1933 e->depth = depth;
1934 e->bs = bs;
1935 return 0;
1936}
1937
1938static int img_map(int argc, char **argv)
1939{
1940 int c;
1941 OutputFormat output_format = OFORMAT_HUMAN;
1942 BlockDriverState *bs;
1943 const char *filename, *fmt, *output;
1944 int64_t length;
1945 MapEntry curr = { .length = 0 }, next;
1946 int ret = 0;
1947
1948 fmt = NULL;
1949 output = NULL;
1950 for (;;) {
1951 int option_index = 0;
1952 static const struct option long_options[] = {
1953 {"help", no_argument, 0, 'h'},
1954 {"format", required_argument, 0, 'f'},
1955 {"output", required_argument, 0, OPTION_OUTPUT},
1956 {0, 0, 0, 0}
1957 };
1958 c = getopt_long(argc, argv, "f:h",
1959 long_options, &option_index);
1960 if (c == -1) {
1961 break;
1962 }
1963 switch (c) {
1964 case '?':
1965 case 'h':
1966 help();
1967 break;
1968 case 'f':
1969 fmt = optarg;
1970 break;
1971 case OPTION_OUTPUT:
1972 output = optarg;
1973 break;
1974 }
1975 }
1976 if (optind >= argc) {
1977 help();
1978 }
1979 filename = argv[optind++];
1980
1981 if (output && !strcmp(output, "json")) {
1982 output_format = OFORMAT_JSON;
1983 } else if (output && !strcmp(output, "human")) {
1984 output_format = OFORMAT_HUMAN;
1985 } else if (output) {
1986 error_report("--output must be used with human or json as argument.");
1987 return 1;
1988 }
1989
1990 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS, true, false);
1991 if (!bs) {
1992 return 1;
1993 }
1994
1995 if (output_format == OFORMAT_HUMAN) {
1996 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
1997 }
1998
1999 length = bdrv_getlength(bs);
2000 while (curr.start + curr.length < length) {
2001 int64_t nsectors_left;
2002 int64_t sector_num;
2003 int n;
2004
2005 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2006
2007 /* Probe up to 1 GiB at a time. */
2008 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2009 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2010 ret = get_block_status(bs, sector_num, n, &next);
2011
2012 if (ret < 0) {
2013 error_report("Could not read file metadata: %s", strerror(-ret));
2014 goto out;
2015 }
2016
2017 if (curr.length != 0 && curr.flags == next.flags &&
2018 curr.depth == next.depth &&
2019 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2020 curr.offset + curr.length == next.offset)) {
2021 curr.length += next.length;
2022 continue;
2023 }
2024
2025 if (curr.length > 0) {
2026 dump_map_entry(output_format, &curr, &next);
2027 }
2028 curr = next;
2029 }
2030
2031 dump_map_entry(output_format, &curr, NULL);
2032
2033out:
2034 bdrv_unref(bs);
2035 return ret < 0;
2036}
2037
aliguorif7b4a942009-01-07 17:40:15 +00002038#define SNAPSHOT_LIST 1
2039#define SNAPSHOT_CREATE 2
2040#define SNAPSHOT_APPLY 3
2041#define SNAPSHOT_DELETE 4
2042
Stuart Brady153859b2009-06-07 00:42:17 +01002043static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002044{
2045 BlockDriverState *bs;
2046 QEMUSnapshotInfo sn;
2047 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002048 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002049 int action = 0;
2050 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002051 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002052 Error *err = NULL;
aliguorif7b4a942009-01-07 17:40:15 +00002053
Kevin Wolf710da702011-01-10 12:33:02 +01002054 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002055 /* Parse commandline parameters */
2056 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002057 c = getopt(argc, argv, "la:c:d:hq");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002058 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002059 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002060 }
aliguorif7b4a942009-01-07 17:40:15 +00002061 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002062 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002063 case 'h':
2064 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002065 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002066 case 'l':
2067 if (action) {
2068 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002069 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002070 }
2071 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002072 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002073 break;
2074 case 'a':
2075 if (action) {
2076 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002077 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002078 }
2079 action = SNAPSHOT_APPLY;
2080 snapshot_name = optarg;
2081 break;
2082 case 'c':
2083 if (action) {
2084 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002085 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002086 }
2087 action = SNAPSHOT_CREATE;
2088 snapshot_name = optarg;
2089 break;
2090 case 'd':
2091 if (action) {
2092 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002093 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002094 }
2095 action = SNAPSHOT_DELETE;
2096 snapshot_name = optarg;
2097 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002098 case 'q':
2099 quiet = true;
2100 break;
aliguorif7b4a942009-01-07 17:40:15 +00002101 }
2102 }
2103
Kevin Wolffc11eb22013-08-05 10:53:04 +02002104 if (optind != argc - 1) {
aliguorif7b4a942009-01-07 17:40:15 +00002105 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002106 }
aliguorif7b4a942009-01-07 17:40:15 +00002107 filename = argv[optind++];
2108
2109 /* Open the image */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002110 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002111 if (!bs) {
2112 return 1;
2113 }
aliguorif7b4a942009-01-07 17:40:15 +00002114
2115 /* Perform the requested action */
2116 switch(action) {
2117 case SNAPSHOT_LIST:
2118 dump_snapshots(bs);
2119 break;
2120
2121 case SNAPSHOT_CREATE:
2122 memset(&sn, 0, sizeof(sn));
2123 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2124
2125 qemu_gettimeofday(&tv);
2126 sn.date_sec = tv.tv_sec;
2127 sn.date_nsec = tv.tv_usec * 1000;
2128
2129 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002130 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002131 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002132 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002133 }
aliguorif7b4a942009-01-07 17:40:15 +00002134 break;
2135
2136 case SNAPSHOT_APPLY:
2137 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002138 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002139 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002140 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002141 }
aliguorif7b4a942009-01-07 17:40:15 +00002142 break;
2143
2144 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002145 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2146 if (error_is_set(&err)) {
2147 error_report("Could not delete snapshot '%s': (%s)",
2148 snapshot_name, error_get_pretty(err));
2149 error_free(err);
2150 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002151 }
aliguorif7b4a942009-01-07 17:40:15 +00002152 break;
2153 }
2154
2155 /* Cleanup */
Fam Zheng4f6fd342013-08-23 09:14:47 +08002156 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002157 if (ret) {
2158 return 1;
2159 }
Stuart Brady153859b2009-06-07 00:42:17 +01002160 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002161}
2162
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002163static int img_rebase(int argc, char **argv)
2164{
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002165 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01002166 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002167 char *filename;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002168 const char *fmt, *cache, *out_basefmt, *out_baseimg;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002169 int c, flags, ret;
2170 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002171 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002172 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002173 Error *local_err = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002174
2175 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002176 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002177 cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002178 out_baseimg = NULL;
2179 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002180 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002181 c = getopt(argc, argv, "uhf:F:b:pt:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002182 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002183 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002184 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002185 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002186 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002187 case 'h':
2188 help();
2189 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002190 case 'f':
2191 fmt = optarg;
2192 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002193 case 'F':
2194 out_basefmt = optarg;
2195 break;
2196 case 'b':
2197 out_baseimg = optarg;
2198 break;
2199 case 'u':
2200 unsafe = 1;
2201 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002202 case 'p':
2203 progress = 1;
2204 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002205 case 't':
2206 cache = optarg;
2207 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002208 case 'q':
2209 quiet = true;
2210 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002211 }
2212 }
2213
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002214 if (quiet) {
2215 progress = 0;
2216 }
2217
Kevin Wolffc11eb22013-08-05 10:53:04 +02002218 if ((optind != argc - 1) || (!unsafe && !out_baseimg)) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002219 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002220 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002221 filename = argv[optind++];
2222
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002223 qemu_progress_init(progress, 2.0);
2224 qemu_progress_print(0, 100);
2225
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002226 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01002227 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002228 if (ret < 0) {
2229 error_report("Invalid cache option: %s", cache);
2230 return -1;
2231 }
2232
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002233 /*
2234 * Open the images.
2235 *
2236 * Ignore the old backing file for unsafe rebase in case we want to correct
2237 * the reference to a renamed or moved backing file.
2238 */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002239 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002240 if (!bs) {
2241 return 1;
2242 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002243
2244 /* Find the right drivers for the backing files */
2245 old_backing_drv = NULL;
2246 new_backing_drv = NULL;
2247
2248 if (!unsafe && bs->backing_format[0] != '\0') {
2249 old_backing_drv = bdrv_find_format(bs->backing_format);
2250 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002251 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002252 ret = -1;
2253 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002254 }
2255 }
2256
2257 if (out_basefmt != NULL) {
2258 new_backing_drv = bdrv_find_format(out_basefmt);
2259 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002260 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002261 ret = -1;
2262 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002263 }
2264 }
2265
2266 /* For safe rebasing we need to compare old and new backing file */
2267 if (unsafe) {
2268 /* Make the compiler happy */
2269 bs_old_backing = NULL;
2270 bs_new_backing = NULL;
2271 } else {
2272 char backing_name[1024];
2273
2274 bs_old_backing = bdrv_new("old_backing");
2275 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002276 ret = bdrv_open(bs_old_backing, backing_name, NULL, BDRV_O_FLAGS,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002277 old_backing_drv, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002278 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002279 error_report("Could not open old backing file '%s': %s",
2280 backing_name, error_get_pretty(local_err));
2281 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002282 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002283 }
Alex Bligha6166732012-10-16 13:46:18 +01002284 if (out_baseimg[0]) {
2285 bs_new_backing = bdrv_new("new_backing");
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002286 ret = bdrv_open(bs_new_backing, out_baseimg, NULL, BDRV_O_FLAGS,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002287 new_backing_drv, &local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002288 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002289 error_report("Could not open new backing file '%s': %s",
2290 out_baseimg, error_get_pretty(local_err));
2291 error_free(local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002292 goto out;
2293 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002294 }
2295 }
2296
2297 /*
2298 * Check each unallocated cluster in the COW file. If it is unallocated,
2299 * accesses go to the backing file. We must therefore compare this cluster
2300 * in the old and new backing file, and if they differ we need to copy it
2301 * from the old backing file into the COW file.
2302 *
2303 * If qemu-img crashes during this step, no harm is done. The content of
2304 * the image is the same as the original one at any time.
2305 */
2306 if (!unsafe) {
2307 uint64_t num_sectors;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002308 uint64_t old_backing_num_sectors;
Alex Bligha6166732012-10-16 13:46:18 +01002309 uint64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002310 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02002311 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08002312 uint8_t * buf_old;
2313 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02002314 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08002315
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002316 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2317 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002318
2319 bdrv_get_geometry(bs, &num_sectors);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002320 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
Alex Bligha6166732012-10-16 13:46:18 +01002321 if (bs_new_backing) {
2322 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
2323 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002324
Kevin Wolf1f710492012-10-12 14:29:18 +02002325 if (num_sectors != 0) {
2326 local_progress = (float)100 /
2327 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2328 }
2329
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002330 for (sector = 0; sector < num_sectors; sector += n) {
2331
2332 /* How many sectors can we handle with the next read? */
2333 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2334 n = (IO_BUF_SIZE / 512);
2335 } else {
2336 n = num_sectors - sector;
2337 }
2338
2339 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02002340 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02002341 if (ret < 0) {
2342 error_report("error while reading image metadata: %s",
2343 strerror(-ret));
2344 goto out;
2345 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02002346 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002347 continue;
2348 }
2349
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002350 /*
2351 * Read old and new backing file and take into consideration that
2352 * backing files may be smaller than the COW image.
2353 */
2354 if (sector >= old_backing_num_sectors) {
2355 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2356 } else {
2357 if (sector + n > old_backing_num_sectors) {
2358 n = old_backing_num_sectors - sector;
2359 }
2360
2361 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2362 if (ret < 0) {
2363 error_report("error while reading from old backing file");
2364 goto out;
2365 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002366 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002367
Alex Bligha6166732012-10-16 13:46:18 +01002368 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002369 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2370 } else {
2371 if (sector + n > new_backing_num_sectors) {
2372 n = new_backing_num_sectors - sector;
2373 }
2374
2375 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2376 if (ret < 0) {
2377 error_report("error while reading from new backing file");
2378 goto out;
2379 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002380 }
2381
2382 /* If they differ, we need to write to the COW file */
2383 uint64_t written = 0;
2384
2385 while (written < n) {
2386 int pnum;
2387
2388 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01002389 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002390 {
2391 ret = bdrv_write(bs, sector + written,
2392 buf_old + written * 512, pnum);
2393 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002394 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002395 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002396 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002397 }
2398 }
2399
2400 written += pnum;
2401 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002402 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002403 }
TeLeMand6771bf2010-02-08 16:20:00 +08002404
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002405 qemu_vfree(buf_old);
2406 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002407 }
2408
2409 /*
2410 * Change the backing file. All clusters that are different from the old
2411 * backing file are overwritten in the COW file now, so the visible content
2412 * doesn't change when we switch the backing file.
2413 */
Alex Bligha6166732012-10-16 13:46:18 +01002414 if (out_baseimg && *out_baseimg) {
2415 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2416 } else {
2417 ret = bdrv_change_backing_file(bs, NULL, NULL);
2418 }
2419
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002420 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002421 error_report("Could not change the backing file to '%s': No "
2422 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002423 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002424 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002425 out_baseimg, strerror(-ret));
2426 }
2427
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002428 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002429 /*
2430 * TODO At this point it is possible to check if any clusters that are
2431 * allocated in the COW file are the same in the backing file. If so, they
2432 * could be dropped from the COW file. Don't do this before switching the
2433 * backing file, in case of a crash this would lead to corruption.
2434 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002435out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002436 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002437 /* Cleanup */
2438 if (!unsafe) {
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002439 if (bs_old_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002440 bdrv_unref(bs_old_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002441 }
2442 if (bs_new_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002443 bdrv_unref(bs_new_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002444 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002445 }
2446
Fam Zheng4f6fd342013-08-23 09:14:47 +08002447 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002448 if (ret) {
2449 return 1;
2450 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002451 return 0;
2452}
2453
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002454static int img_resize(int argc, char **argv)
2455{
2456 int c, ret, relative;
2457 const char *filename, *fmt, *size;
2458 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002459 bool quiet = false;
Jes Sorensen2a819982010-12-06 17:08:31 +01002460 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002461 QemuOpts *param;
2462 static QemuOptsList resize_options = {
2463 .name = "resize_options",
2464 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2465 .desc = {
2466 {
2467 .name = BLOCK_OPT_SIZE,
2468 .type = QEMU_OPT_SIZE,
2469 .help = "Virtual disk size"
2470 }, {
2471 /* end of list */
2472 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002473 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002474 };
2475
Kevin Wolfe80fec72011-04-29 10:58:12 +02002476 /* Remove size from argv manually so that negative numbers are not treated
2477 * as options by getopt. */
2478 if (argc < 3) {
2479 help();
2480 return 1;
2481 }
2482
2483 size = argv[--argc];
2484
2485 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002486 fmt = NULL;
2487 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002488 c = getopt(argc, argv, "f:hq");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002489 if (c == -1) {
2490 break;
2491 }
2492 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002493 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002494 case 'h':
2495 help();
2496 break;
2497 case 'f':
2498 fmt = optarg;
2499 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002500 case 'q':
2501 quiet = true;
2502 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002503 }
2504 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002505 if (optind != argc - 1) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002506 help();
2507 }
2508 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002509
2510 /* Choose grow, shrink, or absolute resize mode */
2511 switch (size[0]) {
2512 case '+':
2513 relative = 1;
2514 size++;
2515 break;
2516 case '-':
2517 relative = -1;
2518 size++;
2519 break;
2520 default:
2521 relative = 0;
2522 break;
2523 }
2524
2525 /* Parse size */
Dong Xu Wange478b442012-12-06 14:47:22 +08002526 param = qemu_opts_create_nofail(&resize_options);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002527 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002528 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002529 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002530 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002531 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002532 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002533 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2534 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002535
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002536 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002537 if (!bs) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002538 ret = -1;
2539 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002540 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002541
2542 if (relative) {
2543 total_size = bdrv_getlength(bs) + n * relative;
2544 } else {
2545 total_size = n;
2546 }
2547 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002548 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002549 ret = -1;
2550 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002551 }
2552
2553 ret = bdrv_truncate(bs, total_size);
2554 switch (ret) {
2555 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002556 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002557 break;
2558 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002559 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002560 break;
2561 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002562 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002563 break;
2564 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002565 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002566 break;
2567 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002568out:
Jes Sorensen2a819982010-12-06 17:08:31 +01002569 if (bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002570 bdrv_unref(bs);
Jes Sorensen2a819982010-12-06 17:08:31 +01002571 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002572 if (ret) {
2573 return 1;
2574 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002575 return 0;
2576}
2577
Max Reitz6f176b42013-09-03 10:09:50 +02002578static int img_amend(int argc, char **argv)
2579{
2580 int c, ret = 0;
2581 char *options = NULL;
2582 QEMUOptionParameter *create_options = NULL, *options_param = NULL;
2583 const char *fmt = NULL, *filename;
2584 bool quiet = false;
2585 BlockDriverState *bs = NULL;
2586
2587 for (;;) {
2588 c = getopt(argc, argv, "hqf:o:");
2589 if (c == -1) {
2590 break;
2591 }
2592
2593 switch (c) {
2594 case 'h':
2595 case '?':
2596 help();
2597 break;
2598 case 'o':
2599 options = optarg;
2600 break;
2601 case 'f':
2602 fmt = optarg;
2603 break;
2604 case 'q':
2605 quiet = true;
2606 break;
2607 }
2608 }
2609
2610 if (optind != argc - 1) {
2611 help();
2612 }
2613
2614 if (!options) {
2615 help();
2616 }
2617
2618 filename = argv[argc - 1];
2619
2620 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
2621 if (!bs) {
2622 error_report("Could not open image '%s'", filename);
2623 ret = -1;
2624 goto out;
2625 }
2626
2627 fmt = bs->drv->format_name;
2628
2629 if (is_help_option(options)) {
2630 ret = print_block_option_help(filename, fmt);
2631 goto out;
2632 }
2633
2634 create_options = append_option_parameters(create_options,
2635 bs->drv->create_options);
2636 options_param = parse_option_parameters(options, create_options,
2637 options_param);
2638 if (options_param == NULL) {
2639 error_report("Invalid options for file format '%s'", fmt);
2640 ret = -1;
2641 goto out;
2642 }
2643
2644 ret = bdrv_amend_options(bs, options_param);
2645 if (ret < 0) {
2646 error_report("Error while amending options: %s", strerror(-ret));
2647 goto out;
2648 }
2649
2650out:
2651 if (bs) {
2652 bdrv_unref(bs);
2653 }
2654 free_option_parameters(create_options);
2655 free_option_parameters(options_param);
2656 if (ret) {
2657 return 1;
2658 }
2659 return 0;
2660}
2661
Anthony Liguoric227f092009-10-01 16:12:16 -05002662static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002663#define DEF(option, callback, arg_string) \
2664 { option, callback },
2665#include "qemu-img-cmds.h"
2666#undef DEF
2667#undef GEN_DOCS
2668 { NULL, NULL, },
2669};
2670
bellardea2384d2004-08-01 21:59:26 +00002671int main(int argc, char **argv)
2672{
Anthony Liguoric227f092009-10-01 16:12:16 -05002673 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002674 const char *cmdname;
bellardea2384d2004-08-01 21:59:26 +00002675
MORITA Kazutaka526eda12013-07-23 17:30:11 +09002676#ifdef CONFIG_POSIX
2677 signal(SIGPIPE, SIG_IGN);
2678#endif
2679
Kevin Wolf53f76e52010-12-16 15:10:32 +01002680 error_set_progname(argv[0]);
2681
Paolo Bonzini2592c592012-11-03 18:10:17 +01002682 qemu_init_main_loop();
bellardea2384d2004-08-01 21:59:26 +00002683 bdrv_init();
2684 if (argc < 2)
2685 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002686 cmdname = argv[1];
aurel328f9b1572009-02-09 18:14:31 +00002687 argc--; argv++;
Stuart Brady153859b2009-06-07 00:42:17 +01002688
2689 /* find the command */
2690 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2691 if (!strcmp(cmdname, cmd->name)) {
2692 return cmd->handler(argc, argv);
2693 }
bellardea2384d2004-08-01 21:59:26 +00002694 }
Stuart Brady153859b2009-06-07 00:42:17 +01002695
2696 /* not found */
2697 help();
bellardea2384d2004-08-01 21:59:26 +00002698 return 0;
2699}