blob: 34249fee126c81bbc653f8e681ac9b40a0d83055 [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"
Benoît Canetc054b3f2012-09-05 13:09:02 +020033#include <getopt.h>
aliguori9230eaf2009-03-28 17:55:19 +000034#include <stdio.h>
bellardea2384d2004-08-01 21:59:26 +000035
bellarde8445332006-06-14 15:32:10 +000036#ifdef _WIN32
37#include <windows.h>
38#endif
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
bellardea2384d2004-08-01 21:59:26 +000059static void format_print(void *opaque, const char *name)
60{
61 printf(" %s", name);
62}
63
blueswir1d2c639d2009-01-24 18:19:25 +000064/* Please keep in synch with qemu-img.texi */
pbrook3f379ab2007-11-11 03:33:13 +000065static void help(void)
bellardea2384d2004-08-01 21:59:26 +000066{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010067 const char *help_msg =
68 "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
malc3f020d72010-02-08 12:04:56 +030069 "usage: qemu-img command [command options]\n"
70 "QEMU disk image utility\n"
71 "\n"
72 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +010073#define DEF(option, callback, arg_string) \
74 " " arg_string "\n"
75#include "qemu-img-cmds.h"
76#undef DEF
77#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +030078 "\n"
79 "Command parameters:\n"
80 " 'filename' is a disk image filename\n"
81 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -040082 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +080083 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
84 " 'directsync' and 'unsafe' (default for convert)\n"
malc3f020d72010-02-08 12:04:56 +030085 " 'size' is the disk image size in bytes. Optional suffixes\n"
86 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
87 " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
88 " 'output_filename' is the destination disk image filename\n"
89 " 'output_fmt' is the destination format\n"
90 " 'options' is a comma separated list of format specific options in a\n"
91 " name=value format. Use -o ? for an overview of the options supported by the\n"
92 " used format\n"
93 " '-c' indicates that target image must be compressed (qcow format only)\n"
94 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
95 " match exactly. The image doesn't need a working backing file before\n"
96 " rebasing in this case (useful for renaming the backing file)\n"
97 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +020098 " '-p' show progress of command (only certain commands)\n"
Kevin Wolfa22f1232011-08-26 15:27:13 +020099 " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
100 " for qemu-img to create a sparse image during conversion\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200101 " '--output' takes the format in which the output must be done (human or json)\n"
malc3f020d72010-02-08 12:04:56 +0300102 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200103 "Parameters to check subcommand:\n"
104 " '-r' tries to repair any inconsistencies that are found during the check.\n"
105 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
106 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200107 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200108 "\n"
malc3f020d72010-02-08 12:04:56 +0300109 "Parameters to snapshot subcommand:\n"
110 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
111 " '-a' applies a snapshot (revert disk to saved state)\n"
112 " '-c' creates a snapshot\n"
113 " '-d' deletes a snapshot\n"
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100114 " '-l' lists all snapshots in the given image\n";
115
116 printf("%s\nSupported formats:", help_msg);
bellardea2384d2004-08-01 21:59:26 +0000117 bdrv_iterate_format(format_print, NULL);
118 printf("\n");
119 exit(1);
120}
121
bellardea2384d2004-08-01 21:59:26 +0000122#if defined(WIN32)
123/* XXX: put correct support for win32 */
124static int read_password(char *buf, int buf_size)
125{
126 int c, i;
127 printf("Password: ");
128 fflush(stdout);
129 i = 0;
130 for(;;) {
131 c = getchar();
132 if (c == '\n')
133 break;
134 if (i < (buf_size - 1))
135 buf[i++] = c;
136 }
137 buf[i] = '\0';
138 return 0;
139}
140
141#else
142
143#include <termios.h>
144
145static struct termios oldtty;
146
147static void term_exit(void)
148{
149 tcsetattr (0, TCSANOW, &oldtty);
150}
151
152static void term_init(void)
153{
154 struct termios tty;
155
156 tcgetattr (0, &tty);
157 oldtty = tty;
158
159 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
160 |INLCR|IGNCR|ICRNL|IXON);
161 tty.c_oflag |= OPOST;
162 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
163 tty.c_cflag &= ~(CSIZE|PARENB);
164 tty.c_cflag |= CS8;
165 tty.c_cc[VMIN] = 1;
166 tty.c_cc[VTIME] = 0;
ths3b46e622007-09-17 08:09:54 +0000167
bellardea2384d2004-08-01 21:59:26 +0000168 tcsetattr (0, TCSANOW, &tty);
169
170 atexit(term_exit);
171}
172
pbrook3f379ab2007-11-11 03:33:13 +0000173static int read_password(char *buf, int buf_size)
bellardea2384d2004-08-01 21:59:26 +0000174{
175 uint8_t ch;
176 int i, ret;
177
178 printf("password: ");
179 fflush(stdout);
180 term_init();
181 i = 0;
182 for(;;) {
183 ret = read(0, &ch, 1);
184 if (ret == -1) {
185 if (errno == EAGAIN || errno == EINTR) {
186 continue;
187 } else {
188 ret = -1;
189 break;
190 }
191 } else if (ret == 0) {
192 ret = -1;
193 break;
194 } else {
195 if (ch == '\r') {
196 ret = 0;
197 break;
198 }
199 if (i < (buf_size - 1))
200 buf[i++] = ch;
201 }
202 }
203 term_exit();
204 buf[i] = '\0';
205 printf("\n");
206 return ret;
207}
208#endif
209
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100210static int print_block_option_help(const char *filename, const char *fmt)
211{
212 BlockDriver *drv, *proto_drv;
213 QEMUOptionParameter *create_options = NULL;
214
215 /* Find driver and parse its options */
216 drv = bdrv_find_format(fmt);
217 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100218 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100219 return 1;
220 }
221
222 proto_drv = bdrv_find_protocol(filename);
223 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100224 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100225 return 1;
226 }
227
228 create_options = append_option_parameters(create_options,
229 drv->create_options);
230 create_options = append_option_parameters(create_options,
231 proto_drv->create_options);
232 print_option_help(create_options);
233 free_option_parameters(create_options);
234 return 0;
235}
236
bellard75c23802004-08-27 21:28:58 +0000237static BlockDriverState *bdrv_new_open(const char *filename,
Sheng Yang9bc378c2010-01-29 10:15:06 +0800238 const char *fmt,
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100239 int flags,
240 bool require_io)
bellard75c23802004-08-27 21:28:58 +0000241{
242 BlockDriverState *bs;
243 BlockDriver *drv;
244 char password[256];
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100245 int ret;
bellard75c23802004-08-27 21:28:58 +0000246
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100247 bs = bdrv_new("image");
Kevin Wolfad717132010-12-16 15:37:41 +0100248
bellard75c23802004-08-27 21:28:58 +0000249 if (fmt) {
250 drv = bdrv_find_format(fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900251 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100252 error_report("Unknown file format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900253 goto fail;
254 }
bellard75c23802004-08-27 21:28:58 +0000255 } else {
256 drv = NULL;
257 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100258
259 ret = bdrv_open(bs, filename, flags, drv);
260 if (ret < 0) {
261 error_report("Could not open '%s': %s", filename, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900262 goto fail;
bellard75c23802004-08-27 21:28:58 +0000263 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100264
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100265 if (bdrv_is_encrypted(bs) && require_io) {
bellard75c23802004-08-27 21:28:58 +0000266 printf("Disk image '%s' is encrypted.\n", filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900267 if (read_password(password, sizeof(password)) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100268 error_report("No password given");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900269 goto fail;
270 }
271 if (bdrv_set_key(bs, password) < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100272 error_report("invalid password");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900273 goto fail;
274 }
bellard75c23802004-08-27 21:28:58 +0000275 }
276 return bs;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900277fail:
278 if (bs) {
279 bdrv_delete(bs);
280 }
281 return NULL;
bellard75c23802004-08-27 21:28:58 +0000282}
283
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900284static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100285 const char *base_filename,
286 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200287{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200288 if (base_filename) {
289 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100290 error_report("Backing file not supported for file format '%s'",
291 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900292 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200293 }
294 }
295 if (base_fmt) {
296 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100297 error_report("Backing file format not supported for file "
298 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900299 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200300 }
301 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900302 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200303}
304
bellardea2384d2004-08-01 21:59:26 +0000305static int img_create(int argc, char **argv)
306{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200307 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100308 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000309 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000310 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000311 const char *filename;
312 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200313 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200314 Error *local_err = NULL;
ths3b46e622007-09-17 08:09:54 +0000315
bellardea2384d2004-08-01 21:59:26 +0000316 for(;;) {
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200317 c = getopt(argc, argv, "F:b:f:he6o:");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100318 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000319 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100320 }
bellardea2384d2004-08-01 21:59:26 +0000321 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100322 case '?':
bellardea2384d2004-08-01 21:59:26 +0000323 case 'h':
324 help();
325 break;
aliguori9230eaf2009-03-28 17:55:19 +0000326 case 'F':
327 base_fmt = optarg;
328 break;
bellardea2384d2004-08-01 21:59:26 +0000329 case 'b':
330 base_filename = optarg;
331 break;
332 case 'f':
333 fmt = optarg;
334 break;
335 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200336 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100337 "encryption\' instead!");
338 return 1;
thsd8871c52007-10-24 16:11:42 +0000339 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200340 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100341 "compat6\' instead!");
342 return 1;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200343 case 'o':
344 options = optarg;
345 break;
bellardea2384d2004-08-01 21:59:26 +0000346 }
347 }
aliguori9230eaf2009-03-28 17:55:19 +0000348
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900349 /* Get the filename */
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100350 if (optind >= argc) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900351 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100352 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900353 filename = argv[optind++];
354
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100355 /* Get image size, if specified */
356 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100357 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100358 char *end;
359 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
360 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800361 if (sval == -ERANGE) {
362 error_report("Image size must be less than 8 EiB!");
363 } else {
364 error_report("Invalid image size specified! You may use k, M, "
365 "G or T suffixes for ");
366 error_report("kilobytes, megabytes, gigabytes and terabytes.");
367 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200368 return 1;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100369 }
370 img_size = (uint64_t)sval;
371 }
372
Peter Maydellc8057f92012-08-02 13:45:54 +0100373 if (options && is_help_option(options)) {
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200374 return print_block_option_help(filename, fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100375 }
376
Luiz Capitulino9b375252012-11-30 10:52:05 -0200377 bdrv_img_create(filename, fmt, base_filename, base_fmt,
378 options, img_size, BDRV_O_FLAGS, &local_err);
379 if (error_is_set(&local_err)) {
380 error_report("%s", error_get_pretty(local_err));
381 error_free(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900382 return 1;
383 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200384
bellardea2384d2004-08-01 21:59:26 +0000385 return 0;
386}
387
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500388static void dump_json_image_check(ImageCheck *check)
389{
390 Error *errp = NULL;
391 QString *str;
392 QmpOutputVisitor *ov = qmp_output_visitor_new();
393 QObject *obj;
394 visit_type_ImageCheck(qmp_output_get_visitor(ov),
395 &check, NULL, &errp);
396 obj = qmp_output_get_qobject(ov);
397 str = qobject_to_json_pretty(obj);
398 assert(str != NULL);
399 printf("%s\n", qstring_get_str(str));
400 qobject_decref(obj);
401 qmp_output_visitor_cleanup(ov);
402 QDECREF(str);
403}
404
405static void dump_human_image_check(ImageCheck *check)
406{
407 if (!(check->corruptions || check->leaks || check->check_errors)) {
408 printf("No errors were found on the image.\n");
409 } else {
410 if (check->corruptions) {
411 printf("\n%" PRId64 " errors were found on the image.\n"
412 "Data may be corrupted, or further writes to the image "
413 "may corrupt it.\n",
414 check->corruptions);
415 }
416
417 if (check->leaks) {
418 printf("\n%" PRId64 " leaked clusters were found on the image.\n"
419 "This means waste of disk space, but no harm to data.\n",
420 check->leaks);
421 }
422
423 if (check->check_errors) {
424 printf("\n%" PRId64 " internal errors have occurred during the check.\n",
425 check->check_errors);
426 }
427 }
428
429 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
430 printf("%" PRId64 "/%" PRId64 "= %0.2f%% allocated, %0.2f%% fragmented\n",
431 check->allocated_clusters, check->total_clusters,
432 check->allocated_clusters * 100.0 / check->total_clusters,
433 check->fragmented_clusters * 100.0 / check->allocated_clusters);
434 }
435
436 if (check->image_end_offset) {
437 printf("Image end offset: %" PRId64 "\n", check->image_end_offset);
438 }
439}
440
441static int collect_image_check(BlockDriverState *bs,
442 ImageCheck *check,
443 const char *filename,
444 const char *fmt,
445 int fix)
446{
447 int ret;
448 BdrvCheckResult result;
449
450 ret = bdrv_check(bs, &result, fix);
451 if (ret < 0) {
452 return ret;
453 }
454
455 check->filename = g_strdup(filename);
456 check->format = g_strdup(bdrv_get_format_name(bs));
457 check->check_errors = result.check_errors;
458 check->corruptions = result.corruptions;
459 check->has_corruptions = result.corruptions != 0;
460 check->leaks = result.leaks;
461 check->has_leaks = result.leaks != 0;
462 check->corruptions_fixed = result.corruptions_fixed;
463 check->has_corruptions_fixed = result.corruptions != 0;
464 check->leaks_fixed = result.leaks_fixed;
465 check->has_leaks_fixed = result.leaks != 0;
466 check->image_end_offset = result.image_end_offset;
467 check->has_image_end_offset = result.image_end_offset != 0;
468 check->total_clusters = result.bfi.total_clusters;
469 check->has_total_clusters = result.bfi.total_clusters != 0;
470 check->allocated_clusters = result.bfi.allocated_clusters;
471 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
472 check->fragmented_clusters = result.bfi.fragmented_clusters;
473 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
474
475 return 0;
476}
477
Kevin Wolfe076f332010-06-29 11:43:13 +0200478/*
479 * Checks an image for consistency. Exit codes:
480 *
481 * 0 - Check completed, image is good
482 * 1 - Check not completed because of internal errors
483 * 2 - Check completed, image is corrupted
484 * 3 - Check completed, image has leaked clusters, but is good otherwise
485 */
aliguori15859692009-04-21 23:11:53 +0000486static int img_check(int argc, char **argv)
487{
488 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500489 OutputFormat output_format = OFORMAT_HUMAN;
490 const char *filename, *fmt, *output;
aliguori15859692009-04-21 23:11:53 +0000491 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200492 int fix = 0;
Stefan Hajnoczi058f8f12012-08-09 13:05:56 +0100493 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500494 ImageCheck *check;
aliguori15859692009-04-21 23:11:53 +0000495
496 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500497 output = NULL;
aliguori15859692009-04-21 23:11:53 +0000498 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500499 int option_index = 0;
500 static const struct option long_options[] = {
501 {"help", no_argument, 0, 'h'},
502 {"format", required_argument, 0, 'f'},
503 {"repair", no_argument, 0, 'r'},
504 {"output", required_argument, 0, OPTION_OUTPUT},
505 {0, 0, 0, 0}
506 };
507 c = getopt_long(argc, argv, "f:hr:",
508 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100509 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000510 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100511 }
aliguori15859692009-04-21 23:11:53 +0000512 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100513 case '?':
aliguori15859692009-04-21 23:11:53 +0000514 case 'h':
515 help();
516 break;
517 case 'f':
518 fmt = optarg;
519 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200520 case 'r':
521 flags |= BDRV_O_RDWR;
522
523 if (!strcmp(optarg, "leaks")) {
524 fix = BDRV_FIX_LEAKS;
525 } else if (!strcmp(optarg, "all")) {
526 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
527 } else {
528 help();
529 }
530 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500531 case OPTION_OUTPUT:
532 output = optarg;
533 break;
aliguori15859692009-04-21 23:11:53 +0000534 }
535 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100536 if (optind >= argc) {
aliguori15859692009-04-21 23:11:53 +0000537 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100538 }
aliguori15859692009-04-21 23:11:53 +0000539 filename = argv[optind++];
540
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500541 if (output && !strcmp(output, "json")) {
542 output_format = OFORMAT_JSON;
543 } else if (output && !strcmp(output, "human")) {
544 output_format = OFORMAT_HUMAN;
545 } else if (output) {
546 error_report("--output must be used with human or json as argument.");
547 return 1;
548 }
549
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100550 bs = bdrv_new_open(filename, fmt, flags, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900551 if (!bs) {
552 return 1;
553 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500554
555 check = g_new0(ImageCheck, 1);
556 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200557
558 if (ret == -ENOTSUP) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500559 if (output_format == OFORMAT_HUMAN) {
560 error_report("This image format does not support checks");
561 }
562 ret = 1;
563 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200564 }
565
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500566 if (check->corruptions_fixed || check->leaks_fixed) {
567 int corruptions_fixed, leaks_fixed;
568
569 leaks_fixed = check->leaks_fixed;
570 corruptions_fixed = check->corruptions_fixed;
571
572 if (output_format == OFORMAT_HUMAN) {
573 printf("The following inconsistencies were found and repaired:\n\n"
574 " %" PRId64 " leaked clusters\n"
575 " %" PRId64 " corruptions\n\n"
576 "Double checking the fixed image now...\n",
577 check->leaks_fixed,
578 check->corruptions_fixed);
579 }
580
581 ret = collect_image_check(bs, check, filename, fmt, 0);
582
583 check->leaks_fixed = leaks_fixed;
584 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200585 }
586
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500587 switch (output_format) {
588 case OFORMAT_HUMAN:
589 dump_human_image_check(check);
590 break;
591 case OFORMAT_JSON:
592 dump_json_image_check(check);
593 break;
594 }
595
596 if (ret || check->check_errors) {
597 ret = 1;
598 goto fail;
599 }
600
601 if (check->corruptions) {
602 ret = 2;
603 } else if (check->leaks) {
604 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200605 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500606 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000607 }
608
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500609fail:
610 qapi_free_ImageCheck(check);
aliguori15859692009-04-21 23:11:53 +0000611 bdrv_delete(bs);
Kevin Wolfe076f332010-06-29 11:43:13 +0200612
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500613 return ret;
aliguori15859692009-04-21 23:11:53 +0000614}
615
bellardea2384d2004-08-01 21:59:26 +0000616static int img_commit(int argc, char **argv)
617{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400618 int c, ret, flags;
619 const char *filename, *fmt, *cache;
bellardea2384d2004-08-01 21:59:26 +0000620 BlockDriverState *bs;
621
622 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400623 cache = BDRV_DEFAULT_CACHE;
bellardea2384d2004-08-01 21:59:26 +0000624 for(;;) {
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400625 c = getopt(argc, argv, "f:ht:");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100626 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000627 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100628 }
bellardea2384d2004-08-01 21:59:26 +0000629 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100630 case '?':
bellardea2384d2004-08-01 21:59:26 +0000631 case 'h':
632 help();
633 break;
634 case 'f':
635 fmt = optarg;
636 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400637 case 't':
638 cache = optarg;
639 break;
bellardea2384d2004-08-01 21:59:26 +0000640 }
641 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100642 if (optind >= argc) {
bellardea2384d2004-08-01 21:59:26 +0000643 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100644 }
bellardea2384d2004-08-01 21:59:26 +0000645 filename = argv[optind++];
646
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400647 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100648 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400649 if (ret < 0) {
650 error_report("Invalid cache option: %s", cache);
651 return -1;
652 }
653
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100654 bs = bdrv_new_open(filename, fmt, flags, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900655 if (!bs) {
656 return 1;
657 }
bellardea2384d2004-08-01 21:59:26 +0000658 ret = bdrv_commit(bs);
659 switch(ret) {
660 case 0:
661 printf("Image committed.\n");
662 break;
663 case -ENOENT:
Jes Sorensen15654a62010-12-16 14:31:53 +0100664 error_report("No disk inserted");
bellardea2384d2004-08-01 21:59:26 +0000665 break;
666 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +0100667 error_report("Image is read-only");
bellardea2384d2004-08-01 21:59:26 +0000668 break;
669 case -ENOTSUP:
Jes Sorensen15654a62010-12-16 14:31:53 +0100670 error_report("Image is already committed");
bellardea2384d2004-08-01 21:59:26 +0000671 break;
672 default:
Jes Sorensen15654a62010-12-16 14:31:53 +0100673 error_report("Error while committing image");
bellardea2384d2004-08-01 21:59:26 +0000674 break;
675 }
676
677 bdrv_delete(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900678 if (ret) {
679 return 1;
680 }
bellardea2384d2004-08-01 21:59:26 +0000681 return 0;
682}
683
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400684/*
thsf58c7b32008-06-05 21:53:49 +0000685 * Returns true iff the first sector pointed to by 'buf' contains at least
686 * a non-NUL byte.
687 *
688 * 'pnum' is set to the number of sectors (including and immediately following
689 * the first one) that are known to be in the same allocated/unallocated state.
690 */
bellardea2384d2004-08-01 21:59:26 +0000691static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
692{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000693 bool is_zero;
694 int i;
bellardea2384d2004-08-01 21:59:26 +0000695
696 if (n <= 0) {
697 *pnum = 0;
698 return 0;
699 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000700 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +0000701 for(i = 1; i < n; i++) {
702 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000703 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +0000704 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000705 }
bellardea2384d2004-08-01 21:59:26 +0000706 }
707 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000708 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +0000709}
710
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100711/*
Kevin Wolfa22f1232011-08-26 15:27:13 +0200712 * Like is_allocated_sectors, but if the buffer starts with a used sector,
713 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
714 * breaking up write requests for only small sparse areas.
715 */
716static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
717 int min)
718{
719 int ret;
720 int num_checked, num_used;
721
722 if (n < min) {
723 min = n;
724 }
725
726 ret = is_allocated_sectors(buf, n, pnum);
727 if (!ret) {
728 return ret;
729 }
730
731 num_used = *pnum;
732 buf += BDRV_SECTOR_SIZE * *pnum;
733 n -= *pnum;
734 num_checked = num_used;
735
736 while (n > 0) {
737 ret = is_allocated_sectors(buf, n, pnum);
738
739 buf += BDRV_SECTOR_SIZE * *pnum;
740 n -= *pnum;
741 num_checked += *pnum;
742 if (ret) {
743 num_used = num_checked;
744 } else if (*pnum >= min) {
745 break;
746 }
747 }
748
749 *pnum = num_used;
750 return 1;
751}
752
753/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +0100754 * Compares two buffers sector by sector. Returns 0 if the first sector of both
755 * buffers matches, non-zero otherwise.
756 *
757 * pnum is set to the number of sectors (including and immediately following
758 * the first one) that are known to have the same comparison result
759 */
760static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
761 int *pnum)
762{
763 int res, i;
764
765 if (n <= 0) {
766 *pnum = 0;
767 return 0;
768 }
769
770 res = !!memcmp(buf1, buf2, 512);
771 for(i = 1; i < n; i++) {
772 buf1 += 512;
773 buf2 += 512;
774
775 if (!!memcmp(buf1, buf2, 512) != res) {
776 break;
777 }
778 }
779
780 *pnum = i;
781 return res;
782}
783
Kevin Wolf80ee15a2009-09-15 12:30:43 +0200784#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +0000785
786static int img_convert(int argc, char **argv)
787{
Jes Sorenseneec77d92010-12-07 17:44:34 +0100788 int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400789 int progress = 0, flags;
790 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900791 BlockDriver *drv, *proto_drv;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900792 BlockDriverState **bs = NULL, *out_bs = NULL;
ths96b8f132007-12-17 01:35:20 +0000793 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
794 uint64_t bs_sectors;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900795 uint8_t * buf = NULL;
bellardea2384d2004-08-01 21:59:26 +0000796 const uint8_t *buf1;
bellardfaea38e2006-08-05 21:31:00 +0000797 BlockDriverInfo bdi;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900798 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfa18953f2010-10-14 15:46:04 +0200799 QEMUOptionParameter *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200800 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -0700801 const char *snapshot_name = NULL;
Kevin Wolf1f710492012-10-12 14:29:18 +0200802 float local_progress = 0;
Kevin Wolfa22f1232011-08-26 15:27:13 +0200803 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
bellardea2384d2004-08-01 21:59:26 +0000804
805 fmt = NULL;
806 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400807 cache = "unsafe";
thsf58c7b32008-06-05 21:53:49 +0000808 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +0100809 compress = 0;
bellardea2384d2004-08-01 21:59:26 +0000810 for(;;) {
Kevin Wolfa22f1232011-08-26 15:27:13 +0200811 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100812 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000813 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100814 }
bellardea2384d2004-08-01 21:59:26 +0000815 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100816 case '?':
bellardea2384d2004-08-01 21:59:26 +0000817 case 'h':
818 help();
819 break;
820 case 'f':
821 fmt = optarg;
822 break;
823 case 'O':
824 out_fmt = optarg;
825 break;
thsf58c7b32008-06-05 21:53:49 +0000826 case 'B':
827 out_baseimg = optarg;
828 break;
bellardea2384d2004-08-01 21:59:26 +0000829 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +0100830 compress = 1;
bellardea2384d2004-08-01 21:59:26 +0000831 break;
832 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200833 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100834 "encryption\' instead!");
835 return 1;
thsec36ba12007-09-16 21:59:02 +0000836 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200837 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100838 "compat6\' instead!");
839 return 1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200840 case 'o':
841 options = optarg;
842 break;
edison51ef6722010-09-21 19:58:41 -0700843 case 's':
844 snapshot_name = optarg;
845 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +0200846 case 'S':
847 {
848 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100849 char *end;
850 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
851 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +0200852 error_report("Invalid minimum zero buffer size for sparse output specified");
853 return 1;
854 }
855
856 min_sparse = sval / BDRV_SECTOR_SIZE;
857 break;
858 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200859 case 'p':
860 progress = 1;
861 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400862 case 't':
863 cache = optarg;
864 break;
bellardea2384d2004-08-01 21:59:26 +0000865 }
866 }
ths3b46e622007-09-17 08:09:54 +0000867
balrog926c2d22007-10-31 01:11:44 +0000868 bs_n = argc - optind - 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100869 if (bs_n < 1) {
870 help();
871 }
balrog926c2d22007-10-31 01:11:44 +0000872
873 out_filename = argv[argc - 1];
thsf58c7b32008-06-05 21:53:49 +0000874
Charles Arnoldfa170c12012-05-11 10:57:54 -0600875 /* Initialize before goto out */
876 qemu_progress_init(progress, 2.0);
877
Peter Maydellc8057f92012-08-02 13:45:54 +0100878 if (options && is_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100879 ret = print_block_option_help(out_filename, out_fmt);
880 goto out;
881 }
882
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900883 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100884 error_report("-B makes no sense when concatenating multiple input "
885 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +0100886 ret = -1;
887 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900888 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +0800889
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200890 qemu_progress_print(0, 100);
891
Anthony Liguori7267c092011-08-20 22:09:37 -0500892 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
balrog926c2d22007-10-31 01:11:44 +0000893
894 total_sectors = 0;
895 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +0100896 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900897 if (!bs[bs_i]) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100898 error_report("Could not open '%s'", argv[optind + bs_i]);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900899 ret = -1;
900 goto out;
901 }
balrog926c2d22007-10-31 01:11:44 +0000902 bdrv_get_geometry(bs[bs_i], &bs_sectors);
903 total_sectors += bs_sectors;
904 }
bellardea2384d2004-08-01 21:59:26 +0000905
edison51ef6722010-09-21 19:58:41 -0700906 if (snapshot_name != NULL) {
907 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +0200908 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -0700909 ret = -1;
910 goto out;
911 }
912 if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
Markus Armbruster6daf1942011-06-22 14:03:54 +0200913 error_report("Failed to load snapshot");
edison51ef6722010-09-21 19:58:41 -0700914 ret = -1;
915 goto out;
916 }
917 }
918
Kevin Wolfefa84d42009-05-18 16:42:12 +0200919 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +0000920 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900921 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100922 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900923 ret = -1;
924 goto out;
925 }
balrog926c2d22007-10-31 01:11:44 +0000926
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900927 proto_drv = bdrv_find_protocol(out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900928 if (!proto_drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100929 error_report("Unknown protocol '%s'", out_filename);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900930 ret = -1;
931 goto out;
932 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900933
934 create_options = append_option_parameters(create_options,
935 drv->create_options);
936 create_options = append_option_parameters(create_options,
937 proto_drv->create_options);
Kevin Wolfdb08adf2009-06-04 15:39:38 +0200938
Kevin Wolfefa84d42009-05-18 16:42:12 +0200939 if (options) {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900940 param = parse_option_parameters(options, create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +0200941 if (param == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100942 error_report("Invalid options for file format '%s'.", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900943 ret = -1;
944 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200945 }
946 } else {
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900947 param = parse_option_parameters("", create_options, param);
Kevin Wolfefa84d42009-05-18 16:42:12 +0200948 }
949
950 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
Jes Sorenseneec77d92010-12-07 17:44:34 +0100951 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900952 if (ret < 0) {
953 goto out;
954 }
Kevin Wolfefa84d42009-05-18 16:42:12 +0200955
Kevin Wolfa18953f2010-10-14 15:46:04 +0200956 /* Get backing file name if -o backing_file was used */
957 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
958 if (out_baseimg_param) {
959 out_baseimg = out_baseimg_param->value.s;
960 }
961
Kevin Wolfefa84d42009-05-18 16:42:12 +0200962 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +0100963 if (compress) {
Kevin Wolfefa84d42009-05-18 16:42:12 +0200964 QEMUOptionParameter *encryption =
965 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
Kevin Wolf41521fa2011-10-18 16:19:42 +0200966 QEMUOptionParameter *preallocation =
967 get_option_parameter(param, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +0200968
969 if (!drv->bdrv_write_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100970 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900971 ret = -1;
972 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200973 }
974
975 if (encryption && encryption->value.n) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100976 error_report("Compression and encryption not supported at "
977 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900978 ret = -1;
979 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200980 }
Kevin Wolf41521fa2011-10-18 16:19:42 +0200981
982 if (preallocation && preallocation->value.s
983 && strcmp(preallocation->value.s, "off"))
984 {
985 error_report("Compression and preallocation not supported at "
986 "the same time");
987 ret = -1;
988 goto out;
989 }
Kevin Wolfefa84d42009-05-18 16:42:12 +0200990 }
991
992 /* Create the new image */
993 ret = bdrv_create(drv, out_filename, param);
bellardea2384d2004-08-01 21:59:26 +0000994 if (ret < 0) {
995 if (ret == -ENOTSUP) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100996 error_report("Formatting not supported for file format '%s'",
997 out_fmt);
aurel326e9ea0c2009-04-15 14:42:46 +0000998 } else if (ret == -EFBIG) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100999 error_report("The image size is too large for file format '%s'",
1000 out_fmt);
bellardea2384d2004-08-01 21:59:26 +00001001 } else {
Jes Sorensen15654a62010-12-16 14:31:53 +01001002 error_report("%s: error while converting %s: %s",
1003 out_filename, out_fmt, strerror(-ret));
bellardea2384d2004-08-01 21:59:26 +00001004 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001005 goto out;
bellardea2384d2004-08-01 21:59:26 +00001006 }
ths3b46e622007-09-17 08:09:54 +00001007
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001008 flags = BDRV_O_RDWR;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001009 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001010 if (ret < 0) {
1011 error_report("Invalid cache option: %s", cache);
1012 return -1;
1013 }
1014
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +01001015 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001016 if (!out_bs) {
1017 ret = -1;
1018 goto out;
1019 }
bellardea2384d2004-08-01 21:59:26 +00001020
balrog926c2d22007-10-31 01:11:44 +00001021 bs_i = 0;
1022 bs_offset = 0;
1023 bdrv_get_geometry(bs[0], &bs_sectors);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001024 buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
balrog926c2d22007-10-31 01:11:44 +00001025
Jes Sorenseneec77d92010-12-07 17:44:34 +01001026 if (compress) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001027 ret = bdrv_get_info(out_bs, &bdi);
1028 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001029 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001030 goto out;
1031 }
bellardfaea38e2006-08-05 21:31:00 +00001032 cluster_size = bdi.cluster_size;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001033 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001034 error_report("invalid cluster size");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001035 ret = -1;
1036 goto out;
1037 }
bellardea2384d2004-08-01 21:59:26 +00001038 cluster_sectors = cluster_size >> 9;
1039 sector_num = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001040
1041 nb_sectors = total_sectors;
Kevin Wolf1f710492012-10-12 14:29:18 +02001042 if (nb_sectors != 0) {
1043 local_progress = (float)100 /
1044 (nb_sectors / MIN(nb_sectors, cluster_sectors));
1045 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001046
bellardea2384d2004-08-01 21:59:26 +00001047 for(;;) {
balrog926c2d22007-10-31 01:11:44 +00001048 int64_t bs_num;
1049 int remainder;
1050 uint8_t *buf2;
1051
bellardea2384d2004-08-01 21:59:26 +00001052 nb_sectors = total_sectors - sector_num;
1053 if (nb_sectors <= 0)
1054 break;
1055 if (nb_sectors >= cluster_sectors)
1056 n = cluster_sectors;
1057 else
1058 n = nb_sectors;
balrog926c2d22007-10-31 01:11:44 +00001059
1060 bs_num = sector_num - bs_offset;
1061 assert (bs_num >= 0);
1062 remainder = n;
1063 buf2 = buf;
1064 while (remainder > 0) {
1065 int nlow;
1066 while (bs_num == bs_sectors) {
1067 bs_i++;
1068 assert (bs_i < bs_n);
1069 bs_offset += bs_sectors;
1070 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1071 bs_num = 0;
Blue Swirl0bfcd592010-05-22 08:02:12 +00001072 /* printf("changing part: sector_num=%" PRId64 ", "
1073 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1074 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
balrog926c2d22007-10-31 01:11:44 +00001075 }
1076 assert (bs_num < bs_sectors);
1077
1078 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1079
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001080 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1081 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001082 error_report("error while reading sector %" PRId64 ": %s",
1083 bs_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001084 goto out;
1085 }
balrog926c2d22007-10-31 01:11:44 +00001086
1087 buf2 += nlow * 512;
1088 bs_num += nlow;
1089
1090 remainder -= nlow;
1091 }
1092 assert (remainder == 0);
1093
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001094 if (n < cluster_sectors) {
bellardea2384d2004-08-01 21:59:26 +00001095 memset(buf + n * 512, 0, cluster_size - n * 512);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001096 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001097 if (!buffer_is_zero(buf, cluster_size)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001098 ret = bdrv_write_compressed(out_bs, sector_num, buf,
1099 cluster_sectors);
1100 if (ret != 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001101 error_report("error while compressing sector %" PRId64
1102 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001103 goto out;
1104 }
bellardea2384d2004-08-01 21:59:26 +00001105 }
1106 sector_num += n;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001107 qemu_progress_print(local_progress, 100);
bellardea2384d2004-08-01 21:59:26 +00001108 }
bellardfaea38e2006-08-05 21:31:00 +00001109 /* signal EOF to align */
1110 bdrv_write_compressed(out_bs, 0, NULL, 0);
bellardea2384d2004-08-01 21:59:26 +00001111 } else {
Kevin Wolff2feebb2010-04-14 17:30:35 +02001112 int has_zero_init = bdrv_has_zero_init(out_bs);
1113
thsf58c7b32008-06-05 21:53:49 +00001114 sector_num = 0; // total number of sectors converted so far
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001115 nb_sectors = total_sectors - sector_num;
Kevin Wolf1f710492012-10-12 14:29:18 +02001116 if (nb_sectors != 0) {
1117 local_progress = (float)100 /
1118 (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
1119 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001120
bellardea2384d2004-08-01 21:59:26 +00001121 for(;;) {
1122 nb_sectors = total_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001123 if (nb_sectors <= 0) {
bellardea2384d2004-08-01 21:59:26 +00001124 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001125 }
1126 if (nb_sectors >= (IO_BUF_SIZE / 512)) {
bellardea2384d2004-08-01 21:59:26 +00001127 n = (IO_BUF_SIZE / 512);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001128 } else {
bellardea2384d2004-08-01 21:59:26 +00001129 n = nb_sectors;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001130 }
balrog926c2d22007-10-31 01:11:44 +00001131
1132 while (sector_num - bs_offset >= bs_sectors) {
1133 bs_i ++;
1134 assert (bs_i < bs_n);
1135 bs_offset += bs_sectors;
1136 bdrv_get_geometry(bs[bs_i], &bs_sectors);
Blue Swirl0bfcd592010-05-22 08:02:12 +00001137 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1138 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
balrog926c2d22007-10-31 01:11:44 +00001139 sector_num, bs_i, bs_offset, bs_sectors); */
1140 }
1141
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001142 if (n > bs_offset + bs_sectors - sector_num) {
balrog926c2d22007-10-31 01:11:44 +00001143 n = bs_offset + bs_sectors - sector_num;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001144 }
balrog926c2d22007-10-31 01:11:44 +00001145
Kevin Wolff2feebb2010-04-14 17:30:35 +02001146 if (has_zero_init) {
Akkarit Sangpetchd0320442009-07-17 10:02:15 +02001147 /* If the output image is being created as a copy on write image,
1148 assume that sectors which are unallocated in the input image
1149 are present in both the output's and input's base images (no
1150 need to copy them). */
1151 if (out_baseimg) {
1152 if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
1153 n, &n1)) {
1154 sector_num += n1;
1155 continue;
1156 }
1157 /* The next 'n1' sectors are allocated in the input image. Copy
1158 only those as they may be followed by unallocated sectors. */
1159 n = n1;
aliguori93c65b42009-04-05 17:40:43 +00001160 }
aliguori93c65b42009-04-05 17:40:43 +00001161 } else {
1162 n1 = n;
thsf58c7b32008-06-05 21:53:49 +00001163 }
1164
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001165 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1166 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001167 error_report("error while reading sector %" PRId64 ": %s",
1168 sector_num - bs_offset, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001169 goto out;
1170 }
bellardea2384d2004-08-01 21:59:26 +00001171 /* NOTE: at the same time we convert, we do not write zero
1172 sectors to have a chance to compress the image. Ideally, we
1173 should add a specific call to have the info to go faster */
1174 buf1 = buf;
1175 while (n > 0) {
thsf58c7b32008-06-05 21:53:49 +00001176 /* If the output image is being created as a copy on write image,
1177 copy all sectors even the ones containing only NUL bytes,
aliguori93c65b42009-04-05 17:40:43 +00001178 because they may differ from the sectors in the base image.
1179
1180 If the output is to a host device, we also write out
1181 sectors that are entirely 0, since whatever data was
1182 already there is garbage, not 0s. */
Kevin Wolff2feebb2010-04-14 17:30:35 +02001183 if (!has_zero_init || out_baseimg ||
Kevin Wolfa22f1232011-08-26 15:27:13 +02001184 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001185 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1186 if (ret < 0) {
Stefan Hajnoczi3fba9d82011-08-17 17:41:09 +01001187 error_report("error while writing sector %" PRId64
1188 ": %s", sector_num, strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001189 goto out;
1190 }
bellardea2384d2004-08-01 21:59:26 +00001191 }
1192 sector_num += n1;
1193 n -= n1;
1194 buf1 += n1 * 512;
1195 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001196 qemu_progress_print(local_progress, 100);
bellardea2384d2004-08-01 21:59:26 +00001197 }
1198 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001199out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001200 qemu_progress_end();
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001201 free_option_parameters(create_options);
1202 free_option_parameters(param);
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001203 qemu_vfree(buf);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001204 if (out_bs) {
1205 bdrv_delete(out_bs);
1206 }
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001207 if (bs) {
1208 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1209 if (bs[bs_i]) {
1210 bdrv_delete(bs[bs_i]);
1211 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001212 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001213 g_free(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001214 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001215 if (ret) {
1216 return 1;
1217 }
bellardea2384d2004-08-01 21:59:26 +00001218 return 0;
1219}
1220
bellard57d1a2b2004-08-03 21:15:11 +00001221
bellardfaea38e2006-08-05 21:31:00 +00001222static void dump_snapshots(BlockDriverState *bs)
1223{
1224 QEMUSnapshotInfo *sn_tab, *sn;
1225 int nb_sns, i;
1226 char buf[256];
1227
1228 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1229 if (nb_sns <= 0)
1230 return;
1231 printf("Snapshot list:\n");
1232 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1233 for(i = 0; i < nb_sns; i++) {
1234 sn = &sn_tab[i];
1235 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
1236 }
Anthony Liguori7267c092011-08-20 22:09:37 -05001237 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00001238}
1239
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001240static void dump_json_image_info_list(ImageInfoList *list)
1241{
1242 Error *errp = NULL;
1243 QString *str;
1244 QmpOutputVisitor *ov = qmp_output_visitor_new();
1245 QObject *obj;
1246 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1247 &list, NULL, &errp);
1248 obj = qmp_output_get_qobject(ov);
1249 str = qobject_to_json_pretty(obj);
1250 assert(str != NULL);
1251 printf("%s\n", qstring_get_str(str));
1252 qobject_decref(obj);
1253 qmp_output_visitor_cleanup(ov);
1254 QDECREF(str);
1255}
1256
Benoît Canetc054b3f2012-09-05 13:09:02 +02001257static void collect_snapshots(BlockDriverState *bs , ImageInfo *info)
bellardea2384d2004-08-01 21:59:26 +00001258{
Benoît Canetc054b3f2012-09-05 13:09:02 +02001259 int i, sn_count;
1260 QEMUSnapshotInfo *sn_tab = NULL;
1261 SnapshotInfoList *info_list, *cur_item = NULL;
1262 sn_count = bdrv_snapshot_list(bs, &sn_tab);
1263
1264 for (i = 0; i < sn_count; i++) {
1265 info->has_snapshots = true;
1266 info_list = g_new0(SnapshotInfoList, 1);
1267
1268 info_list->value = g_new0(SnapshotInfo, 1);
1269 info_list->value->id = g_strdup(sn_tab[i].id_str);
1270 info_list->value->name = g_strdup(sn_tab[i].name);
1271 info_list->value->vm_state_size = sn_tab[i].vm_state_size;
1272 info_list->value->date_sec = sn_tab[i].date_sec;
1273 info_list->value->date_nsec = sn_tab[i].date_nsec;
1274 info_list->value->vm_clock_sec = sn_tab[i].vm_clock_nsec / 1000000000;
1275 info_list->value->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
1276
1277 /* XXX: waiting for the qapi to support qemu-queue.h types */
1278 if (!cur_item) {
1279 info->snapshots = cur_item = info_list;
1280 } else {
1281 cur_item->next = info_list;
1282 cur_item = info_list;
1283 }
1284
1285 }
1286
1287 g_free(sn_tab);
1288}
1289
1290static void dump_json_image_info(ImageInfo *info)
1291{
1292 Error *errp = NULL;
1293 QString *str;
1294 QmpOutputVisitor *ov = qmp_output_visitor_new();
1295 QObject *obj;
1296 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1297 &info, NULL, &errp);
1298 obj = qmp_output_get_qobject(ov);
1299 str = qobject_to_json_pretty(obj);
1300 assert(str != NULL);
1301 printf("%s\n", qstring_get_str(str));
1302 qobject_decref(obj);
1303 qmp_output_visitor_cleanup(ov);
1304 QDECREF(str);
1305}
1306
1307static void collect_image_info(BlockDriverState *bs,
1308 ImageInfo *info,
1309 const char *filename,
1310 const char *fmt)
1311{
ths96b8f132007-12-17 01:35:20 +00001312 uint64_t total_sectors;
bellard93b6b2a2006-08-01 15:51:11 +00001313 char backing_filename[1024];
1314 char backing_filename2[1024];
bellardfaea38e2006-08-05 21:31:00 +00001315 BlockDriverInfo bdi;
bellardea2384d2004-08-01 21:59:26 +00001316
Benoît Canetc054b3f2012-09-05 13:09:02 +02001317 bdrv_get_geometry(bs, &total_sectors);
1318
1319 info->filename = g_strdup(filename);
1320 info->format = g_strdup(bdrv_get_format_name(bs));
1321 info->virtual_size = total_sectors * 512;
1322 info->actual_size = bdrv_get_allocated_file_size(bs);
1323 info->has_actual_size = info->actual_size >= 0;
1324 if (bdrv_is_encrypted(bs)) {
1325 info->encrypted = true;
1326 info->has_encrypted = true;
1327 }
1328 if (bdrv_get_info(bs, &bdi) >= 0) {
1329 if (bdi.cluster_size != 0) {
1330 info->cluster_size = bdi.cluster_size;
1331 info->has_cluster_size = true;
1332 }
1333 info->dirty_flag = bdi.is_dirty;
1334 info->has_dirty_flag = true;
1335 }
1336 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
1337 if (backing_filename[0] != '\0') {
1338 info->backing_filename = g_strdup(backing_filename);
1339 info->has_backing_filename = true;
1340 bdrv_get_full_backing_filename(bs, backing_filename2,
1341 sizeof(backing_filename2));
1342
1343 if (strcmp(backing_filename, backing_filename2) != 0) {
1344 info->full_backing_filename =
1345 g_strdup(backing_filename2);
1346 info->has_full_backing_filename = true;
1347 }
1348
1349 if (bs->backing_format[0]) {
1350 info->backing_filename_format = g_strdup(bs->backing_format);
1351 info->has_backing_filename_format = true;
1352 }
1353 }
1354}
1355
1356static void dump_human_image_info(ImageInfo *info)
1357{
1358 char size_buf[128], dsize_buf[128];
1359 if (!info->has_actual_size) {
1360 snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
1361 } else {
1362 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
1363 info->actual_size);
1364 }
1365 get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
1366 printf("image: %s\n"
1367 "file format: %s\n"
1368 "virtual size: %s (%" PRId64 " bytes)\n"
1369 "disk size: %s\n",
1370 info->filename, info->format, size_buf,
1371 info->virtual_size,
1372 dsize_buf);
1373
1374 if (info->has_encrypted && info->encrypted) {
1375 printf("encrypted: yes\n");
1376 }
1377
1378 if (info->has_cluster_size) {
1379 printf("cluster_size: %" PRId64 "\n", info->cluster_size);
1380 }
1381
1382 if (info->has_dirty_flag && info->dirty_flag) {
1383 printf("cleanly shut down: no\n");
1384 }
1385
1386 if (info->has_backing_filename) {
1387 printf("backing file: %s", info->backing_filename);
1388 if (info->has_full_backing_filename) {
1389 printf(" (actual path: %s)", info->full_backing_filename);
1390 }
1391 putchar('\n');
1392 if (info->has_backing_filename_format) {
1393 printf("backing file format: %s\n", info->backing_filename_format);
1394 }
1395 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001396
1397 if (info->has_snapshots) {
1398 SnapshotInfoList *elem;
1399 char buf[256];
1400
1401 printf("Snapshot list:\n");
1402 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1403
1404 /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
1405 * we convert to the block layer's native QEMUSnapshotInfo for now.
1406 */
1407 for (elem = info->snapshots; elem; elem = elem->next) {
1408 QEMUSnapshotInfo sn = {
1409 .vm_state_size = elem->value->vm_state_size,
1410 .date_sec = elem->value->date_sec,
1411 .date_nsec = elem->value->date_nsec,
1412 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
1413 elem->value->vm_clock_nsec,
1414 };
1415
1416 pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
1417 pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
1418 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), &sn));
1419 }
1420 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001421}
1422
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001423static void dump_human_image_info_list(ImageInfoList *list)
1424{
1425 ImageInfoList *elem;
1426 bool delim = false;
1427
1428 for (elem = list; elem; elem = elem->next) {
1429 if (delim) {
1430 printf("\n");
1431 }
1432 delim = true;
1433
1434 dump_human_image_info(elem->value);
1435 }
1436}
1437
1438static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1439{
1440 return strcmp(a, b) == 0;
1441}
1442
1443/**
1444 * Open an image file chain and return an ImageInfoList
1445 *
1446 * @filename: topmost image filename
1447 * @fmt: topmost image format (may be NULL to autodetect)
1448 * @chain: true - enumerate entire backing file chain
1449 * false - only topmost image file
1450 *
1451 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1452 * image file. If there was an error a message will have been printed to
1453 * stderr.
1454 */
1455static ImageInfoList *collect_image_info_list(const char *filename,
1456 const char *fmt,
1457 bool chain)
1458{
1459 ImageInfoList *head = NULL;
1460 ImageInfoList **last = &head;
1461 GHashTable *filenames;
1462
1463 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1464
1465 while (filename) {
1466 BlockDriverState *bs;
1467 ImageInfo *info;
1468 ImageInfoList *elem;
1469
1470 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1471 error_report("Backing file '%s' creates an infinite loop.",
1472 filename);
1473 goto err;
1474 }
1475 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1476
1477 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
1478 false);
1479 if (!bs) {
1480 goto err;
1481 }
1482
1483 info = g_new0(ImageInfo, 1);
1484 collect_image_info(bs, info, filename, fmt);
1485 collect_snapshots(bs, info);
1486
1487 elem = g_new0(ImageInfoList, 1);
1488 elem->value = info;
1489 *last = elem;
1490 last = &elem->next;
1491
1492 bdrv_delete(bs);
1493
1494 filename = fmt = NULL;
1495 if (chain) {
1496 if (info->has_full_backing_filename) {
1497 filename = info->full_backing_filename;
1498 } else if (info->has_backing_filename) {
1499 filename = info->backing_filename;
1500 }
1501 if (info->has_backing_filename_format) {
1502 fmt = info->backing_filename_format;
1503 }
1504 }
1505 }
1506 g_hash_table_destroy(filenames);
1507 return head;
1508
1509err:
1510 qapi_free_ImageInfoList(head);
1511 g_hash_table_destroy(filenames);
1512 return NULL;
1513}
1514
Benoît Canetc054b3f2012-09-05 13:09:02 +02001515static int img_info(int argc, char **argv)
1516{
1517 int c;
1518 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001519 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001520 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001521 ImageInfoList *list;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001522
bellardea2384d2004-08-01 21:59:26 +00001523 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001524 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00001525 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02001526 int option_index = 0;
1527 static const struct option long_options[] = {
1528 {"help", no_argument, 0, 'h'},
1529 {"format", required_argument, 0, 'f'},
1530 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001531 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Benoît Canetc054b3f2012-09-05 13:09:02 +02001532 {0, 0, 0, 0}
1533 };
1534 c = getopt_long(argc, argv, "f:h",
1535 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001536 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001537 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001538 }
bellardea2384d2004-08-01 21:59:26 +00001539 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001540 case '?':
bellardea2384d2004-08-01 21:59:26 +00001541 case 'h':
1542 help();
1543 break;
1544 case 'f':
1545 fmt = optarg;
1546 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02001547 case OPTION_OUTPUT:
1548 output = optarg;
1549 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001550 case OPTION_BACKING_CHAIN:
1551 chain = true;
1552 break;
bellardea2384d2004-08-01 21:59:26 +00001553 }
1554 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001555 if (optind >= argc) {
bellardea2384d2004-08-01 21:59:26 +00001556 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001557 }
bellardea2384d2004-08-01 21:59:26 +00001558 filename = argv[optind++];
1559
Benoît Canetc054b3f2012-09-05 13:09:02 +02001560 if (output && !strcmp(output, "json")) {
1561 output_format = OFORMAT_JSON;
1562 } else if (output && !strcmp(output, "human")) {
1563 output_format = OFORMAT_HUMAN;
1564 } else if (output) {
1565 error_report("--output must be used with human or json as argument.");
1566 return 1;
1567 }
1568
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001569 list = collect_image_info_list(filename, fmt, chain);
1570 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001571 return 1;
1572 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001573
Benoît Canetc054b3f2012-09-05 13:09:02 +02001574 switch (output_format) {
1575 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001576 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02001577 break;
1578 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001579 if (chain) {
1580 dump_json_image_info_list(list);
1581 } else {
1582 dump_json_image_info(list->value);
1583 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001584 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001585 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02001586
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02001587 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00001588 return 0;
1589}
1590
aliguorif7b4a942009-01-07 17:40:15 +00001591#define SNAPSHOT_LIST 1
1592#define SNAPSHOT_CREATE 2
1593#define SNAPSHOT_APPLY 3
1594#define SNAPSHOT_DELETE 4
1595
Stuart Brady153859b2009-06-07 00:42:17 +01001596static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00001597{
1598 BlockDriverState *bs;
1599 QEMUSnapshotInfo sn;
1600 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001601 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00001602 int action = 0;
1603 qemu_timeval tv;
1604
Kevin Wolf710da702011-01-10 12:33:02 +01001605 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00001606 /* Parse commandline parameters */
1607 for(;;) {
1608 c = getopt(argc, argv, "la:c:d:h");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001609 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00001610 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001611 }
aliguorif7b4a942009-01-07 17:40:15 +00001612 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001613 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00001614 case 'h':
1615 help();
Stuart Brady153859b2009-06-07 00:42:17 +01001616 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00001617 case 'l':
1618 if (action) {
1619 help();
Stuart Brady153859b2009-06-07 00:42:17 +01001620 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00001621 }
1622 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02001623 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00001624 break;
1625 case 'a':
1626 if (action) {
1627 help();
Stuart Brady153859b2009-06-07 00:42:17 +01001628 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00001629 }
1630 action = SNAPSHOT_APPLY;
1631 snapshot_name = optarg;
1632 break;
1633 case 'c':
1634 if (action) {
1635 help();
Stuart Brady153859b2009-06-07 00:42:17 +01001636 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00001637 }
1638 action = SNAPSHOT_CREATE;
1639 snapshot_name = optarg;
1640 break;
1641 case 'd':
1642 if (action) {
1643 help();
Stuart Brady153859b2009-06-07 00:42:17 +01001644 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00001645 }
1646 action = SNAPSHOT_DELETE;
1647 snapshot_name = optarg;
1648 break;
1649 }
1650 }
1651
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001652 if (optind >= argc) {
aliguorif7b4a942009-01-07 17:40:15 +00001653 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001654 }
aliguorif7b4a942009-01-07 17:40:15 +00001655 filename = argv[optind++];
1656
1657 /* Open the image */
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +01001658 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001659 if (!bs) {
1660 return 1;
1661 }
aliguorif7b4a942009-01-07 17:40:15 +00001662
1663 /* Perform the requested action */
1664 switch(action) {
1665 case SNAPSHOT_LIST:
1666 dump_snapshots(bs);
1667 break;
1668
1669 case SNAPSHOT_CREATE:
1670 memset(&sn, 0, sizeof(sn));
1671 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
1672
1673 qemu_gettimeofday(&tv);
1674 sn.date_sec = tv.tv_sec;
1675 sn.date_nsec = tv.tv_usec * 1000;
1676
1677 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001678 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001679 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00001680 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001681 }
aliguorif7b4a942009-01-07 17:40:15 +00001682 break;
1683
1684 case SNAPSHOT_APPLY:
1685 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001686 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001687 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00001688 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001689 }
aliguorif7b4a942009-01-07 17:40:15 +00001690 break;
1691
1692 case SNAPSHOT_DELETE:
1693 ret = bdrv_snapshot_delete(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001694 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001695 error_report("Could not delete snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00001696 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001697 }
aliguorif7b4a942009-01-07 17:40:15 +00001698 break;
1699 }
1700
1701 /* Cleanup */
1702 bdrv_delete(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001703 if (ret) {
1704 return 1;
1705 }
Stuart Brady153859b2009-06-07 00:42:17 +01001706 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00001707}
1708
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001709static int img_rebase(int argc, char **argv)
1710{
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001711 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
Stefan Hajnoczif163d072010-04-13 10:29:34 +01001712 BlockDriver *old_backing_drv, *new_backing_drv;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001713 char *filename;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001714 const char *fmt, *cache, *out_basefmt, *out_baseimg;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001715 int c, flags, ret;
1716 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001717 int progress = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001718
1719 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01001720 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001721 cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001722 out_baseimg = NULL;
1723 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001724 for(;;) {
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001725 c = getopt(argc, argv, "uhf:F:b:pt:");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001726 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001727 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001728 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001729 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001730 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001731 case 'h':
1732 help();
1733 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01001734 case 'f':
1735 fmt = optarg;
1736 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001737 case 'F':
1738 out_basefmt = optarg;
1739 break;
1740 case 'b':
1741 out_baseimg = optarg;
1742 break;
1743 case 'u':
1744 unsafe = 1;
1745 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001746 case 'p':
1747 progress = 1;
1748 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001749 case 't':
1750 cache = optarg;
1751 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001752 }
1753 }
1754
Anthony Liguori9a9d9db2011-04-13 15:51:47 +01001755 if ((optind >= argc) || (!unsafe && !out_baseimg)) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001756 help();
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001757 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001758 filename = argv[optind++];
1759
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001760 qemu_progress_init(progress, 2.0);
1761 qemu_progress_print(0, 100);
1762
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001763 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001764 ret = bdrv_parse_cache_flags(cache, &flags);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001765 if (ret < 0) {
1766 error_report("Invalid cache option: %s", cache);
1767 return -1;
1768 }
1769
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001770 /*
1771 * Open the images.
1772 *
1773 * Ignore the old backing file for unsafe rebase in case we want to correct
1774 * the reference to a renamed or moved backing file.
1775 */
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +01001776 bs = bdrv_new_open(filename, fmt, flags, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001777 if (!bs) {
1778 return 1;
1779 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001780
1781 /* Find the right drivers for the backing files */
1782 old_backing_drv = NULL;
1783 new_backing_drv = NULL;
1784
1785 if (!unsafe && bs->backing_format[0] != '\0') {
1786 old_backing_drv = bdrv_find_format(bs->backing_format);
1787 if (old_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001788 error_report("Invalid format name: '%s'", bs->backing_format);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001789 ret = -1;
1790 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001791 }
1792 }
1793
1794 if (out_basefmt != NULL) {
1795 new_backing_drv = bdrv_find_format(out_basefmt);
1796 if (new_backing_drv == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001797 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001798 ret = -1;
1799 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001800 }
1801 }
1802
1803 /* For safe rebasing we need to compare old and new backing file */
1804 if (unsafe) {
1805 /* Make the compiler happy */
1806 bs_old_backing = NULL;
1807 bs_new_backing = NULL;
1808 } else {
1809 char backing_name[1024];
1810
1811 bs_old_backing = bdrv_new("old_backing");
1812 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001813 ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
1814 old_backing_drv);
1815 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001816 error_report("Could not open old backing file '%s'", backing_name);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001817 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001818 }
Alex Bligha6166732012-10-16 13:46:18 +01001819 if (out_baseimg[0]) {
1820 bs_new_backing = bdrv_new("new_backing");
1821 ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001822 new_backing_drv);
Alex Bligha6166732012-10-16 13:46:18 +01001823 if (ret) {
1824 error_report("Could not open new backing file '%s'",
1825 out_baseimg);
1826 goto out;
1827 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001828 }
1829 }
1830
1831 /*
1832 * Check each unallocated cluster in the COW file. If it is unallocated,
1833 * accesses go to the backing file. We must therefore compare this cluster
1834 * in the old and new backing file, and if they differ we need to copy it
1835 * from the old backing file into the COW file.
1836 *
1837 * If qemu-img crashes during this step, no harm is done. The content of
1838 * the image is the same as the original one at any time.
1839 */
1840 if (!unsafe) {
1841 uint64_t num_sectors;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01001842 uint64_t old_backing_num_sectors;
Alex Bligha6166732012-10-16 13:46:18 +01001843 uint64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001844 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02001845 int n;
TeLeMand6771bf2010-02-08 16:20:00 +08001846 uint8_t * buf_old;
1847 uint8_t * buf_new;
Kevin Wolf1f710492012-10-12 14:29:18 +02001848 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08001849
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001850 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
1851 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001852
1853 bdrv_get_geometry(bs, &num_sectors);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01001854 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
Alex Bligha6166732012-10-16 13:46:18 +01001855 if (bs_new_backing) {
1856 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
1857 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001858
Kevin Wolf1f710492012-10-12 14:29:18 +02001859 if (num_sectors != 0) {
1860 local_progress = (float)100 /
1861 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
1862 }
1863
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001864 for (sector = 0; sector < num_sectors; sector += n) {
1865
1866 /* How many sectors can we handle with the next read? */
1867 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
1868 n = (IO_BUF_SIZE / 512);
1869 } else {
1870 n = num_sectors - sector;
1871 }
1872
1873 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02001874 ret = bdrv_is_allocated(bs, sector, n, &n);
1875 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001876 continue;
1877 }
1878
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01001879 /*
1880 * Read old and new backing file and take into consideration that
1881 * backing files may be smaller than the COW image.
1882 */
1883 if (sector >= old_backing_num_sectors) {
1884 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
1885 } else {
1886 if (sector + n > old_backing_num_sectors) {
1887 n = old_backing_num_sectors - sector;
1888 }
1889
1890 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
1891 if (ret < 0) {
1892 error_report("error while reading from old backing file");
1893 goto out;
1894 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001895 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01001896
Alex Bligha6166732012-10-16 13:46:18 +01001897 if (sector >= new_backing_num_sectors || !bs_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01001898 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
1899 } else {
1900 if (sector + n > new_backing_num_sectors) {
1901 n = new_backing_num_sectors - sector;
1902 }
1903
1904 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
1905 if (ret < 0) {
1906 error_report("error while reading from new backing file");
1907 goto out;
1908 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001909 }
1910
1911 /* If they differ, we need to write to the COW file */
1912 uint64_t written = 0;
1913
1914 while (written < n) {
1915 int pnum;
1916
1917 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01001918 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001919 {
1920 ret = bdrv_write(bs, sector + written,
1921 buf_old + written * 512, pnum);
1922 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001923 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001924 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001925 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001926 }
1927 }
1928
1929 written += pnum;
1930 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001931 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001932 }
TeLeMand6771bf2010-02-08 16:20:00 +08001933
Kevin Wolfbb1c0592011-08-08 14:09:12 +02001934 qemu_vfree(buf_old);
1935 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001936 }
1937
1938 /*
1939 * Change the backing file. All clusters that are different from the old
1940 * backing file are overwritten in the COW file now, so the visible content
1941 * doesn't change when we switch the backing file.
1942 */
Alex Bligha6166732012-10-16 13:46:18 +01001943 if (out_baseimg && *out_baseimg) {
1944 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
1945 } else {
1946 ret = bdrv_change_backing_file(bs, NULL, NULL);
1947 }
1948
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001949 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001950 error_report("Could not change the backing file to '%s': No "
1951 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001952 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001953 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001954 out_baseimg, strerror(-ret));
1955 }
1956
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001957 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001958 /*
1959 * TODO At this point it is possible to check if any clusters that are
1960 * allocated in the COW file are the same in the backing file. If so, they
1961 * could be dropped from the COW file. Don't do this before switching the
1962 * backing file, in case of a crash this would lead to corruption.
1963 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001964out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001965 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001966 /* Cleanup */
1967 if (!unsafe) {
Kevin Wolfeb863ad2011-03-31 12:39:51 +02001968 if (bs_old_backing != NULL) {
1969 bdrv_delete(bs_old_backing);
1970 }
1971 if (bs_new_backing != NULL) {
1972 bdrv_delete(bs_new_backing);
1973 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001974 }
1975
1976 bdrv_delete(bs);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001977 if (ret) {
1978 return 1;
1979 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001980 return 0;
1981}
1982
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01001983static int img_resize(int argc, char **argv)
1984{
1985 int c, ret, relative;
1986 const char *filename, *fmt, *size;
1987 int64_t n, total_size;
Jes Sorensen2a819982010-12-06 17:08:31 +01001988 BlockDriverState *bs = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08001989 QemuOpts *param;
1990 static QemuOptsList resize_options = {
1991 .name = "resize_options",
1992 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
1993 .desc = {
1994 {
1995 .name = BLOCK_OPT_SIZE,
1996 .type = QEMU_OPT_SIZE,
1997 .help = "Virtual disk size"
1998 }, {
1999 /* end of list */
2000 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002001 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002002 };
2003
Kevin Wolfe80fec72011-04-29 10:58:12 +02002004 /* Remove size from argv manually so that negative numbers are not treated
2005 * as options by getopt. */
2006 if (argc < 3) {
2007 help();
2008 return 1;
2009 }
2010
2011 size = argv[--argc];
2012
2013 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002014 fmt = NULL;
2015 for(;;) {
2016 c = getopt(argc, argv, "f:h");
2017 if (c == -1) {
2018 break;
2019 }
2020 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002021 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002022 case 'h':
2023 help();
2024 break;
2025 case 'f':
2026 fmt = optarg;
2027 break;
2028 }
2029 }
Kevin Wolfe80fec72011-04-29 10:58:12 +02002030 if (optind >= argc) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002031 help();
2032 }
2033 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002034
2035 /* Choose grow, shrink, or absolute resize mode */
2036 switch (size[0]) {
2037 case '+':
2038 relative = 1;
2039 size++;
2040 break;
2041 case '-':
2042 relative = -1;
2043 size++;
2044 break;
2045 default:
2046 relative = 0;
2047 break;
2048 }
2049
2050 /* Parse size */
Dong Xu Wange478b442012-12-06 14:47:22 +08002051 param = qemu_opts_create_nofail(&resize_options);
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002052 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002053 /* Error message already printed when size parsing fails */
Jes Sorensen2a819982010-12-06 17:08:31 +01002054 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002055 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01002056 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002057 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08002058 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2059 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002060
Daniel P. Berrangef0536bb2012-09-10 12:11:31 +01002061 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002062 if (!bs) {
Jes Sorensen2a819982010-12-06 17:08:31 +01002063 ret = -1;
2064 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002065 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002066
2067 if (relative) {
2068 total_size = bdrv_getlength(bs) + n * relative;
2069 } else {
2070 total_size = n;
2071 }
2072 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002073 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002074 ret = -1;
2075 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002076 }
2077
2078 ret = bdrv_truncate(bs, total_size);
2079 switch (ret) {
2080 case 0:
2081 printf("Image resized.\n");
2082 break;
2083 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01002084 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002085 break;
2086 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01002087 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002088 break;
2089 default:
Jes Sorensen15654a62010-12-16 14:31:53 +01002090 error_report("Error resizing image (%d)", -ret);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002091 break;
2092 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002093out:
Jes Sorensen2a819982010-12-06 17:08:31 +01002094 if (bs) {
2095 bdrv_delete(bs);
2096 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002097 if (ret) {
2098 return 1;
2099 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01002100 return 0;
2101}
2102
Anthony Liguoric227f092009-10-01 16:12:16 -05002103static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01002104#define DEF(option, callback, arg_string) \
2105 { option, callback },
2106#include "qemu-img-cmds.h"
2107#undef DEF
2108#undef GEN_DOCS
2109 { NULL, NULL, },
2110};
2111
bellardea2384d2004-08-01 21:59:26 +00002112int main(int argc, char **argv)
2113{
Anthony Liguoric227f092009-10-01 16:12:16 -05002114 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01002115 const char *cmdname;
bellardea2384d2004-08-01 21:59:26 +00002116
Kevin Wolf53f76e52010-12-16 15:10:32 +01002117 error_set_progname(argv[0]);
2118
Paolo Bonzini2592c592012-11-03 18:10:17 +01002119 qemu_init_main_loop();
bellardea2384d2004-08-01 21:59:26 +00002120 bdrv_init();
2121 if (argc < 2)
2122 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002123 cmdname = argv[1];
aurel328f9b1572009-02-09 18:14:31 +00002124 argc--; argv++;
Stuart Brady153859b2009-06-07 00:42:17 +01002125
2126 /* find the command */
2127 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2128 if (!strcmp(cmdname, cmd->name)) {
2129 return cmd->handler(argc, argv);
2130 }
bellardea2384d2004-08-01 21:59:26 +00002131 }
Stuart Brady153859b2009-06-07 00:42:17 +01002132
2133 /* not found */
2134 help();
bellardea2384d2004-08-01 21:59:26 +00002135 return 0;
2136}