blob: 59b101347c1f2ea26a3511554231a6d915e5571d [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"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200113 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100114 " '-n' skips the target volume creation (useful if the volume is created\n"
115 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300116 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200117 "Parameters to check subcommand:\n"
118 " '-r' tries to repair any inconsistencies that are found during the check.\n"
119 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
120 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200121 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200122 "\n"
malc3f020d72010-02-08 12:04:56 +0300123 "Parameters to snapshot subcommand:\n"
124 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
125 " '-a' applies a snapshot (revert disk to saved state)\n"
126 " '-c' creates a snapshot\n"
127 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100128 " '-l' lists all snapshots in the given image\n"
129 "\n"
130 "Parameters to compare subcommand:\n"
131 " '-f' first image format\n"
132 " '-F' second image format\n"
133 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100134
135 printf("%s\nSupported formats:", help_msg);
bellardea2384d2004-08-01 21:59:26 +0000136 bdrv_iterate_format(format_print, NULL);
137 printf("\n");
138 exit(1);
139}
140
Stefan Weil7c30f652013-06-16 17:01:05 +0200141static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100142{
143 int ret = 0;
144 if (!quiet) {
145 va_list args;
146 va_start(args, fmt);
147 ret = vprintf(fmt, args);
148 va_end(args);
149 }
150 return ret;
151}
152
bellardea2384d2004-08-01 21:59:26 +0000153#if defined(WIN32)
154/* XXX: put correct support for win32 */
155static int read_password(char *buf, int buf_size)
156{
157 int c, i;
158 printf("Password: ");
159 fflush(stdout);
160 i = 0;
161 for(;;) {
162 c = getchar();
163 if (c == '\n')
164 break;
165 if (i < (buf_size - 1))
166 buf[i++] = c;
167 }
168 buf[i] = '\0';
169 return 0;
170}
171
172#else
173
174#include <termios.h>
175
176static struct termios oldtty;
177
178static void term_exit(void)
179{
180 tcsetattr (0, TCSANOW, &oldtty);
181}
182
183static void term_init(void)
184{
185 struct termios tty;
186
187 tcgetattr (0, &tty);
188 oldtty = tty;
189
190 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
191 |INLCR|IGNCR|ICRNL|IXON);
192 tty.c_oflag |= OPOST;
193 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
194 tty.c_cflag &= ~(CSIZE|PARENB);
195 tty.c_cflag |= CS8;
196 tty.c_cc[VMIN] = 1;
197 tty.c_cc[VTIME] = 0;
ths3b46e622007-09-17 08:09:54 +0000198
bellardea2384d2004-08-01 21:59:26 +0000199 tcsetattr (0, TCSANOW, &tty);
200
201 atexit(term_exit);
202}
203
pbrook3f379ab2007-11-11 03:33:13 +0000204static int read_password(char *buf, int buf_size)
bellardea2384d2004-08-01 21:59:26 +0000205{
206 uint8_t ch;
207 int i, ret;
208
209 printf("password: ");
210 fflush(stdout);
211 term_init();
212 i = 0;
213 for(;;) {
214 ret = read(0, &ch, 1);
215 if (ret == -1) {
216 if (errno == EAGAIN || errno == EINTR) {
217 continue;
218 } else {
219 ret = -1;
220 break;
221 }
222 } else if (ret == 0) {
223 ret = -1;
224 break;
225 } else {
226 if (ch == '\r') {
227 ret = 0;
228 break;
229 }
230 if (i < (buf_size - 1))
231 buf[i++] = ch;
232 }
233 }
234 term_exit();
235 buf[i] = '\0';
236 printf("\n");
237 return ret;
238}
239#endif
240
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100241static int print_block_option_help(const char *filename, const char *fmt)
242{
243 BlockDriver *drv, *proto_drv;
244 QEMUOptionParameter *create_options = NULL;
245
246 /* Find driver and parse its options */
247 drv = bdrv_find_format(fmt);
248 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100249 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100250 return 1;
251 }
252
Kevin Wolf98289622013-07-10 15:47:39 +0200253 proto_drv = bdrv_find_protocol(filename, true);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100254 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100255 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100256 return 1;
257 }
258
259 create_options = append_option_parameters(create_options,
260 drv->create_options);
261 create_options = append_option_parameters(create_options,
262 proto_drv->create_options);
263 print_option_help(create_options);
264 free_option_parameters(create_options);
265 return 0;
266}
267
bellard75c23802004-08-27 21:28:58 +0000268static BlockDriverState *bdrv_new_open(const char *filename,
Sheng Yang9bc378c2010-01-29 10:15:06 +0800269 const char *fmt,
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100270 int flags,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100271 bool require_io,
272 bool quiet)
bellard75c23802004-08-27 21:28:58 +0000273{
274 BlockDriverState *bs;
275 BlockDriver *drv;
276 char password[256];
Max Reitz34b5d2c2013-09-05 14:45:29 +0200277 Error *local_err = NULL;
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100278 int ret;
bellard75c23802004-08-27 21:28:58 +0000279
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100280 bs = bdrv_new("image");
Kevin Wolfad717132010-12-16 15:37:41 +0100281
bellard75c23802004-08-27 21:28:58 +0000282 if (fmt) {
283 drv = bdrv_find_format(fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900284 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100285 error_report("Unknown file format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900286 goto fail;
287 }
bellard75c23802004-08-27 21:28:58 +0000288 } else {
289 drv = NULL;
290 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100291
Max Reitzf67503e2014-02-18 18:33:05 +0100292 ret = bdrv_open(&bs, filename, NULL, flags, drv, &local_err);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100293 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200294 error_report("Could not open '%s': %s", filename,
295 error_get_pretty(local_err));
296 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900297 goto fail;
bellard75c23802004-08-27 21:28:58 +0000298 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100299
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100300 if (bdrv_is_encrypted(bs) && require_io) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100301 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900302 if (read_password(password, sizeof(password)) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100303 error_report("No password given");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900304 goto fail;
305 }
306 if (bdrv_set_key(bs, password) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100307 error_report("invalid password");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900308 goto fail;
309 }
bellard75c23802004-08-27 21:28:58 +0000310 }
311 return bs;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900312fail:
Max Reitzf67503e2014-02-18 18:33:05 +0100313 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900314 return NULL;
bellard75c23802004-08-27 21:28:58 +0000315}
316
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900317static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100318 const char *base_filename,
319 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200320{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200321 if (base_filename) {
322 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100323 error_report("Backing file not supported for file format '%s'",
324 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900325 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200326 }
327 }
328 if (base_fmt) {
329 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100330 error_report("Backing file format not supported for file "
331 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900332 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200333 }
334 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900335 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200336}
337
bellardea2384d2004-08-01 21:59:26 +0000338static int img_create(int argc, char **argv)
339{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200340 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100341 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000342 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000343 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000344 const char *filename;
345 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200346 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200347 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100348 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000349
bellardea2384d2004-08-01 21:59:26 +0000350 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100351 c = getopt(argc, argv, "F:b:f:he6o:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100352 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000353 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100354 }
bellardea2384d2004-08-01 21:59:26 +0000355 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100356 case '?':
bellardea2384d2004-08-01 21:59:26 +0000357 case 'h':
358 help();
359 break;
aliguori9230eaf2009-03-28 17:55:19 +0000360 case 'F':
361 base_fmt = optarg;
362 break;
bellardea2384d2004-08-01 21:59:26 +0000363 case 'b':
364 base_filename = optarg;
365 break;
366 case 'f':
367 fmt = optarg;
368 break;
369 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200370 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100371 "encryption\' instead!");
372 return 1;
thsd8871c52007-10-24 16:11:42 +0000373 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200374 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100375 "compat6\' instead!");
376 return 1;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200377 case 'o':
378 options = optarg;
379 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100380 case 'q':
381 quiet = true;
382 break;
bellardea2384d2004-08-01 21:59:26 +0000383 }
384 }
aliguori9230eaf2009-03-28 17:55:19 +0000385
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900386 /* Get the filename */
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100387 if (optind >= argc) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900388 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100389 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900390 filename = argv[optind++];
391
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100392 /* Get image size, if specified */
393 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100394 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100395 char *end;
396 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
397 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800398 if (sval == -ERANGE) {
399 error_report("Image size must be less than 8 EiB!");
400 } else {
401 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200402 "G, T, P or E suffixes for ");
403 error_report("kilobytes, megabytes, gigabytes, terabytes, "
404 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800405 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200406 return 1;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100407 }
408 img_size = (uint64_t)sval;
409 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200410 if (optind != argc) {
411 help();
412 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100413
Peter Maydellc8057f92012-08-02 13:45:54 +0100414 if (options && is_help_option(options)) {
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200415 return print_block_option_help(filename, fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100416 }
417
Luiz Capitulino9b375252012-11-30 10:52:05 -0200418 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100419 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100420 if (local_err) {
Max Reitzb70d8c22013-09-06 16:51:03 +0200421 error_report("%s: %s", filename, error_get_pretty(local_err));
Luiz Capitulino9b375252012-11-30 10:52:05 -0200422 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900423 return 1;
424 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200425
bellardea2384d2004-08-01 21:59:26 +0000426 return 0;
427}
428
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100429static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500430{
431 Error *errp = NULL;
432 QString *str;
433 QmpOutputVisitor *ov = qmp_output_visitor_new();
434 QObject *obj;
435 visit_type_ImageCheck(qmp_output_get_visitor(ov),
436 &check, NULL, &errp);
437 obj = qmp_output_get_qobject(ov);
438 str = qobject_to_json_pretty(obj);
439 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100440 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500441 qobject_decref(obj);
442 qmp_output_visitor_cleanup(ov);
443 QDECREF(str);
444}
445
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100446static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500447{
448 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100449 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500450 } else {
451 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100452 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
453 "Data may be corrupted, or further writes to the image "
454 "may corrupt it.\n",
455 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500456 }
457
458 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100459 qprintf(quiet,
460 "\n%" PRId64 " leaked clusters were found on the image.\n"
461 "This means waste of disk space, but no harm to data.\n",
462 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500463 }
464
465 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100466 qprintf(quiet,
467 "\n%" PRId64
468 " internal errors have occurred during the check.\n",
469 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500470 }
471 }
472
473 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100474 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
475 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
476 check->allocated_clusters, check->total_clusters,
477 check->allocated_clusters * 100.0 / check->total_clusters,
478 check->fragmented_clusters * 100.0 / check->allocated_clusters,
479 check->compressed_clusters * 100.0 /
480 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500481 }
482
483 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100484 qprintf(quiet,
485 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500486 }
487}
488
489static int collect_image_check(BlockDriverState *bs,
490 ImageCheck *check,
491 const char *filename,
492 const char *fmt,
493 int fix)
494{
495 int ret;
496 BdrvCheckResult result;
497
498 ret = bdrv_check(bs, &result, fix);
499 if (ret < 0) {
500 return ret;
501 }
502
503 check->filename = g_strdup(filename);
504 check->format = g_strdup(bdrv_get_format_name(bs));
505 check->check_errors = result.check_errors;
506 check->corruptions = result.corruptions;
507 check->has_corruptions = result.corruptions != 0;
508 check->leaks = result.leaks;
509 check->has_leaks = result.leaks != 0;
510 check->corruptions_fixed = result.corruptions_fixed;
511 check->has_corruptions_fixed = result.corruptions != 0;
512 check->leaks_fixed = result.leaks_fixed;
513 check->has_leaks_fixed = result.leaks != 0;
514 check->image_end_offset = result.image_end_offset;
515 check->has_image_end_offset = result.image_end_offset != 0;
516 check->total_clusters = result.bfi.total_clusters;
517 check->has_total_clusters = result.bfi.total_clusters != 0;
518 check->allocated_clusters = result.bfi.allocated_clusters;
519 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
520 check->fragmented_clusters = result.bfi.fragmented_clusters;
521 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100522 check->compressed_clusters = result.bfi.compressed_clusters;
523 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500524
525 return 0;
526}
527
Kevin Wolfe076f332010-06-29 11:43:13 +0200528/*
529 * Checks an image for consistency. Exit codes:
530 *
531 * 0 - Check completed, image is good
532 * 1 - Check not completed because of internal errors
533 * 2 - Check completed, image is corrupted
534 * 3 - Check completed, image has leaked clusters, but is good otherwise
535 */
aliguori15859692009-04-21 23:11:53 +0000536static int img_check(int argc, char **argv)
537{
538 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500539 OutputFormat output_format = OFORMAT_HUMAN;
540 const char *filename, *fmt, *output;
aliguori15859692009-04-21 23:11:53 +0000541 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200542 int fix = 0;
Stefan Hajnoczi058f8f12012-08-09 13:05:56 +0100543 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500544 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100545 bool quiet = false;
aliguori15859692009-04-21 23:11:53 +0000546
547 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500548 output = NULL;
aliguori15859692009-04-21 23:11:53 +0000549 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500550 int option_index = 0;
551 static const struct option long_options[] = {
552 {"help", no_argument, 0, 'h'},
553 {"format", required_argument, 0, 'f'},
554 {"repair", no_argument, 0, 'r'},
555 {"output", required_argument, 0, OPTION_OUTPUT},
556 {0, 0, 0, 0}
557 };
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100558 c = getopt_long(argc, argv, "f:hr:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500559 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100560 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000561 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100562 }
aliguori15859692009-04-21 23:11:53 +0000563 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100564 case '?':
aliguori15859692009-04-21 23:11:53 +0000565 case 'h':
566 help();
567 break;
568 case 'f':
569 fmt = optarg;
570 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200571 case 'r':
572 flags |= BDRV_O_RDWR;
573
574 if (!strcmp(optarg, "leaks")) {
575 fix = BDRV_FIX_LEAKS;
576 } else if (!strcmp(optarg, "all")) {
577 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
578 } else {
579 help();
580 }
581 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500582 case OPTION_OUTPUT:
583 output = optarg;
584 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100585 case 'q':
586 quiet = true;
587 break;
aliguori15859692009-04-21 23:11:53 +0000588 }
589 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200590 if (optind != argc - 1) {
aliguori15859692009-04-21 23:11:53 +0000591 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100592 }
aliguori15859692009-04-21 23:11:53 +0000593 filename = argv[optind++];
594
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500595 if (output && !strcmp(output, "json")) {
596 output_format = OFORMAT_JSON;
597 } else if (output && !strcmp(output, "human")) {
598 output_format = OFORMAT_HUMAN;
599 } else if (output) {
600 error_report("--output must be used with human or json as argument.");
601 return 1;
602 }
603
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100604 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900605 if (!bs) {
606 return 1;
607 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608
609 check = g_new0(ImageCheck, 1);
610 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200611
612 if (ret == -ENOTSUP) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500613 if (output_format == OFORMAT_HUMAN) {
614 error_report("This image format does not support checks");
615 }
Peter Lievenfefddf92013-10-24 08:53:34 +0200616 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500617 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200618 }
619
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500620 if (check->corruptions_fixed || check->leaks_fixed) {
621 int corruptions_fixed, leaks_fixed;
622
623 leaks_fixed = check->leaks_fixed;
624 corruptions_fixed = check->corruptions_fixed;
625
626 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100627 qprintf(quiet,
628 "The following inconsistencies were found and repaired:\n\n"
629 " %" PRId64 " leaked clusters\n"
630 " %" PRId64 " corruptions\n\n"
631 "Double checking the fixed image now...\n",
632 check->leaks_fixed,
633 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500634 }
635
636 ret = collect_image_check(bs, check, filename, fmt, 0);
637
638 check->leaks_fixed = leaks_fixed;
639 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200640 }
641
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500642 switch (output_format) {
643 case OFORMAT_HUMAN:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100644 dump_human_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500645 break;
646 case OFORMAT_JSON:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100647 dump_json_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500648 break;
649 }
650
651 if (ret || check->check_errors) {
652 ret = 1;
653 goto fail;
654 }
655
656 if (check->corruptions) {
657 ret = 2;
658 } else if (check->leaks) {
659 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200660 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500661 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000662 }
663
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500664fail:
665 qapi_free_ImageCheck(check);
Fam Zheng4f6fd342013-08-23 09:14:47 +0800666 bdrv_unref(bs);
Kevin Wolfe076f332010-06-29 11:43:13 +0200667
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500668 return ret;
aliguori15859692009-04-21 23:11:53 +0000669}
670
bellardea2384d2004-08-01 21:59:26 +0000671static int img_commit(int argc, char **argv)
672{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400673 int c, ret, flags;
674 const char *filename, *fmt, *cache;
bellardea2384d2004-08-01 21:59:26 +0000675 BlockDriverState *bs;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100676 bool quiet = false;
bellardea2384d2004-08-01 21:59:26 +0000677
678 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400679 cache = BDRV_DEFAULT_CACHE;
bellardea2384d2004-08-01 21:59:26 +0000680 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100681 c = getopt(argc, argv, "f:ht:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100682 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000683 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100684 }
bellardea2384d2004-08-01 21:59:26 +0000685 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100686 case '?':
bellardea2384d2004-08-01 21:59:26 +0000687 case 'h':
688 help();
689 break;
690 case 'f':
691 fmt = optarg;
692 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400693 case 't':
694 cache = optarg;
695 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100696 case 'q':
697 quiet = true;
698 break;
bellardea2384d2004-08-01 21:59:26 +0000699 }
700 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200701 if (optind != argc - 1) {
bellardea2384d2004-08-01 21:59:26 +0000702 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100703 }
bellardea2384d2004-08-01 21:59:26 +0000704 filename = argv[optind++];
705
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400706 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100707 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400708 if (ret < 0) {
709 error_report("Invalid cache option: %s", cache);
710 return -1;
711 }
712
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100713 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900714 if (!bs) {
715 return 1;
716 }
bellardea2384d2004-08-01 21:59:26 +0000717 ret = bdrv_commit(bs);
718 switch(ret) {
719 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100720 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000721 break;
722 case -ENOENT:
Jes Sorensen15654a62010-12-16 14:31:53 +0100723 error_report("No disk inserted");
bellardea2384d2004-08-01 21:59:26 +0000724 break;
725 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +0100726 error_report("Image is read-only");
bellardea2384d2004-08-01 21:59:26 +0000727 break;
728 case -ENOTSUP:
Jes Sorensen15654a62010-12-16 14:31:53 +0100729 error_report("Image is already committed");
bellardea2384d2004-08-01 21:59:26 +0000730 break;
731 default:
Jes Sorensen15654a62010-12-16 14:31:53 +0100732 error_report("Error while committing image");
bellardea2384d2004-08-01 21:59:26 +0000733 break;
734 }
735
Fam Zheng4f6fd342013-08-23 09:14:47 +0800736 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900737 if (ret) {
738 return 1;
739 }
bellardea2384d2004-08-01 21:59:26 +0000740 return 0;
741}
742
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400743/*
thsf58c7b32008-06-05 21:53:49 +0000744 * Returns true iff the first sector pointed to by 'buf' contains at least
745 * a non-NUL byte.
746 *
747 * 'pnum' is set to the number of sectors (including and immediately following
748 * the first one) that are known to be in the same allocated/unallocated state.
749 */
bellardea2384d2004-08-01 21:59:26 +0000750static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
751{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000752 bool is_zero;
753 int i;
bellardea2384d2004-08-01 21:59:26 +0000754
755 if (n <= 0) {
756 *pnum = 0;
757 return 0;
758 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000759 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +0000760 for(i = 1; i < n; i++) {
761 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000762 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +0000763 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000764 }
bellardea2384d2004-08-01 21:59:26 +0000765 }
766 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000767 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +0000768}
769
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100770/*
Kevin Wolfa22f1232011-08-26 15:27:13 +0200771 * Like is_allocated_sectors, but if the buffer starts with a used sector,
772 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
773 * breaking up write requests for only small sparse areas.
774 */
775static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
776 int min)
777{
778 int ret;
779 int num_checked, num_used;
780
781 if (n < min) {
782 min = n;
783 }
784
785 ret = is_allocated_sectors(buf, n, pnum);
786 if (!ret) {
787 return ret;
788 }
789
790 num_used = *pnum;
791 buf += BDRV_SECTOR_SIZE * *pnum;
792 n -= *pnum;
793 num_checked = num_used;
794
795 while (n > 0) {
796 ret = is_allocated_sectors(buf, n, pnum);
797
798 buf += BDRV_SECTOR_SIZE * *pnum;
799 n -= *pnum;
800 num_checked += *pnum;
801 if (ret) {
802 num_used = num_checked;
803 } else if (*pnum >= min) {
804 break;
805 }
806 }
807
808 *pnum = num_used;
809 return 1;
810}
811
812/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100813 * Compares two buffers sector by sector. Returns 0 if the first sector of both
814 * buffers matches, non-zero otherwise.
815 *
816 * pnum is set to the number of sectors (including and immediately following
817 * the first one) that are known to have the same comparison result
818 */
819static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
820 int *pnum)
821{
822 int res, i;
823
824 if (n <= 0) {
825 *pnum = 0;
826 return 0;
827 }
828
829 res = !!memcmp(buf1, buf2, 512);
830 for(i = 1; i < n; i++) {
831 buf1 += 512;
832 buf2 += 512;
833
834 if (!!memcmp(buf1, buf2, 512) != res) {
835 break;
836 }
837 }
838
839 *pnum = i;
840 return res;
841}
842
Kevin Wolf80ee15a2009-09-15 12:30:43 +0200843#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +0000844
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100845static int64_t sectors_to_bytes(int64_t sectors)
846{
847 return sectors << BDRV_SECTOR_BITS;
848}
849
850static int64_t sectors_to_process(int64_t total, int64_t from)
851{
852 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
853}
854
855/*
856 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
857 *
858 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
859 * data and negative value on error.
860 *
861 * @param bs: Driver used for accessing file
862 * @param sect_num: Number of first sector to check
863 * @param sect_count: Number of sectors to check
864 * @param filename: Name of disk file we are checking (logging purpose)
865 * @param buffer: Allocated buffer for storing read data
866 * @param quiet: Flag for quiet mode
867 */
868static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
869 int sect_count, const char *filename,
870 uint8_t *buffer, bool quiet)
871{
872 int pnum, ret = 0;
873 ret = bdrv_read(bs, sect_num, buffer, sect_count);
874 if (ret < 0) {
875 error_report("Error while reading offset %" PRId64 " of %s: %s",
876 sectors_to_bytes(sect_num), filename, strerror(-ret));
877 return ret;
878 }
879 ret = is_allocated_sectors(buffer, sect_count, &pnum);
880 if (ret || pnum != sect_count) {
881 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
882 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
883 return 1;
884 }
885
886 return 0;
887}
888
889/*
890 * Compares two images. Exit codes:
891 *
892 * 0 - Images are identical
893 * 1 - Images differ
894 * >1 - Error occurred
895 */
896static int img_compare(int argc, char **argv)
897{
898 const char *fmt1 = NULL, *fmt2 = NULL, *filename1, *filename2;
899 BlockDriverState *bs1, *bs2;
900 int64_t total_sectors1, total_sectors2;
901 uint8_t *buf1 = NULL, *buf2 = NULL;
902 int pnum1, pnum2;
903 int allocated1, allocated2;
904 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
905 bool progress = false, quiet = false, strict = false;
906 int64_t total_sectors;
907 int64_t sector_num = 0;
908 int64_t nb_sectors;
909 int c, pnum;
910 uint64_t bs_sectors;
911 uint64_t progress_base;
912
913 for (;;) {
914 c = getopt(argc, argv, "hpf:F:sq");
915 if (c == -1) {
916 break;
917 }
918 switch (c) {
919 case '?':
920 case 'h':
921 help();
922 break;
923 case 'f':
924 fmt1 = optarg;
925 break;
926 case 'F':
927 fmt2 = optarg;
928 break;
929 case 'p':
930 progress = true;
931 break;
932 case 'q':
933 quiet = true;
934 break;
935 case 's':
936 strict = true;
937 break;
938 }
939 }
940
941 /* Progress is not shown in Quiet mode */
942 if (quiet) {
943 progress = false;
944 }
945
946
Kevin Wolffc11eb22013-08-05 10:53:04 +0200947 if (optind != argc - 2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100948 help();
949 }
950 filename1 = argv[optind++];
951 filename2 = argv[optind++];
952
953 /* Initialize before goto out */
954 qemu_progress_init(progress, 2.0);
955
956 bs1 = bdrv_new_open(filename1, fmt1, BDRV_O_FLAGS, true, quiet);
957 if (!bs1) {
958 error_report("Can't open file %s", filename1);
959 ret = 2;
960 goto out3;
961 }
962
963 bs2 = bdrv_new_open(filename2, fmt2, BDRV_O_FLAGS, true, quiet);
964 if (!bs2) {
965 error_report("Can't open file %s", filename2);
966 ret = 2;
967 goto out2;
968 }
969
970 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
971 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
972 bdrv_get_geometry(bs1, &bs_sectors);
973 total_sectors1 = bs_sectors;
974 bdrv_get_geometry(bs2, &bs_sectors);
975 total_sectors2 = bs_sectors;
976 total_sectors = MIN(total_sectors1, total_sectors2);
977 progress_base = MAX(total_sectors1, total_sectors2);
978
979 qemu_progress_print(0, 100);
980
981 if (strict && total_sectors1 != total_sectors2) {
982 ret = 1;
983 qprintf(quiet, "Strict mode: Image size mismatch!\n");
984 goto out;
985 }
986
987 for (;;) {
988 nb_sectors = sectors_to_process(total_sectors, sector_num);
989 if (nb_sectors <= 0) {
990 break;
991 }
992 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
993 &pnum1);
994 if (allocated1 < 0) {
995 ret = 3;
996 error_report("Sector allocation test failed for %s", filename1);
997 goto out;
998 }
999
1000 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1001 &pnum2);
1002 if (allocated2 < 0) {
1003 ret = 3;
1004 error_report("Sector allocation test failed for %s", filename2);
1005 goto out;
1006 }
1007 nb_sectors = MIN(pnum1, pnum2);
1008
1009 if (allocated1 == allocated2) {
1010 if (allocated1) {
1011 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1012 if (ret < 0) {
1013 error_report("Error while reading offset %" PRId64 " of %s:"
1014 " %s", sectors_to_bytes(sector_num), filename1,
1015 strerror(-ret));
1016 ret = 4;
1017 goto out;
1018 }
1019 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1020 if (ret < 0) {
1021 error_report("Error while reading offset %" PRId64
1022 " of %s: %s", sectors_to_bytes(sector_num),
1023 filename2, strerror(-ret));
1024 ret = 4;
1025 goto out;
1026 }
1027 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1028 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001029 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1030 sectors_to_bytes(
1031 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001032 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001033 goto out;
1034 }
1035 }
1036 } else {
1037 if (strict) {
1038 ret = 1;
1039 qprintf(quiet, "Strict mode: Offset %" PRId64
1040 " allocation mismatch!\n",
1041 sectors_to_bytes(sector_num));
1042 goto out;
1043 }
1044
1045 if (allocated1) {
1046 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1047 filename1, buf1, quiet);
1048 } else {
1049 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1050 filename2, buf1, quiet);
1051 }
1052 if (ret) {
1053 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001054 error_report("Error while reading offset %" PRId64 ": %s",
1055 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001056 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001057 }
1058 goto out;
1059 }
1060 }
1061 sector_num += nb_sectors;
1062 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1063 }
1064
1065 if (total_sectors1 != total_sectors2) {
1066 BlockDriverState *bs_over;
1067 int64_t total_sectors_over;
1068 const char *filename_over;
1069
1070 qprintf(quiet, "Warning: Image size mismatch!\n");
1071 if (total_sectors1 > total_sectors2) {
1072 total_sectors_over = total_sectors1;
1073 bs_over = bs1;
1074 filename_over = filename1;
1075 } else {
1076 total_sectors_over = total_sectors2;
1077 bs_over = bs2;
1078 filename_over = filename2;
1079 }
1080
1081 for (;;) {
1082 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1083 if (nb_sectors <= 0) {
1084 break;
1085 }
1086 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1087 nb_sectors, &pnum);
1088 if (ret < 0) {
1089 ret = 3;
1090 error_report("Sector allocation test failed for %s",
1091 filename_over);
1092 goto out;
1093
1094 }
1095 nb_sectors = pnum;
1096 if (ret) {
1097 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1098 filename_over, buf1, quiet);
1099 if (ret) {
1100 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001101 error_report("Error while reading offset %" PRId64
1102 " of %s: %s", sectors_to_bytes(sector_num),
1103 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001104 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001105 }
1106 goto out;
1107 }
1108 }
1109 sector_num += nb_sectors;
1110 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1111 }
1112 }
1113
1114 qprintf(quiet, "Images are identical.\n");
1115 ret = 0;
1116
1117out:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001118 bdrv_unref(bs2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001119 qemu_vfree(buf1);
1120 qemu_vfree(buf2);
1121out2:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001122 bdrv_unref(bs1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001123out3:
1124 qemu_progress_end();
1125 return ret;
1126}
1127
bellardea2384d2004-08-01 21:59:26 +00001128static int img_convert(int argc, char **argv)
1129{
Peter Lieven24f833c2013-11-27 11:07:07 +01001130 int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001131 int64_t ret = 0;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001132 int progress = 0, flags;
1133 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001134 BlockDriver *drv, *proto_drv;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001135 BlockDriverState **bs = NULL, *out_bs = NULL;
Peter Lieven802c3d42013-12-05 15:54:53 +01001136 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
ths96b8f132007-12-17 01:35:20 +00001137 uint64_t bs_sectors;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001138 uint8_t * buf = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001139 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardea2384d2004-08-01 21:59:26 +00001140 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +00001141 BlockDriverInfo bdi;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001142 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfa18953f2010-10-14 15:46:04 +02001143 QEMUOptionParameter *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001144 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001145 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001146 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001147 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001148 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001149 QemuOpts *sn_opts = NULL;
bellardea2384d2004-08-01 21:59:26 +00001150
1151 fmt = NULL;
1152 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001153 cache = "unsafe";
thsf58c7b32008-06-05 21:53:49 +00001154 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001155 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001156 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001157 for(;;) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001158 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:qnl:");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001159 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001160 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001161 }
bellardea2384d2004-08-01 21:59:26 +00001162 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001163 case '?':
bellardea2384d2004-08-01 21:59:26 +00001164 case 'h':
1165 help();
1166 break;
1167 case 'f':
1168 fmt = optarg;
1169 break;
1170 case 'O':
1171 out_fmt = optarg;
1172 break;
thsf58c7b32008-06-05 21:53:49 +00001173 case 'B':
1174 out_baseimg = optarg;
1175 break;
bellardea2384d2004-08-01 21:59:26 +00001176 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001177 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001178 break;
1179 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001180 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001181 "encryption\' instead!");
1182 return 1;
thsec36ba12007-09-16 21:59:02 +00001183 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001184 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001185 "compat6\' instead!");
1186 return 1;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001187 case 'o':
1188 options = optarg;
1189 break;
edison51ef6722010-09-21 19:58:41 -07001190 case 's':
1191 snapshot_name = optarg;
1192 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001193 case 'l':
1194 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1195 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1196 if (!sn_opts) {
1197 error_report("Failed in parsing snapshot param '%s'",
1198 optarg);
1199 return 1;
1200 }
1201 } else {
1202 snapshot_name = optarg;
1203 }
1204 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001205 case 'S':
1206 {
1207 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001208 char *end;
1209 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1210 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001211 error_report("Invalid minimum zero buffer size for sparse output specified");
1212 return 1;
1213 }
1214
1215 min_sparse = sval / BDRV_SECTOR_SIZE;
1216 break;
1217 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001218 case 'p':
1219 progress = 1;
1220 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001221 case 't':
1222 cache = optarg;
1223 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001224 case 'q':
1225 quiet = true;
1226 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001227 case 'n':
1228 skip_create = 1;
1229 break;
bellardea2384d2004-08-01 21:59:26 +00001230 }
1231 }
ths3b46e622007-09-17 08:09:54 +00001232
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001233 if (quiet) {
1234 progress = 0;
1235 }
1236
balrog926c2d22007-10-31 01:11:44 +00001237 bs_n = argc - optind - 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001238 if (bs_n < 1) {
1239 help();
1240 }
balrog926c2d22007-10-31 01:11:44 +00001241
1242 out_filename = argv[argc - 1];
thsf58c7b32008-06-05 21:53:49 +00001243
Charles Arnoldfa170c12012-05-11 10:57:54 -06001244 /* Initialize before goto out */
Peter Lieven40588982013-11-27 11:07:09 +01001245 qemu_progress_init(progress, 1.0);
Charles Arnoldfa170c12012-05-11 10:57:54 -06001246
Peter Maydellc8057f92012-08-02 13:45:54 +01001247 if (options && is_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001248 ret = print_block_option_help(out_filename, out_fmt);
1249 goto out;
1250 }
1251
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001252 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001253 error_report("-B makes no sense when concatenating multiple input "
1254 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001255 ret = -1;
1256 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001257 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001258
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001259 qemu_progress_print(0, 100);
1260
Anthony Liguori7267c092011-08-20 22:09:37 -05001261 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
balrog926c2d22007-10-31 01:11:44 +00001262
1263 total_sectors = 0;
1264 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001265 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
1266 quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001267 if (!bs[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001268 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001269 ret = -1;
1270 goto out;
1271 }
balrog926c2d22007-10-31 01:11:44 +00001272 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1273 total_sectors += bs_sectors;
1274 }
bellardea2384d2004-08-01 21:59:26 +00001275
Wenchao Xiaef806542013-12-04 17:10:57 +08001276 if (sn_opts) {
1277 ret = bdrv_snapshot_load_tmp(bs[0],
1278 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1279 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1280 &local_err);
1281 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001282 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001283 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001284 ret = -1;
1285 goto out;
1286 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001287
1288 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001289 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001290 if (local_err) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001291 error_report("Failed to load snapshot: %s",
1292 error_get_pretty(local_err));
1293 error_free(local_err);
1294 ret = -1;
1295 goto out;
edison51ef6722010-09-21 19:58:41 -07001296 }
1297
Kevin Wolfefa84d42009-05-18 16:42:12 +02001298 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001299 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001300 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001301 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001302 ret = -1;
1303 goto out;
1304 }
balrog926c2d22007-10-31 01:11:44 +00001305
Kevin Wolf98289622013-07-10 15:47:39 +02001306 proto_drv = bdrv_find_protocol(out_filename, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001307 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001308 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001309 ret = -1;
1310 goto out;
1311 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001312
1313 create_options = append_option_parameters(create_options,
1314 drv->create_options);
1315 create_options = append_option_parameters(create_options,
1316 proto_drv->create_options);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02001317
Kevin Wolfefa84d42009-05-18 16:42:12 +02001318 if (options) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001319 param = parse_option_parameters(options, create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001320 if (param == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001321 error_report("Invalid options for file format '%s'.", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001322 ret = -1;
1323 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001324 }
1325 } else {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001326 param = parse_option_parameters("", create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001327 }
1328
1329 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
Jes Sorenseneec77d92010-12-07 17:44:34 +01001330 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001331 if (ret < 0) {
1332 goto out;
1333 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001334
Kevin Wolfa18953f2010-10-14 15:46:04 +02001335 /* Get backing file name if -o backing_file was used */
1336 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
1337 if (out_baseimg_param) {
1338 out_baseimg = out_baseimg_param->value.s;
1339 }
1340
Kevin Wolfefa84d42009-05-18 16:42:12 +02001341 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01001342 if (compress) {
Kevin Wolfefa84d42009-05-18 16:42:12 +02001343 QEMUOptionParameter *encryption =
1344 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
Kevin Wolf41521fa2011-10-18 16:19:42 +02001345 QEMUOptionParameter *preallocation =
1346 get_option_parameter(param, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001347
1348 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001349 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001350 ret = -1;
1351 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001352 }
1353
1354 if (encryption && encryption->value.n) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001355 error_report("Compression and encryption not supported at "
1356 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001357 ret = -1;
1358 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001359 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02001360
1361 if (preallocation && preallocation->value.s
1362 && strcmp(preallocation->value.s, "off"))
1363 {
1364 error_report("Compression and preallocation not supported at "
1365 "the same time");
1366 ret = -1;
1367 goto out;
1368 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001369 }
1370
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001371 if (!skip_create) {
1372 /* Create the new image */
Max Reitzcc84d902013-09-06 17:14:26 +02001373 ret = bdrv_create(drv, out_filename, param, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001374 if (ret < 0) {
Max Reitzcc84d902013-09-06 17:14:26 +02001375 error_report("%s: error while converting %s: %s",
1376 out_filename, out_fmt, error_get_pretty(local_err));
1377 error_free(local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001378 goto out;
bellardea2384d2004-08-01 21:59:26 +00001379 }
1380 }
ths3b46e622007-09-17 08:09:54 +00001381
Peter Lieven5a37b602013-10-24 12:07:06 +02001382 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001383 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001384 if (ret < 0) {
1385 error_report("Invalid cache option: %s", cache);
1386 return -1;
1387 }
1388
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001389 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001390 if (!out_bs) {
1391 ret = -1;
1392 goto out;
1393 }
bellardea2384d2004-08-01 21:59:26 +00001394
balrog926c2d22007-10-31 01:11:44 +00001395 bs_i = 0;
1396 bs_offset = 0;
1397 bdrv_get_geometry(bs[0], &bs_sectors);
Peter Lievenf2521c92013-11-27 11:07:06 +01001398
1399 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1400 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1401 * as maximum. */
1402 bufsectors = MIN(32768,
1403 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1404 out_bs->bl.discard_alignment))
1405 );
1406
1407 buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001408
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001409 if (skip_create) {
1410 int64_t output_length = bdrv_getlength(out_bs);
1411 if (output_length < 0) {
1412 error_report("unable to get output image length: %s\n",
1413 strerror(-output_length));
1414 ret = -1;
1415 goto out;
1416 } else if (output_length < total_sectors << BDRV_SECTOR_BITS) {
1417 error_report("output file is smaller than input file");
1418 ret = -1;
1419 goto out;
1420 }
1421 }
1422
Peter Lieven24f833c2013-11-27 11:07:07 +01001423 cluster_sectors = 0;
1424 ret = bdrv_get_info(out_bs, &bdi);
1425 if (ret < 0) {
1426 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001427 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001428 goto out;
1429 }
Peter Lieven24f833c2013-11-27 11:07:07 +01001430 } else {
1431 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
1432 }
1433
1434 if (compress) {
1435 if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001436 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001437 ret = -1;
1438 goto out;
1439 }
bellardea2384d2004-08-01 21:59:26 +00001440 sector_num = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001441
1442 nb_sectors = total_sectors;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001443
bellardea2384d2004-08-01 21:59:26 +00001444 for(;;) {
balrog926c2d22007-10-31 01:11:44 +00001445 int64_t bs_num;
1446 int remainder;
1447 uint8_t *buf2;
1448
bellardea2384d2004-08-01 21:59:26 +00001449 nb_sectors = total_sectors - sector_num;
1450 if (nb_sectors <= 0)
1451 break;
1452 if (nb_sectors >= cluster_sectors)
1453 n = cluster_sectors;
1454 else
1455 n = nb_sectors;
balrog926c2d22007-10-31 01:11:44 +00001456
1457 bs_num = sector_num - bs_offset;
1458 assert (bs_num >= 0);
1459 remainder = n;
1460 buf2 = buf;
1461 while (remainder > 0) {
1462 int nlow;
1463 while (bs_num == bs_sectors) {
1464 bs_i++;
1465 assert (bs_i < bs_n);
1466 bs_offset += bs_sectors;
1467 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1468 bs_num = 0;
Blue Swirl0bfcd592010-05-22 08:02:12 +00001469 /* printf("changing part: sector_num=%" PRId64 ", "
1470 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1471 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
balrog926c2d22007-10-31 01:11:44 +00001472 }
1473 assert (bs_num < bs_sectors);
1474
1475 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1476
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001477 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1478 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001479 error_report("error while reading sector %" PRId64 ": %s",
1480 bs_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001481 goto out;
1482 }
balrog926c2d22007-10-31 01:11:44 +00001483
1484 buf2 += nlow * 512;
1485 bs_num += nlow;
1486
1487 remainder -= nlow;
1488 }
1489 assert (remainder == 0);
1490
Stefan Hajnoczi54f106d2013-04-15 17:17:33 +02001491 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1492 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001493 if (ret != 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001494 error_report("error while compressing sector %" PRId64
1495 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001496 goto out;
1497 }
bellardea2384d2004-08-01 21:59:26 +00001498 }
1499 sector_num += n;
Peter Lieven13c28af2013-11-27 11:07:01 +01001500 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
bellardea2384d2004-08-01 21:59:26 +00001501 }
bellardfaea38e2006-08-05 21:31:00 +00001502 /* signal EOF to align */
1503 bdrv_write_compressed(out_bs, 0, NULL, 0);
bellardea2384d2004-08-01 21:59:26 +00001504 } else {
Peter Lieven802c3d42013-12-05 15:54:53 +01001505 int64_t sectors_to_read, sectors_read, sector_num_next_status;
1506 bool count_allocated_sectors;
Peter Lieven11b66992013-10-24 12:07:05 +02001507 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02001508
Peter Lieven5a37b602013-10-24 12:07:06 +02001509 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1510 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1511 if (ret < 0) {
1512 goto out;
1513 }
1514 has_zero_init = 1;
1515 }
1516
Peter Lieven802c3d42013-12-05 15:54:53 +01001517 sectors_to_read = total_sectors;
1518 count_allocated_sectors = progress && (out_baseimg || has_zero_init);
1519restart:
thsf58c7b32008-06-05 21:53:49 +00001520 sector_num = 0; // total number of sectors converted so far
Peter Lieven802c3d42013-12-05 15:54:53 +01001521 sectors_read = 0;
1522 sector_num_next_status = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001523
bellardea2384d2004-08-01 21:59:26 +00001524 for(;;) {
1525 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001526 if (nb_sectors <= 0) {
Peter Lieven802c3d42013-12-05 15:54:53 +01001527 if (count_allocated_sectors) {
1528 sectors_to_read = sectors_read;
1529 count_allocated_sectors = false;
1530 goto restart;
1531 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001532 ret = 0;
bellardea2384d2004-08-01 21:59:26 +00001533 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001534 }
balrog926c2d22007-10-31 01:11:44 +00001535
1536 while (sector_num - bs_offset >= bs_sectors) {
1537 bs_i ++;
1538 assert (bs_i < bs_n);
1539 bs_offset += bs_sectors;
1540 bdrv_get_geometry(bs[bs_i], &bs_sectors);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001541 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1542 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
balrog926c2d22007-10-31 01:11:44 +00001543 sector_num, bs_i, bs_offset, bs_sectors); */
1544 }
1545
Peter Lieven13c28af2013-11-27 11:07:01 +01001546 if ((out_baseimg || has_zero_init) &&
1547 sector_num >= sector_num_next_status) {
1548 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1549 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1550 n, &n1);
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001551 if (ret < 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001552 error_report("error while reading block status of sector %"
1553 PRId64 ": %s", sector_num - bs_offset,
1554 strerror(-ret));
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001555 goto out;
aliguori93c65b42009-04-05 17:40:43 +00001556 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001557 /* If the output image is zero initialized, we are not working
1558 * on a shared base and the input is zero we can skip the next
1559 * n1 sectors */
1560 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001561 sector_num += n1;
1562 continue;
1563 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001564 /* If the output image is being created as a copy on write
1565 * image, assume that sectors which are unallocated in the
1566 * input image are present in both the output's and input's
1567 * base images (no need to copy them). */
1568 if (out_baseimg) {
1569 if (!(ret & BDRV_BLOCK_DATA)) {
1570 sector_num += n1;
1571 continue;
1572 }
1573 /* The next 'n1' sectors are allocated in the input image.
1574 * Copy only those as they may be followed by unallocated
1575 * sectors. */
1576 nb_sectors = n1;
1577 }
1578 /* avoid redundant callouts to get_block_status */
1579 sector_num_next_status = sector_num + n1;
thsf58c7b32008-06-05 21:53:49 +00001580 }
1581
Peter Lievenf2521c92013-11-27 11:07:06 +01001582 n = MIN(nb_sectors, bufsectors);
Peter Lieven24f833c2013-11-27 11:07:07 +01001583
1584 /* round down request length to an aligned sector, but
1585 * do not bother doing this on short requests. They happen
1586 * when we found an all-zero area, and the next sector to
1587 * write will not be sector_num + n. */
1588 if (cluster_sectors > 0 && n >= cluster_sectors) {
1589 int64_t next_aligned_sector = (sector_num + n);
1590 next_aligned_sector -= next_aligned_sector % cluster_sectors;
1591 if (sector_num + n > next_aligned_sector) {
1592 n = next_aligned_sector - sector_num;
1593 }
1594 }
1595
Peter Lieven13c28af2013-11-27 11:07:01 +01001596 n = MIN(n, bs_sectors - (sector_num - bs_offset));
Peter Lieven13c28af2013-11-27 11:07:01 +01001597
Peter Lieven802c3d42013-12-05 15:54:53 +01001598 sectors_read += n;
1599 if (count_allocated_sectors) {
1600 sector_num += n;
1601 continue;
1602 }
1603
1604 n1 = n;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001605 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1606 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001607 error_report("error while reading sector %" PRId64 ": %s",
1608 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001609 goto out;
1610 }
bellardea2384d2004-08-01 21:59:26 +00001611 /* NOTE: at the same time we convert, we do not write zero
1612 sectors to have a chance to compress the image. Ideally, we
1613 should add a specific call to have the info to go faster */
1614 buf1 = buf;
1615 while (n > 0) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02001616 if (!has_zero_init ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001617 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001618 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1619 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001620 error_report("error while writing sector %" PRId64
1621 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001622 goto out;
1623 }
bellardea2384d2004-08-01 21:59:26 +00001624 }
1625 sector_num += n1;
1626 n -= n1;
1627 buf1 += n1 * 512;
1628 }
Peter Lieven802c3d42013-12-05 15:54:53 +01001629 qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
bellardea2384d2004-08-01 21:59:26 +00001630 }
1631 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001632out:
Peter Lieven13c28af2013-11-27 11:07:01 +01001633 if (!ret) {
1634 qemu_progress_print(100, 0);
1635 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001636 qemu_progress_end();
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001637 free_option_parameters(create_options);
1638 free_option_parameters(param);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001639 qemu_vfree(buf);
Wenchao Xiaef806542013-12-04 17:10:57 +08001640 if (sn_opts) {
1641 qemu_opts_del(sn_opts);
1642 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001643 if (out_bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001644 bdrv_unref(out_bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001645 }
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001646 if (bs) {
1647 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1648 if (bs[bs_i]) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001649 bdrv_unref(bs[bs_i]);
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001650 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001651 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001652 g_free(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001653 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001654 if (ret) {
1655 return 1;
1656 }
bellardea2384d2004-08-01 21:59:26 +00001657 return 0;
1658}
1659
bellard57d1a2b2004-08-03 21:15:11 +00001660
bellardfaea38e2006-08-05 21:31:00 +00001661static void dump_snapshots(BlockDriverState *bs)
1662{
1663 QEMUSnapshotInfo *sn_tab, *sn;
1664 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00001665
1666 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1667 if (nb_sns <= 0)
1668 return;
1669 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08001670 bdrv_snapshot_dump(fprintf, stdout, NULL);
1671 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001672 for(i = 0; i < nb_sns; i++) {
1673 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08001674 bdrv_snapshot_dump(fprintf, stdout, sn);
1675 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001676 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001677 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001678}
1679
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001680static void dump_json_image_info_list(ImageInfoList *list)
1681{
1682 Error *errp = NULL;
1683 QString *str;
1684 QmpOutputVisitor *ov = qmp_output_visitor_new();
1685 QObject *obj;
1686 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1687 &list, NULL, &errp);
1688 obj = qmp_output_get_qobject(ov);
1689 str = qobject_to_json_pretty(obj);
1690 assert(str != NULL);
1691 printf("%s\n", qstring_get_str(str));
1692 qobject_decref(obj);
1693 qmp_output_visitor_cleanup(ov);
1694 QDECREF(str);
1695}
1696
Benoît Canetc054b3f2012-09-05 13:09:02 +02001697static void dump_json_image_info(ImageInfo *info)
1698{
1699 Error *errp = NULL;
1700 QString *str;
1701 QmpOutputVisitor *ov = qmp_output_visitor_new();
1702 QObject *obj;
1703 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1704 &info, NULL, &errp);
1705 obj = qmp_output_get_qobject(ov);
1706 str = qobject_to_json_pretty(obj);
1707 assert(str != NULL);
1708 printf("%s\n", qstring_get_str(str));
1709 qobject_decref(obj);
1710 qmp_output_visitor_cleanup(ov);
1711 QDECREF(str);
1712}
1713
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001714static void dump_human_image_info_list(ImageInfoList *list)
1715{
1716 ImageInfoList *elem;
1717 bool delim = false;
1718
1719 for (elem = list; elem; elem = elem->next) {
1720 if (delim) {
1721 printf("\n");
1722 }
1723 delim = true;
1724
Wenchao Xia5b917042013-05-25 11:09:45 +08001725 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001726 }
1727}
1728
1729static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1730{
1731 return strcmp(a, b) == 0;
1732}
1733
1734/**
1735 * Open an image file chain and return an ImageInfoList
1736 *
1737 * @filename: topmost image filename
1738 * @fmt: topmost image format (may be NULL to autodetect)
1739 * @chain: true - enumerate entire backing file chain
1740 * false - only topmost image file
1741 *
1742 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1743 * image file. If there was an error a message will have been printed to
1744 * stderr.
1745 */
1746static ImageInfoList *collect_image_info_list(const char *filename,
1747 const char *fmt,
1748 bool chain)
1749{
1750 ImageInfoList *head = NULL;
1751 ImageInfoList **last = &head;
1752 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08001753 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001754
1755 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1756
1757 while (filename) {
1758 BlockDriverState *bs;
1759 ImageInfo *info;
1760 ImageInfoList *elem;
1761
1762 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1763 error_report("Backing file '%s' creates an infinite loop.",
1764 filename);
1765 goto err;
1766 }
1767 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1768
1769 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001770 false, false);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001771 if (!bs) {
1772 goto err;
1773 }
1774
Wenchao Xia43526ec2013-06-06 12:27:58 +08001775 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001776 if (err) {
Wenchao Xia43526ec2013-06-06 12:27:58 +08001777 error_report("%s", error_get_pretty(err));
1778 error_free(err);
1779 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08001780 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001781
1782 elem = g_new0(ImageInfoList, 1);
1783 elem->value = info;
1784 *last = elem;
1785 last = &elem->next;
1786
Fam Zheng4f6fd342013-08-23 09:14:47 +08001787 bdrv_unref(bs);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001788
1789 filename = fmt = NULL;
1790 if (chain) {
1791 if (info->has_full_backing_filename) {
1792 filename = info->full_backing_filename;
1793 } else if (info->has_backing_filename) {
1794 filename = info->backing_filename;
1795 }
1796 if (info->has_backing_filename_format) {
1797 fmt = info->backing_filename_format;
1798 }
1799 }
1800 }
1801 g_hash_table_destroy(filenames);
1802 return head;
1803
1804err:
1805 qapi_free_ImageInfoList(head);
1806 g_hash_table_destroy(filenames);
1807 return NULL;
1808}
1809
Benoît Canetc054b3f2012-09-05 13:09:02 +02001810static int img_info(int argc, char **argv)
1811{
1812 int c;
1813 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001814 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001815 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001816 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001817
bellardea2384d2004-08-01 21:59:26 +00001818 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001819 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001820 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001821 int option_index = 0;
1822 static const struct option long_options[] = {
1823 {"help", no_argument, 0, 'h'},
1824 {"format", required_argument, 0, 'f'},
1825 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001826 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001827 {0, 0, 0, 0}
1828 };
1829 c = getopt_long(argc, argv, "f:h",
1830 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001831 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001832 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001833 }
bellardea2384d2004-08-01 21:59:26 +00001834 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001835 case '?':
bellardea2384d2004-08-01 21:59:26 +00001836 case 'h':
1837 help();
1838 break;
1839 case 'f':
1840 fmt = optarg;
1841 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001842 case OPTION_OUTPUT:
1843 output = optarg;
1844 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001845 case OPTION_BACKING_CHAIN:
1846 chain = true;
1847 break;
bellardea2384d2004-08-01 21:59:26 +00001848 }
1849 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02001850 if (optind != argc - 1) {
bellardea2384d2004-08-01 21:59:26 +00001851 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001852 }
bellardea2384d2004-08-01 21:59:26 +00001853 filename = argv[optind++];
1854
Benoît Canetc054b3f2012-09-05 13:09:02 +02001855 if (output && !strcmp(output, "json")) {
1856 output_format = OFORMAT_JSON;
1857 } else if (output && !strcmp(output, "human")) {
1858 output_format = OFORMAT_HUMAN;
1859 } else if (output) {
1860 error_report("--output must be used with human or json as argument.");
1861 return 1;
1862 }
1863
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001864 list = collect_image_info_list(filename, fmt, chain);
1865 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001866 return 1;
1867 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001868
Benoît Canetc054b3f2012-09-05 13:09:02 +02001869 switch (output_format) {
1870 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001871 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001872 break;
1873 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001874 if (chain) {
1875 dump_json_image_info_list(list);
1876 } else {
1877 dump_json_image_info(list->value);
1878 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001879 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001880 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001881
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001882 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00001883 return 0;
1884}
1885
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001886
1887typedef struct MapEntry {
1888 int flags;
1889 int depth;
1890 int64_t start;
1891 int64_t length;
1892 int64_t offset;
1893 BlockDriverState *bs;
1894} MapEntry;
1895
1896static void dump_map_entry(OutputFormat output_format, MapEntry *e,
1897 MapEntry *next)
1898{
1899 switch (output_format) {
1900 case OFORMAT_HUMAN:
1901 if ((e->flags & BDRV_BLOCK_DATA) &&
1902 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
1903 error_report("File contains external, encrypted or compressed clusters.");
1904 exit(1);
1905 }
1906 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
1907 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
1908 e->start, e->length, e->offset, e->bs->filename);
1909 }
1910 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
1911 * Modify the flags here to allow more coalescing.
1912 */
1913 if (next &&
1914 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
1915 next->flags &= ~BDRV_BLOCK_DATA;
1916 next->flags |= BDRV_BLOCK_ZERO;
1917 }
1918 break;
1919 case OFORMAT_JSON:
1920 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
1921 " \"zero\": %s, \"data\": %s",
1922 (e->start == 0 ? "[" : ",\n"),
1923 e->start, e->length, e->depth,
1924 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
1925 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
1926 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02001927 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001928 }
1929 putchar('}');
1930
1931 if (!next) {
1932 printf("]\n");
1933 }
1934 break;
1935 }
1936}
1937
1938static int get_block_status(BlockDriverState *bs, int64_t sector_num,
1939 int nb_sectors, MapEntry *e)
1940{
1941 int64_t ret;
1942 int depth;
1943
1944 /* As an optimization, we could cache the current range of unallocated
1945 * clusters in each file of the chain, and avoid querying the same
1946 * range repeatedly.
1947 */
1948
1949 depth = 0;
1950 for (;;) {
1951 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
1952 if (ret < 0) {
1953 return ret;
1954 }
1955 assert(nb_sectors);
1956 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
1957 break;
1958 }
1959 bs = bs->backing_hd;
1960 if (bs == NULL) {
1961 ret = 0;
1962 break;
1963 }
1964
1965 depth++;
1966 }
1967
1968 e->start = sector_num * BDRV_SECTOR_SIZE;
1969 e->length = nb_sectors * BDRV_SECTOR_SIZE;
1970 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
1971 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
1972 e->depth = depth;
1973 e->bs = bs;
1974 return 0;
1975}
1976
1977static int img_map(int argc, char **argv)
1978{
1979 int c;
1980 OutputFormat output_format = OFORMAT_HUMAN;
1981 BlockDriverState *bs;
1982 const char *filename, *fmt, *output;
1983 int64_t length;
1984 MapEntry curr = { .length = 0 }, next;
1985 int ret = 0;
1986
1987 fmt = NULL;
1988 output = NULL;
1989 for (;;) {
1990 int option_index = 0;
1991 static const struct option long_options[] = {
1992 {"help", no_argument, 0, 'h'},
1993 {"format", required_argument, 0, 'f'},
1994 {"output", required_argument, 0, OPTION_OUTPUT},
1995 {0, 0, 0, 0}
1996 };
1997 c = getopt_long(argc, argv, "f:h",
1998 long_options, &option_index);
1999 if (c == -1) {
2000 break;
2001 }
2002 switch (c) {
2003 case '?':
2004 case 'h':
2005 help();
2006 break;
2007 case 'f':
2008 fmt = optarg;
2009 break;
2010 case OPTION_OUTPUT:
2011 output = optarg;
2012 break;
2013 }
2014 }
2015 if (optind >= argc) {
2016 help();
2017 }
2018 filename = argv[optind++];
2019
2020 if (output && !strcmp(output, "json")) {
2021 output_format = OFORMAT_JSON;
2022 } else if (output && !strcmp(output, "human")) {
2023 output_format = OFORMAT_HUMAN;
2024 } else if (output) {
2025 error_report("--output must be used with human or json as argument.");
2026 return 1;
2027 }
2028
2029 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS, true, false);
2030 if (!bs) {
2031 return 1;
2032 }
2033
2034 if (output_format == OFORMAT_HUMAN) {
2035 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2036 }
2037
2038 length = bdrv_getlength(bs);
2039 while (curr.start + curr.length < length) {
2040 int64_t nsectors_left;
2041 int64_t sector_num;
2042 int n;
2043
2044 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2045
2046 /* Probe up to 1 GiB at a time. */
2047 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2048 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2049 ret = get_block_status(bs, sector_num, n, &next);
2050
2051 if (ret < 0) {
2052 error_report("Could not read file metadata: %s", strerror(-ret));
2053 goto out;
2054 }
2055
2056 if (curr.length != 0 && curr.flags == next.flags &&
2057 curr.depth == next.depth &&
2058 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2059 curr.offset + curr.length == next.offset)) {
2060 curr.length += next.length;
2061 continue;
2062 }
2063
2064 if (curr.length > 0) {
2065 dump_map_entry(output_format, &curr, &next);
2066 }
2067 curr = next;
2068 }
2069
2070 dump_map_entry(output_format, &curr, NULL);
2071
2072out:
2073 bdrv_unref(bs);
2074 return ret < 0;
2075}
2076
aliguorif7b4a942009-01-07 17:40:15 +00002077#define SNAPSHOT_LIST 1
2078#define SNAPSHOT_CREATE 2
2079#define SNAPSHOT_APPLY 3
2080#define SNAPSHOT_DELETE 4
2081
Stuart Brady153859b2009-06-07 00:42:17 +01002082static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002083{
2084 BlockDriverState *bs;
2085 QEMUSnapshotInfo sn;
2086 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002087 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002088 int action = 0;
2089 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002090 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002091 Error *err = NULL;
aliguorif7b4a942009-01-07 17:40:15 +00002092
Kevin Wolf710da702011-01-10 12:33:02 +01002093 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002094 /* Parse commandline parameters */
2095 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002096 c = getopt(argc, argv, "la:c:d:hq");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002097 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002098 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002099 }
aliguorif7b4a942009-01-07 17:40:15 +00002100 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002101 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002102 case 'h':
2103 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002104 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002105 case 'l':
2106 if (action) {
2107 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002108 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002109 }
2110 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002111 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002112 break;
2113 case 'a':
2114 if (action) {
2115 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002116 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002117 }
2118 action = SNAPSHOT_APPLY;
2119 snapshot_name = optarg;
2120 break;
2121 case 'c':
2122 if (action) {
2123 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002124 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002125 }
2126 action = SNAPSHOT_CREATE;
2127 snapshot_name = optarg;
2128 break;
2129 case 'd':
2130 if (action) {
2131 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002132 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002133 }
2134 action = SNAPSHOT_DELETE;
2135 snapshot_name = optarg;
2136 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002137 case 'q':
2138 quiet = true;
2139 break;
aliguorif7b4a942009-01-07 17:40:15 +00002140 }
2141 }
2142
Kevin Wolffc11eb22013-08-05 10:53:04 +02002143 if (optind != argc - 1) {
aliguorif7b4a942009-01-07 17:40:15 +00002144 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002145 }
aliguorif7b4a942009-01-07 17:40:15 +00002146 filename = argv[optind++];
2147
2148 /* Open the image */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002149 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002150 if (!bs) {
2151 return 1;
2152 }
aliguorif7b4a942009-01-07 17:40:15 +00002153
2154 /* Perform the requested action */
2155 switch(action) {
2156 case SNAPSHOT_LIST:
2157 dump_snapshots(bs);
2158 break;
2159
2160 case SNAPSHOT_CREATE:
2161 memset(&sn, 0, sizeof(sn));
2162 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2163
2164 qemu_gettimeofday(&tv);
2165 sn.date_sec = tv.tv_sec;
2166 sn.date_nsec = tv.tv_usec * 1000;
2167
2168 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002169 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002170 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002171 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002172 }
aliguorif7b4a942009-01-07 17:40:15 +00002173 break;
2174
2175 case SNAPSHOT_APPLY:
2176 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002177 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002178 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002179 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002180 }
aliguorif7b4a942009-01-07 17:40:15 +00002181 break;
2182
2183 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002184 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002185 if (err) {
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002186 error_report("Could not delete snapshot '%s': (%s)",
2187 snapshot_name, error_get_pretty(err));
2188 error_free(err);
2189 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002190 }
aliguorif7b4a942009-01-07 17:40:15 +00002191 break;
2192 }
2193
2194 /* Cleanup */
Fam Zheng4f6fd342013-08-23 09:14:47 +08002195 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002196 if (ret) {
2197 return 1;
2198 }
Stuart Brady153859b2009-06-07 00:42:17 +01002199 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002200}
2201
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002202static int img_rebase(int argc, char **argv)
2203{
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002204 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01002205 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002206 char *filename;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002207 const char *fmt, *cache, *out_basefmt, *out_baseimg;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002208 int c, flags, ret;
2209 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002210 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002211 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002212 Error *local_err = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002213
2214 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002215 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002216 cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002217 out_baseimg = NULL;
2218 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002219 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002220 c = getopt(argc, argv, "uhf:F:b:pt:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002221 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002222 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002223 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002224 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002225 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002226 case 'h':
2227 help();
2228 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002229 case 'f':
2230 fmt = optarg;
2231 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002232 case 'F':
2233 out_basefmt = optarg;
2234 break;
2235 case 'b':
2236 out_baseimg = optarg;
2237 break;
2238 case 'u':
2239 unsafe = 1;
2240 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002241 case 'p':
2242 progress = 1;
2243 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002244 case 't':
2245 cache = optarg;
2246 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002247 case 'q':
2248 quiet = true;
2249 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002250 }
2251 }
2252
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002253 if (quiet) {
2254 progress = 0;
2255 }
2256
Kevin Wolffc11eb22013-08-05 10:53:04 +02002257 if ((optind != argc - 1) || (!unsafe && !out_baseimg)) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002258 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002259 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002260 filename = argv[optind++];
2261
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002262 qemu_progress_init(progress, 2.0);
2263 qemu_progress_print(0, 100);
2264
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002265 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01002266 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002267 if (ret < 0) {
2268 error_report("Invalid cache option: %s", cache);
2269 return -1;
2270 }
2271
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002272 /*
2273 * Open the images.
2274 *
2275 * Ignore the old backing file for unsafe rebase in case we want to correct
2276 * the reference to a renamed or moved backing file.
2277 */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002278 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002279 if (!bs) {
2280 return 1;
2281 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002282
2283 /* Find the right drivers for the backing files */
2284 old_backing_drv = NULL;
2285 new_backing_drv = NULL;
2286
2287 if (!unsafe && bs->backing_format[0] != '\0') {
2288 old_backing_drv = bdrv_find_format(bs->backing_format);
2289 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002290 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002291 ret = -1;
2292 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002293 }
2294 }
2295
2296 if (out_basefmt != NULL) {
2297 new_backing_drv = bdrv_find_format(out_basefmt);
2298 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002299 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002300 ret = -1;
2301 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002302 }
2303 }
2304
2305 /* For safe rebasing we need to compare old and new backing file */
2306 if (unsafe) {
2307 /* Make the compiler happy */
2308 bs_old_backing = NULL;
2309 bs_new_backing = NULL;
2310 } else {
2311 char backing_name[1024];
2312
2313 bs_old_backing = bdrv_new("old_backing");
2314 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzf67503e2014-02-18 18:33:05 +01002315 ret = bdrv_open(&bs_old_backing, backing_name, NULL, BDRV_O_FLAGS,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002316 old_backing_drv, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002317 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002318 error_report("Could not open old backing file '%s': %s",
2319 backing_name, error_get_pretty(local_err));
2320 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002321 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002322 }
Alex Bligha6166732012-10-16 13:46:18 +01002323 if (out_baseimg[0]) {
2324 bs_new_backing = bdrv_new("new_backing");
Max Reitzf67503e2014-02-18 18:33:05 +01002325 ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, BDRV_O_FLAGS,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002326 new_backing_drv, &local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002327 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002328 error_report("Could not open new backing file '%s': %s",
2329 out_baseimg, error_get_pretty(local_err));
2330 error_free(local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002331 goto out;
2332 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002333 }
2334 }
2335
2336 /*
2337 * Check each unallocated cluster in the COW file. If it is unallocated,
2338 * accesses go to the backing file. We must therefore compare this cluster
2339 * in the old and new backing file, and if they differ we need to copy it
2340 * from the old backing file into the COW file.
2341 *
2342 * If qemu-img crashes during this step, no harm is done. The content of
2343 * the image is the same as the original one at any time.
2344 */
2345 if (!unsafe) {
2346 uint64_t num_sectors;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002347 uint64_t old_backing_num_sectors;
Alex Bligha6166732012-10-16 13:46:18 +01002348 uint64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002349 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02002350 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08002351 uint8_t * buf_old;
2352 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02002353 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08002354
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002355 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2356 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002357
2358 bdrv_get_geometry(bs, &num_sectors);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002359 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
Alex Bligha6166732012-10-16 13:46:18 +01002360 if (bs_new_backing) {
2361 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
2362 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002363
Kevin Wolf1f710492012-10-12 14:29:18 +02002364 if (num_sectors != 0) {
2365 local_progress = (float)100 /
2366 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2367 }
2368
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002369 for (sector = 0; sector < num_sectors; sector += n) {
2370
2371 /* How many sectors can we handle with the next read? */
2372 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2373 n = (IO_BUF_SIZE / 512);
2374 } else {
2375 n = num_sectors - sector;
2376 }
2377
2378 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02002379 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02002380 if (ret < 0) {
2381 error_report("error while reading image metadata: %s",
2382 strerror(-ret));
2383 goto out;
2384 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02002385 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002386 continue;
2387 }
2388
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002389 /*
2390 * Read old and new backing file and take into consideration that
2391 * backing files may be smaller than the COW image.
2392 */
2393 if (sector >= old_backing_num_sectors) {
2394 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2395 } else {
2396 if (sector + n > old_backing_num_sectors) {
2397 n = old_backing_num_sectors - sector;
2398 }
2399
2400 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2401 if (ret < 0) {
2402 error_report("error while reading from old backing file");
2403 goto out;
2404 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002405 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002406
Alex Bligha6166732012-10-16 13:46:18 +01002407 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002408 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2409 } else {
2410 if (sector + n > new_backing_num_sectors) {
2411 n = new_backing_num_sectors - sector;
2412 }
2413
2414 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2415 if (ret < 0) {
2416 error_report("error while reading from new backing file");
2417 goto out;
2418 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002419 }
2420
2421 /* If they differ, we need to write to the COW file */
2422 uint64_t written = 0;
2423
2424 while (written < n) {
2425 int pnum;
2426
2427 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01002428 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002429 {
2430 ret = bdrv_write(bs, sector + written,
2431 buf_old + written * 512, pnum);
2432 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002433 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002434 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002435 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002436 }
2437 }
2438
2439 written += pnum;
2440 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002441 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002442 }
TeLeMand6771bf2010-02-08 16:20:00 +08002443
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002444 qemu_vfree(buf_old);
2445 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002446 }
2447
2448 /*
2449 * Change the backing file. All clusters that are different from the old
2450 * backing file are overwritten in the COW file now, so the visible content
2451 * doesn't change when we switch the backing file.
2452 */
Alex Bligha6166732012-10-16 13:46:18 +01002453 if (out_baseimg && *out_baseimg) {
2454 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2455 } else {
2456 ret = bdrv_change_backing_file(bs, NULL, NULL);
2457 }
2458
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002459 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002460 error_report("Could not change the backing file to '%s': No "
2461 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002462 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002463 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002464 out_baseimg, strerror(-ret));
2465 }
2466
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002467 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002468 /*
2469 * TODO At this point it is possible to check if any clusters that are
2470 * allocated in the COW file are the same in the backing file. If so, they
2471 * could be dropped from the COW file. Don't do this before switching the
2472 * backing file, in case of a crash this would lead to corruption.
2473 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002474out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002475 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002476 /* Cleanup */
2477 if (!unsafe) {
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002478 if (bs_old_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002479 bdrv_unref(bs_old_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002480 }
2481 if (bs_new_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002482 bdrv_unref(bs_new_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002483 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002484 }
2485
Fam Zheng4f6fd342013-08-23 09:14:47 +08002486 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002487 if (ret) {
2488 return 1;
2489 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002490 return 0;
2491}
2492
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002493static int img_resize(int argc, char **argv)
2494{
2495 int c, ret, relative;
2496 const char *filename, *fmt, *size;
2497 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002498 bool quiet = false;
Jes Sorensen2a819982010-12-06 17:08:31 +01002499 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002500 QemuOpts *param;
2501 static QemuOptsList resize_options = {
2502 .name = "resize_options",
2503 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2504 .desc = {
2505 {
2506 .name = BLOCK_OPT_SIZE,
2507 .type = QEMU_OPT_SIZE,
2508 .help = "Virtual disk size"
2509 }, {
2510 /* end of list */
2511 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002512 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002513 };
2514
Kevin Wolfe80fec72011-04-29 10:58:12 +02002515 /* Remove size from argv manually so that negative numbers are not treated
2516 * as options by getopt. */
2517 if (argc < 3) {
2518 help();
2519 return 1;
2520 }
2521
2522 size = argv[--argc];
2523
2524 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002525 fmt = NULL;
2526 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002527 c = getopt(argc, argv, "f:hq");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002528 if (c == -1) {
2529 break;
2530 }
2531 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002532 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002533 case 'h':
2534 help();
2535 break;
2536 case 'f':
2537 fmt = optarg;
2538 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002539 case 'q':
2540 quiet = true;
2541 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002542 }
2543 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002544 if (optind != argc - 1) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002545 help();
2546 }
2547 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002548
2549 /* Choose grow, shrink, or absolute resize mode */
2550 switch (size[0]) {
2551 case '+':
2552 relative = 1;
2553 size++;
2554 break;
2555 case '-':
2556 relative = -1;
2557 size++;
2558 break;
2559 default:
2560 relative = 0;
2561 break;
2562 }
2563
2564 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08002565 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002566 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002567 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002568 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002569 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002570 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002571 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002572 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2573 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002574
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002575 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002576 if (!bs) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002577 ret = -1;
2578 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002579 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002580
2581 if (relative) {
2582 total_size = bdrv_getlength(bs) + n * relative;
2583 } else {
2584 total_size = n;
2585 }
2586 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002587 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002588 ret = -1;
2589 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002590 }
2591
2592 ret = bdrv_truncate(bs, total_size);
2593 switch (ret) {
2594 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002595 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002596 break;
2597 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002598 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002599 break;
2600 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002601 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002602 break;
2603 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002604 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002605 break;
2606 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002607out:
Jes Sorensen2a819982010-12-06 17:08:31 +01002608 if (bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002609 bdrv_unref(bs);
Jes Sorensen2a819982010-12-06 17:08:31 +01002610 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002611 if (ret) {
2612 return 1;
2613 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002614 return 0;
2615}
2616
Max Reitz6f176b42013-09-03 10:09:50 +02002617static int img_amend(int argc, char **argv)
2618{
2619 int c, ret = 0;
2620 char *options = NULL;
2621 QEMUOptionParameter *create_options = NULL, *options_param = NULL;
2622 const char *fmt = NULL, *filename;
2623 bool quiet = false;
2624 BlockDriverState *bs = NULL;
2625
2626 for (;;) {
2627 c = getopt(argc, argv, "hqf:o:");
2628 if (c == -1) {
2629 break;
2630 }
2631
2632 switch (c) {
2633 case 'h':
2634 case '?':
2635 help();
2636 break;
2637 case 'o':
2638 options = optarg;
2639 break;
2640 case 'f':
2641 fmt = optarg;
2642 break;
2643 case 'q':
2644 quiet = true;
2645 break;
2646 }
2647 }
2648
2649 if (optind != argc - 1) {
2650 help();
2651 }
2652
2653 if (!options) {
2654 help();
2655 }
2656
2657 filename = argv[argc - 1];
2658
2659 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
2660 if (!bs) {
2661 error_report("Could not open image '%s'", filename);
2662 ret = -1;
2663 goto out;
2664 }
2665
2666 fmt = bs->drv->format_name;
2667
2668 if (is_help_option(options)) {
2669 ret = print_block_option_help(filename, fmt);
2670 goto out;
2671 }
2672
2673 create_options = append_option_parameters(create_options,
2674 bs->drv->create_options);
2675 options_param = parse_option_parameters(options, create_options,
2676 options_param);
2677 if (options_param == NULL) {
2678 error_report("Invalid options for file format '%s'", fmt);
2679 ret = -1;
2680 goto out;
2681 }
2682
2683 ret = bdrv_amend_options(bs, options_param);
2684 if (ret < 0) {
2685 error_report("Error while amending options: %s", strerror(-ret));
2686 goto out;
2687 }
2688
2689out:
2690 if (bs) {
2691 bdrv_unref(bs);
2692 }
2693 free_option_parameters(create_options);
2694 free_option_parameters(options_param);
2695 if (ret) {
2696 return 1;
2697 }
2698 return 0;
2699}
2700
Anthony Liguoric227f092009-10-01 16:12:16 -05002701static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002702#define DEF(option, callback, arg_string) \
2703 { option, callback },
2704#include "qemu-img-cmds.h"
2705#undef DEF
2706#undef GEN_DOCS
2707 { NULL, NULL, },
2708};
2709
bellardea2384d2004-08-01 21:59:26 +00002710int main(int argc, char **argv)
2711{
Anthony Liguoric227f092009-10-01 16:12:16 -05002712 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002713 const char *cmdname;
bellardea2384d2004-08-01 21:59:26 +00002714
MORITA Kazutaka526eda12013-07-23 17:30:11 +09002715#ifdef CONFIG_POSIX
2716 signal(SIGPIPE, SIG_IGN);
2717#endif
2718
Kevin Wolf53f76e52010-12-16 15:10:32 +01002719 error_set_progname(argv[0]);
2720
Paolo Bonzini2592c592012-11-03 18:10:17 +01002721 qemu_init_main_loop();
bellardea2384d2004-08-01 21:59:26 +00002722 bdrv_init();
2723 if (argc < 2)
2724 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002725 cmdname = argv[1];
aurel328f9b1572009-02-09 18:14:31 +00002726 argc--; argv++;
Stuart Brady153859b2009-06-07 00:42:17 +01002727
2728 /* find the command */
2729 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2730 if (!strcmp(cmdname, cmd->name)) {
2731 return cmd->handler(argc, argv);
2732 }
bellardea2384d2004-08-01 21:59:26 +00002733 }
Stuart Brady153859b2009-06-07 00:42:17 +01002734
2735 /* not found */
2736 help();
bellardea2384d2004-08-01 21:59:26 +00002737 return 0;
2738}