blob: 09e7e72f5ac4c3fa4ac5eb343734bd735a68eaea [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Benoît Canetc054b3f2012-09-05 13:09:02 +020024#include "qapi-visit.h"
25#include "qapi/qmp-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010026#include "qapi/qmp/qjson.h"
pbrookfaf07962007-11-11 02:51:17 +000027#include "qemu-common.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010028#include "qemu/option.h"
29#include "qemu/error-report.h"
30#include "qemu/osdep.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010031#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020032#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010033#include "block/block_int.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080034#include "block/qapi.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020035#include <getopt.h>
bellarde8445332006-06-14 15:32:10 +000036
Jeff Cody5f6979c2014-04-28 14:37:18 -040037#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION \
38 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
39
Anthony Liguoric227f092009-10-01 16:12:16 -050040typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010041 const char *name;
42 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050043} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010044
Federico Simoncelli8599ea42013-01-28 06:59:47 -050045enum {
46 OPTION_OUTPUT = 256,
47 OPTION_BACKING_CHAIN = 257,
48};
49
50typedef enum OutputFormat {
51 OFORMAT_JSON,
52 OFORMAT_HUMAN,
53} OutputFormat;
54
aurel32137519c2008-11-30 19:12:49 +000055/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
Stefan Hajnocziadfe0782010-04-13 10:29:35 +010056#define BDRV_O_FLAGS BDRV_O_CACHE_WB
Federico Simoncelli661a0f72011-06-20 12:48:19 -040057#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000058
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010059static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000060{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010061 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000062}
63
Fam Zhengac1307a2014-04-22 13:36:11 +080064static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
65{
66 va_list ap;
67
68 error_printf("qemu-img: ");
69
70 va_start(ap, fmt);
71 error_vprintf(fmt, ap);
72 va_end(ap);
73
74 error_printf("\nTry 'qemu-img --help' for more information\n");
75 exit(EXIT_FAILURE);
76}
77
blueswir1d2c639d2009-01-24 18:19:25 +000078/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +080079static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +000080{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010081 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -040082 QEMU_IMG_VERSION
malc3f020d72010-02-08 12:04:56 +030083 "usage: qemu-img command [command options]\n"
84 "QEMU disk image utility\n"
85 "\n"
86 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +010087#define DEF(option, callback, arg_string) \
88 " " arg_string "\n"
89#include "qemu-img-cmds.h"
90#undef DEF
91#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +030092 "\n"
93 "Command parameters:\n"
94 " 'filename' is a disk image filename\n"
95 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -040096 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +080097 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
98 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +010099 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
100 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300101 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200102 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
103 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
104 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300105 " 'output_filename' is the destination disk image filename\n"
106 " 'output_fmt' is the destination format\n"
107 " 'options' is a comma separated list of format specific options in a\n"
108 " name=value format. Use -o ? for an overview of the options supported by the\n"
109 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800110 " 'snapshot_param' is param used for internal snapshot, format\n"
111 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
112 " '[ID_OR_NAME]'\n"
113 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
114 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300115 " '-c' indicates that target image must be compressed (qcow format only)\n"
116 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
117 " match exactly. The image doesn't need a working backing file before\n"
118 " rebasing in this case (useful for renaming the backing file)\n"
119 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200120 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100121 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200122 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
123 " contain only zeros for qemu-img to create a sparse image during\n"
124 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
125 " unallocated or zero sectors, and the destination image will always be\n"
126 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200127 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100128 " '-n' skips the target volume creation (useful if the volume is created\n"
129 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300130 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200131 "Parameters to check subcommand:\n"
132 " '-r' tries to repair any inconsistencies that are found during the check.\n"
133 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
134 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200135 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200136 "\n"
malc3f020d72010-02-08 12:04:56 +0300137 "Parameters to snapshot subcommand:\n"
138 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
139 " '-a' applies a snapshot (revert disk to saved state)\n"
140 " '-c' creates a snapshot\n"
141 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100142 " '-l' lists all snapshots in the given image\n"
143 "\n"
144 "Parameters to compare subcommand:\n"
145 " '-f' first image format\n"
146 " '-F' second image format\n"
147 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100148
149 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100150 bdrv_iterate_format(format_print, NULL);
bellardea2384d2004-08-01 21:59:26 +0000151 printf("\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800152 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000153}
154
Stefan Weil7c30f652013-06-16 17:01:05 +0200155static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100156{
157 int ret = 0;
158 if (!quiet) {
159 va_list args;
160 va_start(args, fmt);
161 ret = vprintf(fmt, args);
162 va_end(args);
163 }
164 return ret;
165}
166
bellardea2384d2004-08-01 21:59:26 +0000167#if defined(WIN32)
168/* XXX: put correct support for win32 */
169static int read_password(char *buf, int buf_size)
170{
171 int c, i;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800172
bellardea2384d2004-08-01 21:59:26 +0000173 printf("Password: ");
174 fflush(stdout);
175 i = 0;
176 for(;;) {
177 c = getchar();
Chen Gangfdcf6e62014-07-06 16:43:33 +0800178 if (c < 0) {
179 buf[i] = '\0';
180 return -1;
181 } else if (c == '\n') {
bellardea2384d2004-08-01 21:59:26 +0000182 break;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800183 } else if (i < (buf_size - 1)) {
bellardea2384d2004-08-01 21:59:26 +0000184 buf[i++] = c;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800185 }
bellardea2384d2004-08-01 21:59:26 +0000186 }
187 buf[i] = '\0';
188 return 0;
189}
190
191#else
192
193#include <termios.h>
194
195static struct termios oldtty;
196
197static void term_exit(void)
198{
199 tcsetattr (0, TCSANOW, &oldtty);
200}
201
202static void term_init(void)
203{
204 struct termios tty;
205
206 tcgetattr (0, &tty);
207 oldtty = tty;
208
209 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
210 |INLCR|IGNCR|ICRNL|IXON);
211 tty.c_oflag |= OPOST;
212 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
213 tty.c_cflag &= ~(CSIZE|PARENB);
214 tty.c_cflag |= CS8;
215 tty.c_cc[VMIN] = 1;
216 tty.c_cc[VTIME] = 0;
ths3b46e622007-09-17 08:09:54 +0000217
bellardea2384d2004-08-01 21:59:26 +0000218 tcsetattr (0, TCSANOW, &tty);
219
220 atexit(term_exit);
221}
222
pbrook3f379ab2007-11-11 03:33:13 +0000223static int read_password(char *buf, int buf_size)
bellardea2384d2004-08-01 21:59:26 +0000224{
225 uint8_t ch;
226 int i, ret;
227
228 printf("password: ");
229 fflush(stdout);
230 term_init();
231 i = 0;
232 for(;;) {
233 ret = read(0, &ch, 1);
234 if (ret == -1) {
235 if (errno == EAGAIN || errno == EINTR) {
236 continue;
237 } else {
bellardea2384d2004-08-01 21:59:26 +0000238 break;
239 }
240 } else if (ret == 0) {
241 ret = -1;
242 break;
243 } else {
244 if (ch == '\r') {
245 ret = 0;
246 break;
247 }
248 if (i < (buf_size - 1))
249 buf[i++] = ch;
250 }
251 }
252 term_exit();
253 buf[i] = '\0';
254 printf("\n");
255 return ret;
256}
257#endif
258
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100259static int print_block_option_help(const char *filename, const char *fmt)
260{
261 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800262 QemuOptsList *create_opts = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100263
264 /* Find driver and parse its options */
265 drv = bdrv_find_format(fmt);
266 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100267 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100268 return 1;
269 }
270
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800271 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100272 if (filename) {
273 proto_drv = bdrv_find_protocol(filename, true);
274 if (!proto_drv) {
275 error_report("Unknown protocol '%s'", filename);
Chunyan Liu83d05212014-06-05 17:20:51 +0800276 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100277 return 1;
278 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800279 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100280 }
281
Chunyan Liu83d05212014-06-05 17:20:51 +0800282 qemu_opts_print_help(create_opts);
283 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100284 return 0;
285}
286
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200287static BlockBackend *img_open(const char *id, const char *filename,
288 const char *fmt, int flags,
289 bool require_io, bool quiet)
bellard75c23802004-08-27 21:28:58 +0000290{
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200291 BlockBackend *blk;
bellard75c23802004-08-27 21:28:58 +0000292 BlockDriverState *bs;
293 BlockDriver *drv;
294 char password[256];
Max Reitz34b5d2c2013-09-05 14:45:29 +0200295 Error *local_err = NULL;
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100296 int ret;
bellard75c23802004-08-27 21:28:58 +0000297
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200298 blk = blk_new_with_bs(id, &error_abort);
299 bs = blk_bs(blk);
Kevin Wolfad717132010-12-16 15:37:41 +0100300
bellard75c23802004-08-27 21:28:58 +0000301 if (fmt) {
302 drv = bdrv_find_format(fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900303 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100304 error_report("Unknown file format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900305 goto fail;
306 }
bellard75c23802004-08-27 21:28:58 +0000307 } else {
308 drv = NULL;
309 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100310
Max Reitzddf56362014-02-18 18:33:06 +0100311 ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100312 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200313 error_report("Could not open '%s': %s", filename,
314 error_get_pretty(local_err));
315 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900316 goto fail;
bellard75c23802004-08-27 21:28:58 +0000317 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100318
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100319 if (bdrv_is_encrypted(bs) && require_io) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100320 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900321 if (read_password(password, sizeof(password)) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100322 error_report("No password given");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900323 goto fail;
324 }
325 if (bdrv_set_key(bs, password) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100326 error_report("invalid password");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900327 goto fail;
328 }
bellard75c23802004-08-27 21:28:58 +0000329 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200330 return blk;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900331fail:
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200332 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900333 return NULL;
bellard75c23802004-08-27 21:28:58 +0000334}
335
Chunyan Liu83d05212014-06-05 17:20:51 +0800336static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100337 const char *base_filename,
338 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200339{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200340 if (base_filename) {
Chunyan Liu83d05212014-06-05 17:20:51 +0800341 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100342 error_report("Backing file not supported for file format '%s'",
343 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900344 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200345 }
346 }
347 if (base_fmt) {
Chunyan Liu83d05212014-06-05 17:20:51 +0800348 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100349 error_report("Backing file format not supported for file "
350 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900351 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200352 }
353 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900354 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200355}
356
bellardea2384d2004-08-01 21:59:26 +0000357static int img_create(int argc, char **argv)
358{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200359 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100360 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000361 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000362 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000363 const char *filename;
364 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200365 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200366 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100367 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000368
bellardea2384d2004-08-01 21:59:26 +0000369 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100370 c = getopt(argc, argv, "F:b:f:he6o:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100371 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000372 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100373 }
bellardea2384d2004-08-01 21:59:26 +0000374 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100375 case '?':
bellardea2384d2004-08-01 21:59:26 +0000376 case 'h':
377 help();
378 break;
aliguori9230eaf2009-03-28 17:55:19 +0000379 case 'F':
380 base_fmt = optarg;
381 break;
bellardea2384d2004-08-01 21:59:26 +0000382 case 'b':
383 base_filename = optarg;
384 break;
385 case 'f':
386 fmt = optarg;
387 break;
388 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200389 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100390 "encryption\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100391 goto fail;
thsd8871c52007-10-24 16:11:42 +0000392 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200393 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100394 "compat6\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100395 goto fail;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200396 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100397 if (!is_valid_option_list(optarg)) {
398 error_report("Invalid option list: %s", optarg);
399 goto fail;
400 }
401 if (!options) {
402 options = g_strdup(optarg);
403 } else {
404 char *old_options = options;
405 options = g_strdup_printf("%s,%s", options, optarg);
406 g_free(old_options);
407 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200408 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100409 case 'q':
410 quiet = true;
411 break;
bellardea2384d2004-08-01 21:59:26 +0000412 }
413 }
aliguori9230eaf2009-03-28 17:55:19 +0000414
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900415 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100416 filename = (optind < argc) ? argv[optind] : NULL;
417 if (options && has_help_option(options)) {
418 g_free(options);
419 return print_block_option_help(filename, fmt);
420 }
421
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100422 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800423 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100424 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100425 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900426
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100427 /* Get image size, if specified */
428 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100429 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100430 char *end;
431 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
432 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800433 if (sval == -ERANGE) {
434 error_report("Image size must be less than 8 EiB!");
435 } else {
436 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200437 "G, T, P or E suffixes for ");
438 error_report("kilobytes, megabytes, gigabytes, terabytes, "
439 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800440 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100441 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100442 }
443 img_size = (uint64_t)sval;
444 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200445 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800446 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200447 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100448
Luiz Capitulino9b375252012-11-30 10:52:05 -0200449 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100450 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100451 if (local_err) {
Max Reitzb70d8c22013-09-06 16:51:03 +0200452 error_report("%s: %s", filename, error_get_pretty(local_err));
Luiz Capitulino9b375252012-11-30 10:52:05 -0200453 error_free(local_err);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100454 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900455 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200456
Kevin Wolf77386bf2014-02-21 16:24:04 +0100457 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000458 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100459
460fail:
461 g_free(options);
462 return 1;
bellardea2384d2004-08-01 21:59:26 +0000463}
464
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100465static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500466{
Markus Armbruster4399c432014-04-25 16:50:32 +0200467 Error *local_err = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500468 QString *str;
469 QmpOutputVisitor *ov = qmp_output_visitor_new();
470 QObject *obj;
471 visit_type_ImageCheck(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +0200472 &check, NULL, &local_err);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500473 obj = qmp_output_get_qobject(ov);
474 str = qobject_to_json_pretty(obj);
475 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100476 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500477 qobject_decref(obj);
478 qmp_output_visitor_cleanup(ov);
479 QDECREF(str);
480}
481
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100482static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500483{
484 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100485 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500486 } else {
487 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100488 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
489 "Data may be corrupted, or further writes to the image "
490 "may corrupt it.\n",
491 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500492 }
493
494 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100495 qprintf(quiet,
496 "\n%" PRId64 " leaked clusters were found on the image.\n"
497 "This means waste of disk space, but no harm to data.\n",
498 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500499 }
500
501 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100502 qprintf(quiet,
503 "\n%" PRId64
504 " internal errors have occurred during the check.\n",
505 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500506 }
507 }
508
509 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100510 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
511 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
512 check->allocated_clusters, check->total_clusters,
513 check->allocated_clusters * 100.0 / check->total_clusters,
514 check->fragmented_clusters * 100.0 / check->allocated_clusters,
515 check->compressed_clusters * 100.0 /
516 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500517 }
518
519 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100520 qprintf(quiet,
521 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500522 }
523}
524
525static int collect_image_check(BlockDriverState *bs,
526 ImageCheck *check,
527 const char *filename,
528 const char *fmt,
529 int fix)
530{
531 int ret;
532 BdrvCheckResult result;
533
534 ret = bdrv_check(bs, &result, fix);
535 if (ret < 0) {
536 return ret;
537 }
538
539 check->filename = g_strdup(filename);
540 check->format = g_strdup(bdrv_get_format_name(bs));
541 check->check_errors = result.check_errors;
542 check->corruptions = result.corruptions;
543 check->has_corruptions = result.corruptions != 0;
544 check->leaks = result.leaks;
545 check->has_leaks = result.leaks != 0;
546 check->corruptions_fixed = result.corruptions_fixed;
547 check->has_corruptions_fixed = result.corruptions != 0;
548 check->leaks_fixed = result.leaks_fixed;
549 check->has_leaks_fixed = result.leaks != 0;
550 check->image_end_offset = result.image_end_offset;
551 check->has_image_end_offset = result.image_end_offset != 0;
552 check->total_clusters = result.bfi.total_clusters;
553 check->has_total_clusters = result.bfi.total_clusters != 0;
554 check->allocated_clusters = result.bfi.allocated_clusters;
555 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
556 check->fragmented_clusters = result.bfi.fragmented_clusters;
557 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100558 check->compressed_clusters = result.bfi.compressed_clusters;
559 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560
561 return 0;
562}
563
Kevin Wolfe076f332010-06-29 11:43:13 +0200564/*
565 * Checks an image for consistency. Exit codes:
566 *
Max Reitzd6635c42014-06-02 22:15:21 +0200567 * 0 - Check completed, image is good
568 * 1 - Check not completed because of internal errors
569 * 2 - Check completed, image is corrupted
570 * 3 - Check completed, image has leaked clusters, but is good otherwise
571 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200572 */
aliguori15859692009-04-21 23:11:53 +0000573static int img_check(int argc, char **argv)
574{
575 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500576 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200577 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200578 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000579 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200580 int fix = 0;
Stefan Hajnoczi058f8f12012-08-09 13:05:56 +0100581 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200582 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100583 bool quiet = false;
aliguori15859692009-04-21 23:11:53 +0000584
585 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500586 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200587 cache = BDRV_DEFAULT_CACHE;
aliguori15859692009-04-21 23:11:53 +0000588 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500589 int option_index = 0;
590 static const struct option long_options[] = {
591 {"help", no_argument, 0, 'h'},
592 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530593 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500594 {"output", required_argument, 0, OPTION_OUTPUT},
595 {0, 0, 0, 0}
596 };
Max Reitz40055952014-07-22 22:58:42 +0200597 c = getopt_long(argc, argv, "hf:r:T:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500598 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100599 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000600 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100601 }
aliguori15859692009-04-21 23:11:53 +0000602 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100603 case '?':
aliguori15859692009-04-21 23:11:53 +0000604 case 'h':
605 help();
606 break;
607 case 'f':
608 fmt = optarg;
609 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200610 case 'r':
611 flags |= BDRV_O_RDWR;
612
613 if (!strcmp(optarg, "leaks")) {
614 fix = BDRV_FIX_LEAKS;
615 } else if (!strcmp(optarg, "all")) {
616 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
617 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800618 error_exit("Unknown option value for -r "
619 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200620 }
621 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500622 case OPTION_OUTPUT:
623 output = optarg;
624 break;
Max Reitz40055952014-07-22 22:58:42 +0200625 case 'T':
626 cache = optarg;
627 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100628 case 'q':
629 quiet = true;
630 break;
aliguori15859692009-04-21 23:11:53 +0000631 }
632 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200633 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800634 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100635 }
aliguori15859692009-04-21 23:11:53 +0000636 filename = argv[optind++];
637
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500638 if (output && !strcmp(output, "json")) {
639 output_format = OFORMAT_JSON;
640 } else if (output && !strcmp(output, "human")) {
641 output_format = OFORMAT_HUMAN;
642 } else if (output) {
643 error_report("--output must be used with human or json as argument.");
644 return 1;
645 }
646
Max Reitz40055952014-07-22 22:58:42 +0200647 ret = bdrv_parse_cache_flags(cache, &flags);
648 if (ret < 0) {
649 error_report("Invalid source cache option: %s", cache);
650 return 1;
651 }
652
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200653 blk = img_open("image", filename, fmt, flags, true, quiet);
654 if (!blk) {
655 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900656 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200657 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500658
659 check = g_new0(ImageCheck, 1);
660 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200661
662 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200663 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200664 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500665 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200666 }
667
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500668 if (check->corruptions_fixed || check->leaks_fixed) {
669 int corruptions_fixed, leaks_fixed;
670
671 leaks_fixed = check->leaks_fixed;
672 corruptions_fixed = check->corruptions_fixed;
673
674 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100675 qprintf(quiet,
676 "The following inconsistencies were found and repaired:\n\n"
677 " %" PRId64 " leaked clusters\n"
678 " %" PRId64 " corruptions\n\n"
679 "Double checking the fixed image now...\n",
680 check->leaks_fixed,
681 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500682 }
683
684 ret = collect_image_check(bs, check, filename, fmt, 0);
685
686 check->leaks_fixed = leaks_fixed;
687 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200688 }
689
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500690 switch (output_format) {
691 case OFORMAT_HUMAN:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100692 dump_human_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500693 break;
694 case OFORMAT_JSON:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100695 dump_json_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500696 break;
697 }
698
699 if (ret || check->check_errors) {
700 ret = 1;
701 goto fail;
702 }
703
704 if (check->corruptions) {
705 ret = 2;
706 } else if (check->leaks) {
707 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200708 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500709 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000710 }
711
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500712fail:
713 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200714 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500715 return ret;
aliguori15859692009-04-21 23:11:53 +0000716}
717
bellardea2384d2004-08-01 21:59:26 +0000718static int img_commit(int argc, char **argv)
719{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400720 int c, ret, flags;
721 const char *filename, *fmt, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200722 BlockBackend *blk;
bellardea2384d2004-08-01 21:59:26 +0000723 BlockDriverState *bs;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100724 bool quiet = false;
bellardea2384d2004-08-01 21:59:26 +0000725
726 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400727 cache = BDRV_DEFAULT_CACHE;
bellardea2384d2004-08-01 21:59:26 +0000728 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100729 c = getopt(argc, argv, "f:ht:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100730 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000731 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100732 }
bellardea2384d2004-08-01 21:59:26 +0000733 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100734 case '?':
bellardea2384d2004-08-01 21:59:26 +0000735 case 'h':
736 help();
737 break;
738 case 'f':
739 fmt = optarg;
740 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400741 case 't':
742 cache = optarg;
743 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100744 case 'q':
745 quiet = true;
746 break;
bellardea2384d2004-08-01 21:59:26 +0000747 }
748 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200749 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800750 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100751 }
bellardea2384d2004-08-01 21:59:26 +0000752 filename = argv[optind++];
753
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400754 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100755 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400756 if (ret < 0) {
757 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100758 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400759 }
760
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200761 blk = img_open("image", filename, fmt, flags, true, quiet);
762 if (!blk) {
763 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900764 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200765 bs = blk_bs(blk);
766
bellardea2384d2004-08-01 21:59:26 +0000767 ret = bdrv_commit(bs);
768 switch(ret) {
769 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100770 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000771 break;
772 case -ENOENT:
Jes Sorensen15654a62010-12-16 14:31:53 +0100773 error_report("No disk inserted");
bellardea2384d2004-08-01 21:59:26 +0000774 break;
775 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +0100776 error_report("Image is read-only");
bellardea2384d2004-08-01 21:59:26 +0000777 break;
778 case -ENOTSUP:
Jes Sorensen15654a62010-12-16 14:31:53 +0100779 error_report("Image is already committed");
bellardea2384d2004-08-01 21:59:26 +0000780 break;
781 default:
Jes Sorensen15654a62010-12-16 14:31:53 +0100782 error_report("Error while committing image");
bellardea2384d2004-08-01 21:59:26 +0000783 break;
784 }
785
Markus Armbruster26f54e92014-10-07 13:59:04 +0200786 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900787 if (ret) {
788 return 1;
789 }
bellardea2384d2004-08-01 21:59:26 +0000790 return 0;
791}
792
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400793/*
thsf58c7b32008-06-05 21:53:49 +0000794 * Returns true iff the first sector pointed to by 'buf' contains at least
795 * a non-NUL byte.
796 *
797 * 'pnum' is set to the number of sectors (including and immediately following
798 * the first one) that are known to be in the same allocated/unallocated state.
799 */
bellardea2384d2004-08-01 21:59:26 +0000800static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
801{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000802 bool is_zero;
803 int i;
bellardea2384d2004-08-01 21:59:26 +0000804
805 if (n <= 0) {
806 *pnum = 0;
807 return 0;
808 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000809 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +0000810 for(i = 1; i < n; i++) {
811 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000812 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +0000813 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000814 }
bellardea2384d2004-08-01 21:59:26 +0000815 }
816 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000817 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +0000818}
819
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100820/*
Kevin Wolfa22f1232011-08-26 15:27:13 +0200821 * Like is_allocated_sectors, but if the buffer starts with a used sector,
822 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
823 * breaking up write requests for only small sparse areas.
824 */
825static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
826 int min)
827{
828 int ret;
829 int num_checked, num_used;
830
831 if (n < min) {
832 min = n;
833 }
834
835 ret = is_allocated_sectors(buf, n, pnum);
836 if (!ret) {
837 return ret;
838 }
839
840 num_used = *pnum;
841 buf += BDRV_SECTOR_SIZE * *pnum;
842 n -= *pnum;
843 num_checked = num_used;
844
845 while (n > 0) {
846 ret = is_allocated_sectors(buf, n, pnum);
847
848 buf += BDRV_SECTOR_SIZE * *pnum;
849 n -= *pnum;
850 num_checked += *pnum;
851 if (ret) {
852 num_used = num_checked;
853 } else if (*pnum >= min) {
854 break;
855 }
856 }
857
858 *pnum = num_used;
859 return 1;
860}
861
862/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100863 * Compares two buffers sector by sector. Returns 0 if the first sector of both
864 * buffers matches, non-zero otherwise.
865 *
866 * pnum is set to the number of sectors (including and immediately following
867 * the first one) that are known to have the same comparison result
868 */
869static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
870 int *pnum)
871{
872 int res, i;
873
874 if (n <= 0) {
875 *pnum = 0;
876 return 0;
877 }
878
879 res = !!memcmp(buf1, buf2, 512);
880 for(i = 1; i < n; i++) {
881 buf1 += 512;
882 buf2 += 512;
883
884 if (!!memcmp(buf1, buf2, 512) != res) {
885 break;
886 }
887 }
888
889 *pnum = i;
890 return res;
891}
892
Kevin Wolf80ee15a2009-09-15 12:30:43 +0200893#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +0000894
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100895static int64_t sectors_to_bytes(int64_t sectors)
896{
897 return sectors << BDRV_SECTOR_BITS;
898}
899
900static int64_t sectors_to_process(int64_t total, int64_t from)
901{
902 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
903}
904
905/*
906 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
907 *
908 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
909 * data and negative value on error.
910 *
911 * @param bs: Driver used for accessing file
912 * @param sect_num: Number of first sector to check
913 * @param sect_count: Number of sectors to check
914 * @param filename: Name of disk file we are checking (logging purpose)
915 * @param buffer: Allocated buffer for storing read data
916 * @param quiet: Flag for quiet mode
917 */
918static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
919 int sect_count, const char *filename,
920 uint8_t *buffer, bool quiet)
921{
922 int pnum, ret = 0;
923 ret = bdrv_read(bs, sect_num, buffer, sect_count);
924 if (ret < 0) {
925 error_report("Error while reading offset %" PRId64 " of %s: %s",
926 sectors_to_bytes(sect_num), filename, strerror(-ret));
927 return ret;
928 }
929 ret = is_allocated_sectors(buffer, sect_count, &pnum);
930 if (ret || pnum != sect_count) {
931 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
932 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
933 return 1;
934 }
935
936 return 0;
937}
938
939/*
940 * Compares two images. Exit codes:
941 *
942 * 0 - Images are identical
943 * 1 - Images differ
944 * >1 - Error occurred
945 */
946static int img_compare(int argc, char **argv)
947{
Max Reitz40055952014-07-22 22:58:42 +0200948 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200949 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100950 BlockDriverState *bs1, *bs2;
951 int64_t total_sectors1, total_sectors2;
952 uint8_t *buf1 = NULL, *buf2 = NULL;
953 int pnum1, pnum2;
954 int allocated1, allocated2;
955 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
956 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +0200957 int flags;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100958 int64_t total_sectors;
959 int64_t sector_num = 0;
960 int64_t nb_sectors;
961 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100962 uint64_t progress_base;
963
Max Reitz40055952014-07-22 22:58:42 +0200964 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100965 for (;;) {
Max Reitz40055952014-07-22 22:58:42 +0200966 c = getopt(argc, argv, "hf:F:T:pqs");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100967 if (c == -1) {
968 break;
969 }
970 switch (c) {
971 case '?':
972 case 'h':
973 help();
974 break;
975 case 'f':
976 fmt1 = optarg;
977 break;
978 case 'F':
979 fmt2 = optarg;
980 break;
Max Reitz40055952014-07-22 22:58:42 +0200981 case 'T':
982 cache = optarg;
983 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100984 case 'p':
985 progress = true;
986 break;
987 case 'q':
988 quiet = true;
989 break;
990 case 's':
991 strict = true;
992 break;
993 }
994 }
995
996 /* Progress is not shown in Quiet mode */
997 if (quiet) {
998 progress = false;
999 }
1000
1001
Kevin Wolffc11eb22013-08-05 10:53:04 +02001002 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001003 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001004 }
1005 filename1 = argv[optind++];
1006 filename2 = argv[optind++];
1007
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001008 /* Initialize before goto out */
1009 qemu_progress_init(progress, 2.0);
1010
Max Reitz40055952014-07-22 22:58:42 +02001011 flags = BDRV_O_FLAGS;
1012 ret = bdrv_parse_cache_flags(cache, &flags);
1013 if (ret < 0) {
1014 error_report("Invalid source cache option: %s", cache);
1015 ret = 2;
1016 goto out3;
1017 }
1018
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001019 blk1 = img_open("image_1", filename1, fmt1, flags, true, quiet);
1020 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001021 error_report("Can't open file %s", filename1);
1022 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001023 goto out3;
1024 }
1025 bs1 = blk_bs(blk1);
1026
1027 blk2 = img_open("image_2", filename2, fmt2, flags, true, quiet);
1028 if (!blk2) {
1029 error_report("Can't open file %s", filename2);
1030 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001031 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001032 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001033 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001034
1035 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
1036 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001037 total_sectors1 = bdrv_nb_sectors(bs1);
1038 if (total_sectors1 < 0) {
1039 error_report("Can't get size of %s: %s",
1040 filename1, strerror(-total_sectors1));
1041 ret = 4;
1042 goto out;
1043 }
1044 total_sectors2 = bdrv_nb_sectors(bs2);
1045 if (total_sectors2 < 0) {
1046 error_report("Can't get size of %s: %s",
1047 filename2, strerror(-total_sectors2));
1048 ret = 4;
1049 goto out;
1050 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001051 total_sectors = MIN(total_sectors1, total_sectors2);
1052 progress_base = MAX(total_sectors1, total_sectors2);
1053
1054 qemu_progress_print(0, 100);
1055
1056 if (strict && total_sectors1 != total_sectors2) {
1057 ret = 1;
1058 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1059 goto out;
1060 }
1061
1062 for (;;) {
1063 nb_sectors = sectors_to_process(total_sectors, sector_num);
1064 if (nb_sectors <= 0) {
1065 break;
1066 }
1067 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
1068 &pnum1);
1069 if (allocated1 < 0) {
1070 ret = 3;
1071 error_report("Sector allocation test failed for %s", filename1);
1072 goto out;
1073 }
1074
1075 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1076 &pnum2);
1077 if (allocated2 < 0) {
1078 ret = 3;
1079 error_report("Sector allocation test failed for %s", filename2);
1080 goto out;
1081 }
1082 nb_sectors = MIN(pnum1, pnum2);
1083
1084 if (allocated1 == allocated2) {
1085 if (allocated1) {
1086 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1087 if (ret < 0) {
1088 error_report("Error while reading offset %" PRId64 " of %s:"
1089 " %s", sectors_to_bytes(sector_num), filename1,
1090 strerror(-ret));
1091 ret = 4;
1092 goto out;
1093 }
1094 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1095 if (ret < 0) {
1096 error_report("Error while reading offset %" PRId64
1097 " of %s: %s", sectors_to_bytes(sector_num),
1098 filename2, strerror(-ret));
1099 ret = 4;
1100 goto out;
1101 }
1102 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1103 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001104 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1105 sectors_to_bytes(
1106 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001107 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001108 goto out;
1109 }
1110 }
1111 } else {
1112 if (strict) {
1113 ret = 1;
1114 qprintf(quiet, "Strict mode: Offset %" PRId64
1115 " allocation mismatch!\n",
1116 sectors_to_bytes(sector_num));
1117 goto out;
1118 }
1119
1120 if (allocated1) {
1121 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1122 filename1, buf1, quiet);
1123 } else {
1124 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1125 filename2, buf1, quiet);
1126 }
1127 if (ret) {
1128 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001129 error_report("Error while reading offset %" PRId64 ": %s",
1130 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001131 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001132 }
1133 goto out;
1134 }
1135 }
1136 sector_num += nb_sectors;
1137 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1138 }
1139
1140 if (total_sectors1 != total_sectors2) {
1141 BlockDriverState *bs_over;
1142 int64_t total_sectors_over;
1143 const char *filename_over;
1144
1145 qprintf(quiet, "Warning: Image size mismatch!\n");
1146 if (total_sectors1 > total_sectors2) {
1147 total_sectors_over = total_sectors1;
1148 bs_over = bs1;
1149 filename_over = filename1;
1150 } else {
1151 total_sectors_over = total_sectors2;
1152 bs_over = bs2;
1153 filename_over = filename2;
1154 }
1155
1156 for (;;) {
1157 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1158 if (nb_sectors <= 0) {
1159 break;
1160 }
1161 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1162 nb_sectors, &pnum);
1163 if (ret < 0) {
1164 ret = 3;
1165 error_report("Sector allocation test failed for %s",
1166 filename_over);
1167 goto out;
1168
1169 }
1170 nb_sectors = pnum;
1171 if (ret) {
1172 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1173 filename_over, buf1, quiet);
1174 if (ret) {
1175 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001176 error_report("Error while reading offset %" PRId64
1177 " of %s: %s", sectors_to_bytes(sector_num),
1178 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001179 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001180 }
1181 goto out;
1182 }
1183 }
1184 sector_num += nb_sectors;
1185 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1186 }
1187 }
1188
1189 qprintf(quiet, "Images are identical.\n");
1190 ret = 0;
1191
1192out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001193 qemu_vfree(buf1);
1194 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001195 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001196out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001197 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001198out3:
1199 qemu_progress_end();
1200 return ret;
1201}
1202
bellardea2384d2004-08-01 21:59:26 +00001203static int img_convert(int argc, char **argv)
1204{
Peter Lieven24f833c2013-11-27 11:07:07 +01001205 int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001206 int64_t ret = 0;
Max Reitz40055952014-07-22 22:58:42 +02001207 int progress = 0, flags, src_flags;
1208 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001209 BlockDriver *drv, *proto_drv;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001210 BlockBackend **blk = NULL, *out_blk = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001211 BlockDriverState **bs = NULL, *out_bs = NULL;
Peter Lieven802c3d42013-12-05 15:54:53 +01001212 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001213 int64_t *bs_sectors = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001214 uint8_t * buf = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001215 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardea2384d2004-08-01 21:59:26 +00001216 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +00001217 BlockDriverInfo bdi;
Chunyan Liu83d05212014-06-05 17:20:51 +08001218 QemuOpts *opts = NULL;
1219 QemuOptsList *create_opts = NULL;
1220 const char *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001221 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001222 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001223 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001224 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001225 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001226 QemuOpts *sn_opts = NULL;
bellardea2384d2004-08-01 21:59:26 +00001227
1228 fmt = NULL;
1229 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001230 cache = "unsafe";
Max Reitz40055952014-07-22 22:58:42 +02001231 src_cache = BDRV_DEFAULT_CACHE;
thsf58c7b32008-06-05 21:53:49 +00001232 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001233 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001234 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001235 for(;;) {
Max Reitz40055952014-07-22 22:58:42 +02001236 c = getopt(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001237 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001238 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001239 }
bellardea2384d2004-08-01 21:59:26 +00001240 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001241 case '?':
bellardea2384d2004-08-01 21:59:26 +00001242 case 'h':
1243 help();
1244 break;
1245 case 'f':
1246 fmt = optarg;
1247 break;
1248 case 'O':
1249 out_fmt = optarg;
1250 break;
thsf58c7b32008-06-05 21:53:49 +00001251 case 'B':
1252 out_baseimg = optarg;
1253 break;
bellardea2384d2004-08-01 21:59:26 +00001254 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001255 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001256 break;
1257 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001258 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001259 "encryption\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001260 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001261 goto fail_getopt;
thsec36ba12007-09-16 21:59:02 +00001262 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001263 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001264 "compat6\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001265 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001266 goto fail_getopt;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001267 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001268 if (!is_valid_option_list(optarg)) {
1269 error_report("Invalid option list: %s", optarg);
1270 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001271 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001272 }
1273 if (!options) {
1274 options = g_strdup(optarg);
1275 } else {
1276 char *old_options = options;
1277 options = g_strdup_printf("%s,%s", options, optarg);
1278 g_free(old_options);
1279 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001280 break;
edison51ef6722010-09-21 19:58:41 -07001281 case 's':
1282 snapshot_name = optarg;
1283 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001284 case 'l':
1285 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1286 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1287 if (!sn_opts) {
1288 error_report("Failed in parsing snapshot param '%s'",
1289 optarg);
Kevin Wolf2dc83282014-02-21 16:24:05 +01001290 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001291 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08001292 }
1293 } else {
1294 snapshot_name = optarg;
1295 }
1296 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001297 case 'S':
1298 {
1299 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001300 char *end;
1301 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1302 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001303 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001304 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001305 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001306 }
1307
1308 min_sparse = sval / BDRV_SECTOR_SIZE;
1309 break;
1310 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001311 case 'p':
1312 progress = 1;
1313 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001314 case 't':
1315 cache = optarg;
1316 break;
Max Reitz40055952014-07-22 22:58:42 +02001317 case 'T':
1318 src_cache = optarg;
1319 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001320 case 'q':
1321 quiet = true;
1322 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001323 case 'n':
1324 skip_create = 1;
1325 break;
bellardea2384d2004-08-01 21:59:26 +00001326 }
1327 }
ths3b46e622007-09-17 08:09:54 +00001328
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001329 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001330 if (quiet) {
1331 progress = 0;
1332 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001333 qemu_progress_init(progress, 1.0);
1334
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001335
balrog926c2d22007-10-31 01:11:44 +00001336 bs_n = argc - optind - 1;
Kevin Wolfa283cb62014-02-21 16:24:07 +01001337 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
thsf58c7b32008-06-05 21:53:49 +00001338
Kevin Wolf2dc83282014-02-21 16:24:05 +01001339 if (options && has_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001340 ret = print_block_option_help(out_filename, out_fmt);
1341 goto out;
1342 }
1343
bellardea2384d2004-08-01 21:59:26 +00001344 if (bs_n < 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001345 error_exit("Must specify image file name");
ths5fafdf22007-09-16 21:08:06 +00001346 }
bellardea2384d2004-08-01 21:59:26 +00001347
thsf58c7b32008-06-05 21:53:49 +00001348
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001349 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001350 error_report("-B makes no sense when concatenating multiple input "
1351 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001352 ret = -1;
1353 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001354 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001355
Max Reitz40055952014-07-22 22:58:42 +02001356 src_flags = BDRV_O_FLAGS;
1357 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1358 if (ret < 0) {
1359 error_report("Invalid source cache option: %s", src_cache);
1360 goto out;
1361 }
1362
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001363 qemu_progress_print(0, 100);
1364
Markus Armbruster26f54e92014-10-07 13:59:04 +02001365 blk = g_new0(BlockBackend *, bs_n);
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001366 bs = g_new0(BlockDriverState *, bs_n);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001367 bs_sectors = g_new(int64_t, bs_n);
balrog926c2d22007-10-31 01:11:44 +00001368
1369 total_sectors = 0;
1370 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Kevin Wolf9aebf3b2014-09-25 09:54:02 +02001371 char *id = bs_n > 1 ? g_strdup_printf("source_%d", bs_i)
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001372 : g_strdup("source");
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001373 blk[bs_i] = img_open(id, argv[optind + bs_i], fmt, src_flags,
1374 true, quiet);
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001375 g_free(id);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001376 if (!blk[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001377 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001378 ret = -1;
1379 goto out;
1380 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001381 bs[bs_i] = blk_bs(blk[bs_i]);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001382 bs_sectors[bs_i] = bdrv_nb_sectors(bs[bs_i]);
1383 if (bs_sectors[bs_i] < 0) {
1384 error_report("Could not get size of %s: %s",
1385 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1386 ret = -1;
1387 goto out;
1388 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001389 total_sectors += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001390 }
bellardea2384d2004-08-01 21:59:26 +00001391
Wenchao Xiaef806542013-12-04 17:10:57 +08001392 if (sn_opts) {
1393 ret = bdrv_snapshot_load_tmp(bs[0],
1394 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1395 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1396 &local_err);
1397 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001398 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001399 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001400 ret = -1;
1401 goto out;
1402 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001403
1404 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001405 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001406 if (local_err) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001407 error_report("Failed to load snapshot: %s",
1408 error_get_pretty(local_err));
1409 error_free(local_err);
1410 ret = -1;
1411 goto out;
edison51ef6722010-09-21 19:58:41 -07001412 }
1413
Kevin Wolfefa84d42009-05-18 16:42:12 +02001414 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001415 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001416 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001417 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001418 ret = -1;
1419 goto out;
1420 }
balrog926c2d22007-10-31 01:11:44 +00001421
Kevin Wolf98289622013-07-10 15:47:39 +02001422 proto_drv = bdrv_find_protocol(out_filename, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001423 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001424 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001425 ret = -1;
1426 goto out;
1427 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001428
Chunyan Liuc282e1f2014-06-05 17:21:11 +08001429 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1430 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02001431
Chunyan Liu83d05212014-06-05 17:20:51 +08001432 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1433 if (options && qemu_opts_do_parse(opts, options, NULL)) {
1434 error_report("Invalid options for file format '%s'", out_fmt);
1435 ret = -1;
1436 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001437 }
1438
Chunyan Liu83d05212014-06-05 17:20:51 +08001439 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512);
1440 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001441 if (ret < 0) {
1442 goto out;
1443 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001444
Kevin Wolfa18953f2010-10-14 15:46:04 +02001445 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08001446 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02001447 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08001448 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02001449 }
1450
Kevin Wolfefa84d42009-05-18 16:42:12 +02001451 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01001452 if (compress) {
Chunyan Liu83d05212014-06-05 17:20:51 +08001453 bool encryption =
1454 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1455 const char *preallocation =
1456 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001457
1458 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001459 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001460 ret = -1;
1461 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001462 }
1463
Chunyan Liu83d05212014-06-05 17:20:51 +08001464 if (encryption) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001465 error_report("Compression and encryption not supported at "
1466 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001467 ret = -1;
1468 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001469 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02001470
Chunyan Liu83d05212014-06-05 17:20:51 +08001471 if (preallocation
1472 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02001473 {
1474 error_report("Compression and preallocation not supported at "
1475 "the same time");
1476 ret = -1;
1477 goto out;
1478 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001479 }
1480
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001481 if (!skip_create) {
1482 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08001483 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001484 if (ret < 0) {
Max Reitzcc84d902013-09-06 17:14:26 +02001485 error_report("%s: error while converting %s: %s",
1486 out_filename, out_fmt, error_get_pretty(local_err));
1487 error_free(local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001488 goto out;
bellardea2384d2004-08-01 21:59:26 +00001489 }
1490 }
ths3b46e622007-09-17 08:09:54 +00001491
Peter Lieven5a37b602013-10-24 12:07:06 +02001492 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001493 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001494 if (ret < 0) {
1495 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02001496 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001497 }
1498
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001499 out_blk = img_open("target", out_filename, out_fmt, flags, true, quiet);
1500 if (!out_blk) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001501 ret = -1;
1502 goto out;
1503 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001504 out_bs = blk_bs(out_blk);
bellardea2384d2004-08-01 21:59:26 +00001505
balrog926c2d22007-10-31 01:11:44 +00001506 bs_i = 0;
1507 bs_offset = 0;
Peter Lievenf2521c92013-11-27 11:07:06 +01001508
1509 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1510 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1511 * as maximum. */
1512 bufsectors = MIN(32768,
1513 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1514 out_bs->bl.discard_alignment))
1515 );
1516
1517 buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001518
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001519 if (skip_create) {
Markus Armbruster43716fa2014-06-26 13:23:21 +02001520 int64_t output_sectors = bdrv_nb_sectors(out_bs);
1521 if (output_sectors < 0) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001522 error_report("unable to get output image length: %s\n",
Markus Armbruster43716fa2014-06-26 13:23:21 +02001523 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001524 ret = -1;
1525 goto out;
Markus Armbruster43716fa2014-06-26 13:23:21 +02001526 } else if (output_sectors < total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001527 error_report("output file is smaller than input file");
1528 ret = -1;
1529 goto out;
1530 }
1531 }
1532
Peter Lieven24f833c2013-11-27 11:07:07 +01001533 cluster_sectors = 0;
1534 ret = bdrv_get_info(out_bs, &bdi);
1535 if (ret < 0) {
1536 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001537 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001538 goto out;
1539 }
Peter Lieven24f833c2013-11-27 11:07:07 +01001540 } else {
Fam Zheng85f49ca2014-05-06 21:08:43 +08001541 compress = compress || bdi.needs_compressed_writes;
Peter Lieven24f833c2013-11-27 11:07:07 +01001542 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
1543 }
1544
1545 if (compress) {
1546 if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001547 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001548 ret = -1;
1549 goto out;
1550 }
bellardea2384d2004-08-01 21:59:26 +00001551 sector_num = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001552
1553 nb_sectors = total_sectors;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001554
bellardea2384d2004-08-01 21:59:26 +00001555 for(;;) {
balrog926c2d22007-10-31 01:11:44 +00001556 int64_t bs_num;
1557 int remainder;
1558 uint8_t *buf2;
1559
bellardea2384d2004-08-01 21:59:26 +00001560 nb_sectors = total_sectors - sector_num;
1561 if (nb_sectors <= 0)
1562 break;
1563 if (nb_sectors >= cluster_sectors)
1564 n = cluster_sectors;
1565 else
1566 n = nb_sectors;
balrog926c2d22007-10-31 01:11:44 +00001567
1568 bs_num = sector_num - bs_offset;
1569 assert (bs_num >= 0);
1570 remainder = n;
1571 buf2 = buf;
1572 while (remainder > 0) {
1573 int nlow;
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001574 while (bs_num == bs_sectors[bs_i]) {
1575 bs_offset += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001576 bs_i++;
1577 assert (bs_i < bs_n);
balrog926c2d22007-10-31 01:11:44 +00001578 bs_num = 0;
Blue Swirl0bfcd592010-05-22 08:02:12 +00001579 /* printf("changing part: sector_num=%" PRId64 ", "
1580 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001581 "\n", sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
balrog926c2d22007-10-31 01:11:44 +00001582 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001583 assert (bs_num < bs_sectors[bs_i]);
balrog926c2d22007-10-31 01:11:44 +00001584
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001585 nlow = remainder > bs_sectors[bs_i] - bs_num
1586 ? bs_sectors[bs_i] - bs_num : remainder;
balrog926c2d22007-10-31 01:11:44 +00001587
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001588 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1589 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001590 error_report("error while reading sector %" PRId64 ": %s",
1591 bs_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001592 goto out;
1593 }
balrog926c2d22007-10-31 01:11:44 +00001594
1595 buf2 += nlow * 512;
1596 bs_num += nlow;
1597
1598 remainder -= nlow;
1599 }
1600 assert (remainder == 0);
1601
Stefan Hajnoczi54f106d2013-04-15 17:17:33 +02001602 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1603 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001604 if (ret != 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001605 error_report("error while compressing sector %" PRId64
1606 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001607 goto out;
1608 }
bellardea2384d2004-08-01 21:59:26 +00001609 }
1610 sector_num += n;
Peter Lieven13c28af2013-11-27 11:07:01 +01001611 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
bellardea2384d2004-08-01 21:59:26 +00001612 }
bellardfaea38e2006-08-05 21:31:00 +00001613 /* signal EOF to align */
1614 bdrv_write_compressed(out_bs, 0, NULL, 0);
bellardea2384d2004-08-01 21:59:26 +00001615 } else {
Peter Lieven802c3d42013-12-05 15:54:53 +01001616 int64_t sectors_to_read, sectors_read, sector_num_next_status;
1617 bool count_allocated_sectors;
Peter Lieven11b66992013-10-24 12:07:05 +02001618 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02001619
Peter Lieven5a37b602013-10-24 12:07:06 +02001620 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1621 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1622 if (ret < 0) {
1623 goto out;
1624 }
1625 has_zero_init = 1;
1626 }
1627
Peter Lieven802c3d42013-12-05 15:54:53 +01001628 sectors_to_read = total_sectors;
1629 count_allocated_sectors = progress && (out_baseimg || has_zero_init);
1630restart:
thsf58c7b32008-06-05 21:53:49 +00001631 sector_num = 0; // total number of sectors converted so far
Peter Lieven802c3d42013-12-05 15:54:53 +01001632 sectors_read = 0;
1633 sector_num_next_status = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001634
bellardea2384d2004-08-01 21:59:26 +00001635 for(;;) {
1636 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001637 if (nb_sectors <= 0) {
Peter Lieven802c3d42013-12-05 15:54:53 +01001638 if (count_allocated_sectors) {
1639 sectors_to_read = sectors_read;
1640 count_allocated_sectors = false;
1641 goto restart;
1642 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001643 ret = 0;
bellardea2384d2004-08-01 21:59:26 +00001644 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001645 }
balrog926c2d22007-10-31 01:11:44 +00001646
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001647 while (sector_num - bs_offset >= bs_sectors[bs_i]) {
1648 bs_offset += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001649 bs_i ++;
1650 assert (bs_i < bs_n);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001651 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1652 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001653 sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
balrog926c2d22007-10-31 01:11:44 +00001654 }
1655
Peter Lieven13c28af2013-11-27 11:07:01 +01001656 if ((out_baseimg || has_zero_init) &&
1657 sector_num >= sector_num_next_status) {
1658 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1659 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1660 n, &n1);
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001661 if (ret < 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001662 error_report("error while reading block status of sector %"
1663 PRId64 ": %s", sector_num - bs_offset,
1664 strerror(-ret));
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001665 goto out;
aliguori93c65b42009-04-05 17:40:43 +00001666 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001667 /* If the output image is zero initialized, we are not working
1668 * on a shared base and the input is zero we can skip the next
1669 * n1 sectors */
1670 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001671 sector_num += n1;
1672 continue;
1673 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001674 /* If the output image is being created as a copy on write
1675 * image, assume that sectors which are unallocated in the
1676 * input image are present in both the output's and input's
1677 * base images (no need to copy them). */
1678 if (out_baseimg) {
1679 if (!(ret & BDRV_BLOCK_DATA)) {
1680 sector_num += n1;
1681 continue;
1682 }
1683 /* The next 'n1' sectors are allocated in the input image.
1684 * Copy only those as they may be followed by unallocated
1685 * sectors. */
1686 nb_sectors = n1;
1687 }
1688 /* avoid redundant callouts to get_block_status */
1689 sector_num_next_status = sector_num + n1;
thsf58c7b32008-06-05 21:53:49 +00001690 }
1691
Peter Lievenf2521c92013-11-27 11:07:06 +01001692 n = MIN(nb_sectors, bufsectors);
Peter Lieven24f833c2013-11-27 11:07:07 +01001693
1694 /* round down request length to an aligned sector, but
1695 * do not bother doing this on short requests. They happen
1696 * when we found an all-zero area, and the next sector to
1697 * write will not be sector_num + n. */
1698 if (cluster_sectors > 0 && n >= cluster_sectors) {
1699 int64_t next_aligned_sector = (sector_num + n);
1700 next_aligned_sector -= next_aligned_sector % cluster_sectors;
1701 if (sector_num + n > next_aligned_sector) {
1702 n = next_aligned_sector - sector_num;
1703 }
1704 }
1705
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001706 n = MIN(n, bs_sectors[bs_i] - (sector_num - bs_offset));
Peter Lieven13c28af2013-11-27 11:07:01 +01001707
Peter Lieven802c3d42013-12-05 15:54:53 +01001708 sectors_read += n;
1709 if (count_allocated_sectors) {
1710 sector_num += n;
1711 continue;
1712 }
1713
1714 n1 = n;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001715 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1716 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001717 error_report("error while reading sector %" PRId64 ": %s",
1718 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001719 goto out;
1720 }
bellardea2384d2004-08-01 21:59:26 +00001721 /* NOTE: at the same time we convert, we do not write zero
1722 sectors to have a chance to compress the image. Ideally, we
1723 should add a specific call to have the info to go faster */
1724 buf1 = buf;
1725 while (n > 0) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02001726 if (!has_zero_init ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001727 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001728 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1729 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001730 error_report("error while writing sector %" PRId64
1731 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001732 goto out;
1733 }
bellardea2384d2004-08-01 21:59:26 +00001734 }
1735 sector_num += n1;
1736 n -= n1;
1737 buf1 += n1 * 512;
1738 }
Peter Lieven802c3d42013-12-05 15:54:53 +01001739 qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
bellardea2384d2004-08-01 21:59:26 +00001740 }
1741 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001742out:
Peter Lieven13c28af2013-11-27 11:07:01 +01001743 if (!ret) {
1744 qemu_progress_print(100, 0);
1745 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001746 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08001747 qemu_opts_del(opts);
1748 qemu_opts_free(create_opts);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001749 qemu_vfree(buf);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02001750 qemu_opts_del(sn_opts);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001751 blk_unref(out_blk);
Markus Armbruster9ba10c92014-10-07 13:59:08 +02001752 g_free(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001753 if (blk) {
1754 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1755 blk_unref(blk[bs_i]);
1756 }
1757 g_free(blk);
1758 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001759 g_free(bs_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001760fail_getopt:
1761 g_free(options);
1762
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001763 if (ret) {
1764 return 1;
1765 }
bellardea2384d2004-08-01 21:59:26 +00001766 return 0;
1767}
1768
bellard57d1a2b2004-08-03 21:15:11 +00001769
bellardfaea38e2006-08-05 21:31:00 +00001770static void dump_snapshots(BlockDriverState *bs)
1771{
1772 QEMUSnapshotInfo *sn_tab, *sn;
1773 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00001774
1775 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1776 if (nb_sns <= 0)
1777 return;
1778 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08001779 bdrv_snapshot_dump(fprintf, stdout, NULL);
1780 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001781 for(i = 0; i < nb_sns; i++) {
1782 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08001783 bdrv_snapshot_dump(fprintf, stdout, sn);
1784 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001785 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001786 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001787}
1788
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001789static void dump_json_image_info_list(ImageInfoList *list)
1790{
Markus Armbruster4399c432014-04-25 16:50:32 +02001791 Error *local_err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001792 QString *str;
1793 QmpOutputVisitor *ov = qmp_output_visitor_new();
1794 QObject *obj;
1795 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +02001796 &list, NULL, &local_err);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001797 obj = qmp_output_get_qobject(ov);
1798 str = qobject_to_json_pretty(obj);
1799 assert(str != NULL);
1800 printf("%s\n", qstring_get_str(str));
1801 qobject_decref(obj);
1802 qmp_output_visitor_cleanup(ov);
1803 QDECREF(str);
1804}
1805
Benoît Canetc054b3f2012-09-05 13:09:02 +02001806static void dump_json_image_info(ImageInfo *info)
1807{
Markus Armbruster4399c432014-04-25 16:50:32 +02001808 Error *local_err = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001809 QString *str;
1810 QmpOutputVisitor *ov = qmp_output_visitor_new();
1811 QObject *obj;
1812 visit_type_ImageInfo(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +02001813 &info, NULL, &local_err);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001814 obj = qmp_output_get_qobject(ov);
1815 str = qobject_to_json_pretty(obj);
1816 assert(str != NULL);
1817 printf("%s\n", qstring_get_str(str));
1818 qobject_decref(obj);
1819 qmp_output_visitor_cleanup(ov);
1820 QDECREF(str);
1821}
1822
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001823static void dump_human_image_info_list(ImageInfoList *list)
1824{
1825 ImageInfoList *elem;
1826 bool delim = false;
1827
1828 for (elem = list; elem; elem = elem->next) {
1829 if (delim) {
1830 printf("\n");
1831 }
1832 delim = true;
1833
Wenchao Xia5b917042013-05-25 11:09:45 +08001834 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001835 }
1836}
1837
1838static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1839{
1840 return strcmp(a, b) == 0;
1841}
1842
1843/**
1844 * Open an image file chain and return an ImageInfoList
1845 *
1846 * @filename: topmost image filename
1847 * @fmt: topmost image format (may be NULL to autodetect)
1848 * @chain: true - enumerate entire backing file chain
1849 * false - only topmost image file
1850 *
1851 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1852 * image file. If there was an error a message will have been printed to
1853 * stderr.
1854 */
1855static ImageInfoList *collect_image_info_list(const char *filename,
1856 const char *fmt,
1857 bool chain)
1858{
1859 ImageInfoList *head = NULL;
1860 ImageInfoList **last = &head;
1861 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08001862 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001863
1864 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1865
1866 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02001867 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001868 BlockDriverState *bs;
1869 ImageInfo *info;
1870 ImageInfoList *elem;
1871
1872 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1873 error_report("Backing file '%s' creates an infinite loop.",
1874 filename);
1875 goto err;
1876 }
1877 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1878
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001879 blk = img_open("image", filename, fmt,
1880 BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
1881 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001882 goto err;
1883 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001884 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001885
Wenchao Xia43526ec2013-06-06 12:27:58 +08001886 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001887 if (err) {
Wenchao Xia43526ec2013-06-06 12:27:58 +08001888 error_report("%s", error_get_pretty(err));
1889 error_free(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001890 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08001891 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08001892 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001893
1894 elem = g_new0(ImageInfoList, 1);
1895 elem->value = info;
1896 *last = elem;
1897 last = &elem->next;
1898
Markus Armbruster26f54e92014-10-07 13:59:04 +02001899 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001900
1901 filename = fmt = NULL;
1902 if (chain) {
1903 if (info->has_full_backing_filename) {
1904 filename = info->full_backing_filename;
1905 } else if (info->has_backing_filename) {
1906 filename = info->backing_filename;
1907 }
1908 if (info->has_backing_filename_format) {
1909 fmt = info->backing_filename_format;
1910 }
1911 }
1912 }
1913 g_hash_table_destroy(filenames);
1914 return head;
1915
1916err:
1917 qapi_free_ImageInfoList(head);
1918 g_hash_table_destroy(filenames);
1919 return NULL;
1920}
1921
Benoît Canetc054b3f2012-09-05 13:09:02 +02001922static int img_info(int argc, char **argv)
1923{
1924 int c;
1925 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001926 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001927 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001928 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001929
bellardea2384d2004-08-01 21:59:26 +00001930 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001931 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001932 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001933 int option_index = 0;
1934 static const struct option long_options[] = {
1935 {"help", no_argument, 0, 'h'},
1936 {"format", required_argument, 0, 'f'},
1937 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001938 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001939 {0, 0, 0, 0}
1940 };
1941 c = getopt_long(argc, argv, "f:h",
1942 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001943 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001944 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001945 }
bellardea2384d2004-08-01 21:59:26 +00001946 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001947 case '?':
bellardea2384d2004-08-01 21:59:26 +00001948 case 'h':
1949 help();
1950 break;
1951 case 'f':
1952 fmt = optarg;
1953 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001954 case OPTION_OUTPUT:
1955 output = optarg;
1956 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001957 case OPTION_BACKING_CHAIN:
1958 chain = true;
1959 break;
bellardea2384d2004-08-01 21:59:26 +00001960 }
1961 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02001962 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001963 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001964 }
bellardea2384d2004-08-01 21:59:26 +00001965 filename = argv[optind++];
1966
Benoît Canetc054b3f2012-09-05 13:09:02 +02001967 if (output && !strcmp(output, "json")) {
1968 output_format = OFORMAT_JSON;
1969 } else if (output && !strcmp(output, "human")) {
1970 output_format = OFORMAT_HUMAN;
1971 } else if (output) {
1972 error_report("--output must be used with human or json as argument.");
1973 return 1;
1974 }
1975
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001976 list = collect_image_info_list(filename, fmt, chain);
1977 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001978 return 1;
1979 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001980
Benoît Canetc054b3f2012-09-05 13:09:02 +02001981 switch (output_format) {
1982 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001983 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001984 break;
1985 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001986 if (chain) {
1987 dump_json_image_info_list(list);
1988 } else {
1989 dump_json_image_info(list->value);
1990 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001991 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001992 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001993
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001994 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00001995 return 0;
1996}
1997
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02001998
1999typedef struct MapEntry {
2000 int flags;
2001 int depth;
2002 int64_t start;
2003 int64_t length;
2004 int64_t offset;
2005 BlockDriverState *bs;
2006} MapEntry;
2007
2008static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2009 MapEntry *next)
2010{
2011 switch (output_format) {
2012 case OFORMAT_HUMAN:
2013 if ((e->flags & BDRV_BLOCK_DATA) &&
2014 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
2015 error_report("File contains external, encrypted or compressed clusters.");
2016 exit(1);
2017 }
2018 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
2019 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2020 e->start, e->length, e->offset, e->bs->filename);
2021 }
2022 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2023 * Modify the flags here to allow more coalescing.
2024 */
2025 if (next &&
2026 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
2027 next->flags &= ~BDRV_BLOCK_DATA;
2028 next->flags |= BDRV_BLOCK_ZERO;
2029 }
2030 break;
2031 case OFORMAT_JSON:
2032 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
2033 " \"zero\": %s, \"data\": %s",
2034 (e->start == 0 ? "[" : ",\n"),
2035 e->start, e->length, e->depth,
2036 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
2037 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
2038 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002039 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002040 }
2041 putchar('}');
2042
2043 if (!next) {
2044 printf("]\n");
2045 }
2046 break;
2047 }
2048}
2049
2050static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2051 int nb_sectors, MapEntry *e)
2052{
2053 int64_t ret;
2054 int depth;
2055
2056 /* As an optimization, we could cache the current range of unallocated
2057 * clusters in each file of the chain, and avoid querying the same
2058 * range repeatedly.
2059 */
2060
2061 depth = 0;
2062 for (;;) {
2063 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
2064 if (ret < 0) {
2065 return ret;
2066 }
2067 assert(nb_sectors);
2068 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2069 break;
2070 }
2071 bs = bs->backing_hd;
2072 if (bs == NULL) {
2073 ret = 0;
2074 break;
2075 }
2076
2077 depth++;
2078 }
2079
2080 e->start = sector_num * BDRV_SECTOR_SIZE;
2081 e->length = nb_sectors * BDRV_SECTOR_SIZE;
2082 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
2083 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
2084 e->depth = depth;
2085 e->bs = bs;
2086 return 0;
2087}
2088
2089static int img_map(int argc, char **argv)
2090{
2091 int c;
2092 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002093 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002094 BlockDriverState *bs;
2095 const char *filename, *fmt, *output;
2096 int64_t length;
2097 MapEntry curr = { .length = 0 }, next;
2098 int ret = 0;
2099
2100 fmt = NULL;
2101 output = NULL;
2102 for (;;) {
2103 int option_index = 0;
2104 static const struct option long_options[] = {
2105 {"help", no_argument, 0, 'h'},
2106 {"format", required_argument, 0, 'f'},
2107 {"output", required_argument, 0, OPTION_OUTPUT},
2108 {0, 0, 0, 0}
2109 };
2110 c = getopt_long(argc, argv, "f:h",
2111 long_options, &option_index);
2112 if (c == -1) {
2113 break;
2114 }
2115 switch (c) {
2116 case '?':
2117 case 'h':
2118 help();
2119 break;
2120 case 'f':
2121 fmt = optarg;
2122 break;
2123 case OPTION_OUTPUT:
2124 output = optarg;
2125 break;
2126 }
2127 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002128 if (optind != argc - 1) {
2129 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002130 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002131 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002132
2133 if (output && !strcmp(output, "json")) {
2134 output_format = OFORMAT_JSON;
2135 } else if (output && !strcmp(output, "human")) {
2136 output_format = OFORMAT_HUMAN;
2137 } else if (output) {
2138 error_report("--output must be used with human or json as argument.");
2139 return 1;
2140 }
2141
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002142 blk = img_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
2143 if (!blk) {
2144 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002145 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002146 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002147
2148 if (output_format == OFORMAT_HUMAN) {
2149 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2150 }
2151
2152 length = bdrv_getlength(bs);
2153 while (curr.start + curr.length < length) {
2154 int64_t nsectors_left;
2155 int64_t sector_num;
2156 int n;
2157
2158 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2159
2160 /* Probe up to 1 GiB at a time. */
2161 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2162 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2163 ret = get_block_status(bs, sector_num, n, &next);
2164
2165 if (ret < 0) {
2166 error_report("Could not read file metadata: %s", strerror(-ret));
2167 goto out;
2168 }
2169
2170 if (curr.length != 0 && curr.flags == next.flags &&
2171 curr.depth == next.depth &&
2172 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2173 curr.offset + curr.length == next.offset)) {
2174 curr.length += next.length;
2175 continue;
2176 }
2177
2178 if (curr.length > 0) {
2179 dump_map_entry(output_format, &curr, &next);
2180 }
2181 curr = next;
2182 }
2183
2184 dump_map_entry(output_format, &curr, NULL);
2185
2186out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002187 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002188 return ret < 0;
2189}
2190
aliguorif7b4a942009-01-07 17:40:15 +00002191#define SNAPSHOT_LIST 1
2192#define SNAPSHOT_CREATE 2
2193#define SNAPSHOT_APPLY 3
2194#define SNAPSHOT_DELETE 4
2195
Stuart Brady153859b2009-06-07 00:42:17 +01002196static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002197{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002198 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002199 BlockDriverState *bs;
2200 QEMUSnapshotInfo sn;
2201 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002202 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002203 int action = 0;
2204 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002205 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002206 Error *err = NULL;
aliguorif7b4a942009-01-07 17:40:15 +00002207
Kevin Wolf710da702011-01-10 12:33:02 +01002208 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002209 /* Parse commandline parameters */
2210 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002211 c = getopt(argc, argv, "la:c:d:hq");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002212 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002213 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002214 }
aliguorif7b4a942009-01-07 17:40:15 +00002215 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002216 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002217 case 'h':
2218 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002219 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002220 case 'l':
2221 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002222 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002223 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002224 }
2225 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002226 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002227 break;
2228 case 'a':
2229 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002230 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002231 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002232 }
2233 action = SNAPSHOT_APPLY;
2234 snapshot_name = optarg;
2235 break;
2236 case 'c':
2237 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002238 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002239 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002240 }
2241 action = SNAPSHOT_CREATE;
2242 snapshot_name = optarg;
2243 break;
2244 case 'd':
2245 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002246 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002247 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002248 }
2249 action = SNAPSHOT_DELETE;
2250 snapshot_name = optarg;
2251 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002252 case 'q':
2253 quiet = true;
2254 break;
aliguorif7b4a942009-01-07 17:40:15 +00002255 }
2256 }
2257
Kevin Wolffc11eb22013-08-05 10:53:04 +02002258 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002259 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002260 }
aliguorif7b4a942009-01-07 17:40:15 +00002261 filename = argv[optind++];
2262
2263 /* Open the image */
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002264 blk = img_open("image", filename, NULL, bdrv_oflags, true, quiet);
2265 if (!blk) {
2266 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002267 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002268 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002269
2270 /* Perform the requested action */
2271 switch(action) {
2272 case SNAPSHOT_LIST:
2273 dump_snapshots(bs);
2274 break;
2275
2276 case SNAPSHOT_CREATE:
2277 memset(&sn, 0, sizeof(sn));
2278 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2279
2280 qemu_gettimeofday(&tv);
2281 sn.date_sec = tv.tv_sec;
2282 sn.date_nsec = tv.tv_usec * 1000;
2283
2284 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002285 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002286 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002287 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002288 }
aliguorif7b4a942009-01-07 17:40:15 +00002289 break;
2290
2291 case SNAPSHOT_APPLY:
2292 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002293 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002294 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002295 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002296 }
aliguorif7b4a942009-01-07 17:40:15 +00002297 break;
2298
2299 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002300 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002301 if (err) {
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002302 error_report("Could not delete snapshot '%s': (%s)",
2303 snapshot_name, error_get_pretty(err));
2304 error_free(err);
2305 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002306 }
aliguorif7b4a942009-01-07 17:40:15 +00002307 break;
2308 }
2309
2310 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002311 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002312 if (ret) {
2313 return 1;
2314 }
Stuart Brady153859b2009-06-07 00:42:17 +01002315 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002316}
2317
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002318static int img_rebase(int argc, char **argv)
2319{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002320 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002321 BlockDriverState *bs = NULL, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01002322 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002323 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02002324 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2325 int c, flags, src_flags, ret;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002326 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002327 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002328 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002329 Error *local_err = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002330
2331 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002332 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002333 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02002334 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002335 out_baseimg = NULL;
2336 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002337 for(;;) {
Max Reitz40055952014-07-22 22:58:42 +02002338 c = getopt(argc, argv, "hf:F:b:upt:T:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002339 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002340 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002341 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002342 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002343 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002344 case 'h':
2345 help();
2346 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002347 case 'f':
2348 fmt = optarg;
2349 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002350 case 'F':
2351 out_basefmt = optarg;
2352 break;
2353 case 'b':
2354 out_baseimg = optarg;
2355 break;
2356 case 'u':
2357 unsafe = 1;
2358 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002359 case 'p':
2360 progress = 1;
2361 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002362 case 't':
2363 cache = optarg;
2364 break;
Max Reitz40055952014-07-22 22:58:42 +02002365 case 'T':
2366 src_cache = optarg;
2367 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002368 case 'q':
2369 quiet = true;
2370 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002371 }
2372 }
2373
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002374 if (quiet) {
2375 progress = 0;
2376 }
2377
Fam Zhengac1307a2014-04-22 13:36:11 +08002378 if (optind != argc - 1) {
2379 error_exit("Expecting one image file name");
2380 }
2381 if (!unsafe && !out_baseimg) {
2382 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002383 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002384 filename = argv[optind++];
2385
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002386 qemu_progress_init(progress, 2.0);
2387 qemu_progress_print(0, 100);
2388
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002389 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01002390 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002391 if (ret < 0) {
2392 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002393 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002394 }
2395
Max Reitz40055952014-07-22 22:58:42 +02002396 src_flags = BDRV_O_FLAGS;
2397 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2398 if (ret < 0) {
2399 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002400 goto out;
Max Reitz40055952014-07-22 22:58:42 +02002401 }
2402
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002403 /*
2404 * Open the images.
2405 *
2406 * Ignore the old backing file for unsafe rebase in case we want to correct
2407 * the reference to a renamed or moved backing file.
2408 */
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002409 blk = img_open("image", filename, fmt, flags, true, quiet);
2410 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002411 ret = -1;
2412 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002413 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002414 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002415
2416 /* Find the right drivers for the backing files */
2417 old_backing_drv = NULL;
2418 new_backing_drv = NULL;
2419
2420 if (!unsafe && bs->backing_format[0] != '\0') {
2421 old_backing_drv = bdrv_find_format(bs->backing_format);
2422 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002423 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002424 ret = -1;
2425 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002426 }
2427 }
2428
2429 if (out_basefmt != NULL) {
2430 new_backing_drv = bdrv_find_format(out_basefmt);
2431 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002432 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002433 ret = -1;
2434 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002435 }
2436 }
2437
2438 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002439 if (!unsafe) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002440 char backing_name[1024];
2441
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002442 blk_old_backing = blk_new_with_bs("old_backing", &error_abort);
2443 bs_old_backing = blk_bs(blk_old_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002444 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitz40055952014-07-22 22:58:42 +02002445 ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002446 old_backing_drv, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002447 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002448 error_report("Could not open old backing file '%s': %s",
2449 backing_name, error_get_pretty(local_err));
2450 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002451 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002452 }
Alex Bligha6166732012-10-16 13:46:18 +01002453 if (out_baseimg[0]) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002454 blk_new_backing = blk_new_with_bs("new_backing", &error_abort);
2455 bs_new_backing = blk_bs(blk_new_backing);
Max Reitz40055952014-07-22 22:58:42 +02002456 ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
2457 new_backing_drv, &local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002458 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002459 error_report("Could not open new backing file '%s': %s",
2460 out_baseimg, error_get_pretty(local_err));
2461 error_free(local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002462 goto out;
2463 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002464 }
2465 }
2466
2467 /*
2468 * Check each unallocated cluster in the COW file. If it is unallocated,
2469 * accesses go to the backing file. We must therefore compare this cluster
2470 * in the old and new backing file, and if they differ we need to copy it
2471 * from the old backing file into the COW file.
2472 *
2473 * If qemu-img crashes during this step, no harm is done. The content of
2474 * the image is the same as the original one at any time.
2475 */
2476 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002477 int64_t num_sectors;
2478 int64_t old_backing_num_sectors;
2479 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002480 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02002481 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08002482 uint8_t * buf_old;
2483 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02002484 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08002485
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002486 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2487 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002488
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002489 num_sectors = bdrv_nb_sectors(bs);
2490 if (num_sectors < 0) {
2491 error_report("Could not get size of '%s': %s",
2492 filename, strerror(-num_sectors));
2493 ret = -1;
2494 goto out;
2495 }
2496 old_backing_num_sectors = bdrv_nb_sectors(bs_old_backing);
2497 if (old_backing_num_sectors < 0) {
2498 char backing_name[1024];
2499
2500 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2501 error_report("Could not get size of '%s': %s",
2502 backing_name, strerror(-old_backing_num_sectors));
2503 ret = -1;
2504 goto out;
2505 }
Alex Bligha6166732012-10-16 13:46:18 +01002506 if (bs_new_backing) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002507 new_backing_num_sectors = bdrv_nb_sectors(bs_new_backing);
2508 if (new_backing_num_sectors < 0) {
2509 error_report("Could not get size of '%s': %s",
2510 out_baseimg, strerror(-new_backing_num_sectors));
2511 ret = -1;
2512 goto out;
2513 }
Alex Bligha6166732012-10-16 13:46:18 +01002514 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002515
Kevin Wolf1f710492012-10-12 14:29:18 +02002516 if (num_sectors != 0) {
2517 local_progress = (float)100 /
2518 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2519 }
2520
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002521 for (sector = 0; sector < num_sectors; sector += n) {
2522
2523 /* How many sectors can we handle with the next read? */
2524 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2525 n = (IO_BUF_SIZE / 512);
2526 } else {
2527 n = num_sectors - sector;
2528 }
2529
2530 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02002531 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02002532 if (ret < 0) {
2533 error_report("error while reading image metadata: %s",
2534 strerror(-ret));
2535 goto out;
2536 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02002537 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002538 continue;
2539 }
2540
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002541 /*
2542 * Read old and new backing file and take into consideration that
2543 * backing files may be smaller than the COW image.
2544 */
2545 if (sector >= old_backing_num_sectors) {
2546 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2547 } else {
2548 if (sector + n > old_backing_num_sectors) {
2549 n = old_backing_num_sectors - sector;
2550 }
2551
2552 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2553 if (ret < 0) {
2554 error_report("error while reading from old backing file");
2555 goto out;
2556 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002557 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002558
Alex Bligha6166732012-10-16 13:46:18 +01002559 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002560 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2561 } else {
2562 if (sector + n > new_backing_num_sectors) {
2563 n = new_backing_num_sectors - sector;
2564 }
2565
2566 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2567 if (ret < 0) {
2568 error_report("error while reading from new backing file");
2569 goto out;
2570 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002571 }
2572
2573 /* If they differ, we need to write to the COW file */
2574 uint64_t written = 0;
2575
2576 while (written < n) {
2577 int pnum;
2578
2579 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01002580 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002581 {
2582 ret = bdrv_write(bs, sector + written,
2583 buf_old + written * 512, pnum);
2584 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002585 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002586 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002587 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002588 }
2589 }
2590
2591 written += pnum;
2592 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002593 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002594 }
TeLeMand6771bf2010-02-08 16:20:00 +08002595
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002596 qemu_vfree(buf_old);
2597 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002598 }
2599
2600 /*
2601 * Change the backing file. All clusters that are different from the old
2602 * backing file are overwritten in the COW file now, so the visible content
2603 * doesn't change when we switch the backing file.
2604 */
Alex Bligha6166732012-10-16 13:46:18 +01002605 if (out_baseimg && *out_baseimg) {
2606 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2607 } else {
2608 ret = bdrv_change_backing_file(bs, NULL, NULL);
2609 }
2610
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002611 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002612 error_report("Could not change the backing file to '%s': No "
2613 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002614 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002615 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002616 out_baseimg, strerror(-ret));
2617 }
2618
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002619 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002620 /*
2621 * TODO At this point it is possible to check if any clusters that are
2622 * allocated in the COW file are the same in the backing file. If so, they
2623 * could be dropped from the COW file. Don't do this before switching the
2624 * backing file, in case of a crash this would lead to corruption.
2625 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002626out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002627 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002628 /* Cleanup */
2629 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002630 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002631 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002632 }
2633
Markus Armbruster26f54e92014-10-07 13:59:04 +02002634 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002635 if (ret) {
2636 return 1;
2637 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002638 return 0;
2639}
2640
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002641static int img_resize(int argc, char **argv)
2642{
2643 int c, ret, relative;
2644 const char *filename, *fmt, *size;
2645 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002646 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002647 BlockBackend *blk = NULL;
Jes Sorensen2a819982010-12-06 17:08:31 +01002648 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002649 QemuOpts *param;
2650 static QemuOptsList resize_options = {
2651 .name = "resize_options",
2652 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2653 .desc = {
2654 {
2655 .name = BLOCK_OPT_SIZE,
2656 .type = QEMU_OPT_SIZE,
2657 .help = "Virtual disk size"
2658 }, {
2659 /* end of list */
2660 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002661 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002662 };
2663
Kevin Wolfe80fec72011-04-29 10:58:12 +02002664 /* Remove size from argv manually so that negative numbers are not treated
2665 * as options by getopt. */
2666 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002667 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02002668 return 1;
2669 }
2670
2671 size = argv[--argc];
2672
2673 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002674 fmt = NULL;
2675 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002676 c = getopt(argc, argv, "f:hq");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002677 if (c == -1) {
2678 break;
2679 }
2680 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002681 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002682 case 'h':
2683 help();
2684 break;
2685 case 'f':
2686 fmt = optarg;
2687 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002688 case 'q':
2689 quiet = true;
2690 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002691 }
2692 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002693 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002694 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002695 }
2696 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002697
2698 /* Choose grow, shrink, or absolute resize mode */
2699 switch (size[0]) {
2700 case '+':
2701 relative = 1;
2702 size++;
2703 break;
2704 case '-':
2705 relative = -1;
2706 size++;
2707 break;
2708 default:
2709 relative = 0;
2710 break;
2711 }
2712
2713 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08002714 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002715 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002716 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002717 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002718 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002719 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002720 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002721 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2722 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002723
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002724 blk = img_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
2725 true, quiet);
2726 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002727 ret = -1;
2728 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002729 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002730 bs = blk_bs(blk);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002731
2732 if (relative) {
2733 total_size = bdrv_getlength(bs) + n * relative;
2734 } else {
2735 total_size = n;
2736 }
2737 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002738 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002739 ret = -1;
2740 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002741 }
2742
2743 ret = bdrv_truncate(bs, total_size);
2744 switch (ret) {
2745 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002746 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002747 break;
2748 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002749 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002750 break;
2751 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002752 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002753 break;
2754 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002755 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002756 break;
2757 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002758out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002759 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002760 if (ret) {
2761 return 1;
2762 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002763 return 0;
2764}
2765
Max Reitz6f176b42013-09-03 10:09:50 +02002766static int img_amend(int argc, char **argv)
2767{
2768 int c, ret = 0;
2769 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002770 QemuOptsList *create_opts = NULL;
2771 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02002772 const char *fmt = NULL, *filename, *cache;
2773 int flags;
Max Reitz6f176b42013-09-03 10:09:50 +02002774 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002775 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02002776 BlockDriverState *bs = NULL;
2777
Max Reitzbd39e6e2014-07-22 22:58:43 +02002778 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02002779 for (;;) {
Max Reitzbd39e6e2014-07-22 22:58:43 +02002780 c = getopt(argc, argv, "ho:f:t:q");
Max Reitz6f176b42013-09-03 10:09:50 +02002781 if (c == -1) {
2782 break;
2783 }
2784
2785 switch (c) {
2786 case 'h':
2787 case '?':
2788 help();
2789 break;
2790 case 'o':
Kevin Wolf626f84f2014-02-21 16:24:06 +01002791 if (!is_valid_option_list(optarg)) {
2792 error_report("Invalid option list: %s", optarg);
2793 ret = -1;
2794 goto out;
2795 }
2796 if (!options) {
2797 options = g_strdup(optarg);
2798 } else {
2799 char *old_options = options;
2800 options = g_strdup_printf("%s,%s", options, optarg);
2801 g_free(old_options);
2802 }
Max Reitz6f176b42013-09-03 10:09:50 +02002803 break;
2804 case 'f':
2805 fmt = optarg;
2806 break;
Max Reitzbd39e6e2014-07-22 22:58:43 +02002807 case 't':
2808 cache = optarg;
2809 break;
Max Reitz6f176b42013-09-03 10:09:50 +02002810 case 'q':
2811 quiet = true;
2812 break;
2813 }
2814 }
2815
Max Reitz6f176b42013-09-03 10:09:50 +02002816 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002817 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02002818 }
2819
Kevin Wolfa283cb62014-02-21 16:24:07 +01002820 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
2821 if (fmt && has_help_option(options)) {
2822 /* If a format is explicitly specified (and possibly no filename is
2823 * given), print option help here */
2824 ret = print_block_option_help(filename, fmt);
2825 goto out;
2826 }
2827
2828 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002829 error_exit("Expecting one image file name");
Kevin Wolfa283cb62014-02-21 16:24:07 +01002830 }
Max Reitz6f176b42013-09-03 10:09:50 +02002831
Max Reitzbd39e6e2014-07-22 22:58:43 +02002832 flags = BDRV_O_FLAGS | BDRV_O_RDWR;
2833 ret = bdrv_parse_cache_flags(cache, &flags);
2834 if (ret < 0) {
2835 error_report("Invalid cache option: %s", cache);
2836 goto out;
2837 }
2838
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002839 blk = img_open("image", filename, fmt, flags, true, quiet);
2840 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02002841 error_report("Could not open image '%s'", filename);
2842 ret = -1;
2843 goto out;
2844 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002845 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02002846
2847 fmt = bs->drv->format_name;
2848
Kevin Wolf626f84f2014-02-21 16:24:06 +01002849 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01002850 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02002851 ret = print_block_option_help(filename, fmt);
2852 goto out;
2853 }
2854
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002855 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08002856 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2857 if (options && qemu_opts_do_parse(opts, options, NULL)) {
Max Reitz6f176b42013-09-03 10:09:50 +02002858 error_report("Invalid options for file format '%s'", fmt);
2859 ret = -1;
2860 goto out;
2861 }
2862
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002863 ret = bdrv_amend_options(bs, opts);
Max Reitz6f176b42013-09-03 10:09:50 +02002864 if (ret < 0) {
2865 error_report("Error while amending options: %s", strerror(-ret));
2866 goto out;
2867 }
2868
2869out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002870 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08002871 qemu_opts_del(opts);
2872 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01002873 g_free(options);
2874
Max Reitz6f176b42013-09-03 10:09:50 +02002875 if (ret) {
2876 return 1;
2877 }
2878 return 0;
2879}
2880
Anthony Liguoric227f092009-10-01 16:12:16 -05002881static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002882#define DEF(option, callback, arg_string) \
2883 { option, callback },
2884#include "qemu-img-cmds.h"
2885#undef DEF
2886#undef GEN_DOCS
2887 { NULL, NULL, },
2888};
2889
bellardea2384d2004-08-01 21:59:26 +00002890int main(int argc, char **argv)
2891{
Anthony Liguoric227f092009-10-01 16:12:16 -05002892 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002893 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03002894 Error *local_error = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04002895 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04002896 static const struct option long_options[] = {
2897 {"help", no_argument, 0, 'h'},
Jeff Cody5f6979c2014-04-28 14:37:18 -04002898 {"version", no_argument, 0, 'v'},
Jeff Cody7db16892014-04-25 17:02:32 -04002899 {0, 0, 0, 0}
2900 };
bellardea2384d2004-08-01 21:59:26 +00002901
MORITA Kazutaka526eda12013-07-23 17:30:11 +09002902#ifdef CONFIG_POSIX
2903 signal(SIGPIPE, SIG_IGN);
2904#endif
2905
Kevin Wolf53f76e52010-12-16 15:10:32 +01002906 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08002907 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01002908
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03002909 if (qemu_init_main_loop(&local_error)) {
2910 error_report("%s", error_get_pretty(local_error));
2911 error_free(local_error);
2912 exit(EXIT_FAILURE);
2913 }
2914
bellardea2384d2004-08-01 21:59:26 +00002915 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08002916 if (argc < 2) {
2917 error_exit("Not enough arguments");
2918 }
Stuart Brady153859b2009-06-07 00:42:17 +01002919 cmdname = argv[1];
Stuart Brady153859b2009-06-07 00:42:17 +01002920
2921 /* find the command */
Jeff Cody5f6979c2014-04-28 14:37:18 -04002922 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
Stuart Brady153859b2009-06-07 00:42:17 +01002923 if (!strcmp(cmdname, cmd->name)) {
Jeff Cody7db16892014-04-25 17:02:32 -04002924 return cmd->handler(argc - 1, argv + 1);
Stuart Brady153859b2009-06-07 00:42:17 +01002925 }
bellardea2384d2004-08-01 21:59:26 +00002926 }
Stuart Brady153859b2009-06-07 00:42:17 +01002927
Jeff Cody5f6979c2014-04-28 14:37:18 -04002928 c = getopt_long(argc, argv, "h", long_options, NULL);
Jeff Cody7db16892014-04-25 17:02:32 -04002929
2930 if (c == 'h') {
2931 help();
2932 }
Jeff Cody5f6979c2014-04-28 14:37:18 -04002933 if (c == 'v') {
2934 printf(QEMU_IMG_VERSION);
2935 return 0;
2936 }
Jeff Cody7db16892014-04-25 17:02:32 -04002937
Stuart Brady153859b2009-06-07 00:42:17 +01002938 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08002939 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00002940}