blob: 494146d6bbfb60c15d56ecda34db6ea7d238a78d [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"
Max Reitzd4a32382014-10-24 15:57:37 +020034#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080035#include "block/qapi.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020036#include <getopt.h>
bellarde8445332006-06-14 15:32:10 +000037
Jeff Cody5f6979c2014-04-28 14:37:18 -040038#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION \
39 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
40
Anthony Liguoric227f092009-10-01 16:12:16 -050041typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010042 const char *name;
43 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050044} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010045
Federico Simoncelli8599ea42013-01-28 06:59:47 -050046enum {
47 OPTION_OUTPUT = 256,
48 OPTION_BACKING_CHAIN = 257,
49};
50
51typedef enum OutputFormat {
52 OFORMAT_JSON,
53 OFORMAT_HUMAN,
54} OutputFormat;
55
aurel32137519c2008-11-30 19:12:49 +000056/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
Stefan Hajnocziadfe0782010-04-13 10:29:35 +010057#define BDRV_O_FLAGS BDRV_O_CACHE_WB
Federico Simoncelli661a0f72011-06-20 12:48:19 -040058#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000059
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010060static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000061{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010062 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000063}
64
Fam Zhengac1307a2014-04-22 13:36:11 +080065static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
66{
67 va_list ap;
68
69 error_printf("qemu-img: ");
70
71 va_start(ap, fmt);
72 error_vprintf(fmt, ap);
73 va_end(ap);
74
75 error_printf("\nTry 'qemu-img --help' for more information\n");
76 exit(EXIT_FAILURE);
77}
78
blueswir1d2c639d2009-01-24 18:19:25 +000079/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +080080static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +000081{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010082 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -040083 QEMU_IMG_VERSION
malc3f020d72010-02-08 12:04:56 +030084 "usage: qemu-img command [command options]\n"
85 "QEMU disk image utility\n"
86 "\n"
87 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +010088#define DEF(option, callback, arg_string) \
89 " " arg_string "\n"
90#include "qemu-img-cmds.h"
91#undef DEF
92#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +030093 "\n"
94 "Command parameters:\n"
95 " 'filename' is a disk image filename\n"
96 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -040097 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +080098 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
99 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100100 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
101 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300102 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200103 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
104 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
105 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300106 " 'output_filename' is the destination disk image filename\n"
107 " 'output_fmt' is the destination format\n"
108 " 'options' is a comma separated list of format specific options in a\n"
109 " name=value format. Use -o ? for an overview of the options supported by the\n"
110 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800111 " 'snapshot_param' is param used for internal snapshot, format\n"
112 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
113 " '[ID_OR_NAME]'\n"
114 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
115 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300116 " '-c' indicates that target image must be compressed (qcow format only)\n"
117 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
118 " match exactly. The image doesn't need a working backing file before\n"
119 " rebasing in this case (useful for renaming the backing file)\n"
120 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200121 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100122 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200123 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
124 " contain only zeros for qemu-img to create a sparse image during\n"
125 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
126 " unallocated or zero sectors, and the destination image will always be\n"
127 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200128 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100129 " '-n' skips the target volume creation (useful if the volume is created\n"
130 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300131 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200132 "Parameters to check subcommand:\n"
133 " '-r' tries to repair any inconsistencies that are found during the check.\n"
134 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
135 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200136 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200137 "\n"
malc3f020d72010-02-08 12:04:56 +0300138 "Parameters to snapshot subcommand:\n"
139 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
140 " '-a' applies a snapshot (revert disk to saved state)\n"
141 " '-c' creates a snapshot\n"
142 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100143 " '-l' lists all snapshots in the given image\n"
144 "\n"
145 "Parameters to compare subcommand:\n"
146 " '-f' first image format\n"
147 " '-F' second image format\n"
148 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100149
150 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100151 bdrv_iterate_format(format_print, NULL);
bellardea2384d2004-08-01 21:59:26 +0000152 printf("\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800153 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000154}
155
Stefan Weil7c30f652013-06-16 17:01:05 +0200156static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100157{
158 int ret = 0;
159 if (!quiet) {
160 va_list args;
161 va_start(args, fmt);
162 ret = vprintf(fmt, args);
163 va_end(args);
164 }
165 return ret;
166}
167
bellardea2384d2004-08-01 21:59:26 +0000168#if defined(WIN32)
169/* XXX: put correct support for win32 */
170static int read_password(char *buf, int buf_size)
171{
172 int c, i;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800173
bellardea2384d2004-08-01 21:59:26 +0000174 printf("Password: ");
175 fflush(stdout);
176 i = 0;
177 for(;;) {
178 c = getchar();
Chen Gangfdcf6e62014-07-06 16:43:33 +0800179 if (c < 0) {
180 buf[i] = '\0';
181 return -1;
182 } else if (c == '\n') {
bellardea2384d2004-08-01 21:59:26 +0000183 break;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800184 } else if (i < (buf_size - 1)) {
bellardea2384d2004-08-01 21:59:26 +0000185 buf[i++] = c;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800186 }
bellardea2384d2004-08-01 21:59:26 +0000187 }
188 buf[i] = '\0';
189 return 0;
190}
191
192#else
193
194#include <termios.h>
195
196static struct termios oldtty;
197
198static void term_exit(void)
199{
200 tcsetattr (0, TCSANOW, &oldtty);
201}
202
203static void term_init(void)
204{
205 struct termios tty;
206
207 tcgetattr (0, &tty);
208 oldtty = tty;
209
210 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
211 |INLCR|IGNCR|ICRNL|IXON);
212 tty.c_oflag |= OPOST;
213 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
214 tty.c_cflag &= ~(CSIZE|PARENB);
215 tty.c_cflag |= CS8;
216 tty.c_cc[VMIN] = 1;
217 tty.c_cc[VTIME] = 0;
ths3b46e622007-09-17 08:09:54 +0000218
bellardea2384d2004-08-01 21:59:26 +0000219 tcsetattr (0, TCSANOW, &tty);
220
221 atexit(term_exit);
222}
223
pbrook3f379ab2007-11-11 03:33:13 +0000224static int read_password(char *buf, int buf_size)
bellardea2384d2004-08-01 21:59:26 +0000225{
226 uint8_t ch;
227 int i, ret;
228
229 printf("password: ");
230 fflush(stdout);
231 term_init();
232 i = 0;
233 for(;;) {
234 ret = read(0, &ch, 1);
235 if (ret == -1) {
236 if (errno == EAGAIN || errno == EINTR) {
237 continue;
238 } else {
bellardea2384d2004-08-01 21:59:26 +0000239 break;
240 }
241 } else if (ret == 0) {
242 ret = -1;
243 break;
244 } else {
245 if (ch == '\r') {
246 ret = 0;
247 break;
248 }
249 if (i < (buf_size - 1))
250 buf[i++] = ch;
251 }
252 }
253 term_exit();
254 buf[i] = '\0';
255 printf("\n");
256 return ret;
257}
258#endif
259
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100260static int print_block_option_help(const char *filename, const char *fmt)
261{
262 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800263 QemuOptsList *create_opts = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100264
265 /* Find driver and parse its options */
266 drv = bdrv_find_format(fmt);
267 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100268 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100269 return 1;
270 }
271
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800272 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100273 if (filename) {
274 proto_drv = bdrv_find_protocol(filename, true);
275 if (!proto_drv) {
276 error_report("Unknown protocol '%s'", filename);
Chunyan Liu83d05212014-06-05 17:20:51 +0800277 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100278 return 1;
279 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800280 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100281 }
282
Chunyan Liu83d05212014-06-05 17:20:51 +0800283 qemu_opts_print_help(create_opts);
284 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100285 return 0;
286}
287
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200288static BlockBackend *img_open(const char *id, const char *filename,
289 const char *fmt, int flags,
290 bool require_io, bool quiet)
bellard75c23802004-08-27 21:28:58 +0000291{
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200292 BlockBackend *blk;
bellard75c23802004-08-27 21:28:58 +0000293 BlockDriverState *bs;
294 BlockDriver *drv;
295 char password[256];
Max Reitz34b5d2c2013-09-05 14:45:29 +0200296 Error *local_err = NULL;
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100297 int ret;
bellard75c23802004-08-27 21:28:58 +0000298
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200299 blk = blk_new_with_bs(id, &error_abort);
300 bs = blk_bs(blk);
Kevin Wolfad717132010-12-16 15:37:41 +0100301
bellard75c23802004-08-27 21:28:58 +0000302 if (fmt) {
303 drv = bdrv_find_format(fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900304 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100305 error_report("Unknown file format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900306 goto fail;
307 }
bellard75c23802004-08-27 21:28:58 +0000308 } else {
309 drv = NULL;
310 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100311
Max Reitzddf56362014-02-18 18:33:06 +0100312 ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100313 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200314 error_report("Could not open '%s': %s", filename,
315 error_get_pretty(local_err));
316 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900317 goto fail;
bellard75c23802004-08-27 21:28:58 +0000318 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100319
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100320 if (bdrv_is_encrypted(bs) && require_io) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100321 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900322 if (read_password(password, sizeof(password)) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100323 error_report("No password given");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900324 goto fail;
325 }
326 if (bdrv_set_key(bs, password) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100327 error_report("invalid password");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900328 goto fail;
329 }
bellard75c23802004-08-27 21:28:58 +0000330 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200331 return blk;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900332fail:
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200333 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900334 return NULL;
bellard75c23802004-08-27 21:28:58 +0000335}
336
Chunyan Liu83d05212014-06-05 17:20:51 +0800337static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100338 const char *base_filename,
339 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200340{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200341 if (base_filename) {
Chunyan Liu83d05212014-06-05 17:20:51 +0800342 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100343 error_report("Backing file not supported for file format '%s'",
344 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900345 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200346 }
347 }
348 if (base_fmt) {
Chunyan Liu83d05212014-06-05 17:20:51 +0800349 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100350 error_report("Backing file format not supported for file "
351 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900352 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200353 }
354 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900355 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200356}
357
bellardea2384d2004-08-01 21:59:26 +0000358static int img_create(int argc, char **argv)
359{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200360 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100361 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000362 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000363 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000364 const char *filename;
365 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200366 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200367 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100368 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000369
bellardea2384d2004-08-01 21:59:26 +0000370 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100371 c = getopt(argc, argv, "F:b:f:he6o:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100372 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000373 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100374 }
bellardea2384d2004-08-01 21:59:26 +0000375 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100376 case '?':
bellardea2384d2004-08-01 21:59:26 +0000377 case 'h':
378 help();
379 break;
aliguori9230eaf2009-03-28 17:55:19 +0000380 case 'F':
381 base_fmt = optarg;
382 break;
bellardea2384d2004-08-01 21:59:26 +0000383 case 'b':
384 base_filename = optarg;
385 break;
386 case 'f':
387 fmt = optarg;
388 break;
389 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200390 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100391 "encryption\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100392 goto fail;
thsd8871c52007-10-24 16:11:42 +0000393 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200394 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100395 "compat6\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100396 goto fail;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200397 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100398 if (!is_valid_option_list(optarg)) {
399 error_report("Invalid option list: %s", optarg);
400 goto fail;
401 }
402 if (!options) {
403 options = g_strdup(optarg);
404 } else {
405 char *old_options = options;
406 options = g_strdup_printf("%s,%s", options, optarg);
407 g_free(old_options);
408 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200409 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100410 case 'q':
411 quiet = true;
412 break;
bellardea2384d2004-08-01 21:59:26 +0000413 }
414 }
aliguori9230eaf2009-03-28 17:55:19 +0000415
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900416 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100417 filename = (optind < argc) ? argv[optind] : NULL;
418 if (options && has_help_option(options)) {
419 g_free(options);
420 return print_block_option_help(filename, fmt);
421 }
422
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100423 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800424 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100425 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100426 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900427
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100428 /* Get image size, if specified */
429 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100430 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100431 char *end;
432 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
433 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800434 if (sval == -ERANGE) {
435 error_report("Image size must be less than 8 EiB!");
436 } else {
437 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200438 "G, T, P or E suffixes for ");
439 error_report("kilobytes, megabytes, gigabytes, terabytes, "
440 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800441 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100442 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100443 }
444 img_size = (uint64_t)sval;
445 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200446 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800447 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200448 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100449
Luiz Capitulino9b375252012-11-30 10:52:05 -0200450 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100451 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100452 if (local_err) {
Max Reitzb70d8c22013-09-06 16:51:03 +0200453 error_report("%s: %s", filename, error_get_pretty(local_err));
Luiz Capitulino9b375252012-11-30 10:52:05 -0200454 error_free(local_err);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100455 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900456 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200457
Kevin Wolf77386bf2014-02-21 16:24:04 +0100458 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000459 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100460
461fail:
462 g_free(options);
463 return 1;
bellardea2384d2004-08-01 21:59:26 +0000464}
465
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100466static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500467{
Markus Armbruster4399c432014-04-25 16:50:32 +0200468 Error *local_err = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500469 QString *str;
470 QmpOutputVisitor *ov = qmp_output_visitor_new();
471 QObject *obj;
472 visit_type_ImageCheck(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +0200473 &check, NULL, &local_err);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500474 obj = qmp_output_get_qobject(ov);
475 str = qobject_to_json_pretty(obj);
476 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100477 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500478 qobject_decref(obj);
479 qmp_output_visitor_cleanup(ov);
480 QDECREF(str);
481}
482
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100483static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500484{
485 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100486 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500487 } else {
488 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100489 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
490 "Data may be corrupted, or further writes to the image "
491 "may corrupt it.\n",
492 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500493 }
494
495 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100496 qprintf(quiet,
497 "\n%" PRId64 " leaked clusters were found on the image.\n"
498 "This means waste of disk space, but no harm to data.\n",
499 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500500 }
501
502 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100503 qprintf(quiet,
504 "\n%" PRId64
505 " internal errors have occurred during the check.\n",
506 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500507 }
508 }
509
510 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100511 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
512 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
513 check->allocated_clusters, check->total_clusters,
514 check->allocated_clusters * 100.0 / check->total_clusters,
515 check->fragmented_clusters * 100.0 / check->allocated_clusters,
516 check->compressed_clusters * 100.0 /
517 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500518 }
519
520 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100521 qprintf(quiet,
522 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500523 }
524}
525
526static int collect_image_check(BlockDriverState *bs,
527 ImageCheck *check,
528 const char *filename,
529 const char *fmt,
530 int fix)
531{
532 int ret;
533 BdrvCheckResult result;
534
535 ret = bdrv_check(bs, &result, fix);
536 if (ret < 0) {
537 return ret;
538 }
539
540 check->filename = g_strdup(filename);
541 check->format = g_strdup(bdrv_get_format_name(bs));
542 check->check_errors = result.check_errors;
543 check->corruptions = result.corruptions;
544 check->has_corruptions = result.corruptions != 0;
545 check->leaks = result.leaks;
546 check->has_leaks = result.leaks != 0;
547 check->corruptions_fixed = result.corruptions_fixed;
548 check->has_corruptions_fixed = result.corruptions != 0;
549 check->leaks_fixed = result.leaks_fixed;
550 check->has_leaks_fixed = result.leaks != 0;
551 check->image_end_offset = result.image_end_offset;
552 check->has_image_end_offset = result.image_end_offset != 0;
553 check->total_clusters = result.bfi.total_clusters;
554 check->has_total_clusters = result.bfi.total_clusters != 0;
555 check->allocated_clusters = result.bfi.allocated_clusters;
556 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
557 check->fragmented_clusters = result.bfi.fragmented_clusters;
558 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100559 check->compressed_clusters = result.bfi.compressed_clusters;
560 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500561
562 return 0;
563}
564
Kevin Wolfe076f332010-06-29 11:43:13 +0200565/*
566 * Checks an image for consistency. Exit codes:
567 *
Max Reitzd6635c42014-06-02 22:15:21 +0200568 * 0 - Check completed, image is good
569 * 1 - Check not completed because of internal errors
570 * 2 - Check completed, image is corrupted
571 * 3 - Check completed, image has leaked clusters, but is good otherwise
572 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200573 */
aliguori15859692009-04-21 23:11:53 +0000574static int img_check(int argc, char **argv)
575{
576 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500577 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200578 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200579 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000580 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200581 int fix = 0;
Stefan Hajnoczi058f8f12012-08-09 13:05:56 +0100582 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200583 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100584 bool quiet = false;
aliguori15859692009-04-21 23:11:53 +0000585
586 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500587 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200588 cache = BDRV_DEFAULT_CACHE;
aliguori15859692009-04-21 23:11:53 +0000589 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500590 int option_index = 0;
591 static const struct option long_options[] = {
592 {"help", no_argument, 0, 'h'},
593 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530594 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500595 {"output", required_argument, 0, OPTION_OUTPUT},
596 {0, 0, 0, 0}
597 };
Max Reitz40055952014-07-22 22:58:42 +0200598 c = getopt_long(argc, argv, "hf:r:T:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500599 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100600 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000601 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100602 }
aliguori15859692009-04-21 23:11:53 +0000603 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100604 case '?':
aliguori15859692009-04-21 23:11:53 +0000605 case 'h':
606 help();
607 break;
608 case 'f':
609 fmt = optarg;
610 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200611 case 'r':
612 flags |= BDRV_O_RDWR;
613
614 if (!strcmp(optarg, "leaks")) {
615 fix = BDRV_FIX_LEAKS;
616 } else if (!strcmp(optarg, "all")) {
617 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
618 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800619 error_exit("Unknown option value for -r "
620 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200621 }
622 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500623 case OPTION_OUTPUT:
624 output = optarg;
625 break;
Max Reitz40055952014-07-22 22:58:42 +0200626 case 'T':
627 cache = optarg;
628 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100629 case 'q':
630 quiet = true;
631 break;
aliguori15859692009-04-21 23:11:53 +0000632 }
633 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200634 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800635 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100636 }
aliguori15859692009-04-21 23:11:53 +0000637 filename = argv[optind++];
638
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500639 if (output && !strcmp(output, "json")) {
640 output_format = OFORMAT_JSON;
641 } else if (output && !strcmp(output, "human")) {
642 output_format = OFORMAT_HUMAN;
643 } else if (output) {
644 error_report("--output must be used with human or json as argument.");
645 return 1;
646 }
647
Max Reitz40055952014-07-22 22:58:42 +0200648 ret = bdrv_parse_cache_flags(cache, &flags);
649 if (ret < 0) {
650 error_report("Invalid source cache option: %s", cache);
651 return 1;
652 }
653
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200654 blk = img_open("image", filename, fmt, flags, true, quiet);
655 if (!blk) {
656 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900657 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200658 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500659
660 check = g_new0(ImageCheck, 1);
661 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200662
663 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200664 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200665 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500666 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200667 }
668
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500669 if (check->corruptions_fixed || check->leaks_fixed) {
670 int corruptions_fixed, leaks_fixed;
671
672 leaks_fixed = check->leaks_fixed;
673 corruptions_fixed = check->corruptions_fixed;
674
675 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100676 qprintf(quiet,
677 "The following inconsistencies were found and repaired:\n\n"
678 " %" PRId64 " leaked clusters\n"
679 " %" PRId64 " corruptions\n\n"
680 "Double checking the fixed image now...\n",
681 check->leaks_fixed,
682 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500683 }
684
685 ret = collect_image_check(bs, check, filename, fmt, 0);
686
687 check->leaks_fixed = leaks_fixed;
688 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200689 }
690
Max Reitz832390a2014-10-23 15:29:12 +0200691 if (!ret) {
692 switch (output_format) {
693 case OFORMAT_HUMAN:
694 dump_human_image_check(check, quiet);
695 break;
696 case OFORMAT_JSON:
697 dump_json_image_check(check, quiet);
698 break;
699 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500700 }
701
702 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200703 if (ret) {
704 error_report("Check failed: %s", strerror(-ret));
705 } else {
706 error_report("Check failed");
707 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500708 ret = 1;
709 goto fail;
710 }
711
712 if (check->corruptions) {
713 ret = 2;
714 } else if (check->leaks) {
715 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200716 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500717 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000718 }
719
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500720fail:
721 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200722 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500723 return ret;
aliguori15859692009-04-21 23:11:53 +0000724}
725
Max Reitzd4a32382014-10-24 15:57:37 +0200726typedef struct CommonBlockJobCBInfo {
727 BlockDriverState *bs;
728 Error **errp;
729} CommonBlockJobCBInfo;
730
731static void common_block_job_cb(void *opaque, int ret)
732{
733 CommonBlockJobCBInfo *cbi = opaque;
734
735 if (ret < 0) {
736 error_setg_errno(cbi->errp, -ret, "Block job failed");
737 }
738
739 /* Drop this block job's reference */
740 bdrv_unref(cbi->bs);
741}
742
743static void run_block_job(BlockJob *job, Error **errp)
744{
745 AioContext *aio_context = bdrv_get_aio_context(job->bs);
746
747 do {
748 aio_poll(aio_context, true);
749 } while (!job->ready);
750
751 block_job_complete_sync(job, errp);
752}
753
bellardea2384d2004-08-01 21:59:26 +0000754static int img_commit(int argc, char **argv)
755{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400756 int c, ret, flags;
757 const char *filename, *fmt, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200758 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200759 BlockDriverState *bs, *base_bs;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100760 bool quiet = false;
Max Reitzd4a32382014-10-24 15:57:37 +0200761 Error *local_err = NULL;
762 CommonBlockJobCBInfo cbi;
bellardea2384d2004-08-01 21:59:26 +0000763
764 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400765 cache = BDRV_DEFAULT_CACHE;
bellardea2384d2004-08-01 21:59:26 +0000766 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100767 c = getopt(argc, argv, "f:ht:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100768 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000769 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100770 }
bellardea2384d2004-08-01 21:59:26 +0000771 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100772 case '?':
bellardea2384d2004-08-01 21:59:26 +0000773 case 'h':
774 help();
775 break;
776 case 'f':
777 fmt = optarg;
778 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400779 case 't':
780 cache = optarg;
781 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100782 case 'q':
783 quiet = true;
784 break;
bellardea2384d2004-08-01 21:59:26 +0000785 }
786 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200787 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800788 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100789 }
bellardea2384d2004-08-01 21:59:26 +0000790 filename = argv[optind++];
791
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400792 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100793 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400794 if (ret < 0) {
795 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100796 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400797 }
798
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200799 blk = img_open("image", filename, fmt, flags, true, quiet);
800 if (!blk) {
801 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900802 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200803 bs = blk_bs(blk);
804
Max Reitzd4a32382014-10-24 15:57:37 +0200805 /* This is different from QMP, which by default uses the deepest file in the
806 * backing chain (i.e., the very base); however, the traditional behavior of
807 * qemu-img commit is using the immediate backing file. */
808 base_bs = bs->backing_hd;
809 if (!base_bs) {
810 error_setg(&local_err, "Image does not have a backing file");
811 goto done;
bellardea2384d2004-08-01 21:59:26 +0000812 }
813
Max Reitzd4a32382014-10-24 15:57:37 +0200814 cbi = (CommonBlockJobCBInfo){
815 .errp = &local_err,
816 .bs = bs,
817 };
818
819 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
820 common_block_job_cb, &cbi, &local_err);
821 if (local_err) {
822 goto done;
823 }
824
825 run_block_job(bs->job, &local_err);
826
827done:
Markus Armbruster26f54e92014-10-07 13:59:04 +0200828 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200829
830 if (local_err) {
831 qerror_report_err(local_err);
832 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900833 return 1;
834 }
Max Reitzd4a32382014-10-24 15:57:37 +0200835
836 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000837 return 0;
838}
839
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400840/*
thsf58c7b32008-06-05 21:53:49 +0000841 * Returns true iff the first sector pointed to by 'buf' contains at least
842 * a non-NUL byte.
843 *
844 * 'pnum' is set to the number of sectors (including and immediately following
845 * the first one) that are known to be in the same allocated/unallocated state.
846 */
bellardea2384d2004-08-01 21:59:26 +0000847static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
848{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000849 bool is_zero;
850 int i;
bellardea2384d2004-08-01 21:59:26 +0000851
852 if (n <= 0) {
853 *pnum = 0;
854 return 0;
855 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000856 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +0000857 for(i = 1; i < n; i++) {
858 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000859 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +0000860 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000861 }
bellardea2384d2004-08-01 21:59:26 +0000862 }
863 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000864 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +0000865}
866
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100867/*
Kevin Wolfa22f1232011-08-26 15:27:13 +0200868 * Like is_allocated_sectors, but if the buffer starts with a used sector,
869 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
870 * breaking up write requests for only small sparse areas.
871 */
872static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
873 int min)
874{
875 int ret;
876 int num_checked, num_used;
877
878 if (n < min) {
879 min = n;
880 }
881
882 ret = is_allocated_sectors(buf, n, pnum);
883 if (!ret) {
884 return ret;
885 }
886
887 num_used = *pnum;
888 buf += BDRV_SECTOR_SIZE * *pnum;
889 n -= *pnum;
890 num_checked = num_used;
891
892 while (n > 0) {
893 ret = is_allocated_sectors(buf, n, pnum);
894
895 buf += BDRV_SECTOR_SIZE * *pnum;
896 n -= *pnum;
897 num_checked += *pnum;
898 if (ret) {
899 num_used = num_checked;
900 } else if (*pnum >= min) {
901 break;
902 }
903 }
904
905 *pnum = num_used;
906 return 1;
907}
908
909/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100910 * Compares two buffers sector by sector. Returns 0 if the first sector of both
911 * buffers matches, non-zero otherwise.
912 *
913 * pnum is set to the number of sectors (including and immediately following
914 * the first one) that are known to have the same comparison result
915 */
916static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
917 int *pnum)
918{
919 int res, i;
920
921 if (n <= 0) {
922 *pnum = 0;
923 return 0;
924 }
925
926 res = !!memcmp(buf1, buf2, 512);
927 for(i = 1; i < n; i++) {
928 buf1 += 512;
929 buf2 += 512;
930
931 if (!!memcmp(buf1, buf2, 512) != res) {
932 break;
933 }
934 }
935
936 *pnum = i;
937 return res;
938}
939
Kevin Wolf80ee15a2009-09-15 12:30:43 +0200940#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +0000941
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100942static int64_t sectors_to_bytes(int64_t sectors)
943{
944 return sectors << BDRV_SECTOR_BITS;
945}
946
947static int64_t sectors_to_process(int64_t total, int64_t from)
948{
949 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
950}
951
952/*
953 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
954 *
955 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
956 * data and negative value on error.
957 *
958 * @param bs: Driver used for accessing file
959 * @param sect_num: Number of first sector to check
960 * @param sect_count: Number of sectors to check
961 * @param filename: Name of disk file we are checking (logging purpose)
962 * @param buffer: Allocated buffer for storing read data
963 * @param quiet: Flag for quiet mode
964 */
965static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
966 int sect_count, const char *filename,
967 uint8_t *buffer, bool quiet)
968{
969 int pnum, ret = 0;
970 ret = bdrv_read(bs, sect_num, buffer, sect_count);
971 if (ret < 0) {
972 error_report("Error while reading offset %" PRId64 " of %s: %s",
973 sectors_to_bytes(sect_num), filename, strerror(-ret));
974 return ret;
975 }
976 ret = is_allocated_sectors(buffer, sect_count, &pnum);
977 if (ret || pnum != sect_count) {
978 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
979 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
980 return 1;
981 }
982
983 return 0;
984}
985
986/*
987 * Compares two images. Exit codes:
988 *
989 * 0 - Images are identical
990 * 1 - Images differ
991 * >1 - Error occurred
992 */
993static int img_compare(int argc, char **argv)
994{
Max Reitz40055952014-07-22 22:58:42 +0200995 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200996 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100997 BlockDriverState *bs1, *bs2;
998 int64_t total_sectors1, total_sectors2;
999 uint8_t *buf1 = NULL, *buf2 = NULL;
1000 int pnum1, pnum2;
1001 int allocated1, allocated2;
1002 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1003 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001004 int flags;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001005 int64_t total_sectors;
1006 int64_t sector_num = 0;
1007 int64_t nb_sectors;
1008 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001009 uint64_t progress_base;
1010
Max Reitz40055952014-07-22 22:58:42 +02001011 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001012 for (;;) {
Max Reitz40055952014-07-22 22:58:42 +02001013 c = getopt(argc, argv, "hf:F:T:pqs");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001014 if (c == -1) {
1015 break;
1016 }
1017 switch (c) {
1018 case '?':
1019 case 'h':
1020 help();
1021 break;
1022 case 'f':
1023 fmt1 = optarg;
1024 break;
1025 case 'F':
1026 fmt2 = optarg;
1027 break;
Max Reitz40055952014-07-22 22:58:42 +02001028 case 'T':
1029 cache = optarg;
1030 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001031 case 'p':
1032 progress = true;
1033 break;
1034 case 'q':
1035 quiet = true;
1036 break;
1037 case 's':
1038 strict = true;
1039 break;
1040 }
1041 }
1042
1043 /* Progress is not shown in Quiet mode */
1044 if (quiet) {
1045 progress = false;
1046 }
1047
1048
Kevin Wolffc11eb22013-08-05 10:53:04 +02001049 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001050 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001051 }
1052 filename1 = argv[optind++];
1053 filename2 = argv[optind++];
1054
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001055 /* Initialize before goto out */
1056 qemu_progress_init(progress, 2.0);
1057
Max Reitz40055952014-07-22 22:58:42 +02001058 flags = BDRV_O_FLAGS;
1059 ret = bdrv_parse_cache_flags(cache, &flags);
1060 if (ret < 0) {
1061 error_report("Invalid source cache option: %s", cache);
1062 ret = 2;
1063 goto out3;
1064 }
1065
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001066 blk1 = img_open("image_1", filename1, fmt1, flags, true, quiet);
1067 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001068 error_report("Can't open file %s", filename1);
1069 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001070 goto out3;
1071 }
1072 bs1 = blk_bs(blk1);
1073
1074 blk2 = img_open("image_2", filename2, fmt2, flags, true, quiet);
1075 if (!blk2) {
1076 error_report("Can't open file %s", filename2);
1077 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001078 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001079 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001080 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001081
1082 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
1083 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001084 total_sectors1 = bdrv_nb_sectors(bs1);
1085 if (total_sectors1 < 0) {
1086 error_report("Can't get size of %s: %s",
1087 filename1, strerror(-total_sectors1));
1088 ret = 4;
1089 goto out;
1090 }
1091 total_sectors2 = bdrv_nb_sectors(bs2);
1092 if (total_sectors2 < 0) {
1093 error_report("Can't get size of %s: %s",
1094 filename2, strerror(-total_sectors2));
1095 ret = 4;
1096 goto out;
1097 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001098 total_sectors = MIN(total_sectors1, total_sectors2);
1099 progress_base = MAX(total_sectors1, total_sectors2);
1100
1101 qemu_progress_print(0, 100);
1102
1103 if (strict && total_sectors1 != total_sectors2) {
1104 ret = 1;
1105 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1106 goto out;
1107 }
1108
1109 for (;;) {
1110 nb_sectors = sectors_to_process(total_sectors, sector_num);
1111 if (nb_sectors <= 0) {
1112 break;
1113 }
1114 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
1115 &pnum1);
1116 if (allocated1 < 0) {
1117 ret = 3;
1118 error_report("Sector allocation test failed for %s", filename1);
1119 goto out;
1120 }
1121
1122 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1123 &pnum2);
1124 if (allocated2 < 0) {
1125 ret = 3;
1126 error_report("Sector allocation test failed for %s", filename2);
1127 goto out;
1128 }
1129 nb_sectors = MIN(pnum1, pnum2);
1130
1131 if (allocated1 == allocated2) {
1132 if (allocated1) {
1133 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1134 if (ret < 0) {
1135 error_report("Error while reading offset %" PRId64 " of %s:"
1136 " %s", sectors_to_bytes(sector_num), filename1,
1137 strerror(-ret));
1138 ret = 4;
1139 goto out;
1140 }
1141 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1142 if (ret < 0) {
1143 error_report("Error while reading offset %" PRId64
1144 " of %s: %s", sectors_to_bytes(sector_num),
1145 filename2, strerror(-ret));
1146 ret = 4;
1147 goto out;
1148 }
1149 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1150 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001151 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1152 sectors_to_bytes(
1153 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001154 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001155 goto out;
1156 }
1157 }
1158 } else {
1159 if (strict) {
1160 ret = 1;
1161 qprintf(quiet, "Strict mode: Offset %" PRId64
1162 " allocation mismatch!\n",
1163 sectors_to_bytes(sector_num));
1164 goto out;
1165 }
1166
1167 if (allocated1) {
1168 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1169 filename1, buf1, quiet);
1170 } else {
1171 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1172 filename2, buf1, quiet);
1173 }
1174 if (ret) {
1175 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001176 error_report("Error while reading offset %" PRId64 ": %s",
1177 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001178 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001179 }
1180 goto out;
1181 }
1182 }
1183 sector_num += nb_sectors;
1184 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1185 }
1186
1187 if (total_sectors1 != total_sectors2) {
1188 BlockDriverState *bs_over;
1189 int64_t total_sectors_over;
1190 const char *filename_over;
1191
1192 qprintf(quiet, "Warning: Image size mismatch!\n");
1193 if (total_sectors1 > total_sectors2) {
1194 total_sectors_over = total_sectors1;
1195 bs_over = bs1;
1196 filename_over = filename1;
1197 } else {
1198 total_sectors_over = total_sectors2;
1199 bs_over = bs2;
1200 filename_over = filename2;
1201 }
1202
1203 for (;;) {
1204 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1205 if (nb_sectors <= 0) {
1206 break;
1207 }
1208 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1209 nb_sectors, &pnum);
1210 if (ret < 0) {
1211 ret = 3;
1212 error_report("Sector allocation test failed for %s",
1213 filename_over);
1214 goto out;
1215
1216 }
1217 nb_sectors = pnum;
1218 if (ret) {
1219 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1220 filename_over, buf1, quiet);
1221 if (ret) {
1222 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001223 error_report("Error while reading offset %" PRId64
1224 " of %s: %s", sectors_to_bytes(sector_num),
1225 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001226 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001227 }
1228 goto out;
1229 }
1230 }
1231 sector_num += nb_sectors;
1232 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1233 }
1234 }
1235
1236 qprintf(quiet, "Images are identical.\n");
1237 ret = 0;
1238
1239out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001240 qemu_vfree(buf1);
1241 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001242 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001243out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001244 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001245out3:
1246 qemu_progress_end();
1247 return ret;
1248}
1249
bellardea2384d2004-08-01 21:59:26 +00001250static int img_convert(int argc, char **argv)
1251{
Peter Lieven24f833c2013-11-27 11:07:07 +01001252 int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001253 int64_t ret = 0;
Max Reitz40055952014-07-22 22:58:42 +02001254 int progress = 0, flags, src_flags;
1255 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001256 BlockDriver *drv, *proto_drv;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001257 BlockBackend **blk = NULL, *out_blk = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001258 BlockDriverState **bs = NULL, *out_bs = NULL;
Peter Lieven802c3d42013-12-05 15:54:53 +01001259 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001260 int64_t *bs_sectors = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001261 uint8_t * buf = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001262 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardea2384d2004-08-01 21:59:26 +00001263 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +00001264 BlockDriverInfo bdi;
Chunyan Liu83d05212014-06-05 17:20:51 +08001265 QemuOpts *opts = NULL;
1266 QemuOptsList *create_opts = NULL;
1267 const char *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001268 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001269 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001270 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001271 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001272 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001273 QemuOpts *sn_opts = NULL;
bellardea2384d2004-08-01 21:59:26 +00001274
1275 fmt = NULL;
1276 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001277 cache = "unsafe";
Max Reitz40055952014-07-22 22:58:42 +02001278 src_cache = BDRV_DEFAULT_CACHE;
thsf58c7b32008-06-05 21:53:49 +00001279 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001280 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001281 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001282 for(;;) {
Max Reitz40055952014-07-22 22:58:42 +02001283 c = getopt(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001284 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001285 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001286 }
bellardea2384d2004-08-01 21:59:26 +00001287 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001288 case '?':
bellardea2384d2004-08-01 21:59:26 +00001289 case 'h':
1290 help();
1291 break;
1292 case 'f':
1293 fmt = optarg;
1294 break;
1295 case 'O':
1296 out_fmt = optarg;
1297 break;
thsf58c7b32008-06-05 21:53:49 +00001298 case 'B':
1299 out_baseimg = optarg;
1300 break;
bellardea2384d2004-08-01 21:59:26 +00001301 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001302 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001303 break;
1304 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001305 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001306 "encryption\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001307 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001308 goto fail_getopt;
thsec36ba12007-09-16 21:59:02 +00001309 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001310 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001311 "compat6\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001312 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001313 goto fail_getopt;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001314 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001315 if (!is_valid_option_list(optarg)) {
1316 error_report("Invalid option list: %s", optarg);
1317 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001318 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001319 }
1320 if (!options) {
1321 options = g_strdup(optarg);
1322 } else {
1323 char *old_options = options;
1324 options = g_strdup_printf("%s,%s", options, optarg);
1325 g_free(old_options);
1326 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001327 break;
edison51ef6722010-09-21 19:58:41 -07001328 case 's':
1329 snapshot_name = optarg;
1330 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001331 case 'l':
1332 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1333 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1334 if (!sn_opts) {
1335 error_report("Failed in parsing snapshot param '%s'",
1336 optarg);
Kevin Wolf2dc83282014-02-21 16:24:05 +01001337 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001338 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08001339 }
1340 } else {
1341 snapshot_name = optarg;
1342 }
1343 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001344 case 'S':
1345 {
1346 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001347 char *end;
1348 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1349 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001350 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001351 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001352 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001353 }
1354
1355 min_sparse = sval / BDRV_SECTOR_SIZE;
1356 break;
1357 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001358 case 'p':
1359 progress = 1;
1360 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001361 case 't':
1362 cache = optarg;
1363 break;
Max Reitz40055952014-07-22 22:58:42 +02001364 case 'T':
1365 src_cache = optarg;
1366 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001367 case 'q':
1368 quiet = true;
1369 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001370 case 'n':
1371 skip_create = 1;
1372 break;
bellardea2384d2004-08-01 21:59:26 +00001373 }
1374 }
ths3b46e622007-09-17 08:09:54 +00001375
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001376 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001377 if (quiet) {
1378 progress = 0;
1379 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001380 qemu_progress_init(progress, 1.0);
1381
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001382
balrog926c2d22007-10-31 01:11:44 +00001383 bs_n = argc - optind - 1;
Kevin Wolfa283cb62014-02-21 16:24:07 +01001384 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
thsf58c7b32008-06-05 21:53:49 +00001385
Kevin Wolf2dc83282014-02-21 16:24:05 +01001386 if (options && has_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001387 ret = print_block_option_help(out_filename, out_fmt);
1388 goto out;
1389 }
1390
bellardea2384d2004-08-01 21:59:26 +00001391 if (bs_n < 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001392 error_exit("Must specify image file name");
ths5fafdf22007-09-16 21:08:06 +00001393 }
bellardea2384d2004-08-01 21:59:26 +00001394
thsf58c7b32008-06-05 21:53:49 +00001395
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001396 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001397 error_report("-B makes no sense when concatenating multiple input "
1398 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001399 ret = -1;
1400 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001401 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001402
Max Reitz40055952014-07-22 22:58:42 +02001403 src_flags = BDRV_O_FLAGS;
1404 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1405 if (ret < 0) {
1406 error_report("Invalid source cache option: %s", src_cache);
1407 goto out;
1408 }
1409
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001410 qemu_progress_print(0, 100);
1411
Markus Armbruster26f54e92014-10-07 13:59:04 +02001412 blk = g_new0(BlockBackend *, bs_n);
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001413 bs = g_new0(BlockDriverState *, bs_n);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001414 bs_sectors = g_new(int64_t, bs_n);
balrog926c2d22007-10-31 01:11:44 +00001415
1416 total_sectors = 0;
1417 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Kevin Wolf9aebf3b2014-09-25 09:54:02 +02001418 char *id = bs_n > 1 ? g_strdup_printf("source_%d", bs_i)
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001419 : g_strdup("source");
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001420 blk[bs_i] = img_open(id, argv[optind + bs_i], fmt, src_flags,
1421 true, quiet);
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001422 g_free(id);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001423 if (!blk[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001424 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001425 ret = -1;
1426 goto out;
1427 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001428 bs[bs_i] = blk_bs(blk[bs_i]);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001429 bs_sectors[bs_i] = bdrv_nb_sectors(bs[bs_i]);
1430 if (bs_sectors[bs_i] < 0) {
1431 error_report("Could not get size of %s: %s",
1432 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1433 ret = -1;
1434 goto out;
1435 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001436 total_sectors += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001437 }
bellardea2384d2004-08-01 21:59:26 +00001438
Wenchao Xiaef806542013-12-04 17:10:57 +08001439 if (sn_opts) {
1440 ret = bdrv_snapshot_load_tmp(bs[0],
1441 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1442 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1443 &local_err);
1444 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001445 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001446 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001447 ret = -1;
1448 goto out;
1449 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001450
1451 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001452 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001453 if (local_err) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001454 error_report("Failed to load snapshot: %s",
1455 error_get_pretty(local_err));
1456 error_free(local_err);
1457 ret = -1;
1458 goto out;
edison51ef6722010-09-21 19:58:41 -07001459 }
1460
Kevin Wolfefa84d42009-05-18 16:42:12 +02001461 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001462 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001463 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001464 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001465 ret = -1;
1466 goto out;
1467 }
balrog926c2d22007-10-31 01:11:44 +00001468
Kevin Wolf98289622013-07-10 15:47:39 +02001469 proto_drv = bdrv_find_protocol(out_filename, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001470 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001471 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001472 ret = -1;
1473 goto out;
1474 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001475
Chunyan Liuc282e1f2014-06-05 17:21:11 +08001476 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1477 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02001478
Chunyan Liu83d05212014-06-05 17:20:51 +08001479 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1480 if (options && qemu_opts_do_parse(opts, options, NULL)) {
1481 error_report("Invalid options for file format '%s'", out_fmt);
1482 ret = -1;
1483 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001484 }
1485
Chunyan Liu83d05212014-06-05 17:20:51 +08001486 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512);
1487 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001488 if (ret < 0) {
1489 goto out;
1490 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001491
Kevin Wolfa18953f2010-10-14 15:46:04 +02001492 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08001493 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02001494 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08001495 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02001496 }
1497
Kevin Wolfefa84d42009-05-18 16:42:12 +02001498 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01001499 if (compress) {
Chunyan Liu83d05212014-06-05 17:20:51 +08001500 bool encryption =
1501 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1502 const char *preallocation =
1503 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001504
1505 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001506 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001507 ret = -1;
1508 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001509 }
1510
Chunyan Liu83d05212014-06-05 17:20:51 +08001511 if (encryption) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001512 error_report("Compression and encryption not supported at "
1513 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001514 ret = -1;
1515 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001516 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02001517
Chunyan Liu83d05212014-06-05 17:20:51 +08001518 if (preallocation
1519 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02001520 {
1521 error_report("Compression and preallocation not supported at "
1522 "the same time");
1523 ret = -1;
1524 goto out;
1525 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001526 }
1527
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001528 if (!skip_create) {
1529 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08001530 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001531 if (ret < 0) {
Max Reitzcc84d902013-09-06 17:14:26 +02001532 error_report("%s: error while converting %s: %s",
1533 out_filename, out_fmt, error_get_pretty(local_err));
1534 error_free(local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001535 goto out;
bellardea2384d2004-08-01 21:59:26 +00001536 }
1537 }
ths3b46e622007-09-17 08:09:54 +00001538
Peter Lieven5a37b602013-10-24 12:07:06 +02001539 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001540 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001541 if (ret < 0) {
1542 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02001543 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001544 }
1545
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001546 out_blk = img_open("target", out_filename, out_fmt, flags, true, quiet);
1547 if (!out_blk) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001548 ret = -1;
1549 goto out;
1550 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001551 out_bs = blk_bs(out_blk);
bellardea2384d2004-08-01 21:59:26 +00001552
balrog926c2d22007-10-31 01:11:44 +00001553 bs_i = 0;
1554 bs_offset = 0;
Peter Lievenf2521c92013-11-27 11:07:06 +01001555
1556 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1557 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1558 * as maximum. */
1559 bufsectors = MIN(32768,
1560 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1561 out_bs->bl.discard_alignment))
1562 );
1563
1564 buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001565
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001566 if (skip_create) {
Markus Armbruster43716fa2014-06-26 13:23:21 +02001567 int64_t output_sectors = bdrv_nb_sectors(out_bs);
1568 if (output_sectors < 0) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001569 error_report("unable to get output image length: %s\n",
Markus Armbruster43716fa2014-06-26 13:23:21 +02001570 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001571 ret = -1;
1572 goto out;
Markus Armbruster43716fa2014-06-26 13:23:21 +02001573 } else if (output_sectors < total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001574 error_report("output file is smaller than input file");
1575 ret = -1;
1576 goto out;
1577 }
1578 }
1579
Peter Lieven24f833c2013-11-27 11:07:07 +01001580 cluster_sectors = 0;
1581 ret = bdrv_get_info(out_bs, &bdi);
1582 if (ret < 0) {
1583 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001584 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001585 goto out;
1586 }
Peter Lieven24f833c2013-11-27 11:07:07 +01001587 } else {
Fam Zheng85f49ca2014-05-06 21:08:43 +08001588 compress = compress || bdi.needs_compressed_writes;
Peter Lieven24f833c2013-11-27 11:07:07 +01001589 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
1590 }
1591
1592 if (compress) {
1593 if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001594 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001595 ret = -1;
1596 goto out;
1597 }
bellardea2384d2004-08-01 21:59:26 +00001598 sector_num = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001599
1600 nb_sectors = total_sectors;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001601
bellardea2384d2004-08-01 21:59:26 +00001602 for(;;) {
balrog926c2d22007-10-31 01:11:44 +00001603 int64_t bs_num;
1604 int remainder;
1605 uint8_t *buf2;
1606
bellardea2384d2004-08-01 21:59:26 +00001607 nb_sectors = total_sectors - sector_num;
1608 if (nb_sectors <= 0)
1609 break;
1610 if (nb_sectors >= cluster_sectors)
1611 n = cluster_sectors;
1612 else
1613 n = nb_sectors;
balrog926c2d22007-10-31 01:11:44 +00001614
1615 bs_num = sector_num - bs_offset;
1616 assert (bs_num >= 0);
1617 remainder = n;
1618 buf2 = buf;
1619 while (remainder > 0) {
1620 int nlow;
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001621 while (bs_num == bs_sectors[bs_i]) {
1622 bs_offset += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001623 bs_i++;
1624 assert (bs_i < bs_n);
balrog926c2d22007-10-31 01:11:44 +00001625 bs_num = 0;
Blue Swirl0bfcd592010-05-22 08:02:12 +00001626 /* printf("changing part: sector_num=%" PRId64 ", "
1627 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001628 "\n", sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
balrog926c2d22007-10-31 01:11:44 +00001629 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001630 assert (bs_num < bs_sectors[bs_i]);
balrog926c2d22007-10-31 01:11:44 +00001631
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001632 nlow = remainder > bs_sectors[bs_i] - bs_num
1633 ? bs_sectors[bs_i] - bs_num : remainder;
balrog926c2d22007-10-31 01:11:44 +00001634
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001635 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1636 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001637 error_report("error while reading sector %" PRId64 ": %s",
1638 bs_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001639 goto out;
1640 }
balrog926c2d22007-10-31 01:11:44 +00001641
1642 buf2 += nlow * 512;
1643 bs_num += nlow;
1644
1645 remainder -= nlow;
1646 }
1647 assert (remainder == 0);
1648
Stefan Hajnoczi54f106d2013-04-15 17:17:33 +02001649 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1650 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001651 if (ret != 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001652 error_report("error while compressing sector %" PRId64
1653 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001654 goto out;
1655 }
bellardea2384d2004-08-01 21:59:26 +00001656 }
1657 sector_num += n;
Peter Lieven13c28af2013-11-27 11:07:01 +01001658 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
bellardea2384d2004-08-01 21:59:26 +00001659 }
bellardfaea38e2006-08-05 21:31:00 +00001660 /* signal EOF to align */
1661 bdrv_write_compressed(out_bs, 0, NULL, 0);
bellardea2384d2004-08-01 21:59:26 +00001662 } else {
Peter Lieven802c3d42013-12-05 15:54:53 +01001663 int64_t sectors_to_read, sectors_read, sector_num_next_status;
1664 bool count_allocated_sectors;
Peter Lieven11b66992013-10-24 12:07:05 +02001665 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02001666
Peter Lieven5a37b602013-10-24 12:07:06 +02001667 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1668 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1669 if (ret < 0) {
1670 goto out;
1671 }
1672 has_zero_init = 1;
1673 }
1674
Peter Lieven802c3d42013-12-05 15:54:53 +01001675 sectors_to_read = total_sectors;
1676 count_allocated_sectors = progress && (out_baseimg || has_zero_init);
1677restart:
thsf58c7b32008-06-05 21:53:49 +00001678 sector_num = 0; // total number of sectors converted so far
Peter Lieven802c3d42013-12-05 15:54:53 +01001679 sectors_read = 0;
1680 sector_num_next_status = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001681
bellardea2384d2004-08-01 21:59:26 +00001682 for(;;) {
1683 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001684 if (nb_sectors <= 0) {
Peter Lieven802c3d42013-12-05 15:54:53 +01001685 if (count_allocated_sectors) {
1686 sectors_to_read = sectors_read;
1687 count_allocated_sectors = false;
1688 goto restart;
1689 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001690 ret = 0;
bellardea2384d2004-08-01 21:59:26 +00001691 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001692 }
balrog926c2d22007-10-31 01:11:44 +00001693
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001694 while (sector_num - bs_offset >= bs_sectors[bs_i]) {
1695 bs_offset += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001696 bs_i ++;
1697 assert (bs_i < bs_n);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001698 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1699 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001700 sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
balrog926c2d22007-10-31 01:11:44 +00001701 }
1702
Peter Lieven13c28af2013-11-27 11:07:01 +01001703 if ((out_baseimg || has_zero_init) &&
1704 sector_num >= sector_num_next_status) {
1705 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1706 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1707 n, &n1);
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001708 if (ret < 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001709 error_report("error while reading block status of sector %"
1710 PRId64 ": %s", sector_num - bs_offset,
1711 strerror(-ret));
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001712 goto out;
aliguori93c65b42009-04-05 17:40:43 +00001713 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001714 /* If the output image is zero initialized, we are not working
1715 * on a shared base and the input is zero we can skip the next
1716 * n1 sectors */
1717 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001718 sector_num += n1;
1719 continue;
1720 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001721 /* If the output image is being created as a copy on write
1722 * image, assume that sectors which are unallocated in the
1723 * input image are present in both the output's and input's
1724 * base images (no need to copy them). */
1725 if (out_baseimg) {
1726 if (!(ret & BDRV_BLOCK_DATA)) {
1727 sector_num += n1;
1728 continue;
1729 }
1730 /* The next 'n1' sectors are allocated in the input image.
1731 * Copy only those as they may be followed by unallocated
1732 * sectors. */
1733 nb_sectors = n1;
1734 }
1735 /* avoid redundant callouts to get_block_status */
1736 sector_num_next_status = sector_num + n1;
thsf58c7b32008-06-05 21:53:49 +00001737 }
1738
Peter Lievenf2521c92013-11-27 11:07:06 +01001739 n = MIN(nb_sectors, bufsectors);
Peter Lieven24f833c2013-11-27 11:07:07 +01001740
1741 /* round down request length to an aligned sector, but
1742 * do not bother doing this on short requests. They happen
1743 * when we found an all-zero area, and the next sector to
1744 * write will not be sector_num + n. */
1745 if (cluster_sectors > 0 && n >= cluster_sectors) {
1746 int64_t next_aligned_sector = (sector_num + n);
1747 next_aligned_sector -= next_aligned_sector % cluster_sectors;
1748 if (sector_num + n > next_aligned_sector) {
1749 n = next_aligned_sector - sector_num;
1750 }
1751 }
1752
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001753 n = MIN(n, bs_sectors[bs_i] - (sector_num - bs_offset));
Peter Lieven13c28af2013-11-27 11:07:01 +01001754
Peter Lieven802c3d42013-12-05 15:54:53 +01001755 sectors_read += n;
1756 if (count_allocated_sectors) {
1757 sector_num += n;
1758 continue;
1759 }
1760
1761 n1 = n;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001762 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1763 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001764 error_report("error while reading sector %" PRId64 ": %s",
1765 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001766 goto out;
1767 }
bellardea2384d2004-08-01 21:59:26 +00001768 /* NOTE: at the same time we convert, we do not write zero
1769 sectors to have a chance to compress the image. Ideally, we
1770 should add a specific call to have the info to go faster */
1771 buf1 = buf;
1772 while (n > 0) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02001773 if (!has_zero_init ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001774 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001775 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1776 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001777 error_report("error while writing sector %" PRId64
1778 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001779 goto out;
1780 }
bellardea2384d2004-08-01 21:59:26 +00001781 }
1782 sector_num += n1;
1783 n -= n1;
1784 buf1 += n1 * 512;
1785 }
Peter Lieven802c3d42013-12-05 15:54:53 +01001786 qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
bellardea2384d2004-08-01 21:59:26 +00001787 }
1788 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001789out:
Peter Lieven13c28af2013-11-27 11:07:01 +01001790 if (!ret) {
1791 qemu_progress_print(100, 0);
1792 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001793 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08001794 qemu_opts_del(opts);
1795 qemu_opts_free(create_opts);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001796 qemu_vfree(buf);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02001797 qemu_opts_del(sn_opts);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001798 blk_unref(out_blk);
Markus Armbruster9ba10c92014-10-07 13:59:08 +02001799 g_free(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001800 if (blk) {
1801 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1802 blk_unref(blk[bs_i]);
1803 }
1804 g_free(blk);
1805 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001806 g_free(bs_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001807fail_getopt:
1808 g_free(options);
1809
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001810 if (ret) {
1811 return 1;
1812 }
bellardea2384d2004-08-01 21:59:26 +00001813 return 0;
1814}
1815
bellard57d1a2b2004-08-03 21:15:11 +00001816
bellardfaea38e2006-08-05 21:31:00 +00001817static void dump_snapshots(BlockDriverState *bs)
1818{
1819 QEMUSnapshotInfo *sn_tab, *sn;
1820 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00001821
1822 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1823 if (nb_sns <= 0)
1824 return;
1825 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08001826 bdrv_snapshot_dump(fprintf, stdout, NULL);
1827 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001828 for(i = 0; i < nb_sns; i++) {
1829 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08001830 bdrv_snapshot_dump(fprintf, stdout, sn);
1831 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001832 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001833 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001834}
1835
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001836static void dump_json_image_info_list(ImageInfoList *list)
1837{
Markus Armbruster4399c432014-04-25 16:50:32 +02001838 Error *local_err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001839 QString *str;
1840 QmpOutputVisitor *ov = qmp_output_visitor_new();
1841 QObject *obj;
1842 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +02001843 &list, NULL, &local_err);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001844 obj = qmp_output_get_qobject(ov);
1845 str = qobject_to_json_pretty(obj);
1846 assert(str != NULL);
1847 printf("%s\n", qstring_get_str(str));
1848 qobject_decref(obj);
1849 qmp_output_visitor_cleanup(ov);
1850 QDECREF(str);
1851}
1852
Benoît Canetc054b3f2012-09-05 13:09:02 +02001853static void dump_json_image_info(ImageInfo *info)
1854{
Markus Armbruster4399c432014-04-25 16:50:32 +02001855 Error *local_err = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001856 QString *str;
1857 QmpOutputVisitor *ov = qmp_output_visitor_new();
1858 QObject *obj;
1859 visit_type_ImageInfo(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +02001860 &info, NULL, &local_err);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001861 obj = qmp_output_get_qobject(ov);
1862 str = qobject_to_json_pretty(obj);
1863 assert(str != NULL);
1864 printf("%s\n", qstring_get_str(str));
1865 qobject_decref(obj);
1866 qmp_output_visitor_cleanup(ov);
1867 QDECREF(str);
1868}
1869
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001870static void dump_human_image_info_list(ImageInfoList *list)
1871{
1872 ImageInfoList *elem;
1873 bool delim = false;
1874
1875 for (elem = list; elem; elem = elem->next) {
1876 if (delim) {
1877 printf("\n");
1878 }
1879 delim = true;
1880
Wenchao Xia5b917042013-05-25 11:09:45 +08001881 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001882 }
1883}
1884
1885static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1886{
1887 return strcmp(a, b) == 0;
1888}
1889
1890/**
1891 * Open an image file chain and return an ImageInfoList
1892 *
1893 * @filename: topmost image filename
1894 * @fmt: topmost image format (may be NULL to autodetect)
1895 * @chain: true - enumerate entire backing file chain
1896 * false - only topmost image file
1897 *
1898 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1899 * image file. If there was an error a message will have been printed to
1900 * stderr.
1901 */
1902static ImageInfoList *collect_image_info_list(const char *filename,
1903 const char *fmt,
1904 bool chain)
1905{
1906 ImageInfoList *head = NULL;
1907 ImageInfoList **last = &head;
1908 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08001909 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001910
1911 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1912
1913 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02001914 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001915 BlockDriverState *bs;
1916 ImageInfo *info;
1917 ImageInfoList *elem;
1918
1919 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1920 error_report("Backing file '%s' creates an infinite loop.",
1921 filename);
1922 goto err;
1923 }
1924 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1925
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001926 blk = img_open("image", filename, fmt,
1927 BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
1928 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001929 goto err;
1930 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001931 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001932
Wenchao Xia43526ec2013-06-06 12:27:58 +08001933 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001934 if (err) {
Wenchao Xia43526ec2013-06-06 12:27:58 +08001935 error_report("%s", error_get_pretty(err));
1936 error_free(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001937 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08001938 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08001939 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001940
1941 elem = g_new0(ImageInfoList, 1);
1942 elem->value = info;
1943 *last = elem;
1944 last = &elem->next;
1945
Markus Armbruster26f54e92014-10-07 13:59:04 +02001946 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001947
1948 filename = fmt = NULL;
1949 if (chain) {
1950 if (info->has_full_backing_filename) {
1951 filename = info->full_backing_filename;
1952 } else if (info->has_backing_filename) {
1953 filename = info->backing_filename;
1954 }
1955 if (info->has_backing_filename_format) {
1956 fmt = info->backing_filename_format;
1957 }
1958 }
1959 }
1960 g_hash_table_destroy(filenames);
1961 return head;
1962
1963err:
1964 qapi_free_ImageInfoList(head);
1965 g_hash_table_destroy(filenames);
1966 return NULL;
1967}
1968
Benoît Canetc054b3f2012-09-05 13:09:02 +02001969static int img_info(int argc, char **argv)
1970{
1971 int c;
1972 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001973 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001974 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001975 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001976
bellardea2384d2004-08-01 21:59:26 +00001977 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001978 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001979 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001980 int option_index = 0;
1981 static const struct option long_options[] = {
1982 {"help", no_argument, 0, 'h'},
1983 {"format", required_argument, 0, 'f'},
1984 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001985 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001986 {0, 0, 0, 0}
1987 };
1988 c = getopt_long(argc, argv, "f:h",
1989 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001990 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001991 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001992 }
bellardea2384d2004-08-01 21:59:26 +00001993 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001994 case '?':
bellardea2384d2004-08-01 21:59:26 +00001995 case 'h':
1996 help();
1997 break;
1998 case 'f':
1999 fmt = optarg;
2000 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002001 case OPTION_OUTPUT:
2002 output = optarg;
2003 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002004 case OPTION_BACKING_CHAIN:
2005 chain = true;
2006 break;
bellardea2384d2004-08-01 21:59:26 +00002007 }
2008 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002009 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002010 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002011 }
bellardea2384d2004-08-01 21:59:26 +00002012 filename = argv[optind++];
2013
Benoît Canetc054b3f2012-09-05 13:09:02 +02002014 if (output && !strcmp(output, "json")) {
2015 output_format = OFORMAT_JSON;
2016 } else if (output && !strcmp(output, "human")) {
2017 output_format = OFORMAT_HUMAN;
2018 } else if (output) {
2019 error_report("--output must be used with human or json as argument.");
2020 return 1;
2021 }
2022
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002023 list = collect_image_info_list(filename, fmt, chain);
2024 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002025 return 1;
2026 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002027
Benoît Canetc054b3f2012-09-05 13:09:02 +02002028 switch (output_format) {
2029 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002030 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002031 break;
2032 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002033 if (chain) {
2034 dump_json_image_info_list(list);
2035 } else {
2036 dump_json_image_info(list->value);
2037 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002038 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002039 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002040
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002041 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002042 return 0;
2043}
2044
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002045
2046typedef struct MapEntry {
2047 int flags;
2048 int depth;
2049 int64_t start;
2050 int64_t length;
2051 int64_t offset;
2052 BlockDriverState *bs;
2053} MapEntry;
2054
2055static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2056 MapEntry *next)
2057{
2058 switch (output_format) {
2059 case OFORMAT_HUMAN:
2060 if ((e->flags & BDRV_BLOCK_DATA) &&
2061 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
2062 error_report("File contains external, encrypted or compressed clusters.");
2063 exit(1);
2064 }
2065 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
2066 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2067 e->start, e->length, e->offset, e->bs->filename);
2068 }
2069 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2070 * Modify the flags here to allow more coalescing.
2071 */
2072 if (next &&
2073 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
2074 next->flags &= ~BDRV_BLOCK_DATA;
2075 next->flags |= BDRV_BLOCK_ZERO;
2076 }
2077 break;
2078 case OFORMAT_JSON:
2079 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
2080 " \"zero\": %s, \"data\": %s",
2081 (e->start == 0 ? "[" : ",\n"),
2082 e->start, e->length, e->depth,
2083 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
2084 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
2085 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002086 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002087 }
2088 putchar('}');
2089
2090 if (!next) {
2091 printf("]\n");
2092 }
2093 break;
2094 }
2095}
2096
2097static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2098 int nb_sectors, MapEntry *e)
2099{
2100 int64_t ret;
2101 int depth;
2102
2103 /* As an optimization, we could cache the current range of unallocated
2104 * clusters in each file of the chain, and avoid querying the same
2105 * range repeatedly.
2106 */
2107
2108 depth = 0;
2109 for (;;) {
2110 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
2111 if (ret < 0) {
2112 return ret;
2113 }
2114 assert(nb_sectors);
2115 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2116 break;
2117 }
2118 bs = bs->backing_hd;
2119 if (bs == NULL) {
2120 ret = 0;
2121 break;
2122 }
2123
2124 depth++;
2125 }
2126
2127 e->start = sector_num * BDRV_SECTOR_SIZE;
2128 e->length = nb_sectors * BDRV_SECTOR_SIZE;
2129 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
2130 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
2131 e->depth = depth;
2132 e->bs = bs;
2133 return 0;
2134}
2135
2136static int img_map(int argc, char **argv)
2137{
2138 int c;
2139 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002140 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002141 BlockDriverState *bs;
2142 const char *filename, *fmt, *output;
2143 int64_t length;
2144 MapEntry curr = { .length = 0 }, next;
2145 int ret = 0;
2146
2147 fmt = NULL;
2148 output = NULL;
2149 for (;;) {
2150 int option_index = 0;
2151 static const struct option long_options[] = {
2152 {"help", no_argument, 0, 'h'},
2153 {"format", required_argument, 0, 'f'},
2154 {"output", required_argument, 0, OPTION_OUTPUT},
2155 {0, 0, 0, 0}
2156 };
2157 c = getopt_long(argc, argv, "f:h",
2158 long_options, &option_index);
2159 if (c == -1) {
2160 break;
2161 }
2162 switch (c) {
2163 case '?':
2164 case 'h':
2165 help();
2166 break;
2167 case 'f':
2168 fmt = optarg;
2169 break;
2170 case OPTION_OUTPUT:
2171 output = optarg;
2172 break;
2173 }
2174 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002175 if (optind != argc - 1) {
2176 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002177 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002178 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002179
2180 if (output && !strcmp(output, "json")) {
2181 output_format = OFORMAT_JSON;
2182 } else if (output && !strcmp(output, "human")) {
2183 output_format = OFORMAT_HUMAN;
2184 } else if (output) {
2185 error_report("--output must be used with human or json as argument.");
2186 return 1;
2187 }
2188
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002189 blk = img_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
2190 if (!blk) {
2191 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002192 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002193 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002194
2195 if (output_format == OFORMAT_HUMAN) {
2196 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2197 }
2198
2199 length = bdrv_getlength(bs);
2200 while (curr.start + curr.length < length) {
2201 int64_t nsectors_left;
2202 int64_t sector_num;
2203 int n;
2204
2205 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2206
2207 /* Probe up to 1 GiB at a time. */
2208 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2209 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2210 ret = get_block_status(bs, sector_num, n, &next);
2211
2212 if (ret < 0) {
2213 error_report("Could not read file metadata: %s", strerror(-ret));
2214 goto out;
2215 }
2216
2217 if (curr.length != 0 && curr.flags == next.flags &&
2218 curr.depth == next.depth &&
2219 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2220 curr.offset + curr.length == next.offset)) {
2221 curr.length += next.length;
2222 continue;
2223 }
2224
2225 if (curr.length > 0) {
2226 dump_map_entry(output_format, &curr, &next);
2227 }
2228 curr = next;
2229 }
2230
2231 dump_map_entry(output_format, &curr, NULL);
2232
2233out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002234 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002235 return ret < 0;
2236}
2237
aliguorif7b4a942009-01-07 17:40:15 +00002238#define SNAPSHOT_LIST 1
2239#define SNAPSHOT_CREATE 2
2240#define SNAPSHOT_APPLY 3
2241#define SNAPSHOT_DELETE 4
2242
Stuart Brady153859b2009-06-07 00:42:17 +01002243static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002244{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002245 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002246 BlockDriverState *bs;
2247 QEMUSnapshotInfo sn;
2248 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002249 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002250 int action = 0;
2251 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002252 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002253 Error *err = NULL;
aliguorif7b4a942009-01-07 17:40:15 +00002254
Kevin Wolf710da702011-01-10 12:33:02 +01002255 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002256 /* Parse commandline parameters */
2257 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002258 c = getopt(argc, argv, "la:c:d:hq");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002259 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002260 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002261 }
aliguorif7b4a942009-01-07 17:40:15 +00002262 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002263 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002264 case 'h':
2265 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002266 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002267 case 'l':
2268 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002269 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002270 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002271 }
2272 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002273 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002274 break;
2275 case 'a':
2276 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002277 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002278 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002279 }
2280 action = SNAPSHOT_APPLY;
2281 snapshot_name = optarg;
2282 break;
2283 case 'c':
2284 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002285 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002286 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002287 }
2288 action = SNAPSHOT_CREATE;
2289 snapshot_name = optarg;
2290 break;
2291 case 'd':
2292 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002293 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002294 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002295 }
2296 action = SNAPSHOT_DELETE;
2297 snapshot_name = optarg;
2298 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002299 case 'q':
2300 quiet = true;
2301 break;
aliguorif7b4a942009-01-07 17:40:15 +00002302 }
2303 }
2304
Kevin Wolffc11eb22013-08-05 10:53:04 +02002305 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002306 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002307 }
aliguorif7b4a942009-01-07 17:40:15 +00002308 filename = argv[optind++];
2309
2310 /* Open the image */
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002311 blk = img_open("image", filename, NULL, bdrv_oflags, true, quiet);
2312 if (!blk) {
2313 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002314 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002315 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002316
2317 /* Perform the requested action */
2318 switch(action) {
2319 case SNAPSHOT_LIST:
2320 dump_snapshots(bs);
2321 break;
2322
2323 case SNAPSHOT_CREATE:
2324 memset(&sn, 0, sizeof(sn));
2325 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2326
2327 qemu_gettimeofday(&tv);
2328 sn.date_sec = tv.tv_sec;
2329 sn.date_nsec = tv.tv_usec * 1000;
2330
2331 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002332 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002333 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002334 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002335 }
aliguorif7b4a942009-01-07 17:40:15 +00002336 break;
2337
2338 case SNAPSHOT_APPLY:
2339 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002340 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002341 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002342 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002343 }
aliguorif7b4a942009-01-07 17:40:15 +00002344 break;
2345
2346 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002347 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002348 if (err) {
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002349 error_report("Could not delete snapshot '%s': (%s)",
2350 snapshot_name, error_get_pretty(err));
2351 error_free(err);
2352 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002353 }
aliguorif7b4a942009-01-07 17:40:15 +00002354 break;
2355 }
2356
2357 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002358 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002359 if (ret) {
2360 return 1;
2361 }
Stuart Brady153859b2009-06-07 00:42:17 +01002362 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002363}
2364
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002365static int img_rebase(int argc, char **argv)
2366{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002367 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002368 BlockDriverState *bs = NULL, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01002369 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002370 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02002371 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2372 int c, flags, src_flags, ret;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002373 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002374 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002375 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002376 Error *local_err = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002377
2378 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002379 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002380 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02002381 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002382 out_baseimg = NULL;
2383 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002384 for(;;) {
Max Reitz40055952014-07-22 22:58:42 +02002385 c = getopt(argc, argv, "hf:F:b:upt:T:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002386 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002387 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002388 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002389 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002390 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002391 case 'h':
2392 help();
2393 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002394 case 'f':
2395 fmt = optarg;
2396 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002397 case 'F':
2398 out_basefmt = optarg;
2399 break;
2400 case 'b':
2401 out_baseimg = optarg;
2402 break;
2403 case 'u':
2404 unsafe = 1;
2405 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002406 case 'p':
2407 progress = 1;
2408 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002409 case 't':
2410 cache = optarg;
2411 break;
Max Reitz40055952014-07-22 22:58:42 +02002412 case 'T':
2413 src_cache = optarg;
2414 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002415 case 'q':
2416 quiet = true;
2417 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002418 }
2419 }
2420
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002421 if (quiet) {
2422 progress = 0;
2423 }
2424
Fam Zhengac1307a2014-04-22 13:36:11 +08002425 if (optind != argc - 1) {
2426 error_exit("Expecting one image file name");
2427 }
2428 if (!unsafe && !out_baseimg) {
2429 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002430 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002431 filename = argv[optind++];
2432
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002433 qemu_progress_init(progress, 2.0);
2434 qemu_progress_print(0, 100);
2435
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002436 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01002437 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002438 if (ret < 0) {
2439 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002440 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002441 }
2442
Max Reitz40055952014-07-22 22:58:42 +02002443 src_flags = BDRV_O_FLAGS;
2444 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2445 if (ret < 0) {
2446 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002447 goto out;
Max Reitz40055952014-07-22 22:58:42 +02002448 }
2449
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002450 /*
2451 * Open the images.
2452 *
2453 * Ignore the old backing file for unsafe rebase in case we want to correct
2454 * the reference to a renamed or moved backing file.
2455 */
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002456 blk = img_open("image", filename, fmt, flags, true, quiet);
2457 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002458 ret = -1;
2459 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002460 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002461 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002462
2463 /* Find the right drivers for the backing files */
2464 old_backing_drv = NULL;
2465 new_backing_drv = NULL;
2466
2467 if (!unsafe && bs->backing_format[0] != '\0') {
2468 old_backing_drv = bdrv_find_format(bs->backing_format);
2469 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002470 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002471 ret = -1;
2472 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002473 }
2474 }
2475
2476 if (out_basefmt != NULL) {
2477 new_backing_drv = bdrv_find_format(out_basefmt);
2478 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002479 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002480 ret = -1;
2481 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002482 }
2483 }
2484
2485 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002486 if (!unsafe) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002487 char backing_name[1024];
2488
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002489 blk_old_backing = blk_new_with_bs("old_backing", &error_abort);
2490 bs_old_backing = blk_bs(blk_old_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002491 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitz40055952014-07-22 22:58:42 +02002492 ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002493 old_backing_drv, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002494 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002495 error_report("Could not open old backing file '%s': %s",
2496 backing_name, error_get_pretty(local_err));
2497 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002498 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002499 }
Alex Bligha6166732012-10-16 13:46:18 +01002500 if (out_baseimg[0]) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002501 blk_new_backing = blk_new_with_bs("new_backing", &error_abort);
2502 bs_new_backing = blk_bs(blk_new_backing);
Max Reitz40055952014-07-22 22:58:42 +02002503 ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
2504 new_backing_drv, &local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002505 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002506 error_report("Could not open new backing file '%s': %s",
2507 out_baseimg, error_get_pretty(local_err));
2508 error_free(local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002509 goto out;
2510 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002511 }
2512 }
2513
2514 /*
2515 * Check each unallocated cluster in the COW file. If it is unallocated,
2516 * accesses go to the backing file. We must therefore compare this cluster
2517 * in the old and new backing file, and if they differ we need to copy it
2518 * from the old backing file into the COW file.
2519 *
2520 * If qemu-img crashes during this step, no harm is done. The content of
2521 * the image is the same as the original one at any time.
2522 */
2523 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002524 int64_t num_sectors;
2525 int64_t old_backing_num_sectors;
2526 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002527 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02002528 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08002529 uint8_t * buf_old;
2530 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02002531 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08002532
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002533 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2534 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002535
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002536 num_sectors = bdrv_nb_sectors(bs);
2537 if (num_sectors < 0) {
2538 error_report("Could not get size of '%s': %s",
2539 filename, strerror(-num_sectors));
2540 ret = -1;
2541 goto out;
2542 }
2543 old_backing_num_sectors = bdrv_nb_sectors(bs_old_backing);
2544 if (old_backing_num_sectors < 0) {
2545 char backing_name[1024];
2546
2547 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2548 error_report("Could not get size of '%s': %s",
2549 backing_name, strerror(-old_backing_num_sectors));
2550 ret = -1;
2551 goto out;
2552 }
Alex Bligha6166732012-10-16 13:46:18 +01002553 if (bs_new_backing) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002554 new_backing_num_sectors = bdrv_nb_sectors(bs_new_backing);
2555 if (new_backing_num_sectors < 0) {
2556 error_report("Could not get size of '%s': %s",
2557 out_baseimg, strerror(-new_backing_num_sectors));
2558 ret = -1;
2559 goto out;
2560 }
Alex Bligha6166732012-10-16 13:46:18 +01002561 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002562
Kevin Wolf1f710492012-10-12 14:29:18 +02002563 if (num_sectors != 0) {
2564 local_progress = (float)100 /
2565 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2566 }
2567
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002568 for (sector = 0; sector < num_sectors; sector += n) {
2569
2570 /* How many sectors can we handle with the next read? */
2571 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2572 n = (IO_BUF_SIZE / 512);
2573 } else {
2574 n = num_sectors - sector;
2575 }
2576
2577 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02002578 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02002579 if (ret < 0) {
2580 error_report("error while reading image metadata: %s",
2581 strerror(-ret));
2582 goto out;
2583 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02002584 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002585 continue;
2586 }
2587
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002588 /*
2589 * Read old and new backing file and take into consideration that
2590 * backing files may be smaller than the COW image.
2591 */
2592 if (sector >= old_backing_num_sectors) {
2593 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2594 } else {
2595 if (sector + n > old_backing_num_sectors) {
2596 n = old_backing_num_sectors - sector;
2597 }
2598
2599 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2600 if (ret < 0) {
2601 error_report("error while reading from old backing file");
2602 goto out;
2603 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002604 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002605
Alex Bligha6166732012-10-16 13:46:18 +01002606 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002607 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2608 } else {
2609 if (sector + n > new_backing_num_sectors) {
2610 n = new_backing_num_sectors - sector;
2611 }
2612
2613 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2614 if (ret < 0) {
2615 error_report("error while reading from new backing file");
2616 goto out;
2617 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002618 }
2619
2620 /* If they differ, we need to write to the COW file */
2621 uint64_t written = 0;
2622
2623 while (written < n) {
2624 int pnum;
2625
2626 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01002627 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002628 {
2629 ret = bdrv_write(bs, sector + written,
2630 buf_old + written * 512, pnum);
2631 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002632 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002633 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002634 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002635 }
2636 }
2637
2638 written += pnum;
2639 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002640 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002641 }
TeLeMand6771bf2010-02-08 16:20:00 +08002642
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002643 qemu_vfree(buf_old);
2644 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002645 }
2646
2647 /*
2648 * Change the backing file. All clusters that are different from the old
2649 * backing file are overwritten in the COW file now, so the visible content
2650 * doesn't change when we switch the backing file.
2651 */
Alex Bligha6166732012-10-16 13:46:18 +01002652 if (out_baseimg && *out_baseimg) {
2653 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2654 } else {
2655 ret = bdrv_change_backing_file(bs, NULL, NULL);
2656 }
2657
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002658 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002659 error_report("Could not change the backing file to '%s': No "
2660 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002661 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002662 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002663 out_baseimg, strerror(-ret));
2664 }
2665
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002666 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002667 /*
2668 * TODO At this point it is possible to check if any clusters that are
2669 * allocated in the COW file are the same in the backing file. If so, they
2670 * could be dropped from the COW file. Don't do this before switching the
2671 * backing file, in case of a crash this would lead to corruption.
2672 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002673out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002674 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002675 /* Cleanup */
2676 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002677 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002678 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002679 }
2680
Markus Armbruster26f54e92014-10-07 13:59:04 +02002681 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002682 if (ret) {
2683 return 1;
2684 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002685 return 0;
2686}
2687
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002688static int img_resize(int argc, char **argv)
2689{
2690 int c, ret, relative;
2691 const char *filename, *fmt, *size;
2692 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002693 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002694 BlockBackend *blk = NULL;
Jes Sorensen2a819982010-12-06 17:08:31 +01002695 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002696 QemuOpts *param;
2697 static QemuOptsList resize_options = {
2698 .name = "resize_options",
2699 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2700 .desc = {
2701 {
2702 .name = BLOCK_OPT_SIZE,
2703 .type = QEMU_OPT_SIZE,
2704 .help = "Virtual disk size"
2705 }, {
2706 /* end of list */
2707 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002708 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002709 };
2710
Kevin Wolfe80fec72011-04-29 10:58:12 +02002711 /* Remove size from argv manually so that negative numbers are not treated
2712 * as options by getopt. */
2713 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002714 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02002715 return 1;
2716 }
2717
2718 size = argv[--argc];
2719
2720 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002721 fmt = NULL;
2722 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002723 c = getopt(argc, argv, "f:hq");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002724 if (c == -1) {
2725 break;
2726 }
2727 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002728 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002729 case 'h':
2730 help();
2731 break;
2732 case 'f':
2733 fmt = optarg;
2734 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002735 case 'q':
2736 quiet = true;
2737 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002738 }
2739 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002740 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002741 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002742 }
2743 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002744
2745 /* Choose grow, shrink, or absolute resize mode */
2746 switch (size[0]) {
2747 case '+':
2748 relative = 1;
2749 size++;
2750 break;
2751 case '-':
2752 relative = -1;
2753 size++;
2754 break;
2755 default:
2756 relative = 0;
2757 break;
2758 }
2759
2760 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08002761 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002762 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002763 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002764 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002765 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002766 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002767 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002768 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2769 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002770
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002771 blk = img_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
2772 true, quiet);
2773 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002774 ret = -1;
2775 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002776 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002777 bs = blk_bs(blk);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002778
2779 if (relative) {
2780 total_size = bdrv_getlength(bs) + n * relative;
2781 } else {
2782 total_size = n;
2783 }
2784 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002785 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002786 ret = -1;
2787 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002788 }
2789
2790 ret = bdrv_truncate(bs, total_size);
2791 switch (ret) {
2792 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002793 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002794 break;
2795 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002796 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002797 break;
2798 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002799 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002800 break;
2801 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002802 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002803 break;
2804 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002805out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002806 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002807 if (ret) {
2808 return 1;
2809 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002810 return 0;
2811}
2812
Max Reitz6f176b42013-09-03 10:09:50 +02002813static int img_amend(int argc, char **argv)
2814{
2815 int c, ret = 0;
2816 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002817 QemuOptsList *create_opts = NULL;
2818 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02002819 const char *fmt = NULL, *filename, *cache;
2820 int flags;
Max Reitz6f176b42013-09-03 10:09:50 +02002821 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002822 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02002823 BlockDriverState *bs = NULL;
2824
Max Reitzbd39e6e2014-07-22 22:58:43 +02002825 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02002826 for (;;) {
Max Reitzbd39e6e2014-07-22 22:58:43 +02002827 c = getopt(argc, argv, "ho:f:t:q");
Max Reitz6f176b42013-09-03 10:09:50 +02002828 if (c == -1) {
2829 break;
2830 }
2831
2832 switch (c) {
2833 case 'h':
2834 case '?':
2835 help();
2836 break;
2837 case 'o':
Kevin Wolf626f84f2014-02-21 16:24:06 +01002838 if (!is_valid_option_list(optarg)) {
2839 error_report("Invalid option list: %s", optarg);
2840 ret = -1;
2841 goto out;
2842 }
2843 if (!options) {
2844 options = g_strdup(optarg);
2845 } else {
2846 char *old_options = options;
2847 options = g_strdup_printf("%s,%s", options, optarg);
2848 g_free(old_options);
2849 }
Max Reitz6f176b42013-09-03 10:09:50 +02002850 break;
2851 case 'f':
2852 fmt = optarg;
2853 break;
Max Reitzbd39e6e2014-07-22 22:58:43 +02002854 case 't':
2855 cache = optarg;
2856 break;
Max Reitz6f176b42013-09-03 10:09:50 +02002857 case 'q':
2858 quiet = true;
2859 break;
2860 }
2861 }
2862
Max Reitz6f176b42013-09-03 10:09:50 +02002863 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002864 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02002865 }
2866
Kevin Wolfa283cb62014-02-21 16:24:07 +01002867 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
2868 if (fmt && has_help_option(options)) {
2869 /* If a format is explicitly specified (and possibly no filename is
2870 * given), print option help here */
2871 ret = print_block_option_help(filename, fmt);
2872 goto out;
2873 }
2874
2875 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002876 error_exit("Expecting one image file name");
Kevin Wolfa283cb62014-02-21 16:24:07 +01002877 }
Max Reitz6f176b42013-09-03 10:09:50 +02002878
Max Reitzbd39e6e2014-07-22 22:58:43 +02002879 flags = BDRV_O_FLAGS | BDRV_O_RDWR;
2880 ret = bdrv_parse_cache_flags(cache, &flags);
2881 if (ret < 0) {
2882 error_report("Invalid cache option: %s", cache);
2883 goto out;
2884 }
2885
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002886 blk = img_open("image", filename, fmt, flags, true, quiet);
2887 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02002888 error_report("Could not open image '%s'", filename);
2889 ret = -1;
2890 goto out;
2891 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002892 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02002893
2894 fmt = bs->drv->format_name;
2895
Kevin Wolf626f84f2014-02-21 16:24:06 +01002896 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01002897 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02002898 ret = print_block_option_help(filename, fmt);
2899 goto out;
2900 }
2901
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002902 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08002903 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2904 if (options && qemu_opts_do_parse(opts, options, NULL)) {
Max Reitz6f176b42013-09-03 10:09:50 +02002905 error_report("Invalid options for file format '%s'", fmt);
2906 ret = -1;
2907 goto out;
2908 }
2909
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002910 ret = bdrv_amend_options(bs, opts);
Max Reitz6f176b42013-09-03 10:09:50 +02002911 if (ret < 0) {
2912 error_report("Error while amending options: %s", strerror(-ret));
2913 goto out;
2914 }
2915
2916out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002917 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08002918 qemu_opts_del(opts);
2919 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01002920 g_free(options);
2921
Max Reitz6f176b42013-09-03 10:09:50 +02002922 if (ret) {
2923 return 1;
2924 }
2925 return 0;
2926}
2927
Anthony Liguoric227f092009-10-01 16:12:16 -05002928static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002929#define DEF(option, callback, arg_string) \
2930 { option, callback },
2931#include "qemu-img-cmds.h"
2932#undef DEF
2933#undef GEN_DOCS
2934 { NULL, NULL, },
2935};
2936
bellardea2384d2004-08-01 21:59:26 +00002937int main(int argc, char **argv)
2938{
Anthony Liguoric227f092009-10-01 16:12:16 -05002939 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002940 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03002941 Error *local_error = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04002942 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04002943 static const struct option long_options[] = {
2944 {"help", no_argument, 0, 'h'},
Jeff Cody5f6979c2014-04-28 14:37:18 -04002945 {"version", no_argument, 0, 'v'},
Jeff Cody7db16892014-04-25 17:02:32 -04002946 {0, 0, 0, 0}
2947 };
bellardea2384d2004-08-01 21:59:26 +00002948
MORITA Kazutaka526eda12013-07-23 17:30:11 +09002949#ifdef CONFIG_POSIX
2950 signal(SIGPIPE, SIG_IGN);
2951#endif
2952
Kevin Wolf53f76e52010-12-16 15:10:32 +01002953 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08002954 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01002955
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03002956 if (qemu_init_main_loop(&local_error)) {
2957 error_report("%s", error_get_pretty(local_error));
2958 error_free(local_error);
2959 exit(EXIT_FAILURE);
2960 }
2961
bellardea2384d2004-08-01 21:59:26 +00002962 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08002963 if (argc < 2) {
2964 error_exit("Not enough arguments");
2965 }
Stuart Brady153859b2009-06-07 00:42:17 +01002966 cmdname = argv[1];
Stuart Brady153859b2009-06-07 00:42:17 +01002967
2968 /* find the command */
Jeff Cody5f6979c2014-04-28 14:37:18 -04002969 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
Stuart Brady153859b2009-06-07 00:42:17 +01002970 if (!strcmp(cmdname, cmd->name)) {
Jeff Cody7db16892014-04-25 17:02:32 -04002971 return cmd->handler(argc - 1, argv + 1);
Stuart Brady153859b2009-06-07 00:42:17 +01002972 }
bellardea2384d2004-08-01 21:59:26 +00002973 }
Stuart Brady153859b2009-06-07 00:42:17 +01002974
Jeff Cody5f6979c2014-04-28 14:37:18 -04002975 c = getopt_long(argc, argv, "h", long_options, NULL);
Jeff Cody7db16892014-04-25 17:02:32 -04002976
2977 if (c == 'h') {
2978 help();
2979 }
Jeff Cody5f6979c2014-04-28 14:37:18 -04002980 if (c == 'v') {
2981 printf(QEMU_IMG_VERSION);
2982 return 0;
2983 }
Jeff Cody7db16892014-04-25 17:02:32 -04002984
Stuart Brady153859b2009-06-07 00:42:17 +01002985 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08002986 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00002987}