blob: c8434206b84252f762de173c4744fca91e9620a8 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Benoît Canetc054b3f2012-09-05 13:09:02 +020024#include "qapi-visit.h"
25#include "qapi/qmp-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010026#include "qapi/qmp/qjson.h"
pbrookfaf07962007-11-11 02:51:17 +000027#include "qemu-common.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010028#include "qemu/option.h"
29#include "qemu/error-report.h"
30#include "qemu/osdep.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010031#include "sysemu/sysemu.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010032#include "block/block_int.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080033#include "block/qapi.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020034#include <getopt.h>
Mike Day1a443c12014-05-05 12:53:34 -040035#include <glib.h>
bellarde8445332006-06-14 15:32:10 +000036
Jeff Cody5f6979c2014-04-28 14:37:18 -040037#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION \
38 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
39
Anthony Liguoric227f092009-10-01 16:12:16 -050040typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010041 const char *name;
42 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050043} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010044
Federico Simoncelli8599ea42013-01-28 06:59:47 -050045enum {
46 OPTION_OUTPUT = 256,
47 OPTION_BACKING_CHAIN = 257,
48};
49
50typedef enum OutputFormat {
51 OFORMAT_JSON,
52 OFORMAT_HUMAN,
53} OutputFormat;
54
aurel32137519c2008-11-30 19:12:49 +000055/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
Stefan Hajnocziadfe0782010-04-13 10:29:35 +010056#define BDRV_O_FLAGS BDRV_O_CACHE_WB
Federico Simoncelli661a0f72011-06-20 12:48:19 -040057#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000058
Mike Day1a443c12014-05-05 12:53:34 -040059static gint compare_data(gconstpointer a, gconstpointer b, gpointer user)
bellardea2384d2004-08-01 21:59:26 +000060{
Mike Day1a443c12014-05-05 12:53:34 -040061 return g_strcmp0(a, b);
62}
63
64static void print_format(gpointer data, gpointer user)
65{
66 printf(" %s", (char *)data);
67}
68
69static void add_format_to_seq(void *opaque, const char *fmt_name)
70{
71 GSequence *seq = opaque;
72
Mike Day395071a2014-05-13 17:11:06 -040073 g_sequence_insert_sorted(seq, (gpointer)fmt_name,
74 compare_data, NULL);
bellardea2384d2004-08-01 21:59:26 +000075}
76
Fam Zhengac1307a2014-04-22 13:36:11 +080077static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
78{
79 va_list ap;
80
81 error_printf("qemu-img: ");
82
83 va_start(ap, fmt);
84 error_vprintf(fmt, ap);
85 va_end(ap);
86
87 error_printf("\nTry 'qemu-img --help' for more information\n");
88 exit(EXIT_FAILURE);
89}
90
blueswir1d2c639d2009-01-24 18:19:25 +000091/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +080092static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +000093{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010094 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -040095 QEMU_IMG_VERSION
malc3f020d72010-02-08 12:04:56 +030096 "usage: qemu-img command [command options]\n"
97 "QEMU disk image utility\n"
98 "\n"
99 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100100#define DEF(option, callback, arg_string) \
101 " " arg_string "\n"
102#include "qemu-img-cmds.h"
103#undef DEF
104#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +0300105 "\n"
106 "Command parameters:\n"
107 " 'filename' is a disk image filename\n"
108 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400109 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800110 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
111 " 'directsync' and 'unsafe' (default for convert)\n"
Max Reitz40055952014-07-22 22:58:42 +0200112 " 'src_cache' in contrast is the cache mode used to read input disk images\n"
malc3f020d72010-02-08 12:04:56 +0300113 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200114 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
115 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
116 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300117 " 'output_filename' is the destination disk image filename\n"
118 " 'output_fmt' is the destination format\n"
119 " 'options' is a comma separated list of format specific options in a\n"
120 " name=value format. Use -o ? for an overview of the options supported by the\n"
121 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800122 " 'snapshot_param' is param used for internal snapshot, format\n"
123 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
124 " '[ID_OR_NAME]'\n"
125 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
126 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300127 " '-c' indicates that target image must be compressed (qcow format only)\n"
128 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
129 " match exactly. The image doesn't need a working backing file before\n"
130 " rebasing in this case (useful for renaming the backing file)\n"
131 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200132 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100133 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200134 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
135 " contain only zeros for qemu-img to create a sparse image during\n"
136 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
137 " unallocated or zero sectors, and the destination image will always be\n"
138 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200139 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100140 " '-n' skips the target volume creation (useful if the volume is created\n"
141 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300142 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200143 "Parameters to check subcommand:\n"
144 " '-r' tries to repair any inconsistencies that are found during the check.\n"
145 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
146 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200147 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200148 "\n"
malc3f020d72010-02-08 12:04:56 +0300149 "Parameters to snapshot subcommand:\n"
150 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
151 " '-a' applies a snapshot (revert disk to saved state)\n"
152 " '-c' creates a snapshot\n"
153 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100154 " '-l' lists all snapshots in the given image\n"
155 "\n"
156 "Parameters to compare subcommand:\n"
157 " '-f' first image format\n"
158 " '-F' second image format\n"
159 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
Mike Day1a443c12014-05-05 12:53:34 -0400160 GSequence *seq;
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100161
162 printf("%s\nSupported formats:", help_msg);
Mike Day1a443c12014-05-05 12:53:34 -0400163 seq = g_sequence_new(NULL);
164 bdrv_iterate_format(add_format_to_seq, seq);
165 g_sequence_foreach(seq, print_format, NULL);
bellardea2384d2004-08-01 21:59:26 +0000166 printf("\n");
Mike Day1a443c12014-05-05 12:53:34 -0400167 g_sequence_free(seq);
168
Fam Zhengac1307a2014-04-22 13:36:11 +0800169 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000170}
171
Stefan Weil7c30f652013-06-16 17:01:05 +0200172static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100173{
174 int ret = 0;
175 if (!quiet) {
176 va_list args;
177 va_start(args, fmt);
178 ret = vprintf(fmt, args);
179 va_end(args);
180 }
181 return ret;
182}
183
bellardea2384d2004-08-01 21:59:26 +0000184#if defined(WIN32)
185/* XXX: put correct support for win32 */
186static int read_password(char *buf, int buf_size)
187{
188 int c, i;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800189
bellardea2384d2004-08-01 21:59:26 +0000190 printf("Password: ");
191 fflush(stdout);
192 i = 0;
193 for(;;) {
194 c = getchar();
Chen Gangfdcf6e62014-07-06 16:43:33 +0800195 if (c < 0) {
196 buf[i] = '\0';
197 return -1;
198 } else if (c == '\n') {
bellardea2384d2004-08-01 21:59:26 +0000199 break;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800200 } else if (i < (buf_size - 1)) {
bellardea2384d2004-08-01 21:59:26 +0000201 buf[i++] = c;
Chen Gangfdcf6e62014-07-06 16:43:33 +0800202 }
bellardea2384d2004-08-01 21:59:26 +0000203 }
204 buf[i] = '\0';
205 return 0;
206}
207
208#else
209
210#include <termios.h>
211
212static struct termios oldtty;
213
214static void term_exit(void)
215{
216 tcsetattr (0, TCSANOW, &oldtty);
217}
218
219static void term_init(void)
220{
221 struct termios tty;
222
223 tcgetattr (0, &tty);
224 oldtty = tty;
225
226 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
227 |INLCR|IGNCR|ICRNL|IXON);
228 tty.c_oflag |= OPOST;
229 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
230 tty.c_cflag &= ~(CSIZE|PARENB);
231 tty.c_cflag |= CS8;
232 tty.c_cc[VMIN] = 1;
233 tty.c_cc[VTIME] = 0;
ths3b46e622007-09-17 08:09:54 +0000234
bellardea2384d2004-08-01 21:59:26 +0000235 tcsetattr (0, TCSANOW, &tty);
236
237 atexit(term_exit);
238}
239
pbrook3f379ab2007-11-11 03:33:13 +0000240static int read_password(char *buf, int buf_size)
bellardea2384d2004-08-01 21:59:26 +0000241{
242 uint8_t ch;
243 int i, ret;
244
245 printf("password: ");
246 fflush(stdout);
247 term_init();
248 i = 0;
249 for(;;) {
250 ret = read(0, &ch, 1);
251 if (ret == -1) {
252 if (errno == EAGAIN || errno == EINTR) {
253 continue;
254 } else {
bellardea2384d2004-08-01 21:59:26 +0000255 break;
256 }
257 } else if (ret == 0) {
258 ret = -1;
259 break;
260 } else {
261 if (ch == '\r') {
262 ret = 0;
263 break;
264 }
265 if (i < (buf_size - 1))
266 buf[i++] = ch;
267 }
268 }
269 term_exit();
270 buf[i] = '\0';
271 printf("\n");
272 return ret;
273}
274#endif
275
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100276static int print_block_option_help(const char *filename, const char *fmt)
277{
278 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800279 QemuOptsList *create_opts = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100280
281 /* Find driver and parse its options */
282 drv = bdrv_find_format(fmt);
283 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100284 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100285 return 1;
286 }
287
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800288 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100289 if (filename) {
290 proto_drv = bdrv_find_protocol(filename, true);
291 if (!proto_drv) {
292 error_report("Unknown protocol '%s'", filename);
Chunyan Liu83d05212014-06-05 17:20:51 +0800293 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100294 return 1;
295 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800296 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100297 }
298
Chunyan Liu83d05212014-06-05 17:20:51 +0800299 qemu_opts_print_help(create_opts);
300 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100301 return 0;
302}
303
Kevin Wolf9ffe3332014-04-17 16:57:13 +0200304static BlockDriverState *bdrv_new_open(const char *id,
305 const char *filename,
Sheng Yang9bc378c2010-01-29 10:15:06 +0800306 const char *fmt,
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100307 int flags,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100308 bool require_io,
309 bool quiet)
bellard75c23802004-08-27 21:28:58 +0000310{
311 BlockDriverState *bs;
312 BlockDriver *drv;
313 char password[256];
Max Reitz34b5d2c2013-09-05 14:45:29 +0200314 Error *local_err = NULL;
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100315 int ret;
bellard75c23802004-08-27 21:28:58 +0000316
Kevin Wolf9ffe3332014-04-17 16:57:13 +0200317 bs = bdrv_new(id, &error_abort);
Kevin Wolfad717132010-12-16 15:37:41 +0100318
bellard75c23802004-08-27 21:28:58 +0000319 if (fmt) {
320 drv = bdrv_find_format(fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900321 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100322 error_report("Unknown file format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900323 goto fail;
324 }
bellard75c23802004-08-27 21:28:58 +0000325 } else {
326 drv = NULL;
327 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100328
Max Reitzddf56362014-02-18 18:33:06 +0100329 ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100330 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200331 error_report("Could not open '%s': %s", filename,
332 error_get_pretty(local_err));
333 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900334 goto fail;
bellard75c23802004-08-27 21:28:58 +0000335 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100336
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100337 if (bdrv_is_encrypted(bs) && require_io) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100338 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900339 if (read_password(password, sizeof(password)) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100340 error_report("No password given");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900341 goto fail;
342 }
343 if (bdrv_set_key(bs, password) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100344 error_report("invalid password");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900345 goto fail;
346 }
bellard75c23802004-08-27 21:28:58 +0000347 }
348 return bs;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900349fail:
Max Reitzf67503e2014-02-18 18:33:05 +0100350 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900351 return NULL;
bellard75c23802004-08-27 21:28:58 +0000352}
353
Chunyan Liu83d05212014-06-05 17:20:51 +0800354static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100355 const char *base_filename,
356 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200357{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200358 if (base_filename) {
Chunyan Liu83d05212014-06-05 17:20:51 +0800359 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100360 error_report("Backing file not supported for file format '%s'",
361 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900362 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200363 }
364 }
365 if (base_fmt) {
Chunyan Liu83d05212014-06-05 17:20:51 +0800366 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100367 error_report("Backing file format not supported for file "
368 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900369 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200370 }
371 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900372 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200373}
374
bellardea2384d2004-08-01 21:59:26 +0000375static int img_create(int argc, char **argv)
376{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200377 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100378 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000379 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000380 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000381 const char *filename;
382 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200383 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200384 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100385 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000386
bellardea2384d2004-08-01 21:59:26 +0000387 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100388 c = getopt(argc, argv, "F:b:f:he6o:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100389 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000390 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100391 }
bellardea2384d2004-08-01 21:59:26 +0000392 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100393 case '?':
bellardea2384d2004-08-01 21:59:26 +0000394 case 'h':
395 help();
396 break;
aliguori9230eaf2009-03-28 17:55:19 +0000397 case 'F':
398 base_fmt = optarg;
399 break;
bellardea2384d2004-08-01 21:59:26 +0000400 case 'b':
401 base_filename = optarg;
402 break;
403 case 'f':
404 fmt = optarg;
405 break;
406 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200407 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100408 "encryption\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100409 goto fail;
thsd8871c52007-10-24 16:11:42 +0000410 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200411 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100412 "compat6\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100413 goto fail;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200414 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100415 if (!is_valid_option_list(optarg)) {
416 error_report("Invalid option list: %s", optarg);
417 goto fail;
418 }
419 if (!options) {
420 options = g_strdup(optarg);
421 } else {
422 char *old_options = options;
423 options = g_strdup_printf("%s,%s", options, optarg);
424 g_free(old_options);
425 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200426 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100427 case 'q':
428 quiet = true;
429 break;
bellardea2384d2004-08-01 21:59:26 +0000430 }
431 }
aliguori9230eaf2009-03-28 17:55:19 +0000432
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900433 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100434 filename = (optind < argc) ? argv[optind] : NULL;
435 if (options && has_help_option(options)) {
436 g_free(options);
437 return print_block_option_help(filename, fmt);
438 }
439
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100440 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800441 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100442 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100443 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900444
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100445 /* Get image size, if specified */
446 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100447 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100448 char *end;
449 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
450 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800451 if (sval == -ERANGE) {
452 error_report("Image size must be less than 8 EiB!");
453 } else {
454 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200455 "G, T, P or E suffixes for ");
456 error_report("kilobytes, megabytes, gigabytes, terabytes, "
457 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800458 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100459 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100460 }
461 img_size = (uint64_t)sval;
462 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200463 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800464 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200465 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100466
Luiz Capitulino9b375252012-11-30 10:52:05 -0200467 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100468 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100469 if (local_err) {
Max Reitzb70d8c22013-09-06 16:51:03 +0200470 error_report("%s: %s", filename, error_get_pretty(local_err));
Luiz Capitulino9b375252012-11-30 10:52:05 -0200471 error_free(local_err);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100472 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900473 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200474
Kevin Wolf77386bf2014-02-21 16:24:04 +0100475 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000476 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100477
478fail:
479 g_free(options);
480 return 1;
bellardea2384d2004-08-01 21:59:26 +0000481}
482
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100483static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500484{
Markus Armbruster4399c432014-04-25 16:50:32 +0200485 Error *local_err = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500486 QString *str;
487 QmpOutputVisitor *ov = qmp_output_visitor_new();
488 QObject *obj;
489 visit_type_ImageCheck(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +0200490 &check, NULL, &local_err);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500491 obj = qmp_output_get_qobject(ov);
492 str = qobject_to_json_pretty(obj);
493 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100494 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500495 qobject_decref(obj);
496 qmp_output_visitor_cleanup(ov);
497 QDECREF(str);
498}
499
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100500static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500501{
502 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100503 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500504 } else {
505 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100506 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
507 "Data may be corrupted, or further writes to the image "
508 "may corrupt it.\n",
509 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500510 }
511
512 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100513 qprintf(quiet,
514 "\n%" PRId64 " leaked clusters were found on the image.\n"
515 "This means waste of disk space, but no harm to data.\n",
516 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500517 }
518
519 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100520 qprintf(quiet,
521 "\n%" PRId64
522 " internal errors have occurred during the check.\n",
523 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500524 }
525 }
526
527 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100528 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
529 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
530 check->allocated_clusters, check->total_clusters,
531 check->allocated_clusters * 100.0 / check->total_clusters,
532 check->fragmented_clusters * 100.0 / check->allocated_clusters,
533 check->compressed_clusters * 100.0 /
534 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500535 }
536
537 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100538 qprintf(quiet,
539 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500540 }
541}
542
543static int collect_image_check(BlockDriverState *bs,
544 ImageCheck *check,
545 const char *filename,
546 const char *fmt,
547 int fix)
548{
549 int ret;
550 BdrvCheckResult result;
551
552 ret = bdrv_check(bs, &result, fix);
553 if (ret < 0) {
554 return ret;
555 }
556
557 check->filename = g_strdup(filename);
558 check->format = g_strdup(bdrv_get_format_name(bs));
559 check->check_errors = result.check_errors;
560 check->corruptions = result.corruptions;
561 check->has_corruptions = result.corruptions != 0;
562 check->leaks = result.leaks;
563 check->has_leaks = result.leaks != 0;
564 check->corruptions_fixed = result.corruptions_fixed;
565 check->has_corruptions_fixed = result.corruptions != 0;
566 check->leaks_fixed = result.leaks_fixed;
567 check->has_leaks_fixed = result.leaks != 0;
568 check->image_end_offset = result.image_end_offset;
569 check->has_image_end_offset = result.image_end_offset != 0;
570 check->total_clusters = result.bfi.total_clusters;
571 check->has_total_clusters = result.bfi.total_clusters != 0;
572 check->allocated_clusters = result.bfi.allocated_clusters;
573 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
574 check->fragmented_clusters = result.bfi.fragmented_clusters;
575 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100576 check->compressed_clusters = result.bfi.compressed_clusters;
577 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500578
579 return 0;
580}
581
Kevin Wolfe076f332010-06-29 11:43:13 +0200582/*
583 * Checks an image for consistency. Exit codes:
584 *
Max Reitzd6635c42014-06-02 22:15:21 +0200585 * 0 - Check completed, image is good
586 * 1 - Check not completed because of internal errors
587 * 2 - Check completed, image is corrupted
588 * 3 - Check completed, image has leaked clusters, but is good otherwise
589 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200590 */
aliguori15859692009-04-21 23:11:53 +0000591static int img_check(int argc, char **argv)
592{
593 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500594 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200595 const char *filename, *fmt, *output, *cache;
aliguori15859692009-04-21 23:11:53 +0000596 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200597 int fix = 0;
Stefan Hajnoczi058f8f12012-08-09 13:05:56 +0100598 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500599 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100600 bool quiet = false;
aliguori15859692009-04-21 23:11:53 +0000601
602 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500603 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200604 cache = BDRV_DEFAULT_CACHE;
aliguori15859692009-04-21 23:11:53 +0000605 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500606 int option_index = 0;
607 static const struct option long_options[] = {
608 {"help", no_argument, 0, 'h'},
609 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530610 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500611 {"output", required_argument, 0, OPTION_OUTPUT},
612 {0, 0, 0, 0}
613 };
Max Reitz40055952014-07-22 22:58:42 +0200614 c = getopt_long(argc, argv, "hf:r:T:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500615 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100616 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000617 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100618 }
aliguori15859692009-04-21 23:11:53 +0000619 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100620 case '?':
aliguori15859692009-04-21 23:11:53 +0000621 case 'h':
622 help();
623 break;
624 case 'f':
625 fmt = optarg;
626 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200627 case 'r':
628 flags |= BDRV_O_RDWR;
629
630 if (!strcmp(optarg, "leaks")) {
631 fix = BDRV_FIX_LEAKS;
632 } else if (!strcmp(optarg, "all")) {
633 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
634 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800635 error_exit("Unknown option value for -r "
636 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200637 }
638 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500639 case OPTION_OUTPUT:
640 output = optarg;
641 break;
Max Reitz40055952014-07-22 22:58:42 +0200642 case 'T':
643 cache = optarg;
644 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100645 case 'q':
646 quiet = true;
647 break;
aliguori15859692009-04-21 23:11:53 +0000648 }
649 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200650 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800651 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100652 }
aliguori15859692009-04-21 23:11:53 +0000653 filename = argv[optind++];
654
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500655 if (output && !strcmp(output, "json")) {
656 output_format = OFORMAT_JSON;
657 } else if (output && !strcmp(output, "human")) {
658 output_format = OFORMAT_HUMAN;
659 } else if (output) {
660 error_report("--output must be used with human or json as argument.");
661 return 1;
662 }
663
Max Reitz40055952014-07-22 22:58:42 +0200664 ret = bdrv_parse_cache_flags(cache, &flags);
665 if (ret < 0) {
666 error_report("Invalid source cache option: %s", cache);
667 return 1;
668 }
669
Kevin Wolf9ffe3332014-04-17 16:57:13 +0200670 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900671 if (!bs) {
672 return 1;
673 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500674
675 check = g_new0(ImageCheck, 1);
676 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200677
678 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200679 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200680 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500681 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200682 }
683
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 if (check->corruptions_fixed || check->leaks_fixed) {
685 int corruptions_fixed, leaks_fixed;
686
687 leaks_fixed = check->leaks_fixed;
688 corruptions_fixed = check->corruptions_fixed;
689
690 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100691 qprintf(quiet,
692 "The following inconsistencies were found and repaired:\n\n"
693 " %" PRId64 " leaked clusters\n"
694 " %" PRId64 " corruptions\n\n"
695 "Double checking the fixed image now...\n",
696 check->leaks_fixed,
697 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500698 }
699
700 ret = collect_image_check(bs, check, filename, fmt, 0);
701
702 check->leaks_fixed = leaks_fixed;
703 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200704 }
705
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500706 switch (output_format) {
707 case OFORMAT_HUMAN:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100708 dump_human_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500709 break;
710 case OFORMAT_JSON:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100711 dump_json_image_check(check, quiet);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500712 break;
713 }
714
715 if (ret || check->check_errors) {
716 ret = 1;
717 goto fail;
718 }
719
720 if (check->corruptions) {
721 ret = 2;
722 } else if (check->leaks) {
723 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200724 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500725 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000726 }
727
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500728fail:
729 qapi_free_ImageCheck(check);
Fam Zheng4f6fd342013-08-23 09:14:47 +0800730 bdrv_unref(bs);
Kevin Wolfe076f332010-06-29 11:43:13 +0200731
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500732 return ret;
aliguori15859692009-04-21 23:11:53 +0000733}
734
bellardea2384d2004-08-01 21:59:26 +0000735static int img_commit(int argc, char **argv)
736{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400737 int c, ret, flags;
738 const char *filename, *fmt, *cache;
bellardea2384d2004-08-01 21:59:26 +0000739 BlockDriverState *bs;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100740 bool quiet = false;
bellardea2384d2004-08-01 21:59:26 +0000741
742 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400743 cache = BDRV_DEFAULT_CACHE;
bellardea2384d2004-08-01 21:59:26 +0000744 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100745 c = getopt(argc, argv, "f:ht:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100746 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000747 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100748 }
bellardea2384d2004-08-01 21:59:26 +0000749 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100750 case '?':
bellardea2384d2004-08-01 21:59:26 +0000751 case 'h':
752 help();
753 break;
754 case 'f':
755 fmt = optarg;
756 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400757 case 't':
758 cache = optarg;
759 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100760 case 'q':
761 quiet = true;
762 break;
bellardea2384d2004-08-01 21:59:26 +0000763 }
764 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200765 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800766 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100767 }
bellardea2384d2004-08-01 21:59:26 +0000768 filename = argv[optind++];
769
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400770 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100771 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400772 if (ret < 0) {
773 error_report("Invalid cache option: %s", cache);
774 return -1;
775 }
776
Kevin Wolf9ffe3332014-04-17 16:57:13 +0200777 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900778 if (!bs) {
779 return 1;
780 }
bellardea2384d2004-08-01 21:59:26 +0000781 ret = bdrv_commit(bs);
782 switch(ret) {
783 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100784 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000785 break;
786 case -ENOENT:
Jes Sorensen15654a62010-12-16 14:31:53 +0100787 error_report("No disk inserted");
bellardea2384d2004-08-01 21:59:26 +0000788 break;
789 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +0100790 error_report("Image is read-only");
bellardea2384d2004-08-01 21:59:26 +0000791 break;
792 case -ENOTSUP:
Jes Sorensen15654a62010-12-16 14:31:53 +0100793 error_report("Image is already committed");
bellardea2384d2004-08-01 21:59:26 +0000794 break;
795 default:
Jes Sorensen15654a62010-12-16 14:31:53 +0100796 error_report("Error while committing image");
bellardea2384d2004-08-01 21:59:26 +0000797 break;
798 }
799
Fam Zheng4f6fd342013-08-23 09:14:47 +0800800 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900801 if (ret) {
802 return 1;
803 }
bellardea2384d2004-08-01 21:59:26 +0000804 return 0;
805}
806
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400807/*
thsf58c7b32008-06-05 21:53:49 +0000808 * Returns true iff the first sector pointed to by 'buf' contains at least
809 * a non-NUL byte.
810 *
811 * 'pnum' is set to the number of sectors (including and immediately following
812 * the first one) that are known to be in the same allocated/unallocated state.
813 */
bellardea2384d2004-08-01 21:59:26 +0000814static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
815{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000816 bool is_zero;
817 int i;
bellardea2384d2004-08-01 21:59:26 +0000818
819 if (n <= 0) {
820 *pnum = 0;
821 return 0;
822 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000823 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +0000824 for(i = 1; i < n; i++) {
825 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000826 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +0000827 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000828 }
bellardea2384d2004-08-01 21:59:26 +0000829 }
830 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000831 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +0000832}
833
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100834/*
Kevin Wolfa22f1232011-08-26 15:27:13 +0200835 * Like is_allocated_sectors, but if the buffer starts with a used sector,
836 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
837 * breaking up write requests for only small sparse areas.
838 */
839static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
840 int min)
841{
842 int ret;
843 int num_checked, num_used;
844
845 if (n < min) {
846 min = n;
847 }
848
849 ret = is_allocated_sectors(buf, n, pnum);
850 if (!ret) {
851 return ret;
852 }
853
854 num_used = *pnum;
855 buf += BDRV_SECTOR_SIZE * *pnum;
856 n -= *pnum;
857 num_checked = num_used;
858
859 while (n > 0) {
860 ret = is_allocated_sectors(buf, n, pnum);
861
862 buf += BDRV_SECTOR_SIZE * *pnum;
863 n -= *pnum;
864 num_checked += *pnum;
865 if (ret) {
866 num_used = num_checked;
867 } else if (*pnum >= min) {
868 break;
869 }
870 }
871
872 *pnum = num_used;
873 return 1;
874}
875
876/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100877 * Compares two buffers sector by sector. Returns 0 if the first sector of both
878 * buffers matches, non-zero otherwise.
879 *
880 * pnum is set to the number of sectors (including and immediately following
881 * the first one) that are known to have the same comparison result
882 */
883static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
884 int *pnum)
885{
886 int res, i;
887
888 if (n <= 0) {
889 *pnum = 0;
890 return 0;
891 }
892
893 res = !!memcmp(buf1, buf2, 512);
894 for(i = 1; i < n; i++) {
895 buf1 += 512;
896 buf2 += 512;
897
898 if (!!memcmp(buf1, buf2, 512) != res) {
899 break;
900 }
901 }
902
903 *pnum = i;
904 return res;
905}
906
Kevin Wolf80ee15a2009-09-15 12:30:43 +0200907#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +0000908
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100909static int64_t sectors_to_bytes(int64_t sectors)
910{
911 return sectors << BDRV_SECTOR_BITS;
912}
913
914static int64_t sectors_to_process(int64_t total, int64_t from)
915{
916 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
917}
918
919/*
920 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
921 *
922 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
923 * data and negative value on error.
924 *
925 * @param bs: Driver used for accessing file
926 * @param sect_num: Number of first sector to check
927 * @param sect_count: Number of sectors to check
928 * @param filename: Name of disk file we are checking (logging purpose)
929 * @param buffer: Allocated buffer for storing read data
930 * @param quiet: Flag for quiet mode
931 */
932static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
933 int sect_count, const char *filename,
934 uint8_t *buffer, bool quiet)
935{
936 int pnum, ret = 0;
937 ret = bdrv_read(bs, sect_num, buffer, sect_count);
938 if (ret < 0) {
939 error_report("Error while reading offset %" PRId64 " of %s: %s",
940 sectors_to_bytes(sect_num), filename, strerror(-ret));
941 return ret;
942 }
943 ret = is_allocated_sectors(buffer, sect_count, &pnum);
944 if (ret || pnum != sect_count) {
945 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
946 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
947 return 1;
948 }
949
950 return 0;
951}
952
953/*
954 * Compares two images. Exit codes:
955 *
956 * 0 - Images are identical
957 * 1 - Images differ
958 * >1 - Error occurred
959 */
960static int img_compare(int argc, char **argv)
961{
Max Reitz40055952014-07-22 22:58:42 +0200962 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100963 BlockDriverState *bs1, *bs2;
964 int64_t total_sectors1, total_sectors2;
965 uint8_t *buf1 = NULL, *buf2 = NULL;
966 int pnum1, pnum2;
967 int allocated1, allocated2;
968 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
969 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +0200970 int flags;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100971 int64_t total_sectors;
972 int64_t sector_num = 0;
973 int64_t nb_sectors;
974 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100975 uint64_t progress_base;
976
Max Reitz40055952014-07-22 22:58:42 +0200977 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100978 for (;;) {
Max Reitz40055952014-07-22 22:58:42 +0200979 c = getopt(argc, argv, "hf:F:T:pqs");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100980 if (c == -1) {
981 break;
982 }
983 switch (c) {
984 case '?':
985 case 'h':
986 help();
987 break;
988 case 'f':
989 fmt1 = optarg;
990 break;
991 case 'F':
992 fmt2 = optarg;
993 break;
Max Reitz40055952014-07-22 22:58:42 +0200994 case 'T':
995 cache = optarg;
996 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100997 case 'p':
998 progress = true;
999 break;
1000 case 'q':
1001 quiet = true;
1002 break;
1003 case 's':
1004 strict = true;
1005 break;
1006 }
1007 }
1008
1009 /* Progress is not shown in Quiet mode */
1010 if (quiet) {
1011 progress = false;
1012 }
1013
1014
Kevin Wolffc11eb22013-08-05 10:53:04 +02001015 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001016 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001017 }
1018 filename1 = argv[optind++];
1019 filename2 = argv[optind++];
1020
Max Reitz40055952014-07-22 22:58:42 +02001021 flags = BDRV_O_FLAGS;
1022 ret = bdrv_parse_cache_flags(cache, &flags);
1023 if (ret < 0) {
1024 error_report("Invalid source cache option: %s", cache);
1025 ret = 2;
1026 goto out3;
1027 }
1028
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001029 /* Initialize before goto out */
1030 qemu_progress_init(progress, 2.0);
1031
Max Reitz40055952014-07-22 22:58:42 +02001032 bs1 = bdrv_new_open("image 1", filename1, fmt1, flags, true, quiet);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001033 if (!bs1) {
1034 error_report("Can't open file %s", filename1);
1035 ret = 2;
1036 goto out3;
1037 }
1038
Max Reitz40055952014-07-22 22:58:42 +02001039 bs2 = bdrv_new_open("image 2", filename2, fmt2, flags, true, quiet);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001040 if (!bs2) {
1041 error_report("Can't open file %s", filename2);
1042 ret = 2;
1043 goto out2;
1044 }
1045
1046 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
1047 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001048 total_sectors1 = bdrv_nb_sectors(bs1);
1049 if (total_sectors1 < 0) {
1050 error_report("Can't get size of %s: %s",
1051 filename1, strerror(-total_sectors1));
1052 ret = 4;
1053 goto out;
1054 }
1055 total_sectors2 = bdrv_nb_sectors(bs2);
1056 if (total_sectors2 < 0) {
1057 error_report("Can't get size of %s: %s",
1058 filename2, strerror(-total_sectors2));
1059 ret = 4;
1060 goto out;
1061 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001062 total_sectors = MIN(total_sectors1, total_sectors2);
1063 progress_base = MAX(total_sectors1, total_sectors2);
1064
1065 qemu_progress_print(0, 100);
1066
1067 if (strict && total_sectors1 != total_sectors2) {
1068 ret = 1;
1069 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1070 goto out;
1071 }
1072
1073 for (;;) {
1074 nb_sectors = sectors_to_process(total_sectors, sector_num);
1075 if (nb_sectors <= 0) {
1076 break;
1077 }
1078 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
1079 &pnum1);
1080 if (allocated1 < 0) {
1081 ret = 3;
1082 error_report("Sector allocation test failed for %s", filename1);
1083 goto out;
1084 }
1085
1086 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1087 &pnum2);
1088 if (allocated2 < 0) {
1089 ret = 3;
1090 error_report("Sector allocation test failed for %s", filename2);
1091 goto out;
1092 }
1093 nb_sectors = MIN(pnum1, pnum2);
1094
1095 if (allocated1 == allocated2) {
1096 if (allocated1) {
1097 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1098 if (ret < 0) {
1099 error_report("Error while reading offset %" PRId64 " of %s:"
1100 " %s", sectors_to_bytes(sector_num), filename1,
1101 strerror(-ret));
1102 ret = 4;
1103 goto out;
1104 }
1105 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1106 if (ret < 0) {
1107 error_report("Error while reading offset %" PRId64
1108 " of %s: %s", sectors_to_bytes(sector_num),
1109 filename2, strerror(-ret));
1110 ret = 4;
1111 goto out;
1112 }
1113 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1114 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001115 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1116 sectors_to_bytes(
1117 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001118 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001119 goto out;
1120 }
1121 }
1122 } else {
1123 if (strict) {
1124 ret = 1;
1125 qprintf(quiet, "Strict mode: Offset %" PRId64
1126 " allocation mismatch!\n",
1127 sectors_to_bytes(sector_num));
1128 goto out;
1129 }
1130
1131 if (allocated1) {
1132 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1133 filename1, buf1, quiet);
1134 } else {
1135 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1136 filename2, buf1, quiet);
1137 }
1138 if (ret) {
1139 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001140 error_report("Error while reading offset %" PRId64 ": %s",
1141 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001142 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001143 }
1144 goto out;
1145 }
1146 }
1147 sector_num += nb_sectors;
1148 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1149 }
1150
1151 if (total_sectors1 != total_sectors2) {
1152 BlockDriverState *bs_over;
1153 int64_t total_sectors_over;
1154 const char *filename_over;
1155
1156 qprintf(quiet, "Warning: Image size mismatch!\n");
1157 if (total_sectors1 > total_sectors2) {
1158 total_sectors_over = total_sectors1;
1159 bs_over = bs1;
1160 filename_over = filename1;
1161 } else {
1162 total_sectors_over = total_sectors2;
1163 bs_over = bs2;
1164 filename_over = filename2;
1165 }
1166
1167 for (;;) {
1168 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1169 if (nb_sectors <= 0) {
1170 break;
1171 }
1172 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1173 nb_sectors, &pnum);
1174 if (ret < 0) {
1175 ret = 3;
1176 error_report("Sector allocation test failed for %s",
1177 filename_over);
1178 goto out;
1179
1180 }
1181 nb_sectors = pnum;
1182 if (ret) {
1183 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1184 filename_over, buf1, quiet);
1185 if (ret) {
1186 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001187 error_report("Error while reading offset %" PRId64
1188 " of %s: %s", sectors_to_bytes(sector_num),
1189 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001190 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001191 }
1192 goto out;
1193 }
1194 }
1195 sector_num += nb_sectors;
1196 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1197 }
1198 }
1199
1200 qprintf(quiet, "Images are identical.\n");
1201 ret = 0;
1202
1203out:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001204 bdrv_unref(bs2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001205 qemu_vfree(buf1);
1206 qemu_vfree(buf2);
1207out2:
Fam Zheng4f6fd342013-08-23 09:14:47 +08001208 bdrv_unref(bs1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001209out3:
1210 qemu_progress_end();
1211 return ret;
1212}
1213
bellardea2384d2004-08-01 21:59:26 +00001214static int img_convert(int argc, char **argv)
1215{
Peter Lieven24f833c2013-11-27 11:07:07 +01001216 int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001217 int64_t ret = 0;
Max Reitz40055952014-07-22 22:58:42 +02001218 int progress = 0, flags, src_flags;
1219 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001220 BlockDriver *drv, *proto_drv;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001221 BlockDriverState **bs = NULL, *out_bs = NULL;
Peter Lieven802c3d42013-12-05 15:54:53 +01001222 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001223 int64_t *bs_sectors = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001224 uint8_t * buf = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001225 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardea2384d2004-08-01 21:59:26 +00001226 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +00001227 BlockDriverInfo bdi;
Chunyan Liu83d05212014-06-05 17:20:51 +08001228 QemuOpts *opts = NULL;
1229 QemuOptsList *create_opts = NULL;
1230 const char *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001231 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001232 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001233 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001234 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001235 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001236 QemuOpts *sn_opts = NULL;
bellardea2384d2004-08-01 21:59:26 +00001237
1238 fmt = NULL;
1239 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001240 cache = "unsafe";
Max Reitz40055952014-07-22 22:58:42 +02001241 src_cache = BDRV_DEFAULT_CACHE;
thsf58c7b32008-06-05 21:53:49 +00001242 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001243 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001244 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001245 for(;;) {
Max Reitz40055952014-07-22 22:58:42 +02001246 c = getopt(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001247 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001248 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001249 }
bellardea2384d2004-08-01 21:59:26 +00001250 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001251 case '?':
bellardea2384d2004-08-01 21:59:26 +00001252 case 'h':
1253 help();
1254 break;
1255 case 'f':
1256 fmt = optarg;
1257 break;
1258 case 'O':
1259 out_fmt = optarg;
1260 break;
thsf58c7b32008-06-05 21:53:49 +00001261 case 'B':
1262 out_baseimg = optarg;
1263 break;
bellardea2384d2004-08-01 21:59:26 +00001264 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001265 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001266 break;
1267 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001268 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001269 "encryption\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001270 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001271 goto fail_getopt;
thsec36ba12007-09-16 21:59:02 +00001272 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001273 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001274 "compat6\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001275 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001276 goto fail_getopt;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001277 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001278 if (!is_valid_option_list(optarg)) {
1279 error_report("Invalid option list: %s", optarg);
1280 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001281 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001282 }
1283 if (!options) {
1284 options = g_strdup(optarg);
1285 } else {
1286 char *old_options = options;
1287 options = g_strdup_printf("%s,%s", options, optarg);
1288 g_free(old_options);
1289 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001290 break;
edison51ef6722010-09-21 19:58:41 -07001291 case 's':
1292 snapshot_name = optarg;
1293 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001294 case 'l':
1295 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1296 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1297 if (!sn_opts) {
1298 error_report("Failed in parsing snapshot param '%s'",
1299 optarg);
Kevin Wolf2dc83282014-02-21 16:24:05 +01001300 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001301 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08001302 }
1303 } else {
1304 snapshot_name = optarg;
1305 }
1306 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001307 case 'S':
1308 {
1309 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001310 char *end;
1311 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1312 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001313 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001314 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001315 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001316 }
1317
1318 min_sparse = sval / BDRV_SECTOR_SIZE;
1319 break;
1320 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001321 case 'p':
1322 progress = 1;
1323 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001324 case 't':
1325 cache = optarg;
1326 break;
Max Reitz40055952014-07-22 22:58:42 +02001327 case 'T':
1328 src_cache = optarg;
1329 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001330 case 'q':
1331 quiet = true;
1332 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001333 case 'n':
1334 skip_create = 1;
1335 break;
bellardea2384d2004-08-01 21:59:26 +00001336 }
1337 }
ths3b46e622007-09-17 08:09:54 +00001338
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001339 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001340 if (quiet) {
1341 progress = 0;
1342 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001343 qemu_progress_init(progress, 1.0);
1344
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001345
balrog926c2d22007-10-31 01:11:44 +00001346 bs_n = argc - optind - 1;
Kevin Wolfa283cb62014-02-21 16:24:07 +01001347 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
thsf58c7b32008-06-05 21:53:49 +00001348
Kevin Wolf2dc83282014-02-21 16:24:05 +01001349 if (options && has_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001350 ret = print_block_option_help(out_filename, out_fmt);
1351 goto out;
1352 }
1353
bellardea2384d2004-08-01 21:59:26 +00001354 if (bs_n < 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001355 error_exit("Must specify image file name");
ths5fafdf22007-09-16 21:08:06 +00001356 }
bellardea2384d2004-08-01 21:59:26 +00001357
thsf58c7b32008-06-05 21:53:49 +00001358
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001359 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001360 error_report("-B makes no sense when concatenating multiple input "
1361 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001362 ret = -1;
1363 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001364 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001365
Max Reitz40055952014-07-22 22:58:42 +02001366 src_flags = BDRV_O_FLAGS;
1367 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1368 if (ret < 0) {
1369 error_report("Invalid source cache option: %s", src_cache);
1370 goto out;
1371 }
1372
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001373 qemu_progress_print(0, 100);
1374
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001375 bs = g_new0(BlockDriverState *, bs_n);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001376 bs_sectors = g_new(int64_t, bs_n);
balrog926c2d22007-10-31 01:11:44 +00001377
1378 total_sectors = 0;
1379 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001380 char *id = bs_n > 1 ? g_strdup_printf("source %d", bs_i)
1381 : g_strdup("source");
Max Reitz40055952014-07-22 22:58:42 +02001382 bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001383 true, quiet);
1384 g_free(id);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001385 if (!bs[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001386 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001387 ret = -1;
1388 goto out;
1389 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001390 bs_sectors[bs_i] = bdrv_nb_sectors(bs[bs_i]);
1391 if (bs_sectors[bs_i] < 0) {
1392 error_report("Could not get size of %s: %s",
1393 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1394 ret = -1;
1395 goto out;
1396 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001397 total_sectors += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001398 }
bellardea2384d2004-08-01 21:59:26 +00001399
Wenchao Xiaef806542013-12-04 17:10:57 +08001400 if (sn_opts) {
1401 ret = bdrv_snapshot_load_tmp(bs[0],
1402 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1403 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1404 &local_err);
1405 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001406 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001407 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001408 ret = -1;
1409 goto out;
1410 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001411
1412 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001413 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001414 if (local_err) {
Wenchao Xiaef806542013-12-04 17:10:57 +08001415 error_report("Failed to load snapshot: %s",
1416 error_get_pretty(local_err));
1417 error_free(local_err);
1418 ret = -1;
1419 goto out;
edison51ef6722010-09-21 19:58:41 -07001420 }
1421
Kevin Wolfefa84d42009-05-18 16:42:12 +02001422 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001423 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001424 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001425 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001426 ret = -1;
1427 goto out;
1428 }
balrog926c2d22007-10-31 01:11:44 +00001429
Kevin Wolf98289622013-07-10 15:47:39 +02001430 proto_drv = bdrv_find_protocol(out_filename, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001431 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001432 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001433 ret = -1;
1434 goto out;
1435 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001436
Chunyan Liuc282e1f2014-06-05 17:21:11 +08001437 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1438 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02001439
Chunyan Liu83d05212014-06-05 17:20:51 +08001440 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1441 if (options && qemu_opts_do_parse(opts, options, NULL)) {
1442 error_report("Invalid options for file format '%s'", out_fmt);
1443 ret = -1;
1444 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001445 }
1446
Chunyan Liu83d05212014-06-05 17:20:51 +08001447 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512);
1448 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001449 if (ret < 0) {
1450 goto out;
1451 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001452
Kevin Wolfa18953f2010-10-14 15:46:04 +02001453 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08001454 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02001455 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08001456 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02001457 }
1458
Kevin Wolfefa84d42009-05-18 16:42:12 +02001459 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01001460 if (compress) {
Chunyan Liu83d05212014-06-05 17:20:51 +08001461 bool encryption =
1462 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1463 const char *preallocation =
1464 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02001465
1466 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001467 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001468 ret = -1;
1469 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001470 }
1471
Chunyan Liu83d05212014-06-05 17:20:51 +08001472 if (encryption) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001473 error_report("Compression and encryption not supported at "
1474 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001475 ret = -1;
1476 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001477 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02001478
Chunyan Liu83d05212014-06-05 17:20:51 +08001479 if (preallocation
1480 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02001481 {
1482 error_report("Compression and preallocation not supported at "
1483 "the same time");
1484 ret = -1;
1485 goto out;
1486 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001487 }
1488
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001489 if (!skip_create) {
1490 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08001491 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001492 if (ret < 0) {
Max Reitzcc84d902013-09-06 17:14:26 +02001493 error_report("%s: error while converting %s: %s",
1494 out_filename, out_fmt, error_get_pretty(local_err));
1495 error_free(local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001496 goto out;
bellardea2384d2004-08-01 21:59:26 +00001497 }
1498 }
ths3b46e622007-09-17 08:09:54 +00001499
Peter Lieven5a37b602013-10-24 12:07:06 +02001500 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001501 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001502 if (ret < 0) {
1503 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02001504 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001505 }
1506
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001507 out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001508 if (!out_bs) {
1509 ret = -1;
1510 goto out;
1511 }
bellardea2384d2004-08-01 21:59:26 +00001512
balrog926c2d22007-10-31 01:11:44 +00001513 bs_i = 0;
1514 bs_offset = 0;
Peter Lievenf2521c92013-11-27 11:07:06 +01001515
1516 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1517 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1518 * as maximum. */
1519 bufsectors = MIN(32768,
1520 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1521 out_bs->bl.discard_alignment))
1522 );
1523
1524 buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001525
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001526 if (skip_create) {
Markus Armbruster43716fa2014-06-26 13:23:21 +02001527 int64_t output_sectors = bdrv_nb_sectors(out_bs);
1528 if (output_sectors < 0) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001529 error_report("unable to get output image length: %s\n",
Markus Armbruster43716fa2014-06-26 13:23:21 +02001530 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001531 ret = -1;
1532 goto out;
Markus Armbruster43716fa2014-06-26 13:23:21 +02001533 } else if (output_sectors < total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001534 error_report("output file is smaller than input file");
1535 ret = -1;
1536 goto out;
1537 }
1538 }
1539
Peter Lieven24f833c2013-11-27 11:07:07 +01001540 cluster_sectors = 0;
1541 ret = bdrv_get_info(out_bs, &bdi);
1542 if (ret < 0) {
1543 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001544 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001545 goto out;
1546 }
Peter Lieven24f833c2013-11-27 11:07:07 +01001547 } else {
Fam Zheng85f49ca2014-05-06 21:08:43 +08001548 compress = compress || bdi.needs_compressed_writes;
Peter Lieven24f833c2013-11-27 11:07:07 +01001549 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
1550 }
1551
1552 if (compress) {
1553 if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001554 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001555 ret = -1;
1556 goto out;
1557 }
bellardea2384d2004-08-01 21:59:26 +00001558 sector_num = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001559
1560 nb_sectors = total_sectors;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001561
bellardea2384d2004-08-01 21:59:26 +00001562 for(;;) {
balrog926c2d22007-10-31 01:11:44 +00001563 int64_t bs_num;
1564 int remainder;
1565 uint8_t *buf2;
1566
bellardea2384d2004-08-01 21:59:26 +00001567 nb_sectors = total_sectors - sector_num;
1568 if (nb_sectors <= 0)
1569 break;
1570 if (nb_sectors >= cluster_sectors)
1571 n = cluster_sectors;
1572 else
1573 n = nb_sectors;
balrog926c2d22007-10-31 01:11:44 +00001574
1575 bs_num = sector_num - bs_offset;
1576 assert (bs_num >= 0);
1577 remainder = n;
1578 buf2 = buf;
1579 while (remainder > 0) {
1580 int nlow;
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001581 while (bs_num == bs_sectors[bs_i]) {
1582 bs_offset += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001583 bs_i++;
1584 assert (bs_i < bs_n);
balrog926c2d22007-10-31 01:11:44 +00001585 bs_num = 0;
Blue Swirl0bfcd592010-05-22 08:02:12 +00001586 /* printf("changing part: sector_num=%" PRId64 ", "
1587 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001588 "\n", sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
balrog926c2d22007-10-31 01:11:44 +00001589 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001590 assert (bs_num < bs_sectors[bs_i]);
balrog926c2d22007-10-31 01:11:44 +00001591
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001592 nlow = remainder > bs_sectors[bs_i] - bs_num
1593 ? bs_sectors[bs_i] - bs_num : remainder;
balrog926c2d22007-10-31 01:11:44 +00001594
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001595 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1596 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001597 error_report("error while reading sector %" PRId64 ": %s",
1598 bs_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001599 goto out;
1600 }
balrog926c2d22007-10-31 01:11:44 +00001601
1602 buf2 += nlow * 512;
1603 bs_num += nlow;
1604
1605 remainder -= nlow;
1606 }
1607 assert (remainder == 0);
1608
Stefan Hajnoczi54f106d2013-04-15 17:17:33 +02001609 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1610 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001611 if (ret != 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001612 error_report("error while compressing sector %" PRId64
1613 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001614 goto out;
1615 }
bellardea2384d2004-08-01 21:59:26 +00001616 }
1617 sector_num += n;
Peter Lieven13c28af2013-11-27 11:07:01 +01001618 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
bellardea2384d2004-08-01 21:59:26 +00001619 }
bellardfaea38e2006-08-05 21:31:00 +00001620 /* signal EOF to align */
1621 bdrv_write_compressed(out_bs, 0, NULL, 0);
bellardea2384d2004-08-01 21:59:26 +00001622 } else {
Peter Lieven802c3d42013-12-05 15:54:53 +01001623 int64_t sectors_to_read, sectors_read, sector_num_next_status;
1624 bool count_allocated_sectors;
Peter Lieven11b66992013-10-24 12:07:05 +02001625 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02001626
Peter Lieven5a37b602013-10-24 12:07:06 +02001627 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1628 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1629 if (ret < 0) {
1630 goto out;
1631 }
1632 has_zero_init = 1;
1633 }
1634
Peter Lieven802c3d42013-12-05 15:54:53 +01001635 sectors_to_read = total_sectors;
1636 count_allocated_sectors = progress && (out_baseimg || has_zero_init);
1637restart:
thsf58c7b32008-06-05 21:53:49 +00001638 sector_num = 0; // total number of sectors converted so far
Peter Lieven802c3d42013-12-05 15:54:53 +01001639 sectors_read = 0;
1640 sector_num_next_status = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001641
bellardea2384d2004-08-01 21:59:26 +00001642 for(;;) {
1643 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001644 if (nb_sectors <= 0) {
Peter Lieven802c3d42013-12-05 15:54:53 +01001645 if (count_allocated_sectors) {
1646 sectors_to_read = sectors_read;
1647 count_allocated_sectors = false;
1648 goto restart;
1649 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001650 ret = 0;
bellardea2384d2004-08-01 21:59:26 +00001651 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001652 }
balrog926c2d22007-10-31 01:11:44 +00001653
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001654 while (sector_num - bs_offset >= bs_sectors[bs_i]) {
1655 bs_offset += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001656 bs_i ++;
1657 assert (bs_i < bs_n);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001658 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1659 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001660 sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
balrog926c2d22007-10-31 01:11:44 +00001661 }
1662
Peter Lieven13c28af2013-11-27 11:07:01 +01001663 if ((out_baseimg || has_zero_init) &&
1664 sector_num >= sector_num_next_status) {
1665 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1666 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1667 n, &n1);
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001668 if (ret < 0) {
Peter Lieven13c28af2013-11-27 11:07:01 +01001669 error_report("error while reading block status of sector %"
1670 PRId64 ": %s", sector_num - bs_offset,
1671 strerror(-ret));
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001672 goto out;
aliguori93c65b42009-04-05 17:40:43 +00001673 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001674 /* If the output image is zero initialized, we are not working
1675 * on a shared base and the input is zero we can skip the next
1676 * n1 sectors */
1677 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
Paolo Bonzinie4a86f82013-09-04 19:00:26 +02001678 sector_num += n1;
1679 continue;
1680 }
Peter Lieven13c28af2013-11-27 11:07:01 +01001681 /* If the output image is being created as a copy on write
1682 * image, assume that sectors which are unallocated in the
1683 * input image are present in both the output's and input's
1684 * base images (no need to copy them). */
1685 if (out_baseimg) {
1686 if (!(ret & BDRV_BLOCK_DATA)) {
1687 sector_num += n1;
1688 continue;
1689 }
1690 /* The next 'n1' sectors are allocated in the input image.
1691 * Copy only those as they may be followed by unallocated
1692 * sectors. */
1693 nb_sectors = n1;
1694 }
1695 /* avoid redundant callouts to get_block_status */
1696 sector_num_next_status = sector_num + n1;
thsf58c7b32008-06-05 21:53:49 +00001697 }
1698
Peter Lievenf2521c92013-11-27 11:07:06 +01001699 n = MIN(nb_sectors, bufsectors);
Peter Lieven24f833c2013-11-27 11:07:07 +01001700
1701 /* round down request length to an aligned sector, but
1702 * do not bother doing this on short requests. They happen
1703 * when we found an all-zero area, and the next sector to
1704 * write will not be sector_num + n. */
1705 if (cluster_sectors > 0 && n >= cluster_sectors) {
1706 int64_t next_aligned_sector = (sector_num + n);
1707 next_aligned_sector -= next_aligned_sector % cluster_sectors;
1708 if (sector_num + n > next_aligned_sector) {
1709 n = next_aligned_sector - sector_num;
1710 }
1711 }
1712
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001713 n = MIN(n, bs_sectors[bs_i] - (sector_num - bs_offset));
Peter Lieven13c28af2013-11-27 11:07:01 +01001714
Peter Lieven802c3d42013-12-05 15:54:53 +01001715 sectors_read += n;
1716 if (count_allocated_sectors) {
1717 sector_num += n;
1718 continue;
1719 }
1720
1721 n1 = n;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001722 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1723 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001724 error_report("error while reading sector %" PRId64 ": %s",
1725 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001726 goto out;
1727 }
bellardea2384d2004-08-01 21:59:26 +00001728 /* NOTE: at the same time we convert, we do not write zero
1729 sectors to have a chance to compress the image. Ideally, we
1730 should add a specific call to have the info to go faster */
1731 buf1 = buf;
1732 while (n > 0) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02001733 if (!has_zero_init ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001734 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001735 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1736 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001737 error_report("error while writing sector %" PRId64
1738 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001739 goto out;
1740 }
bellardea2384d2004-08-01 21:59:26 +00001741 }
1742 sector_num += n1;
1743 n -= n1;
1744 buf1 += n1 * 512;
1745 }
Peter Lieven802c3d42013-12-05 15:54:53 +01001746 qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
bellardea2384d2004-08-01 21:59:26 +00001747 }
1748 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001749out:
Peter Lieven13c28af2013-11-27 11:07:01 +01001750 if (!ret) {
1751 qemu_progress_print(100, 0);
1752 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001753 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08001754 qemu_opts_del(opts);
1755 qemu_opts_free(create_opts);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001756 qemu_vfree(buf);
Wenchao Xiaef806542013-12-04 17:10:57 +08001757 if (sn_opts) {
1758 qemu_opts_del(sn_opts);
1759 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001760 if (out_bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001761 bdrv_unref(out_bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001762 }
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001763 if (bs) {
1764 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1765 if (bs[bs_i]) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08001766 bdrv_unref(bs[bs_i]);
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001767 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001768 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001769 g_free(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001770 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001771 g_free(bs_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001772fail_getopt:
1773 g_free(options);
1774
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001775 if (ret) {
1776 return 1;
1777 }
bellardea2384d2004-08-01 21:59:26 +00001778 return 0;
1779}
1780
bellard57d1a2b2004-08-03 21:15:11 +00001781
bellardfaea38e2006-08-05 21:31:00 +00001782static void dump_snapshots(BlockDriverState *bs)
1783{
1784 QEMUSnapshotInfo *sn_tab, *sn;
1785 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00001786
1787 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1788 if (nb_sns <= 0)
1789 return;
1790 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08001791 bdrv_snapshot_dump(fprintf, stdout, NULL);
1792 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001793 for(i = 0; i < nb_sns; i++) {
1794 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08001795 bdrv_snapshot_dump(fprintf, stdout, sn);
1796 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00001797 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001798 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001799}
1800
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001801static void dump_json_image_info_list(ImageInfoList *list)
1802{
Markus Armbruster4399c432014-04-25 16:50:32 +02001803 Error *local_err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001804 QString *str;
1805 QmpOutputVisitor *ov = qmp_output_visitor_new();
1806 QObject *obj;
1807 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +02001808 &list, NULL, &local_err);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001809 obj = qmp_output_get_qobject(ov);
1810 str = qobject_to_json_pretty(obj);
1811 assert(str != NULL);
1812 printf("%s\n", qstring_get_str(str));
1813 qobject_decref(obj);
1814 qmp_output_visitor_cleanup(ov);
1815 QDECREF(str);
1816}
1817
Benoît Canetc054b3f2012-09-05 13:09:02 +02001818static void dump_json_image_info(ImageInfo *info)
1819{
Markus Armbruster4399c432014-04-25 16:50:32 +02001820 Error *local_err = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001821 QString *str;
1822 QmpOutputVisitor *ov = qmp_output_visitor_new();
1823 QObject *obj;
1824 visit_type_ImageInfo(qmp_output_get_visitor(ov),
Markus Armbruster4399c432014-04-25 16:50:32 +02001825 &info, NULL, &local_err);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001826 obj = qmp_output_get_qobject(ov);
1827 str = qobject_to_json_pretty(obj);
1828 assert(str != NULL);
1829 printf("%s\n", qstring_get_str(str));
1830 qobject_decref(obj);
1831 qmp_output_visitor_cleanup(ov);
1832 QDECREF(str);
1833}
1834
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001835static void dump_human_image_info_list(ImageInfoList *list)
1836{
1837 ImageInfoList *elem;
1838 bool delim = false;
1839
1840 for (elem = list; elem; elem = elem->next) {
1841 if (delim) {
1842 printf("\n");
1843 }
1844 delim = true;
1845
Wenchao Xia5b917042013-05-25 11:09:45 +08001846 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001847 }
1848}
1849
1850static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1851{
1852 return strcmp(a, b) == 0;
1853}
1854
1855/**
1856 * Open an image file chain and return an ImageInfoList
1857 *
1858 * @filename: topmost image filename
1859 * @fmt: topmost image format (may be NULL to autodetect)
1860 * @chain: true - enumerate entire backing file chain
1861 * false - only topmost image file
1862 *
1863 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1864 * image file. If there was an error a message will have been printed to
1865 * stderr.
1866 */
1867static ImageInfoList *collect_image_info_list(const char *filename,
1868 const char *fmt,
1869 bool chain)
1870{
1871 ImageInfoList *head = NULL;
1872 ImageInfoList **last = &head;
1873 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08001874 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001875
1876 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1877
1878 while (filename) {
1879 BlockDriverState *bs;
1880 ImageInfo *info;
1881 ImageInfoList *elem;
1882
1883 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1884 error_report("Backing file '%s' creates an infinite loop.",
1885 filename);
1886 goto err;
1887 }
1888 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1889
Kevin Wolf9ffe3332014-04-17 16:57:13 +02001890 bs = bdrv_new_open("image", filename, fmt,
1891 BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001892 if (!bs) {
1893 goto err;
1894 }
1895
Wenchao Xia43526ec2013-06-06 12:27:58 +08001896 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001897 if (err) {
Wenchao Xia43526ec2013-06-06 12:27:58 +08001898 error_report("%s", error_get_pretty(err));
1899 error_free(err);
Prasad Joshibdf866f2014-03-26 01:55:53 +05301900 bdrv_unref(bs);
Wenchao Xia43526ec2013-06-06 12:27:58 +08001901 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08001902 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001903
1904 elem = g_new0(ImageInfoList, 1);
1905 elem->value = info;
1906 *last = elem;
1907 last = &elem->next;
1908
Fam Zheng4f6fd342013-08-23 09:14:47 +08001909 bdrv_unref(bs);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001910
1911 filename = fmt = NULL;
1912 if (chain) {
1913 if (info->has_full_backing_filename) {
1914 filename = info->full_backing_filename;
1915 } else if (info->has_backing_filename) {
1916 filename = info->backing_filename;
1917 }
1918 if (info->has_backing_filename_format) {
1919 fmt = info->backing_filename_format;
1920 }
1921 }
1922 }
1923 g_hash_table_destroy(filenames);
1924 return head;
1925
1926err:
1927 qapi_free_ImageInfoList(head);
1928 g_hash_table_destroy(filenames);
1929 return NULL;
1930}
1931
Benoît Canetc054b3f2012-09-05 13:09:02 +02001932static int img_info(int argc, char **argv)
1933{
1934 int c;
1935 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001936 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001937 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001938 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001939
bellardea2384d2004-08-01 21:59:26 +00001940 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001941 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001942 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001943 int option_index = 0;
1944 static const struct option long_options[] = {
1945 {"help", no_argument, 0, 'h'},
1946 {"format", required_argument, 0, 'f'},
1947 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001948 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001949 {0, 0, 0, 0}
1950 };
1951 c = getopt_long(argc, argv, "f:h",
1952 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001953 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001954 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001955 }
bellardea2384d2004-08-01 21:59:26 +00001956 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001957 case '?':
bellardea2384d2004-08-01 21:59:26 +00001958 case 'h':
1959 help();
1960 break;
1961 case 'f':
1962 fmt = optarg;
1963 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001964 case OPTION_OUTPUT:
1965 output = optarg;
1966 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001967 case OPTION_BACKING_CHAIN:
1968 chain = true;
1969 break;
bellardea2384d2004-08-01 21:59:26 +00001970 }
1971 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02001972 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001973 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001974 }
bellardea2384d2004-08-01 21:59:26 +00001975 filename = argv[optind++];
1976
Benoît Canetc054b3f2012-09-05 13:09:02 +02001977 if (output && !strcmp(output, "json")) {
1978 output_format = OFORMAT_JSON;
1979 } else if (output && !strcmp(output, "human")) {
1980 output_format = OFORMAT_HUMAN;
1981 } else if (output) {
1982 error_report("--output must be used with human or json as argument.");
1983 return 1;
1984 }
1985
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001986 list = collect_image_info_list(filename, fmt, chain);
1987 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001988 return 1;
1989 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001990
Benoît Canetc054b3f2012-09-05 13:09:02 +02001991 switch (output_format) {
1992 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001993 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001994 break;
1995 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001996 if (chain) {
1997 dump_json_image_info_list(list);
1998 } else {
1999 dump_json_image_info(list->value);
2000 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002001 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002002 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002003
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002004 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002005 return 0;
2006}
2007
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002008
2009typedef struct MapEntry {
2010 int flags;
2011 int depth;
2012 int64_t start;
2013 int64_t length;
2014 int64_t offset;
2015 BlockDriverState *bs;
2016} MapEntry;
2017
2018static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2019 MapEntry *next)
2020{
2021 switch (output_format) {
2022 case OFORMAT_HUMAN:
2023 if ((e->flags & BDRV_BLOCK_DATA) &&
2024 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
2025 error_report("File contains external, encrypted or compressed clusters.");
2026 exit(1);
2027 }
2028 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
2029 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2030 e->start, e->length, e->offset, e->bs->filename);
2031 }
2032 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2033 * Modify the flags here to allow more coalescing.
2034 */
2035 if (next &&
2036 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
2037 next->flags &= ~BDRV_BLOCK_DATA;
2038 next->flags |= BDRV_BLOCK_ZERO;
2039 }
2040 break;
2041 case OFORMAT_JSON:
2042 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
2043 " \"zero\": %s, \"data\": %s",
2044 (e->start == 0 ? "[" : ",\n"),
2045 e->start, e->length, e->depth,
2046 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
2047 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
2048 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002049 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002050 }
2051 putchar('}');
2052
2053 if (!next) {
2054 printf("]\n");
2055 }
2056 break;
2057 }
2058}
2059
2060static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2061 int nb_sectors, MapEntry *e)
2062{
2063 int64_t ret;
2064 int depth;
2065
2066 /* As an optimization, we could cache the current range of unallocated
2067 * clusters in each file of the chain, and avoid querying the same
2068 * range repeatedly.
2069 */
2070
2071 depth = 0;
2072 for (;;) {
2073 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
2074 if (ret < 0) {
2075 return ret;
2076 }
2077 assert(nb_sectors);
2078 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2079 break;
2080 }
2081 bs = bs->backing_hd;
2082 if (bs == NULL) {
2083 ret = 0;
2084 break;
2085 }
2086
2087 depth++;
2088 }
2089
2090 e->start = sector_num * BDRV_SECTOR_SIZE;
2091 e->length = nb_sectors * BDRV_SECTOR_SIZE;
2092 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
2093 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
2094 e->depth = depth;
2095 e->bs = bs;
2096 return 0;
2097}
2098
2099static int img_map(int argc, char **argv)
2100{
2101 int c;
2102 OutputFormat output_format = OFORMAT_HUMAN;
2103 BlockDriverState *bs;
2104 const char *filename, *fmt, *output;
2105 int64_t length;
2106 MapEntry curr = { .length = 0 }, next;
2107 int ret = 0;
2108
2109 fmt = NULL;
2110 output = NULL;
2111 for (;;) {
2112 int option_index = 0;
2113 static const struct option long_options[] = {
2114 {"help", no_argument, 0, 'h'},
2115 {"format", required_argument, 0, 'f'},
2116 {"output", required_argument, 0, OPTION_OUTPUT},
2117 {0, 0, 0, 0}
2118 };
2119 c = getopt_long(argc, argv, "f:h",
2120 long_options, &option_index);
2121 if (c == -1) {
2122 break;
2123 }
2124 switch (c) {
2125 case '?':
2126 case 'h':
2127 help();
2128 break;
2129 case 'f':
2130 fmt = optarg;
2131 break;
2132 case OPTION_OUTPUT:
2133 output = optarg;
2134 break;
2135 }
2136 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002137 if (optind != argc - 1) {
2138 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002139 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002140 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002141
2142 if (output && !strcmp(output, "json")) {
2143 output_format = OFORMAT_JSON;
2144 } else if (output && !strcmp(output, "human")) {
2145 output_format = OFORMAT_HUMAN;
2146 } else if (output) {
2147 error_report("--output must be used with human or json as argument.");
2148 return 1;
2149 }
2150
Kevin Wolf9ffe3332014-04-17 16:57:13 +02002151 bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002152 if (!bs) {
2153 return 1;
2154 }
2155
2156 if (output_format == OFORMAT_HUMAN) {
2157 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2158 }
2159
2160 length = bdrv_getlength(bs);
2161 while (curr.start + curr.length < length) {
2162 int64_t nsectors_left;
2163 int64_t sector_num;
2164 int n;
2165
2166 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2167
2168 /* Probe up to 1 GiB at a time. */
2169 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2170 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2171 ret = get_block_status(bs, sector_num, n, &next);
2172
2173 if (ret < 0) {
2174 error_report("Could not read file metadata: %s", strerror(-ret));
2175 goto out;
2176 }
2177
2178 if (curr.length != 0 && curr.flags == next.flags &&
2179 curr.depth == next.depth &&
2180 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2181 curr.offset + curr.length == next.offset)) {
2182 curr.length += next.length;
2183 continue;
2184 }
2185
2186 if (curr.length > 0) {
2187 dump_map_entry(output_format, &curr, &next);
2188 }
2189 curr = next;
2190 }
2191
2192 dump_map_entry(output_format, &curr, NULL);
2193
2194out:
2195 bdrv_unref(bs);
2196 return ret < 0;
2197}
2198
aliguorif7b4a942009-01-07 17:40:15 +00002199#define SNAPSHOT_LIST 1
2200#define SNAPSHOT_CREATE 2
2201#define SNAPSHOT_APPLY 3
2202#define SNAPSHOT_DELETE 4
2203
Stuart Brady153859b2009-06-07 00:42:17 +01002204static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002205{
2206 BlockDriverState *bs;
2207 QEMUSnapshotInfo sn;
2208 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002209 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002210 int action = 0;
2211 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002212 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002213 Error *err = NULL;
aliguorif7b4a942009-01-07 17:40:15 +00002214
Kevin Wolf710da702011-01-10 12:33:02 +01002215 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002216 /* Parse commandline parameters */
2217 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002218 c = getopt(argc, argv, "la:c:d:hq");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002219 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002220 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002221 }
aliguorif7b4a942009-01-07 17:40:15 +00002222 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002223 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002224 case 'h':
2225 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002226 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002227 case 'l':
2228 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002229 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002230 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002231 }
2232 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002233 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002234 break;
2235 case 'a':
2236 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002237 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002238 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002239 }
2240 action = SNAPSHOT_APPLY;
2241 snapshot_name = optarg;
2242 break;
2243 case 'c':
2244 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002245 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002246 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002247 }
2248 action = SNAPSHOT_CREATE;
2249 snapshot_name = optarg;
2250 break;
2251 case 'd':
2252 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002253 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002254 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002255 }
2256 action = SNAPSHOT_DELETE;
2257 snapshot_name = optarg;
2258 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002259 case 'q':
2260 quiet = true;
2261 break;
aliguorif7b4a942009-01-07 17:40:15 +00002262 }
2263 }
2264
Kevin Wolffc11eb22013-08-05 10:53:04 +02002265 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002266 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002267 }
aliguorif7b4a942009-01-07 17:40:15 +00002268 filename = argv[optind++];
2269
2270 /* Open the image */
Kevin Wolf9ffe3332014-04-17 16:57:13 +02002271 bs = bdrv_new_open("image", filename, NULL, bdrv_oflags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002272 if (!bs) {
2273 return 1;
2274 }
aliguorif7b4a942009-01-07 17:40:15 +00002275
2276 /* Perform the requested action */
2277 switch(action) {
2278 case SNAPSHOT_LIST:
2279 dump_snapshots(bs);
2280 break;
2281
2282 case SNAPSHOT_CREATE:
2283 memset(&sn, 0, sizeof(sn));
2284 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2285
2286 qemu_gettimeofday(&tv);
2287 sn.date_sec = tv.tv_sec;
2288 sn.date_nsec = tv.tv_usec * 1000;
2289
2290 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002291 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002292 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002293 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002294 }
aliguorif7b4a942009-01-07 17:40:15 +00002295 break;
2296
2297 case SNAPSHOT_APPLY:
2298 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002299 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002300 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002301 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002302 }
aliguorif7b4a942009-01-07 17:40:15 +00002303 break;
2304
2305 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002306 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002307 if (err) {
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002308 error_report("Could not delete snapshot '%s': (%s)",
2309 snapshot_name, error_get_pretty(err));
2310 error_free(err);
2311 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002312 }
aliguorif7b4a942009-01-07 17:40:15 +00002313 break;
2314 }
2315
2316 /* Cleanup */
Fam Zheng4f6fd342013-08-23 09:14:47 +08002317 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002318 if (ret) {
2319 return 1;
2320 }
Stuart Brady153859b2009-06-07 00:42:17 +01002321 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002322}
2323
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002324static int img_rebase(int argc, char **argv)
2325{
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002326 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01002327 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002328 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02002329 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2330 int c, flags, src_flags, ret;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002331 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002332 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002333 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002334 Error *local_err = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002335
2336 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002337 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002338 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02002339 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002340 out_baseimg = NULL;
2341 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002342 for(;;) {
Max Reitz40055952014-07-22 22:58:42 +02002343 c = getopt(argc, argv, "hf:F:b:upt:T:q");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002344 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002345 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002346 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002347 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002348 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002349 case 'h':
2350 help();
2351 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002352 case 'f':
2353 fmt = optarg;
2354 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002355 case 'F':
2356 out_basefmt = optarg;
2357 break;
2358 case 'b':
2359 out_baseimg = optarg;
2360 break;
2361 case 'u':
2362 unsafe = 1;
2363 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002364 case 'p':
2365 progress = 1;
2366 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002367 case 't':
2368 cache = optarg;
2369 break;
Max Reitz40055952014-07-22 22:58:42 +02002370 case 'T':
2371 src_cache = optarg;
2372 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002373 case 'q':
2374 quiet = true;
2375 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002376 }
2377 }
2378
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002379 if (quiet) {
2380 progress = 0;
2381 }
2382
Fam Zhengac1307a2014-04-22 13:36:11 +08002383 if (optind != argc - 1) {
2384 error_exit("Expecting one image file name");
2385 }
2386 if (!unsafe && !out_baseimg) {
2387 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002388 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002389 filename = argv[optind++];
2390
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002391 qemu_progress_init(progress, 2.0);
2392 qemu_progress_print(0, 100);
2393
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002394 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01002395 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002396 if (ret < 0) {
2397 error_report("Invalid cache option: %s", cache);
2398 return -1;
2399 }
2400
Max Reitz40055952014-07-22 22:58:42 +02002401 src_flags = BDRV_O_FLAGS;
2402 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2403 if (ret < 0) {
2404 error_report("Invalid source cache option: %s", src_cache);
2405 return -1;
2406 }
2407
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002408 /*
2409 * Open the images.
2410 *
2411 * Ignore the old backing file for unsafe rebase in case we want to correct
2412 * the reference to a renamed or moved backing file.
2413 */
Kevin Wolf9ffe3332014-04-17 16:57:13 +02002414 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002415 if (!bs) {
2416 return 1;
2417 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002418
2419 /* Find the right drivers for the backing files */
2420 old_backing_drv = NULL;
2421 new_backing_drv = NULL;
2422
2423 if (!unsafe && bs->backing_format[0] != '\0') {
2424 old_backing_drv = bdrv_find_format(bs->backing_format);
2425 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002426 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002427 ret = -1;
2428 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002429 }
2430 }
2431
2432 if (out_basefmt != NULL) {
2433 new_backing_drv = bdrv_find_format(out_basefmt);
2434 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002435 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002436 ret = -1;
2437 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002438 }
2439 }
2440
2441 /* For safe rebasing we need to compare old and new backing file */
2442 if (unsafe) {
2443 /* Make the compiler happy */
2444 bs_old_backing = NULL;
2445 bs_new_backing = NULL;
2446 } else {
2447 char backing_name[1024];
2448
Kevin Wolf98522f62014-04-17 13:16:01 +02002449 bs_old_backing = bdrv_new("old_backing", &error_abort);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002450 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitz40055952014-07-22 22:58:42 +02002451 ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
Max Reitz34b5d2c2013-09-05 14:45:29 +02002452 old_backing_drv, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002453 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002454 error_report("Could not open old backing file '%s': %s",
2455 backing_name, error_get_pretty(local_err));
2456 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002457 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002458 }
Alex Bligha6166732012-10-16 13:46:18 +01002459 if (out_baseimg[0]) {
Kevin Wolf98522f62014-04-17 13:16:01 +02002460 bs_new_backing = bdrv_new("new_backing", &error_abort);
Max Reitz40055952014-07-22 22:58:42 +02002461 ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
2462 new_backing_drv, &local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002463 if (ret) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02002464 error_report("Could not open new backing file '%s': %s",
2465 out_baseimg, error_get_pretty(local_err));
2466 error_free(local_err);
Alex Bligha6166732012-10-16 13:46:18 +01002467 goto out;
2468 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002469 }
2470 }
2471
2472 /*
2473 * Check each unallocated cluster in the COW file. If it is unallocated,
2474 * accesses go to the backing file. We must therefore compare this cluster
2475 * in the old and new backing file, and if they differ we need to copy it
2476 * from the old backing file into the COW file.
2477 *
2478 * If qemu-img crashes during this step, no harm is done. The content of
2479 * the image is the same as the original one at any time.
2480 */
2481 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002482 int64_t num_sectors;
2483 int64_t old_backing_num_sectors;
2484 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002485 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02002486 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08002487 uint8_t * buf_old;
2488 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02002489 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08002490
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002491 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2492 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002493
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002494 num_sectors = bdrv_nb_sectors(bs);
2495 if (num_sectors < 0) {
2496 error_report("Could not get size of '%s': %s",
2497 filename, strerror(-num_sectors));
2498 ret = -1;
2499 goto out;
2500 }
2501 old_backing_num_sectors = bdrv_nb_sectors(bs_old_backing);
2502 if (old_backing_num_sectors < 0) {
2503 char backing_name[1024];
2504
2505 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2506 error_report("Could not get size of '%s': %s",
2507 backing_name, strerror(-old_backing_num_sectors));
2508 ret = -1;
2509 goto out;
2510 }
Alex Bligha6166732012-10-16 13:46:18 +01002511 if (bs_new_backing) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002512 new_backing_num_sectors = bdrv_nb_sectors(bs_new_backing);
2513 if (new_backing_num_sectors < 0) {
2514 error_report("Could not get size of '%s': %s",
2515 out_baseimg, strerror(-new_backing_num_sectors));
2516 ret = -1;
2517 goto out;
2518 }
Alex Bligha6166732012-10-16 13:46:18 +01002519 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002520
Kevin Wolf1f710492012-10-12 14:29:18 +02002521 if (num_sectors != 0) {
2522 local_progress = (float)100 /
2523 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2524 }
2525
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002526 for (sector = 0; sector < num_sectors; sector += n) {
2527
2528 /* How many sectors can we handle with the next read? */
2529 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2530 n = (IO_BUF_SIZE / 512);
2531 } else {
2532 n = num_sectors - sector;
2533 }
2534
2535 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02002536 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02002537 if (ret < 0) {
2538 error_report("error while reading image metadata: %s",
2539 strerror(-ret));
2540 goto out;
2541 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02002542 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002543 continue;
2544 }
2545
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002546 /*
2547 * Read old and new backing file and take into consideration that
2548 * backing files may be smaller than the COW image.
2549 */
2550 if (sector >= old_backing_num_sectors) {
2551 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2552 } else {
2553 if (sector + n > old_backing_num_sectors) {
2554 n = old_backing_num_sectors - sector;
2555 }
2556
2557 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2558 if (ret < 0) {
2559 error_report("error while reading from old backing file");
2560 goto out;
2561 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002562 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002563
Alex Bligha6166732012-10-16 13:46:18 +01002564 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01002565 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2566 } else {
2567 if (sector + n > new_backing_num_sectors) {
2568 n = new_backing_num_sectors - sector;
2569 }
2570
2571 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2572 if (ret < 0) {
2573 error_report("error while reading from new backing file");
2574 goto out;
2575 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002576 }
2577
2578 /* If they differ, we need to write to the COW file */
2579 uint64_t written = 0;
2580
2581 while (written < n) {
2582 int pnum;
2583
2584 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01002585 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002586 {
2587 ret = bdrv_write(bs, sector + written,
2588 buf_old + written * 512, pnum);
2589 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002590 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002591 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002592 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002593 }
2594 }
2595
2596 written += pnum;
2597 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002598 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002599 }
TeLeMand6771bf2010-02-08 16:20:00 +08002600
Kevin Wolfbb1c0592011-08-08 14:09:12 +02002601 qemu_vfree(buf_old);
2602 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002603 }
2604
2605 /*
2606 * Change the backing file. All clusters that are different from the old
2607 * backing file are overwritten in the COW file now, so the visible content
2608 * doesn't change when we switch the backing file.
2609 */
Alex Bligha6166732012-10-16 13:46:18 +01002610 if (out_baseimg && *out_baseimg) {
2611 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2612 } else {
2613 ret = bdrv_change_backing_file(bs, NULL, NULL);
2614 }
2615
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002616 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002617 error_report("Could not change the backing file to '%s': No "
2618 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002619 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002620 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002621 out_baseimg, strerror(-ret));
2622 }
2623
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002624 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002625 /*
2626 * TODO At this point it is possible to check if any clusters that are
2627 * allocated in the COW file are the same in the backing file. If so, they
2628 * could be dropped from the COW file. Don't do this before switching the
2629 * backing file, in case of a crash this would lead to corruption.
2630 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002631out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002632 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002633 /* Cleanup */
2634 if (!unsafe) {
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002635 if (bs_old_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002636 bdrv_unref(bs_old_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002637 }
2638 if (bs_new_backing != NULL) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002639 bdrv_unref(bs_new_backing);
Kevin Wolfeb863ad2011-03-31 12:39:51 +02002640 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002641 }
2642
Fam Zheng4f6fd342013-08-23 09:14:47 +08002643 bdrv_unref(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002644 if (ret) {
2645 return 1;
2646 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002647 return 0;
2648}
2649
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002650static int img_resize(int argc, char **argv)
2651{
2652 int c, ret, relative;
2653 const char *filename, *fmt, *size;
2654 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002655 bool quiet = false;
Jes Sorensen2a819982010-12-06 17:08:31 +01002656 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002657 QemuOpts *param;
2658 static QemuOptsList resize_options = {
2659 .name = "resize_options",
2660 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2661 .desc = {
2662 {
2663 .name = BLOCK_OPT_SIZE,
2664 .type = QEMU_OPT_SIZE,
2665 .help = "Virtual disk size"
2666 }, {
2667 /* end of list */
2668 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002669 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002670 };
2671
Kevin Wolfe80fec72011-04-29 10:58:12 +02002672 /* Remove size from argv manually so that negative numbers are not treated
2673 * as options by getopt. */
2674 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002675 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02002676 return 1;
2677 }
2678
2679 size = argv[--argc];
2680
2681 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002682 fmt = NULL;
2683 for(;;) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002684 c = getopt(argc, argv, "f:hq");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002685 if (c == -1) {
2686 break;
2687 }
2688 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002689 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002690 case 'h':
2691 help();
2692 break;
2693 case 'f':
2694 fmt = optarg;
2695 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002696 case 'q':
2697 quiet = true;
2698 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002699 }
2700 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002701 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002702 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002703 }
2704 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002705
2706 /* Choose grow, shrink, or absolute resize mode */
2707 switch (size[0]) {
2708 case '+':
2709 relative = 1;
2710 size++;
2711 break;
2712 case '-':
2713 relative = -1;
2714 size++;
2715 break;
2716 default:
2717 relative = 0;
2718 break;
2719 }
2720
2721 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08002722 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002723 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002724 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002725 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002726 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002727 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002728 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002729 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2730 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002731
Kevin Wolf9ffe3332014-04-17 16:57:13 +02002732 bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
2733 true, quiet);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002734 if (!bs) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002735 ret = -1;
2736 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002737 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002738
2739 if (relative) {
2740 total_size = bdrv_getlength(bs) + n * relative;
2741 } else {
2742 total_size = n;
2743 }
2744 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002745 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002746 ret = -1;
2747 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002748 }
2749
2750 ret = bdrv_truncate(bs, total_size);
2751 switch (ret) {
2752 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002753 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002754 break;
2755 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002756 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002757 break;
2758 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002759 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002760 break;
2761 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002762 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002763 break;
2764 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002765out:
Jes Sorensen2a819982010-12-06 17:08:31 +01002766 if (bs) {
Fam Zheng4f6fd342013-08-23 09:14:47 +08002767 bdrv_unref(bs);
Jes Sorensen2a819982010-12-06 17:08:31 +01002768 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002769 if (ret) {
2770 return 1;
2771 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002772 return 0;
2773}
2774
Max Reitz6f176b42013-09-03 10:09:50 +02002775static int img_amend(int argc, char **argv)
2776{
2777 int c, ret = 0;
2778 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002779 QemuOptsList *create_opts = NULL;
2780 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02002781 const char *fmt = NULL, *filename, *cache;
2782 int flags;
Max Reitz6f176b42013-09-03 10:09:50 +02002783 bool quiet = false;
2784 BlockDriverState *bs = NULL;
2785
Max Reitzbd39e6e2014-07-22 22:58:43 +02002786 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02002787 for (;;) {
Max Reitzbd39e6e2014-07-22 22:58:43 +02002788 c = getopt(argc, argv, "ho:f:t:q");
Max Reitz6f176b42013-09-03 10:09:50 +02002789 if (c == -1) {
2790 break;
2791 }
2792
2793 switch (c) {
2794 case 'h':
2795 case '?':
2796 help();
2797 break;
2798 case 'o':
Kevin Wolf626f84f2014-02-21 16:24:06 +01002799 if (!is_valid_option_list(optarg)) {
2800 error_report("Invalid option list: %s", optarg);
2801 ret = -1;
2802 goto out;
2803 }
2804 if (!options) {
2805 options = g_strdup(optarg);
2806 } else {
2807 char *old_options = options;
2808 options = g_strdup_printf("%s,%s", options, optarg);
2809 g_free(old_options);
2810 }
Max Reitz6f176b42013-09-03 10:09:50 +02002811 break;
2812 case 'f':
2813 fmt = optarg;
2814 break;
Max Reitzbd39e6e2014-07-22 22:58:43 +02002815 case 't':
2816 cache = optarg;
2817 break;
Max Reitz6f176b42013-09-03 10:09:50 +02002818 case 'q':
2819 quiet = true;
2820 break;
2821 }
2822 }
2823
Max Reitz6f176b42013-09-03 10:09:50 +02002824 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002825 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02002826 }
2827
Kevin Wolfa283cb62014-02-21 16:24:07 +01002828 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
2829 if (fmt && has_help_option(options)) {
2830 /* If a format is explicitly specified (and possibly no filename is
2831 * given), print option help here */
2832 ret = print_block_option_help(filename, fmt);
2833 goto out;
2834 }
2835
2836 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002837 error_exit("Expecting one image file name");
Kevin Wolfa283cb62014-02-21 16:24:07 +01002838 }
Max Reitz6f176b42013-09-03 10:09:50 +02002839
Max Reitzbd39e6e2014-07-22 22:58:43 +02002840 flags = BDRV_O_FLAGS | BDRV_O_RDWR;
2841 ret = bdrv_parse_cache_flags(cache, &flags);
2842 if (ret < 0) {
2843 error_report("Invalid cache option: %s", cache);
2844 goto out;
2845 }
2846
2847 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
Max Reitz6f176b42013-09-03 10:09:50 +02002848 if (!bs) {
2849 error_report("Could not open image '%s'", filename);
2850 ret = -1;
2851 goto out;
2852 }
2853
2854 fmt = bs->drv->format_name;
2855
Kevin Wolf626f84f2014-02-21 16:24:06 +01002856 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01002857 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02002858 ret = print_block_option_help(filename, fmt);
2859 goto out;
2860 }
2861
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002862 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08002863 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2864 if (options && qemu_opts_do_parse(opts, options, NULL)) {
Max Reitz6f176b42013-09-03 10:09:50 +02002865 error_report("Invalid options for file format '%s'", fmt);
2866 ret = -1;
2867 goto out;
2868 }
2869
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002870 ret = bdrv_amend_options(bs, opts);
Max Reitz6f176b42013-09-03 10:09:50 +02002871 if (ret < 0) {
2872 error_report("Error while amending options: %s", strerror(-ret));
2873 goto out;
2874 }
2875
2876out:
2877 if (bs) {
2878 bdrv_unref(bs);
2879 }
Chunyan Liu83d05212014-06-05 17:20:51 +08002880 qemu_opts_del(opts);
2881 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01002882 g_free(options);
2883
Max Reitz6f176b42013-09-03 10:09:50 +02002884 if (ret) {
2885 return 1;
2886 }
2887 return 0;
2888}
2889
Anthony Liguoric227f092009-10-01 16:12:16 -05002890static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002891#define DEF(option, callback, arg_string) \
2892 { option, callback },
2893#include "qemu-img-cmds.h"
2894#undef DEF
2895#undef GEN_DOCS
2896 { NULL, NULL, },
2897};
2898
bellardea2384d2004-08-01 21:59:26 +00002899int main(int argc, char **argv)
2900{
Anthony Liguoric227f092009-10-01 16:12:16 -05002901 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002902 const char *cmdname;
Jeff Cody7db16892014-04-25 17:02:32 -04002903 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04002904 static const struct option long_options[] = {
2905 {"help", no_argument, 0, 'h'},
Jeff Cody5f6979c2014-04-28 14:37:18 -04002906 {"version", no_argument, 0, 'v'},
Jeff Cody7db16892014-04-25 17:02:32 -04002907 {0, 0, 0, 0}
2908 };
bellardea2384d2004-08-01 21:59:26 +00002909
MORITA Kazutaka526eda12013-07-23 17:30:11 +09002910#ifdef CONFIG_POSIX
2911 signal(SIGPIPE, SIG_IGN);
2912#endif
2913
Kevin Wolf53f76e52010-12-16 15:10:32 +01002914 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08002915 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01002916
Paolo Bonzini2592c592012-11-03 18:10:17 +01002917 qemu_init_main_loop();
bellardea2384d2004-08-01 21:59:26 +00002918 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08002919 if (argc < 2) {
2920 error_exit("Not enough arguments");
2921 }
Stuart Brady153859b2009-06-07 00:42:17 +01002922 cmdname = argv[1];
Stuart Brady153859b2009-06-07 00:42:17 +01002923
2924 /* find the command */
Jeff Cody5f6979c2014-04-28 14:37:18 -04002925 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
Stuart Brady153859b2009-06-07 00:42:17 +01002926 if (!strcmp(cmdname, cmd->name)) {
Jeff Cody7db16892014-04-25 17:02:32 -04002927 return cmd->handler(argc - 1, argv + 1);
Stuart Brady153859b2009-06-07 00:42:17 +01002928 }
bellardea2384d2004-08-01 21:59:26 +00002929 }
Stuart Brady153859b2009-06-07 00:42:17 +01002930
Jeff Cody5f6979c2014-04-28 14:37:18 -04002931 c = getopt_long(argc, argv, "h", long_options, NULL);
Jeff Cody7db16892014-04-25 17:02:32 -04002932
2933 if (c == 'h') {
2934 help();
2935 }
Jeff Cody5f6979c2014-04-28 14:37:18 -04002936 if (c == 'v') {
2937 printf(QEMU_IMG_VERSION);
2938 return 0;
2939 }
Jeff Cody7db16892014-04-25 17:02:32 -04002940
Stuart Brady153859b2009-06-07 00:42:17 +01002941 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08002942 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00002943}