blob: 0725f22cc2ddb088f2306d69105f35ec95e50712 [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 Reitz34b5d2c2013-09-05 14:45:29 +0200292 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:
313 if (bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +0800314 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900315 }
316 return NULL;
bellard75c23802004-08-27 21:28:58 +0000317}
318
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900319static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100320 const char *base_filename,
321 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200322{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200323 if (base_filename) {
324 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100325 error_report("Backing file not supported for file format '%s'",
326 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900327 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200328 }
329 }
330 if (base_fmt) {
331 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100332 error_report("Backing file format not supported for file "
333 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900334 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200335 }
336 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900337 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200338}
339
bellardea2384d2004-08-01 21:59:26 +0000340static int img_create(int argc, char **argv)
341{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200342 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100343 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000344 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000345 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000346 const char *filename;
347 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200348 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200349 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100350 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000351
bellardea2384d2004-08-01 21:59:26 +0000352 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100353 c = getopt(argc, argv, "F:b:f:he6o:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100354 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000355 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100356 }
bellardea2384d2004-08-01 21:59:26 +0000357 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100358 case '?':
bellardea2384d2004-08-01 21:59:26 +0000359 case 'h':
360 help();
361 break;
aliguori9230eaf2009-03-28 17:55:19 +0000362 case 'F':
363 base_fmt = optarg;
364 break;
bellardea2384d2004-08-01 21:59:26 +0000365 case 'b':
366 base_filename = optarg;
367 break;
368 case 'f':
369 fmt = optarg;
370 break;
371 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200372 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100373 "encryption\' instead!");
374 return 1;
thsd8871c52007-10-24 16:11:42 +0000375 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200376 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100377 "compat6\' instead!");
378 return 1;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200379 case 'o':
380 options = optarg;
381 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100382 case 'q':
383 quiet = true;
384 break;
bellardea2384d2004-08-01 21:59:26 +0000385 }
386 }
aliguori9230eaf2009-03-28 17:55:19 +0000387
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900388 /* Get the filename */
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100389 if (optind >= argc) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900390 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100391 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900392 filename = argv[optind++];
393
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100394 /* Get image size, if specified */
395 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100396 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100397 char *end;
398 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
399 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800400 if (sval == -ERANGE) {
401 error_report("Image size must be less than 8 EiB!");
402 } else {
403 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200404 "G, T, P or E suffixes for ");
405 error_report("kilobytes, megabytes, gigabytes, terabytes, "
406 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800407 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200408 return 1;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100409 }
410 img_size = (uint64_t)sval;
411 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200412 if (optind != argc) {
413 help();
414 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100415
Peter Maydellc8057f92012-08-02 13:45:54 +0100416 if (options && is_help_option(options)) {
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200417 return print_block_option_help(filename, fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100418 }
419
Luiz Capitulino9b375252012-11-30 10:52:05 -0200420 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100421 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
Luiz Capitulino9b375252012-11-30 10:52:05 -0200422 if (error_is_set(&local_err)) {
Max Reitzb70d8c22013-09-06 16:51:03 +0200423 error_report("%s: %s", filename, error_get_pretty(local_err));
Luiz Capitulino9b375252012-11-30 10:52:05 -0200424 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900425 return 1;
426 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200427
bellardea2384d2004-08-01 21:59:26 +0000428 return 0;
429}
430
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100431static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500432{
433 Error *errp = NULL;
434 QString *str;
435 QmpOutputVisitor *ov = qmp_output_visitor_new();
436 QObject *obj;
437 visit_type_ImageCheck(qmp_output_get_visitor(ov),
438 &check, NULL, &errp);
439 obj = qmp_output_get_qobject(ov);
440 str = qobject_to_json_pretty(obj);
441 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100442 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500443 qobject_decref(obj);
444 qmp_output_visitor_cleanup(ov);
445 QDECREF(str);
446}
447
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100448static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500449{
450 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100451 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500452 } else {
453 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100454 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
455 "Data may be corrupted, or further writes to the image "
456 "may corrupt it.\n",
457 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500458 }
459
460 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100461 qprintf(quiet,
462 "\n%" PRId64 " leaked clusters were found on the image.\n"
463 "This means waste of disk space, but no harm to data.\n",
464 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500465 }
466
467 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100468 qprintf(quiet,
469 "\n%" PRId64
470 " internal errors have occurred during the check.\n",
471 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500472 }
473 }
474
475 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100476 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
477 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
478 check->allocated_clusters, check->total_clusters,
479 check->allocated_clusters * 100.0 / check->total_clusters,
480 check->fragmented_clusters * 100.0 / check->allocated_clusters,
481 check->compressed_clusters * 100.0 /
482 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500483 }
484
485 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100486 qprintf(quiet,
487 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500488 }
489}
490
491static int collect_image_check(BlockDriverState *bs,
492 ImageCheck *check,
493 const char *filename,
494 const char *fmt,
495 int fix)
496{
497 int ret;
498 BdrvCheckResult result;
499
500 ret = bdrv_check(bs, &result, fix);
501 if (ret < 0) {
502 return ret;
503 }
504
505 check->filename = g_strdup(filename);
506 check->format = g_strdup(bdrv_get_format_name(bs));
507 check->check_errors = result.check_errors;
508 check->corruptions = result.corruptions;
509 check->has_corruptions = result.corruptions != 0;
510 check->leaks = result.leaks;
511 check->has_leaks = result.leaks != 0;
512 check->corruptions_fixed = result.corruptions_fixed;
513 check->has_corruptions_fixed = result.corruptions != 0;
514 check->leaks_fixed = result.leaks_fixed;
515 check->has_leaks_fixed = result.leaks != 0;
516 check->image_end_offset = result.image_end_offset;
517 check->has_image_end_offset = result.image_end_offset != 0;
518 check->total_clusters = result.bfi.total_clusters;
519 check->has_total_clusters = result.bfi.total_clusters != 0;
520 check->allocated_clusters = result.bfi.allocated_clusters;
521 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
522 check->fragmented_clusters = result.bfi.fragmented_clusters;
523 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100524 check->compressed_clusters = result.bfi.compressed_clusters;
525 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500526
527 return 0;
528}
529
Kevin Wolfe076f332010-06-29 11:43:13 +0200530/*
531 * Checks an image for consistency. Exit codes:
532 *
533 * 0 - Check completed, image is good
534 * 1 - Check not completed because of internal errors
535 * 2 - Check completed, image is corrupted
536 * 3 - Check completed, image has leaked clusters, but is good otherwise
537 */
aliguori15859692009-04-21 23:11:53 +0000538static int img_check(int argc, char **argv)
539{
540 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500541 OutputFormat output_format = OFORMAT_HUMAN;
542 const char *filename, *fmt, *output;
aliguori15859692009-04-21 23:11:53 +0000543 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200544 int fix = 0;
Stefan Hajnoczi058f8f12012-08-09 13:05:56 +0100545 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500546 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100547 bool quiet = false;
aliguori15859692009-04-21 23:11:53 +0000548
549 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500550 output = NULL;
aliguori15859692009-04-21 23:11:53 +0000551 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500552 int option_index = 0;
553 static const struct option long_options[] = {
554 {"help", no_argument, 0, 'h'},
555 {"format", required_argument, 0, 'f'},
556 {"repair", no_argument, 0, 'r'},
557 {"output", required_argument, 0, OPTION_OUTPUT},
558 {0, 0, 0, 0}
559 };
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100560 c = getopt_long(argc, argv, "f:hr:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500561 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100562 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000563 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100564 }
aliguori15859692009-04-21 23:11:53 +0000565 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100566 case '?':
aliguori15859692009-04-21 23:11:53 +0000567 case 'h':
568 help();
569 break;
570 case 'f':
571 fmt = optarg;
572 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200573 case 'r':
574 flags |= BDRV_O_RDWR;
575
576 if (!strcmp(optarg, "leaks")) {
577 fix = BDRV_FIX_LEAKS;
578 } else if (!strcmp(optarg, "all")) {
579 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
580 } else {
581 help();
582 }
583 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500584 case OPTION_OUTPUT:
585 output = optarg;
586 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100587 case 'q':
588 quiet = true;
589 break;
aliguori15859692009-04-21 23:11:53 +0000590 }
591 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200592 if (optind != argc - 1) {
aliguori15859692009-04-21 23:11:53 +0000593 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100594 }
aliguori15859692009-04-21 23:11:53 +0000595 filename = argv[optind++];
596
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500597 if (output && !strcmp(output, "json")) {
598 output_format = OFORMAT_JSON;
599 } else if (output && !strcmp(output, "human")) {
600 output_format = OFORMAT_HUMAN;
601 } else if (output) {
602 error_report("--output must be used with human or json as argument.");
603 return 1;
604 }
605
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100606 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900607 if (!bs) {
608 return 1;
609 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500610
611 check = g_new0(ImageCheck, 1);
612 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200613
614 if (ret == -ENOTSUP) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500615 if (output_format == OFORMAT_HUMAN) {
616 error_report("This image format does not support checks");
617 }
Peter Lievenfefddf92013-10-24 08:53:34 +0200618 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500619 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200620 }
621
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500622 if (check->corruptions_fixed || check->leaks_fixed) {
623 int corruptions_fixed, leaks_fixed;
624
625 leaks_fixed = check->leaks_fixed;
626 corruptions_fixed = check->corruptions_fixed;
627
628 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100629 qprintf(quiet,
630 "The following inconsistencies were found and repaired:\n\n"
631 " %" PRId64 " leaked clusters\n"
632 " %" PRId64 " corruptions\n\n"
633 "Double checking the fixed image now...\n",
634 check->leaks_fixed,
635 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500636 }
637
638 ret = collect_image_check(bs, check, filename, fmt, 0);
639
640 check->leaks_fixed = leaks_fixed;
641 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200642 }
643
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500644 switch (output_format) {
645 case OFORMAT_HUMAN:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100646 dump_human_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500647 break;
648 case OFORMAT_JSON:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100649 dump_json_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500650 break;
651 }
652
653 if (ret || check->check_errors) {
654 ret = 1;
655 goto fail;
656 }
657
658 if (check->corruptions) {
659 ret = 2;
660 } else if (check->leaks) {
661 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200662 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500663 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000664 }
665
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500666fail:
667 qapi_free_ImageCheck(check);
Fam Zheng4f6fd342013-08-23 09:14:47 +0800668 bdrv_unref(bs);
Kevin Wolfe076f332010-06-29 11:43:13 +0200669
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500670 return ret;
aliguori15859692009-04-21 23:11:53 +0000671}
672
bellardea2384d2004-08-01 21:59:26 +0000673static int img_commit(int argc, char **argv)
674{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400675 int c, ret, flags;
676 const char *filename, *fmt, *cache;
bellardea2384d2004-08-01 21:59:26 +0000677 BlockDriverState *bs;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100678 bool quiet = false;
bellardea2384d2004-08-01 21:59:26 +0000679
680 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400681 cache = BDRV_DEFAULT_CACHE;
bellardea2384d2004-08-01 21:59:26 +0000682 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100683 c = getopt(argc, argv, "f:ht:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100684 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000685 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100686 }
bellardea2384d2004-08-01 21:59:26 +0000687 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100688 case '?':
bellardea2384d2004-08-01 21:59:26 +0000689 case 'h':
690 help();
691 break;
692 case 'f':
693 fmt = optarg;
694 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400695 case 't':
696 cache = optarg;
697 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100698 case 'q':
699 quiet = true;
700 break;
bellardea2384d2004-08-01 21:59:26 +0000701 }
702 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200703 if (optind != argc - 1) {
bellardea2384d2004-08-01 21:59:26 +0000704 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100705 }
bellardea2384d2004-08-01 21:59:26 +0000706 filename = argv[optind++];
707
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400708 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100709 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400710 if (ret < 0) {
711 error_report("Invalid cache option: %s", cache);
712 return -1;
713 }
714
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100715 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900716 if (!bs) {
717 return 1;
718 }
bellardea2384d2004-08-01 21:59:26 +0000719 ret = bdrv_commit(bs);
720 switch(ret) {
721 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100722 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000723 break;
724 case -ENOENT:
Jes Sorensen15654a62010-12-16 14:31:53 +0100725 error_report("No disk inserted");
bellardea2384d2004-08-01 21:59:26 +0000726 break;
727 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +0100728 error_report("Image is read-only");
bellardea2384d2004-08-01 21:59:26 +0000729 break;
730 case -ENOTSUP:
Jes Sorensen15654a62010-12-16 14:31:53 +0100731 error_report("Image is already committed");
bellardea2384d2004-08-01 21:59:26 +0000732 break;
733 default:
Jes Sorensen15654a62010-12-16 14:31:53 +0100734 error_report("Error while committing image");
bellardea2384d2004-08-01 21:59:26 +0000735 break;
736 }
737
Fam Zheng4f6fd342013-08-23 09:14:47 +0800738 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900739 if (ret) {
740 return 1;
741 }
bellardea2384d2004-08-01 21:59:26 +0000742 return 0;
743}
744
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400745/*
thsf58c7b32008-06-05 21:53:49 +0000746 * Returns true iff the first sector pointed to by 'buf' contains at least
747 * a non-NUL byte.
748 *
749 * 'pnum' is set to the number of sectors (including and immediately following
750 * the first one) that are known to be in the same allocated/unallocated state.
751 */
bellardea2384d2004-08-01 21:59:26 +0000752static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
753{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000754 bool is_zero;
755 int i;
bellardea2384d2004-08-01 21:59:26 +0000756
757 if (n <= 0) {
758 *pnum = 0;
759 return 0;
760 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000761 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +0000762 for(i = 1; i < n; i++) {
763 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000764 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +0000765 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000766 }
bellardea2384d2004-08-01 21:59:26 +0000767 }
768 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000769 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +0000770}
771
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100772/*
Kevin Wolfa22f1232011-08-26 15:27:13 +0200773 * Like is_allocated_sectors, but if the buffer starts with a used sector,
774 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
775 * breaking up write requests for only small sparse areas.
776 */
777static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
778 int min)
779{
780 int ret;
781 int num_checked, num_used;
782
783 if (n < min) {
784 min = n;
785 }
786
787 ret = is_allocated_sectors(buf, n, pnum);
788 if (!ret) {
789 return ret;
790 }
791
792 num_used = *pnum;
793 buf += BDRV_SECTOR_SIZE * *pnum;
794 n -= *pnum;
795 num_checked = num_used;
796
797 while (n > 0) {
798 ret = is_allocated_sectors(buf, n, pnum);
799
800 buf += BDRV_SECTOR_SIZE * *pnum;
801 n -= *pnum;
802 num_checked += *pnum;
803 if (ret) {
804 num_used = num_checked;
805 } else if (*pnum >= min) {
806 break;
807 }
808 }
809
810 *pnum = num_used;
811 return 1;
812}
813
814/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100815 * Compares two buffers sector by sector. Returns 0 if the first sector of both
816 * buffers matches, non-zero otherwise.
817 *
818 * pnum is set to the number of sectors (including and immediately following
819 * the first one) that are known to have the same comparison result
820 */
821static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
822 int *pnum)
823{
824 int res, i;
825
826 if (n <= 0) {
827 *pnum = 0;
828 return 0;
829 }
830
831 res = !!memcmp(buf1, buf2, 512);
832 for(i = 1; i < n; i++) {
833 buf1 += 512;
834 buf2 += 512;
835
836 if (!!memcmp(buf1, buf2, 512) != res) {
837 break;
838 }
839 }
840
841 *pnum = i;
842 return res;
843}
844
Kevin Wolf80ee15a2009-09-15 12:30:43 +0200845#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +0000846
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100847static int64_t sectors_to_bytes(int64_t sectors)
848{
849 return sectors << BDRV_SECTOR_BITS;
850}
851
852static int64_t sectors_to_process(int64_t total, int64_t from)
853{
854 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
855}
856
857/*
858 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
859 *
860 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
861 * data and negative value on error.
862 *
863 * @param bs: Driver used for accessing file
864 * @param sect_num: Number of first sector to check
865 * @param sect_count: Number of sectors to check
866 * @param filename: Name of disk file we are checking (logging purpose)
867 * @param buffer: Allocated buffer for storing read data
868 * @param quiet: Flag for quiet mode
869 */
870static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
871 int sect_count, const char *filename,
872 uint8_t *buffer, bool quiet)
873{
874 int pnum, ret = 0;
875 ret = bdrv_read(bs, sect_num, buffer, sect_count);
876 if (ret < 0) {
877 error_report("Error while reading offset %" PRId64 " of %s: %s",
878 sectors_to_bytes(sect_num), filename, strerror(-ret));
879 return ret;
880 }
881 ret = is_allocated_sectors(buffer, sect_count, &pnum);
882 if (ret || pnum != sect_count) {
883 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
884 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
885 return 1;
886 }
887
888 return 0;
889}
890
891/*
892 * Compares two images. Exit codes:
893 *
894 * 0 - Images are identical
895 * 1 - Images differ
896 * >1 - Error occurred
897 */
898static int img_compare(int argc, char **argv)
899{
900 const char *fmt1 = NULL, *fmt2 = NULL, *filename1, *filename2;
901 BlockDriverState *bs1, *bs2;
902 int64_t total_sectors1, total_sectors2;
903 uint8_t *buf1 = NULL, *buf2 = NULL;
904 int pnum1, pnum2;
905 int allocated1, allocated2;
906 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
907 bool progress = false, quiet = false, strict = false;
908 int64_t total_sectors;
909 int64_t sector_num = 0;
910 int64_t nb_sectors;
911 int c, pnum;
912 uint64_t bs_sectors;
913 uint64_t progress_base;
914
915 for (;;) {
916 c = getopt(argc, argv, "hpf:F:sq");
917 if (c == -1) {
918 break;
919 }
920 switch (c) {
921 case '?':
922 case 'h':
923 help();
924 break;
925 case 'f':
926 fmt1 = optarg;
927 break;
928 case 'F':
929 fmt2 = optarg;
930 break;
931 case 'p':
932 progress = true;
933 break;
934 case 'q':
935 quiet = true;
936 break;
937 case 's':
938 strict = true;
939 break;
940 }
941 }
942
943 /* Progress is not shown in Quiet mode */
944 if (quiet) {
945 progress = false;
946 }
947
948
Kevin Wolffc11eb22013-08-05 10:53:04 +0200949 if (optind != argc - 2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100950 help();
951 }
952 filename1 = argv[optind++];
953 filename2 = argv[optind++];
954
955 /* Initialize before goto out */
956 qemu_progress_init(progress, 2.0);
957
958 bs1 = bdrv_new_open(filename1, fmt1, BDRV_O_FLAGS, true, quiet);
959 if (!bs1) {
960 error_report("Can't open file %s", filename1);
961 ret = 2;
962 goto out3;
963 }
964
965 bs2 = bdrv_new_open(filename2, fmt2, BDRV_O_FLAGS, true, quiet);
966 if (!bs2) {
967 error_report("Can't open file %s", filename2);
968 ret = 2;
969 goto out2;
970 }
971
972 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
973 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
974 bdrv_get_geometry(bs1, &bs_sectors);
975 total_sectors1 = bs_sectors;
976 bdrv_get_geometry(bs2, &bs_sectors);
977 total_sectors2 = bs_sectors;
978 total_sectors = MIN(total_sectors1, total_sectors2);
979 progress_base = MAX(total_sectors1, total_sectors2);
980
981 qemu_progress_print(0, 100);
982
983 if (strict && total_sectors1 != total_sectors2) {
984 ret = 1;
985 qprintf(quiet, "Strict mode: Image size mismatch!\n");
986 goto out;
987 }
988
989 for (;;) {
990 nb_sectors = sectors_to_process(total_sectors, sector_num);
991 if (nb_sectors <= 0) {
992 break;
993 }
994 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
995 &pnum1);
996 if (allocated1 < 0) {
997 ret = 3;
998 error_report("Sector allocation test failed for %s", filename1);
999 goto out;
1000 }
1001
1002 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1003 &pnum2);
1004 if (allocated2 < 0) {
1005 ret = 3;
1006 error_report("Sector allocation test failed for %s", filename2);
1007 goto out;
1008 }
1009 nb_sectors = MIN(pnum1, pnum2);
1010
1011 if (allocated1 == allocated2) {
1012 if (allocated1) {
1013 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1014 if (ret < 0) {
1015 error_report("Error while reading offset %" PRId64 " of %s:"
1016 " %s", sectors_to_bytes(sector_num), filename1,
1017 strerror(-ret));
1018 ret = 4;
1019 goto out;
1020 }
1021 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1022 if (ret < 0) {
1023 error_report("Error while reading offset %" PRId64
1024 " of %s: %s", sectors_to_bytes(sector_num),
1025 filename2, strerror(-ret));
1026 ret = 4;
1027 goto out;
1028 }
1029 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1030 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001031 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1032 sectors_to_bytes(
1033 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001034 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001035 goto out;
1036 }
1037 }
1038 } else {
1039 if (strict) {
1040 ret = 1;
1041 qprintf(quiet, "Strict mode: Offset %" PRId64
1042 " allocation mismatch!\n",
1043 sectors_to_bytes(sector_num));
1044 goto out;
1045 }
1046
1047 if (allocated1) {
1048 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1049 filename1, buf1, quiet);
1050 } else {
1051 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1052 filename2, buf1, quiet);
1053 }
1054 if (ret) {
1055 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001056 error_report("Error while reading offset %" PRId64 ": %s",
1057 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001058 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001059 }
1060 goto out;
1061 }
1062 }
1063 sector_num += nb_sectors;
1064 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1065 }
1066
1067 if (total_sectors1 != total_sectors2) {
1068 BlockDriverState *bs_over;
1069 int64_t total_sectors_over;
1070 const char *filename_over;
1071
1072 qprintf(quiet, "Warning: Image size mismatch!\n");
1073 if (total_sectors1 > total_sectors2) {
1074 total_sectors_over = total_sectors1;
1075 bs_over = bs1;
1076 filename_over = filename1;
1077 } else {
1078 total_sectors_over = total_sectors2;
1079 bs_over = bs2;
1080 filename_over = filename2;
1081 }
1082
1083 for (;;) {
1084 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1085 if (nb_sectors <= 0) {
1086 break;
1087 }
1088 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1089 nb_sectors, &pnum);
1090 if (ret < 0) {
1091 ret = 3;
1092 error_report("Sector allocation test failed for %s",
1093 filename_over);
1094 goto out;
1095
1096 }
1097 nb_sectors = pnum;
1098 if (ret) {
1099 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1100 filename_over, buf1, quiet);
1101 if (ret) {
1102 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001103 error_report("Error while reading offset %" PRId64
1104 " of %s: %s", sectors_to_bytes(sector_num),
1105 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001106 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001107 }
1108 goto out;
1109 }
1110 }
1111 sector_num += nb_sectors;
1112 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1113 }
1114 }
1115
1116 qprintf(quiet, "Images are identical.\n");
1117 ret = 0;
1118
1119out:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001120 bdrv_unref(bs2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001121 qemu_vfree(buf1);
1122 qemu_vfree(buf2);
1123out2:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001124 bdrv_unref(bs1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001125out3:
1126 qemu_progress_end();
1127 return ret;
1128}
1129
bellardea2384d2004-08-01 21:59:26 +00001130static int img_convert(int argc, char **argv)
1131{
Peter Lieven13c28af2013-11-27 11:07:01 +01001132 int c, n, n1, bs_n, bs_i, compress, cluster_size,
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001133 cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001134 int64_t ret = 0;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001135 int progress = 0, flags;
1136 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001137 BlockDriver *drv, *proto_drv;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001138 BlockDriverState **bs = NULL, *out_bs = NULL;
Peter Lieven13c28af2013-11-27 11:07:01 +01001139 int64_t total_sectors, nb_sectors, sector_num, bs_offset,
1140 sector_num_next_status = 0;
ths96b8f132007-12-17 01:35:20 +00001141 uint64_t bs_sectors;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001142 uint8_t * buf = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001143 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardea2384d2004-08-01 21:59:26 +00001144 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +00001145 BlockDriverInfo bdi;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001146 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfa18953f2010-10-14 15:46:04 +02001147 QEMUOptionParameter *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001148 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001149 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001150 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001151 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001152 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001153 QemuOpts *sn_opts = NULL;
bellardea2384d2004-08-01 21:59:26 +00001154
1155 fmt = NULL;
1156 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001157 cache = "unsafe";
thsf58c7b32008-06-05 21:53:49 +00001158 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001159 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001160 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001161 for(;;) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001162 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:qnl:");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001163 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001164 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001165 }
bellardea2384d2004-08-01 21:59:26 +00001166 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001167 case '?':
bellardea2384d2004-08-01 21:59:26 +00001168 case 'h':
1169 help();
1170 break;
1171 case 'f':
1172 fmt = optarg;
1173 break;
1174 case 'O':
1175 out_fmt = optarg;
1176 break;
thsf58c7b32008-06-05 21:53:49 +00001177 case 'B':
1178 out_baseimg = optarg;
1179 break;
bellardea2384d2004-08-01 21:59:26 +00001180 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001181 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001182 break;
1183 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001184 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001185 "encryption\' instead!");
1186 return 1;
thsec36ba12007-09-16 21:59:02 +00001187 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001188 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001189 "compat6\' instead!");
1190 return 1;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001191 case 'o':
1192 options = optarg;
1193 break;
edison51ef6722010-09-21 19:58:41 -07001194 case 's':
1195 snapshot_name = optarg;
1196 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001197 case 'l':
1198 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1199 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1200 if (!sn_opts) {
1201 error_report("Failed in parsing snapshot param '%s'",
1202 optarg);
1203 return 1;
1204 }
1205 } else {
1206 snapshot_name = optarg;
1207 }
1208 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001209 case 'S':
1210 {
1211 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001212 char *end;
1213 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1214 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001215 error_report("Invalid minimum zero buffer size for sparse output specified");
1216 return 1;
1217 }
1218
1219 min_sparse = sval / BDRV_SECTOR_SIZE;
1220 break;
1221 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001222 case 'p':
1223 progress = 1;
1224 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001225 case 't':
1226 cache = optarg;
1227 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001228 case 'q':
1229 quiet = true;
1230 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001231 case 'n':
1232 skip_create = 1;
1233 break;
bellardea2384d2004-08-01 21:59:26 +00001234 }
1235 }
ths3b46e622007-09-17 08:09:54 +00001236
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001237 if (quiet) {
1238 progress = 0;
1239 }
1240
balrog926c2d22007-10-31 01:11:44 +00001241 bs_n = argc - optind - 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001242 if (bs_n < 1) {
1243 help();
1244 }
balrog926c2d22007-10-31 01:11:44 +00001245
1246 out_filename = argv[argc - 1];
thsf58c7b32008-06-05 21:53:49 +00001247
Charles Arnoldfa170c12012-05-11 10:57:54 -06001248 /* Initialize before goto out */
1249 qemu_progress_init(progress, 2.0);
1250
Peter Maydellc8057f92012-08-02 13:45:54 +01001251 if (options && is_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001252 ret = print_block_option_help(out_filename, out_fmt);
1253 goto out;
1254 }
1255
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001256 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001257 error_report("-B makes no sense when concatenating multiple input "
1258 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001259 ret = -1;
1260 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001261 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001262
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001263 qemu_progress_print(0, 100);
1264
Anthony Liguori7267c092011-08-20 22:09:37 -05001265 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
balrog926c2d22007-10-31 01:11:44 +00001266
1267 total_sectors = 0;
1268 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001269 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
1270 quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001271 if (!bs[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001272 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001273 ret = -1;
1274 goto out;
1275 }
balrog926c2d22007-10-31 01:11:44 +00001276 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1277 total_sectors += bs_sectors;
1278 }
bellardea2384d2004-08-01 21:59:26 +00001279
Wenchao Xiaef806542013-12-04 17:10:57 +08001280 if (sn_opts) {
1281 ret = bdrv_snapshot_load_tmp(bs[0],
1282 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1283 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1284 &local_err);
1285 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001286 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001287 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001288 ret = -1;
1289 goto out;
1290 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001291
1292 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001293 }
1294 if (error_is_set(&local_err)) {
1295 error_report("Failed to load snapshot: %s",
1296 error_get_pretty(local_err));
1297 error_free(local_err);
1298 ret = -1;
1299 goto out;
edison51ef6722010-09-21 19:58:41 -07001300 }
1301
Kevin Wolfefa84d42009-05-18 16:42:12 +02001302 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001303 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001304 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001305 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001306 ret = -1;
1307 goto out;
1308 }
balrog926c2d22007-10-31 01:11:44 +00001309
Kevin Wolf98289622013-07-10 15:47:39 +02001310 proto_drv = bdrv_find_protocol(out_filename, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001311 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001312 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001313 ret = -1;
1314 goto out;
1315 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001316
1317 create_options = append_option_parameters(create_options,
1318 drv->create_options);
1319 create_options = append_option_parameters(create_options,
1320 proto_drv->create_options);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02001321
Kevin Wolfefa84d42009-05-18 16:42:12 +02001322 if (options) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001323 param = parse_option_parameters(options, create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001324 if (param == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001325 error_report("Invalid options for file format '%s'.", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001326 ret = -1;
1327 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001328 }
1329 } else {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001330 param = parse_option_parameters("", create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001331 }
1332
1333 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
Jes Sorenseneec77d92010-12-07 17:44:34 +01001334 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001335 if (ret < 0) {
1336 goto out;
1337 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001338
Kevin Wolfa18953f2010-10-14 15:46:04 +02001339 /* Get backing file name if -o backing_file was used */
1340 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
1341 if (out_baseimg_param) {
1342 out_baseimg = out_baseimg_param->value.s;
1343 }
1344
Kevin Wolfefa84d42009-05-18 16:42:12 +02001345 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01001346 if (compress) {
Kevin Wolfefa84d42009-05-18 16:42:12 +02001347 QEMUOptionParameter *encryption =
1348 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
Kevin Wolf41521fa2011-10-18 16:19:42 +02001349 QEMUOptionParameter *preallocation =
1350 get_option_parameter(param, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001351
1352 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001353 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001354 ret = -1;
1355 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001356 }
1357
1358 if (encryption && encryption->value.n) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001359 error_report("Compression and encryption not supported at "
1360 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001361 ret = -1;
1362 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001363 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02001364
1365 if (preallocation && preallocation->value.s
1366 && strcmp(preallocation->value.s, "off"))
1367 {
1368 error_report("Compression and preallocation not supported at "
1369 "the same time");
1370 ret = -1;
1371 goto out;
1372 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001373 }
1374
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001375 if (!skip_create) {
1376 /* Create the new image */
Max Reitzcc84d902013-09-06 17:14:26 +02001377 ret = bdrv_create(drv, out_filename, param, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001378 if (ret < 0) {
Max Reitzcc84d902013-09-06 17:14:26 +02001379 error_report("%s: error while converting %s: %s",
1380 out_filename, out_fmt, error_get_pretty(local_err));
1381 error_free(local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001382 goto out;
bellardea2384d2004-08-01 21:59:26 +00001383 }
1384 }
ths3b46e622007-09-17 08:09:54 +00001385
Peter Lieven5a37b602013-10-24 12:07:06 +02001386 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001387 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001388 if (ret < 0) {
1389 error_report("Invalid cache option: %s", cache);
1390 return -1;
1391 }
1392
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001393 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001394 if (!out_bs) {
1395 ret = -1;
1396 goto out;
1397 }
bellardea2384d2004-08-01 21:59:26 +00001398
balrog926c2d22007-10-31 01:11:44 +00001399 bs_i = 0;
1400 bs_offset = 0;
1401 bdrv_get_geometry(bs[0], &bs_sectors);
Peter Lievenf2521c92013-11-27 11:07:06 +01001402
1403 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1404 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1405 * as maximum. */
1406 bufsectors = MIN(32768,
1407 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1408 out_bs->bl.discard_alignment))
1409 );
1410
1411 buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001412
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001413 if (skip_create) {
1414 int64_t output_length = bdrv_getlength(out_bs);
1415 if (output_length < 0) {
1416 error_report("unable to get output image length: %s\n",
1417 strerror(-output_length));
1418 ret = -1;
1419 goto out;
1420 } else if (output_length < total_sectors << BDRV_SECTOR_BITS) {
1421 error_report("output file is smaller than input file");
1422 ret = -1;
1423 goto out;
1424 }
1425 }
1426
Jes Sorenseneec77d92010-12-07 17:44:34 +01001427 if (compress) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001428 ret = bdrv_get_info(out_bs, &bdi);
1429 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001430 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001431 goto out;
1432 }
bellardfaea38e2006-08-05 21:31:00 +00001433 cluster_size = bdi.cluster_size;
Peter Lievenf2521c92013-11-27 11:07:06 +01001434 if (cluster_size <= 0 || cluster_size > bufsectors * BDRV_SECTOR_SIZE) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001435 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001436 ret = -1;
1437 goto out;
1438 }
bellardea2384d2004-08-01 21:59:26 +00001439 cluster_sectors = cluster_size >> 9;
1440 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 Lieven11b66992013-10-24 12:07:05 +02001505 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02001506
Peter Lieven5a37b602013-10-24 12:07:06 +02001507 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1508 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1509 if (ret < 0) {
1510 goto out;
1511 }
1512 has_zero_init = 1;
1513 }
1514
thsf58c7b32008-06-05 21:53:49 +00001515 sector_num = 0; // total number of sectors converted so far
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001516 nb_sectors = total_sectors - sector_num;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001517
bellardea2384d2004-08-01 21:59:26 +00001518 for(;;) {
1519 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001520 if (nb_sectors <= 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001521 ret = 0;
bellardea2384d2004-08-01 21:59:26 +00001522 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001523 }
balrog926c2d22007-10-31 01:11:44 +00001524
1525 while (sector_num - bs_offset >= bs_sectors) {
1526 bs_i ++;
1527 assert (bs_i < bs_n);
1528 bs_offset += bs_sectors;
1529 bdrv_get_geometry(bs[bs_i], &bs_sectors);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001530 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1531 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
balrog926c2d22007-10-31 01:11:44 +00001532 sector_num, bs_i, bs_offset, bs_sectors); */
1533 }
1534
Peter Lieven13c28af2013-11-27 11:07:01 +01001535 if ((out_baseimg || has_zero_init) &&
1536 sector_num >= sector_num_next_status) {
1537 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1538 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1539 n, &n1);
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001540 if (ret < 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001541 error_report("error while reading block status of sector %"
1542 PRId64 ": %s", sector_num - bs_offset,
1543 strerror(-ret));
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001544 goto out;
aliguori93c65b42009-04-05 17:40:43 +00001545 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001546 /* If the output image is zero initialized, we are not working
1547 * on a shared base and the input is zero we can skip the next
1548 * n1 sectors */
1549 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001550 sector_num += n1;
1551 continue;
1552 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001553 /* If the output image is being created as a copy on write
1554 * image, assume that sectors which are unallocated in the
1555 * input image are present in both the output's and input's
1556 * base images (no need to copy them). */
1557 if (out_baseimg) {
1558 if (!(ret & BDRV_BLOCK_DATA)) {
1559 sector_num += n1;
1560 continue;
1561 }
1562 /* The next 'n1' sectors are allocated in the input image.
1563 * Copy only those as they may be followed by unallocated
1564 * sectors. */
1565 nb_sectors = n1;
1566 }
1567 /* avoid redundant callouts to get_block_status */
1568 sector_num_next_status = sector_num + n1;
thsf58c7b32008-06-05 21:53:49 +00001569 }
1570
Peter Lievenf2521c92013-11-27 11:07:06 +01001571 n = MIN(nb_sectors, bufsectors);
Peter Lieven13c28af2013-11-27 11:07:01 +01001572 n = MIN(n, bs_sectors - (sector_num - bs_offset));
1573 n1 = n;
1574
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001575 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1576 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001577 error_report("error while reading sector %" PRId64 ": %s",
1578 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001579 goto out;
1580 }
bellardea2384d2004-08-01 21:59:26 +00001581 /* NOTE: at the same time we convert, we do not write zero
1582 sectors to have a chance to compress the image. Ideally, we
1583 should add a specific call to have the info to go faster */
1584 buf1 = buf;
1585 while (n > 0) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02001586 if (!has_zero_init ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001587 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001588 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1589 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001590 error_report("error while writing sector %" PRId64
1591 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001592 goto out;
1593 }
bellardea2384d2004-08-01 21:59:26 +00001594 }
1595 sector_num += n1;
1596 n -= n1;
1597 buf1 += n1 * 512;
1598 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001599 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
bellardea2384d2004-08-01 21:59:26 +00001600 }
1601 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001602out:
Peter Lieven13c28af2013-11-27 11:07:01 +01001603 if (!ret) {
1604 qemu_progress_print(100, 0);
1605 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001606 qemu_progress_end();
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001607 free_option_parameters(create_options);
1608 free_option_parameters(param);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001609 qemu_vfree(buf);
Wenchao Xiaef806542013-12-04 17:10:57 +08001610 if (sn_opts) {
1611 qemu_opts_del(sn_opts);
1612 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001613 if (out_bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001614 bdrv_unref(out_bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001615 }
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001616 if (bs) {
1617 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1618 if (bs[bs_i]) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001619 bdrv_unref(bs[bs_i]);
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001620 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001621 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001622 g_free(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001623 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001624 if (ret) {
1625 return 1;
1626 }
bellardea2384d2004-08-01 21:59:26 +00001627 return 0;
1628}
1629
bellard57d1a2b2004-08-03 21:15:11 +00001630
bellardfaea38e2006-08-05 21:31:00 +00001631static void dump_snapshots(BlockDriverState *bs)
1632{
1633 QEMUSnapshotInfo *sn_tab, *sn;
1634 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00001635
1636 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1637 if (nb_sns <= 0)
1638 return;
1639 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08001640 bdrv_snapshot_dump(fprintf, stdout, NULL);
1641 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001642 for(i = 0; i < nb_sns; i++) {
1643 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08001644 bdrv_snapshot_dump(fprintf, stdout, sn);
1645 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001646 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001647 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001648}
1649
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001650static void dump_json_image_info_list(ImageInfoList *list)
1651{
1652 Error *errp = NULL;
1653 QString *str;
1654 QmpOutputVisitor *ov = qmp_output_visitor_new();
1655 QObject *obj;
1656 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1657 &list, NULL, &errp);
1658 obj = qmp_output_get_qobject(ov);
1659 str = qobject_to_json_pretty(obj);
1660 assert(str != NULL);
1661 printf("%s\n", qstring_get_str(str));
1662 qobject_decref(obj);
1663 qmp_output_visitor_cleanup(ov);
1664 QDECREF(str);
1665}
1666
Benoît Canetc054b3f2012-09-05 13:09:02 +02001667static void dump_json_image_info(ImageInfo *info)
1668{
1669 Error *errp = NULL;
1670 QString *str;
1671 QmpOutputVisitor *ov = qmp_output_visitor_new();
1672 QObject *obj;
1673 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1674 &info, NULL, &errp);
1675 obj = qmp_output_get_qobject(ov);
1676 str = qobject_to_json_pretty(obj);
1677 assert(str != NULL);
1678 printf("%s\n", qstring_get_str(str));
1679 qobject_decref(obj);
1680 qmp_output_visitor_cleanup(ov);
1681 QDECREF(str);
1682}
1683
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001684static void dump_human_image_info_list(ImageInfoList *list)
1685{
1686 ImageInfoList *elem;
1687 bool delim = false;
1688
1689 for (elem = list; elem; elem = elem->next) {
1690 if (delim) {
1691 printf("\n");
1692 }
1693 delim = true;
1694
Wenchao Xia5b917042013-05-25 11:09:45 +08001695 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001696 }
1697}
1698
1699static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1700{
1701 return strcmp(a, b) == 0;
1702}
1703
1704/**
1705 * Open an image file chain and return an ImageInfoList
1706 *
1707 * @filename: topmost image filename
1708 * @fmt: topmost image format (may be NULL to autodetect)
1709 * @chain: true - enumerate entire backing file chain
1710 * false - only topmost image file
1711 *
1712 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1713 * image file. If there was an error a message will have been printed to
1714 * stderr.
1715 */
1716static ImageInfoList *collect_image_info_list(const char *filename,
1717 const char *fmt,
1718 bool chain)
1719{
1720 ImageInfoList *head = NULL;
1721 ImageInfoList **last = &head;
1722 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08001723 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001724
1725 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1726
1727 while (filename) {
1728 BlockDriverState *bs;
1729 ImageInfo *info;
1730 ImageInfoList *elem;
1731
1732 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1733 error_report("Backing file '%s' creates an infinite loop.",
1734 filename);
1735 goto err;
1736 }
1737 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1738
1739 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001740 false, false);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001741 if (!bs) {
1742 goto err;
1743 }
1744
Wenchao Xia43526ec2013-06-06 12:27:58 +08001745 bdrv_query_image_info(bs, &info, &err);
1746 if (error_is_set(&err)) {
1747 error_report("%s", error_get_pretty(err));
1748 error_free(err);
1749 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08001750 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001751
1752 elem = g_new0(ImageInfoList, 1);
1753 elem->value = info;
1754 *last = elem;
1755 last = &elem->next;
1756
Fam Zheng4f6fd342013-08-23 09:14:47 +08001757 bdrv_unref(bs);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001758
1759 filename = fmt = NULL;
1760 if (chain) {
1761 if (info->has_full_backing_filename) {
1762 filename = info->full_backing_filename;
1763 } else if (info->has_backing_filename) {
1764 filename = info->backing_filename;
1765 }
1766 if (info->has_backing_filename_format) {
1767 fmt = info->backing_filename_format;
1768 }
1769 }
1770 }
1771 g_hash_table_destroy(filenames);
1772 return head;
1773
1774err:
1775 qapi_free_ImageInfoList(head);
1776 g_hash_table_destroy(filenames);
1777 return NULL;
1778}
1779
Benoît Canetc054b3f2012-09-05 13:09:02 +02001780static int img_info(int argc, char **argv)
1781{
1782 int c;
1783 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001784 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001785 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001786 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001787
bellardea2384d2004-08-01 21:59:26 +00001788 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001789 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001790 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001791 int option_index = 0;
1792 static const struct option long_options[] = {
1793 {"help", no_argument, 0, 'h'},
1794 {"format", required_argument, 0, 'f'},
1795 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001796 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001797 {0, 0, 0, 0}
1798 };
1799 c = getopt_long(argc, argv, "f:h",
1800 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001801 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001802 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001803 }
bellardea2384d2004-08-01 21:59:26 +00001804 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001805 case '?':
bellardea2384d2004-08-01 21:59:26 +00001806 case 'h':
1807 help();
1808 break;
1809 case 'f':
1810 fmt = optarg;
1811 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001812 case OPTION_OUTPUT:
1813 output = optarg;
1814 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001815 case OPTION_BACKING_CHAIN:
1816 chain = true;
1817 break;
bellardea2384d2004-08-01 21:59:26 +00001818 }
1819 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02001820 if (optind != argc - 1) {
bellardea2384d2004-08-01 21:59:26 +00001821 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001822 }
bellardea2384d2004-08-01 21:59:26 +00001823 filename = argv[optind++];
1824
Benoît Canetc054b3f2012-09-05 13:09:02 +02001825 if (output && !strcmp(output, "json")) {
1826 output_format = OFORMAT_JSON;
1827 } else if (output && !strcmp(output, "human")) {
1828 output_format = OFORMAT_HUMAN;
1829 } else if (output) {
1830 error_report("--output must be used with human or json as argument.");
1831 return 1;
1832 }
1833
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001834 list = collect_image_info_list(filename, fmt, chain);
1835 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001836 return 1;
1837 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001838
Benoît Canetc054b3f2012-09-05 13:09:02 +02001839 switch (output_format) {
1840 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001841 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001842 break;
1843 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001844 if (chain) {
1845 dump_json_image_info_list(list);
1846 } else {
1847 dump_json_image_info(list->value);
1848 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001849 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001850 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001851
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001852 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00001853 return 0;
1854}
1855
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001856
1857typedef struct MapEntry {
1858 int flags;
1859 int depth;
1860 int64_t start;
1861 int64_t length;
1862 int64_t offset;
1863 BlockDriverState *bs;
1864} MapEntry;
1865
1866static void dump_map_entry(OutputFormat output_format, MapEntry *e,
1867 MapEntry *next)
1868{
1869 switch (output_format) {
1870 case OFORMAT_HUMAN:
1871 if ((e->flags & BDRV_BLOCK_DATA) &&
1872 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
1873 error_report("File contains external, encrypted or compressed clusters.");
1874 exit(1);
1875 }
1876 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
1877 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
1878 e->start, e->length, e->offset, e->bs->filename);
1879 }
1880 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
1881 * Modify the flags here to allow more coalescing.
1882 */
1883 if (next &&
1884 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
1885 next->flags &= ~BDRV_BLOCK_DATA;
1886 next->flags |= BDRV_BLOCK_ZERO;
1887 }
1888 break;
1889 case OFORMAT_JSON:
1890 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
1891 " \"zero\": %s, \"data\": %s",
1892 (e->start == 0 ? "[" : ",\n"),
1893 e->start, e->length, e->depth,
1894 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
1895 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
1896 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02001897 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001898 }
1899 putchar('}');
1900
1901 if (!next) {
1902 printf("]\n");
1903 }
1904 break;
1905 }
1906}
1907
1908static int get_block_status(BlockDriverState *bs, int64_t sector_num,
1909 int nb_sectors, MapEntry *e)
1910{
1911 int64_t ret;
1912 int depth;
1913
1914 /* As an optimization, we could cache the current range of unallocated
1915 * clusters in each file of the chain, and avoid querying the same
1916 * range repeatedly.
1917 */
1918
1919 depth = 0;
1920 for (;;) {
1921 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
1922 if (ret < 0) {
1923 return ret;
1924 }
1925 assert(nb_sectors);
1926 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
1927 break;
1928 }
1929 bs = bs->backing_hd;
1930 if (bs == NULL) {
1931 ret = 0;
1932 break;
1933 }
1934
1935 depth++;
1936 }
1937
1938 e->start = sector_num * BDRV_SECTOR_SIZE;
1939 e->length = nb_sectors * BDRV_SECTOR_SIZE;
1940 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
1941 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
1942 e->depth = depth;
1943 e->bs = bs;
1944 return 0;
1945}
1946
1947static int img_map(int argc, char **argv)
1948{
1949 int c;
1950 OutputFormat output_format = OFORMAT_HUMAN;
1951 BlockDriverState *bs;
1952 const char *filename, *fmt, *output;
1953 int64_t length;
1954 MapEntry curr = { .length = 0 }, next;
1955 int ret = 0;
1956
1957 fmt = NULL;
1958 output = NULL;
1959 for (;;) {
1960 int option_index = 0;
1961 static const struct option long_options[] = {
1962 {"help", no_argument, 0, 'h'},
1963 {"format", required_argument, 0, 'f'},
1964 {"output", required_argument, 0, OPTION_OUTPUT},
1965 {0, 0, 0, 0}
1966 };
1967 c = getopt_long(argc, argv, "f:h",
1968 long_options, &option_index);
1969 if (c == -1) {
1970 break;
1971 }
1972 switch (c) {
1973 case '?':
1974 case 'h':
1975 help();
1976 break;
1977 case 'f':
1978 fmt = optarg;
1979 break;
1980 case OPTION_OUTPUT:
1981 output = optarg;
1982 break;
1983 }
1984 }
1985 if (optind >= argc) {
1986 help();
1987 }
1988 filename = argv[optind++];
1989
1990 if (output && !strcmp(output, "json")) {
1991 output_format = OFORMAT_JSON;
1992 } else if (output && !strcmp(output, "human")) {
1993 output_format = OFORMAT_HUMAN;
1994 } else if (output) {
1995 error_report("--output must be used with human or json as argument.");
1996 return 1;
1997 }
1998
1999 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS, true, false);
2000 if (!bs) {
2001 return 1;
2002 }
2003
2004 if (output_format == OFORMAT_HUMAN) {
2005 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2006 }
2007
2008 length = bdrv_getlength(bs);
2009 while (curr.start + curr.length < length) {
2010 int64_t nsectors_left;
2011 int64_t sector_num;
2012 int n;
2013
2014 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2015
2016 /* Probe up to 1 GiB at a time. */
2017 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2018 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2019 ret = get_block_status(bs, sector_num, n, &next);
2020
2021 if (ret < 0) {
2022 error_report("Could not read file metadata: %s", strerror(-ret));
2023 goto out;
2024 }
2025
2026 if (curr.length != 0 && curr.flags == next.flags &&
2027 curr.depth == next.depth &&
2028 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2029 curr.offset + curr.length == next.offset)) {
2030 curr.length += next.length;
2031 continue;
2032 }
2033
2034 if (curr.length > 0) {
2035 dump_map_entry(output_format, &curr, &next);
2036 }
2037 curr = next;
2038 }
2039
2040 dump_map_entry(output_format, &curr, NULL);
2041
2042out:
2043 bdrv_unref(bs);
2044 return ret < 0;
2045}
2046
aliguorif7b4a942009-01-07 17:40:15 +00002047#define SNAPSHOT_LIST 1
2048#define SNAPSHOT_CREATE 2
2049#define SNAPSHOT_APPLY 3
2050#define SNAPSHOT_DELETE 4
2051
Stuart Brady153859b2009-06-07 00:42:17 +01002052static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002053{
2054 BlockDriverState *bs;
2055 QEMUSnapshotInfo sn;
2056 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002057 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002058 int action = 0;
2059 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002060 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002061 Error *err = NULL;
aliguorif7b4a942009-01-07 17:40:15 +00002062
Kevin Wolf710da702011-01-10 12:33:02 +01002063 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002064 /* Parse commandline parameters */
2065 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002066 c = getopt(argc, argv, "la:c:d:hq");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002067 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002068 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002069 }
aliguorif7b4a942009-01-07 17:40:15 +00002070 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002071 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002072 case 'h':
2073 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002074 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002075 case 'l':
2076 if (action) {
2077 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002078 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002079 }
2080 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002081 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002082 break;
2083 case 'a':
2084 if (action) {
2085 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002086 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002087 }
2088 action = SNAPSHOT_APPLY;
2089 snapshot_name = optarg;
2090 break;
2091 case 'c':
2092 if (action) {
2093 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002094 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002095 }
2096 action = SNAPSHOT_CREATE;
2097 snapshot_name = optarg;
2098 break;
2099 case 'd':
2100 if (action) {
2101 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002102 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002103 }
2104 action = SNAPSHOT_DELETE;
2105 snapshot_name = optarg;
2106 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002107 case 'q':
2108 quiet = true;
2109 break;
aliguorif7b4a942009-01-07 17:40:15 +00002110 }
2111 }
2112
Kevin Wolffc11eb22013-08-05 10:53:04 +02002113 if (optind != argc - 1) {
aliguorif7b4a942009-01-07 17:40:15 +00002114 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002115 }
aliguorif7b4a942009-01-07 17:40:15 +00002116 filename = argv[optind++];
2117
2118 /* Open the image */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002119 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002120 if (!bs) {
2121 return 1;
2122 }
aliguorif7b4a942009-01-07 17:40:15 +00002123
2124 /* Perform the requested action */
2125 switch(action) {
2126 case SNAPSHOT_LIST:
2127 dump_snapshots(bs);
2128 break;
2129
2130 case SNAPSHOT_CREATE:
2131 memset(&sn, 0, sizeof(sn));
2132 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2133
2134 qemu_gettimeofday(&tv);
2135 sn.date_sec = tv.tv_sec;
2136 sn.date_nsec = tv.tv_usec * 1000;
2137
2138 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002139 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002140 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002141 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002142 }
aliguorif7b4a942009-01-07 17:40:15 +00002143 break;
2144
2145 case SNAPSHOT_APPLY:
2146 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002147 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002148 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002149 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002150 }
aliguorif7b4a942009-01-07 17:40:15 +00002151 break;
2152
2153 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002154 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2155 if (error_is_set(&err)) {
2156 error_report("Could not delete snapshot '%s': (%s)",
2157 snapshot_name, error_get_pretty(err));
2158 error_free(err);
2159 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002160 }
aliguorif7b4a942009-01-07 17:40:15 +00002161 break;
2162 }
2163
2164 /* Cleanup */
Fam Zheng4f6fd342013-08-23 09:14:47 +08002165 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002166 if (ret) {
2167 return 1;
2168 }
Stuart Brady153859b2009-06-07 00:42:17 +01002169 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002170}
2171
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002172static int img_rebase(int argc, char **argv)
2173{
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002174 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01002175 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002176 char *filename;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002177 const char *fmt, *cache, *out_basefmt, *out_baseimg;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002178 int c, flags, ret;
2179 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002180 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002181 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002182 Error *local_err = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002183
2184 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002185 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002186 cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002187 out_baseimg = NULL;
2188 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002189 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002190 c = getopt(argc, argv, "uhf:F:b:pt:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002191 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002192 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002193 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002194 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002195 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002196 case 'h':
2197 help();
2198 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002199 case 'f':
2200 fmt = optarg;
2201 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002202 case 'F':
2203 out_basefmt = optarg;
2204 break;
2205 case 'b':
2206 out_baseimg = optarg;
2207 break;
2208 case 'u':
2209 unsafe = 1;
2210 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002211 case 'p':
2212 progress = 1;
2213 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002214 case 't':
2215 cache = optarg;
2216 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002217 case 'q':
2218 quiet = true;
2219 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002220 }
2221 }
2222
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002223 if (quiet) {
2224 progress = 0;
2225 }
2226
Kevin Wolffc11eb22013-08-05 10:53:04 +02002227 if ((optind != argc - 1) || (!unsafe && !out_baseimg)) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002228 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002229 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002230 filename = argv[optind++];
2231
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002232 qemu_progress_init(progress, 2.0);
2233 qemu_progress_print(0, 100);
2234
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002235 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01002236 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002237 if (ret < 0) {
2238 error_report("Invalid cache option: %s", cache);
2239 return -1;
2240 }
2241
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002242 /*
2243 * Open the images.
2244 *
2245 * Ignore the old backing file for unsafe rebase in case we want to correct
2246 * the reference to a renamed or moved backing file.
2247 */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002248 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002249 if (!bs) {
2250 return 1;
2251 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002252
2253 /* Find the right drivers for the backing files */
2254 old_backing_drv = NULL;
2255 new_backing_drv = NULL;
2256
2257 if (!unsafe && bs->backing_format[0] != '\0') {
2258 old_backing_drv = bdrv_find_format(bs->backing_format);
2259 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002260 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002261 ret = -1;
2262 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002263 }
2264 }
2265
2266 if (out_basefmt != NULL) {
2267 new_backing_drv = bdrv_find_format(out_basefmt);
2268 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002269 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002270 ret = -1;
2271 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002272 }
2273 }
2274
2275 /* For safe rebasing we need to compare old and new backing file */
2276 if (unsafe) {
2277 /* Make the compiler happy */
2278 bs_old_backing = NULL;
2279 bs_new_backing = NULL;
2280 } else {
2281 char backing_name[1024];
2282
2283 bs_old_backing = bdrv_new("old_backing");
2284 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002285 ret = bdrv_open(bs_old_backing, backing_name, NULL, BDRV_O_FLAGS,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002286 old_backing_drv, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002287 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002288 error_report("Could not open old backing file '%s': %s",
2289 backing_name, error_get_pretty(local_err));
2290 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002291 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002292 }
Alex Bligha6166732012-10-16 13:46:18 +01002293 if (out_baseimg[0]) {
2294 bs_new_backing = bdrv_new("new_backing");
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002295 ret = bdrv_open(bs_new_backing, out_baseimg, NULL, BDRV_O_FLAGS,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002296 new_backing_drv, &local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002297 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002298 error_report("Could not open new backing file '%s': %s",
2299 out_baseimg, error_get_pretty(local_err));
2300 error_free(local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002301 goto out;
2302 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002303 }
2304 }
2305
2306 /*
2307 * Check each unallocated cluster in the COW file. If it is unallocated,
2308 * accesses go to the backing file. We must therefore compare this cluster
2309 * in the old and new backing file, and if they differ we need to copy it
2310 * from the old backing file into the COW file.
2311 *
2312 * If qemu-img crashes during this step, no harm is done. The content of
2313 * the image is the same as the original one at any time.
2314 */
2315 if (!unsafe) {
2316 uint64_t num_sectors;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002317 uint64_t old_backing_num_sectors;
Alex Bligha6166732012-10-16 13:46:18 +01002318 uint64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002319 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02002320 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08002321 uint8_t * buf_old;
2322 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02002323 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08002324
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002325 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2326 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002327
2328 bdrv_get_geometry(bs, &num_sectors);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002329 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
Alex Bligha6166732012-10-16 13:46:18 +01002330 if (bs_new_backing) {
2331 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
2332 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002333
Kevin Wolf1f710492012-10-12 14:29:18 +02002334 if (num_sectors != 0) {
2335 local_progress = (float)100 /
2336 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2337 }
2338
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002339 for (sector = 0; sector < num_sectors; sector += n) {
2340
2341 /* How many sectors can we handle with the next read? */
2342 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2343 n = (IO_BUF_SIZE / 512);
2344 } else {
2345 n = num_sectors - sector;
2346 }
2347
2348 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02002349 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02002350 if (ret < 0) {
2351 error_report("error while reading image metadata: %s",
2352 strerror(-ret));
2353 goto out;
2354 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02002355 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002356 continue;
2357 }
2358
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002359 /*
2360 * Read old and new backing file and take into consideration that
2361 * backing files may be smaller than the COW image.
2362 */
2363 if (sector >= old_backing_num_sectors) {
2364 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2365 } else {
2366 if (sector + n > old_backing_num_sectors) {
2367 n = old_backing_num_sectors - sector;
2368 }
2369
2370 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2371 if (ret < 0) {
2372 error_report("error while reading from old backing file");
2373 goto out;
2374 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002375 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002376
Alex Bligha6166732012-10-16 13:46:18 +01002377 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002378 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2379 } else {
2380 if (sector + n > new_backing_num_sectors) {
2381 n = new_backing_num_sectors - sector;
2382 }
2383
2384 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2385 if (ret < 0) {
2386 error_report("error while reading from new backing file");
2387 goto out;
2388 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002389 }
2390
2391 /* If they differ, we need to write to the COW file */
2392 uint64_t written = 0;
2393
2394 while (written < n) {
2395 int pnum;
2396
2397 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01002398 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002399 {
2400 ret = bdrv_write(bs, sector + written,
2401 buf_old + written * 512, pnum);
2402 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002403 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002404 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002405 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002406 }
2407 }
2408
2409 written += pnum;
2410 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002411 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002412 }
TeLeMand6771bf2010-02-08 16:20:00 +08002413
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002414 qemu_vfree(buf_old);
2415 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002416 }
2417
2418 /*
2419 * Change the backing file. All clusters that are different from the old
2420 * backing file are overwritten in the COW file now, so the visible content
2421 * doesn't change when we switch the backing file.
2422 */
Alex Bligha6166732012-10-16 13:46:18 +01002423 if (out_baseimg && *out_baseimg) {
2424 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2425 } else {
2426 ret = bdrv_change_backing_file(bs, NULL, NULL);
2427 }
2428
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002429 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002430 error_report("Could not change the backing file to '%s': No "
2431 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002432 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002433 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002434 out_baseimg, strerror(-ret));
2435 }
2436
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002437 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002438 /*
2439 * TODO At this point it is possible to check if any clusters that are
2440 * allocated in the COW file are the same in the backing file. If so, they
2441 * could be dropped from the COW file. Don't do this before switching the
2442 * backing file, in case of a crash this would lead to corruption.
2443 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002444out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002445 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002446 /* Cleanup */
2447 if (!unsafe) {
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002448 if (bs_old_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002449 bdrv_unref(bs_old_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002450 }
2451 if (bs_new_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002452 bdrv_unref(bs_new_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002453 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002454 }
2455
Fam Zheng4f6fd342013-08-23 09:14:47 +08002456 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002457 if (ret) {
2458 return 1;
2459 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002460 return 0;
2461}
2462
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002463static int img_resize(int argc, char **argv)
2464{
2465 int c, ret, relative;
2466 const char *filename, *fmt, *size;
2467 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002468 bool quiet = false;
Jes Sorensen2a819982010-12-06 17:08:31 +01002469 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002470 QemuOpts *param;
2471 static QemuOptsList resize_options = {
2472 .name = "resize_options",
2473 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2474 .desc = {
2475 {
2476 .name = BLOCK_OPT_SIZE,
2477 .type = QEMU_OPT_SIZE,
2478 .help = "Virtual disk size"
2479 }, {
2480 /* end of list */
2481 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002482 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002483 };
2484
Kevin Wolfe80fec72011-04-29 10:58:12 +02002485 /* Remove size from argv manually so that negative numbers are not treated
2486 * as options by getopt. */
2487 if (argc < 3) {
2488 help();
2489 return 1;
2490 }
2491
2492 size = argv[--argc];
2493
2494 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002495 fmt = NULL;
2496 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002497 c = getopt(argc, argv, "f:hq");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002498 if (c == -1) {
2499 break;
2500 }
2501 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002502 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002503 case 'h':
2504 help();
2505 break;
2506 case 'f':
2507 fmt = optarg;
2508 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002509 case 'q':
2510 quiet = true;
2511 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002512 }
2513 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002514 if (optind != argc - 1) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002515 help();
2516 }
2517 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002518
2519 /* Choose grow, shrink, or absolute resize mode */
2520 switch (size[0]) {
2521 case '+':
2522 relative = 1;
2523 size++;
2524 break;
2525 case '-':
2526 relative = -1;
2527 size++;
2528 break;
2529 default:
2530 relative = 0;
2531 break;
2532 }
2533
2534 /* Parse size */
Dong Xu Wange478b442012-12-06 14:47:22 +08002535 param = qemu_opts_create_nofail(&resize_options);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002536 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002537 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002538 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002539 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002540 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002541 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002542 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2543 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002544
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002545 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002546 if (!bs) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002547 ret = -1;
2548 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002549 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002550
2551 if (relative) {
2552 total_size = bdrv_getlength(bs) + n * relative;
2553 } else {
2554 total_size = n;
2555 }
2556 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002557 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002558 ret = -1;
2559 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002560 }
2561
2562 ret = bdrv_truncate(bs, total_size);
2563 switch (ret) {
2564 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002565 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002566 break;
2567 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002568 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002569 break;
2570 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002571 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002572 break;
2573 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002574 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002575 break;
2576 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002577out:
Jes Sorensen2a819982010-12-06 17:08:31 +01002578 if (bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002579 bdrv_unref(bs);
Jes Sorensen2a819982010-12-06 17:08:31 +01002580 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002581 if (ret) {
2582 return 1;
2583 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002584 return 0;
2585}
2586
Max Reitz6f176b42013-09-03 10:09:50 +02002587static int img_amend(int argc, char **argv)
2588{
2589 int c, ret = 0;
2590 char *options = NULL;
2591 QEMUOptionParameter *create_options = NULL, *options_param = NULL;
2592 const char *fmt = NULL, *filename;
2593 bool quiet = false;
2594 BlockDriverState *bs = NULL;
2595
2596 for (;;) {
2597 c = getopt(argc, argv, "hqf:o:");
2598 if (c == -1) {
2599 break;
2600 }
2601
2602 switch (c) {
2603 case 'h':
2604 case '?':
2605 help();
2606 break;
2607 case 'o':
2608 options = optarg;
2609 break;
2610 case 'f':
2611 fmt = optarg;
2612 break;
2613 case 'q':
2614 quiet = true;
2615 break;
2616 }
2617 }
2618
2619 if (optind != argc - 1) {
2620 help();
2621 }
2622
2623 if (!options) {
2624 help();
2625 }
2626
2627 filename = argv[argc - 1];
2628
2629 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
2630 if (!bs) {
2631 error_report("Could not open image '%s'", filename);
2632 ret = -1;
2633 goto out;
2634 }
2635
2636 fmt = bs->drv->format_name;
2637
2638 if (is_help_option(options)) {
2639 ret = print_block_option_help(filename, fmt);
2640 goto out;
2641 }
2642
2643 create_options = append_option_parameters(create_options,
2644 bs->drv->create_options);
2645 options_param = parse_option_parameters(options, create_options,
2646 options_param);
2647 if (options_param == NULL) {
2648 error_report("Invalid options for file format '%s'", fmt);
2649 ret = -1;
2650 goto out;
2651 }
2652
2653 ret = bdrv_amend_options(bs, options_param);
2654 if (ret < 0) {
2655 error_report("Error while amending options: %s", strerror(-ret));
2656 goto out;
2657 }
2658
2659out:
2660 if (bs) {
2661 bdrv_unref(bs);
2662 }
2663 free_option_parameters(create_options);
2664 free_option_parameters(options_param);
2665 if (ret) {
2666 return 1;
2667 }
2668 return 0;
2669}
2670
Anthony Liguoric227f092009-10-01 16:12:16 -05002671static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002672#define DEF(option, callback, arg_string) \
2673 { option, callback },
2674#include "qemu-img-cmds.h"
2675#undef DEF
2676#undef GEN_DOCS
2677 { NULL, NULL, },
2678};
2679
bellardea2384d2004-08-01 21:59:26 +00002680int main(int argc, char **argv)
2681{
Anthony Liguoric227f092009-10-01 16:12:16 -05002682 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002683 const char *cmdname;
bellardea2384d2004-08-01 21:59:26 +00002684
MORITA Kazutaka526eda12013-07-23 17:30:11 +09002685#ifdef CONFIG_POSIX
2686 signal(SIGPIPE, SIG_IGN);
2687#endif
2688
Kevin Wolf53f76e52010-12-16 15:10:32 +01002689 error_set_progname(argv[0]);
2690
Paolo Bonzini2592c592012-11-03 18:10:17 +01002691 qemu_init_main_loop();
bellardea2384d2004-08-01 21:59:26 +00002692 bdrv_init();
2693 if (argc < 2)
2694 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002695 cmdname = argv[1];
aurel328f9b1572009-02-09 18:14:31 +00002696 argc--; argv++;
Stuart Brady153859b2009-06-07 00:42:17 +01002697
2698 /* find the command */
2699 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2700 if (!strcmp(cmdname, cmd->name)) {
2701 return cmd->handler(argc, argv);
2702 }
bellardea2384d2004-08-01 21:59:26 +00002703 }
Stuart Brady153859b2009-06-07 00:42:17 +01002704
2705 /* not found */
2706 help();
bellardea2384d2004-08-01 21:59:26 +00002707 return 0;
2708}