]> git.proxmox.com Git - qemu.git/blob - qemu-img.c
qemu-img: Add "Quiet mode" option
[qemu.git] / qemu-img.c
1 /*
2 * QEMU disk image utility
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
6 * 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 */
24 #include "qapi-visit.h"
25 #include "qapi/qmp-output-visitor.h"
26 #include "qapi/qmp/qjson.h"
27 #include "qemu-common.h"
28 #include "qemu/option.h"
29 #include "qemu/error-report.h"
30 #include "qemu/osdep.h"
31 #include "sysemu/sysemu.h"
32 #include "block/block_int.h"
33 #include <getopt.h>
34 #include <stdio.h>
35 #include <stdarg.h>
36
37 #ifdef _WIN32
38 #include <windows.h>
39 #endif
40
41 typedef struct img_cmd_t {
42 const char *name;
43 int (*handler)(int argc, char **argv);
44 } img_cmd_t;
45
46 enum {
47 OPTION_OUTPUT = 256,
48 OPTION_BACKING_CHAIN = 257,
49 };
50
51 typedef enum OutputFormat {
52 OFORMAT_JSON,
53 OFORMAT_HUMAN,
54 } OutputFormat;
55
56 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
57 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
58 #define BDRV_DEFAULT_CACHE "writeback"
59
60 static void format_print(void *opaque, const char *name)
61 {
62 printf(" %s", name);
63 }
64
65 /* Please keep in synch with qemu-img.texi */
66 static void help(void)
67 {
68 const char *help_msg =
69 "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
70 "usage: qemu-img command [command options]\n"
71 "QEMU disk image utility\n"
72 "\n"
73 "Command syntax:\n"
74 #define DEF(option, callback, arg_string) \
75 " " arg_string "\n"
76 #include "qemu-img-cmds.h"
77 #undef DEF
78 #undef GEN_DOCS
79 "\n"
80 "Command parameters:\n"
81 " 'filename' is a disk image filename\n"
82 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
83 " 'cache' is the cache mode used to write the output disk image, the valid\n"
84 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
85 " 'directsync' and 'unsafe' (default for convert)\n"
86 " 'size' is the disk image size in bytes. Optional suffixes\n"
87 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
88 " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
89 " 'output_filename' is the destination disk image filename\n"
90 " 'output_fmt' is the destination format\n"
91 " 'options' is a comma separated list of format specific options in a\n"
92 " name=value format. Use -o ? for an overview of the options supported by the\n"
93 " used format\n"
94 " '-c' indicates that target image must be compressed (qcow format only)\n"
95 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
96 " match exactly. The image doesn't need a working backing file before\n"
97 " rebasing in this case (useful for renaming the backing file)\n"
98 " '-h' with or without a command shows this help and lists the supported formats\n"
99 " '-p' show progress of command (only certain commands)\n"
100 " '-q' use Quiet mode - do not print any output (except errors)\n"
101 " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
102 " for qemu-img to create a sparse image during conversion\n"
103 " '--output' takes the format in which the output must be done (human or json)\n"
104 "\n"
105 "Parameters to check subcommand:\n"
106 " '-r' tries to repair any inconsistencies that are found during the check.\n"
107 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
108 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
109 " hiding corruption that has already occurred.\n"
110 "\n"
111 "Parameters to snapshot subcommand:\n"
112 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
113 " '-a' applies a snapshot (revert disk to saved state)\n"
114 " '-c' creates a snapshot\n"
115 " '-d' deletes a snapshot\n"
116 " '-l' lists all snapshots in the given image\n";
117
118 printf("%s\nSupported formats:", help_msg);
119 bdrv_iterate_format(format_print, NULL);
120 printf("\n");
121 exit(1);
122 }
123
124 static int qprintf(bool quiet, const char *fmt, ...)
125 {
126 int ret = 0;
127 if (!quiet) {
128 va_list args;
129 va_start(args, fmt);
130 ret = vprintf(fmt, args);
131 va_end(args);
132 }
133 return ret;
134 }
135
136 #if defined(WIN32)
137 /* XXX: put correct support for win32 */
138 static int read_password(char *buf, int buf_size)
139 {
140 int c, i;
141 printf("Password: ");
142 fflush(stdout);
143 i = 0;
144 for(;;) {
145 c = getchar();
146 if (c == '\n')
147 break;
148 if (i < (buf_size - 1))
149 buf[i++] = c;
150 }
151 buf[i] = '\0';
152 return 0;
153 }
154
155 #else
156
157 #include <termios.h>
158
159 static struct termios oldtty;
160
161 static void term_exit(void)
162 {
163 tcsetattr (0, TCSANOW, &oldtty);
164 }
165
166 static void term_init(void)
167 {
168 struct termios tty;
169
170 tcgetattr (0, &tty);
171 oldtty = tty;
172
173 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
174 |INLCR|IGNCR|ICRNL|IXON);
175 tty.c_oflag |= OPOST;
176 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
177 tty.c_cflag &= ~(CSIZE|PARENB);
178 tty.c_cflag |= CS8;
179 tty.c_cc[VMIN] = 1;
180 tty.c_cc[VTIME] = 0;
181
182 tcsetattr (0, TCSANOW, &tty);
183
184 atexit(term_exit);
185 }
186
187 static int read_password(char *buf, int buf_size)
188 {
189 uint8_t ch;
190 int i, ret;
191
192 printf("password: ");
193 fflush(stdout);
194 term_init();
195 i = 0;
196 for(;;) {
197 ret = read(0, &ch, 1);
198 if (ret == -1) {
199 if (errno == EAGAIN || errno == EINTR) {
200 continue;
201 } else {
202 ret = -1;
203 break;
204 }
205 } else if (ret == 0) {
206 ret = -1;
207 break;
208 } else {
209 if (ch == '\r') {
210 ret = 0;
211 break;
212 }
213 if (i < (buf_size - 1))
214 buf[i++] = ch;
215 }
216 }
217 term_exit();
218 buf[i] = '\0';
219 printf("\n");
220 return ret;
221 }
222 #endif
223
224 static int print_block_option_help(const char *filename, const char *fmt)
225 {
226 BlockDriver *drv, *proto_drv;
227 QEMUOptionParameter *create_options = NULL;
228
229 /* Find driver and parse its options */
230 drv = bdrv_find_format(fmt);
231 if (!drv) {
232 error_report("Unknown file format '%s'", fmt);
233 return 1;
234 }
235
236 proto_drv = bdrv_find_protocol(filename);
237 if (!proto_drv) {
238 error_report("Unknown protocol '%s'", filename);
239 return 1;
240 }
241
242 create_options = append_option_parameters(create_options,
243 drv->create_options);
244 create_options = append_option_parameters(create_options,
245 proto_drv->create_options);
246 print_option_help(create_options);
247 free_option_parameters(create_options);
248 return 0;
249 }
250
251 static BlockDriverState *bdrv_new_open(const char *filename,
252 const char *fmt,
253 int flags,
254 bool require_io,
255 bool quiet)
256 {
257 BlockDriverState *bs;
258 BlockDriver *drv;
259 char password[256];
260 int ret;
261
262 bs = bdrv_new("image");
263
264 if (fmt) {
265 drv = bdrv_find_format(fmt);
266 if (!drv) {
267 error_report("Unknown file format '%s'", fmt);
268 goto fail;
269 }
270 } else {
271 drv = NULL;
272 }
273
274 ret = bdrv_open(bs, filename, flags, drv);
275 if (ret < 0) {
276 error_report("Could not open '%s': %s", filename, strerror(-ret));
277 goto fail;
278 }
279
280 if (bdrv_is_encrypted(bs) && require_io) {
281 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
282 if (read_password(password, sizeof(password)) < 0) {
283 error_report("No password given");
284 goto fail;
285 }
286 if (bdrv_set_key(bs, password) < 0) {
287 error_report("invalid password");
288 goto fail;
289 }
290 }
291 return bs;
292 fail:
293 if (bs) {
294 bdrv_delete(bs);
295 }
296 return NULL;
297 }
298
299 static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
300 const char *base_filename,
301 const char *base_fmt)
302 {
303 if (base_filename) {
304 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
305 error_report("Backing file not supported for file format '%s'",
306 fmt);
307 return -1;
308 }
309 }
310 if (base_fmt) {
311 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
312 error_report("Backing file format not supported for file "
313 "format '%s'", fmt);
314 return -1;
315 }
316 }
317 return 0;
318 }
319
320 static int img_create(int argc, char **argv)
321 {
322 int c;
323 uint64_t img_size = -1;
324 const char *fmt = "raw";
325 const char *base_fmt = NULL;
326 const char *filename;
327 const char *base_filename = NULL;
328 char *options = NULL;
329 Error *local_err = NULL;
330 bool quiet = false;
331
332 for(;;) {
333 c = getopt(argc, argv, "F:b:f:he6o:q");
334 if (c == -1) {
335 break;
336 }
337 switch(c) {
338 case '?':
339 case 'h':
340 help();
341 break;
342 case 'F':
343 base_fmt = optarg;
344 break;
345 case 'b':
346 base_filename = optarg;
347 break;
348 case 'f':
349 fmt = optarg;
350 break;
351 case 'e':
352 error_report("option -e is deprecated, please use \'-o "
353 "encryption\' instead!");
354 return 1;
355 case '6':
356 error_report("option -6 is deprecated, please use \'-o "
357 "compat6\' instead!");
358 return 1;
359 case 'o':
360 options = optarg;
361 break;
362 case 'q':
363 quiet = true;
364 break;
365 }
366 }
367
368 /* Get the filename */
369 if (optind >= argc) {
370 help();
371 }
372 filename = argv[optind++];
373
374 /* Get image size, if specified */
375 if (optind < argc) {
376 int64_t sval;
377 char *end;
378 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
379 if (sval < 0 || *end) {
380 if (sval == -ERANGE) {
381 error_report("Image size must be less than 8 EiB!");
382 } else {
383 error_report("Invalid image size specified! You may use k, M, "
384 "G or T suffixes for ");
385 error_report("kilobytes, megabytes, gigabytes and terabytes.");
386 }
387 return 1;
388 }
389 img_size = (uint64_t)sval;
390 }
391
392 if (options && is_help_option(options)) {
393 return print_block_option_help(filename, fmt);
394 }
395
396 bdrv_img_create(filename, fmt, base_filename, base_fmt,
397 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
398 if (error_is_set(&local_err)) {
399 error_report("%s", error_get_pretty(local_err));
400 error_free(local_err);
401 return 1;
402 }
403
404 return 0;
405 }
406
407 static void dump_json_image_check(ImageCheck *check, bool quiet)
408 {
409 Error *errp = NULL;
410 QString *str;
411 QmpOutputVisitor *ov = qmp_output_visitor_new();
412 QObject *obj;
413 visit_type_ImageCheck(qmp_output_get_visitor(ov),
414 &check, NULL, &errp);
415 obj = qmp_output_get_qobject(ov);
416 str = qobject_to_json_pretty(obj);
417 assert(str != NULL);
418 qprintf(quiet, "%s\n", qstring_get_str(str));
419 qobject_decref(obj);
420 qmp_output_visitor_cleanup(ov);
421 QDECREF(str);
422 }
423
424 static void dump_human_image_check(ImageCheck *check, bool quiet)
425 {
426 if (!(check->corruptions || check->leaks || check->check_errors)) {
427 qprintf(quiet, "No errors were found on the image.\n");
428 } else {
429 if (check->corruptions) {
430 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
431 "Data may be corrupted, or further writes to the image "
432 "may corrupt it.\n",
433 check->corruptions);
434 }
435
436 if (check->leaks) {
437 qprintf(quiet,
438 "\n%" PRId64 " leaked clusters were found on the image.\n"
439 "This means waste of disk space, but no harm to data.\n",
440 check->leaks);
441 }
442
443 if (check->check_errors) {
444 qprintf(quiet,
445 "\n%" PRId64
446 " internal errors have occurred during the check.\n",
447 check->check_errors);
448 }
449 }
450
451 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
452 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
453 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
454 check->allocated_clusters, check->total_clusters,
455 check->allocated_clusters * 100.0 / check->total_clusters,
456 check->fragmented_clusters * 100.0 / check->allocated_clusters,
457 check->compressed_clusters * 100.0 /
458 check->allocated_clusters);
459 }
460
461 if (check->image_end_offset) {
462 qprintf(quiet,
463 "Image end offset: %" PRId64 "\n", check->image_end_offset);
464 }
465 }
466
467 static int collect_image_check(BlockDriverState *bs,
468 ImageCheck *check,
469 const char *filename,
470 const char *fmt,
471 int fix)
472 {
473 int ret;
474 BdrvCheckResult result;
475
476 ret = bdrv_check(bs, &result, fix);
477 if (ret < 0) {
478 return ret;
479 }
480
481 check->filename = g_strdup(filename);
482 check->format = g_strdup(bdrv_get_format_name(bs));
483 check->check_errors = result.check_errors;
484 check->corruptions = result.corruptions;
485 check->has_corruptions = result.corruptions != 0;
486 check->leaks = result.leaks;
487 check->has_leaks = result.leaks != 0;
488 check->corruptions_fixed = result.corruptions_fixed;
489 check->has_corruptions_fixed = result.corruptions != 0;
490 check->leaks_fixed = result.leaks_fixed;
491 check->has_leaks_fixed = result.leaks != 0;
492 check->image_end_offset = result.image_end_offset;
493 check->has_image_end_offset = result.image_end_offset != 0;
494 check->total_clusters = result.bfi.total_clusters;
495 check->has_total_clusters = result.bfi.total_clusters != 0;
496 check->allocated_clusters = result.bfi.allocated_clusters;
497 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
498 check->fragmented_clusters = result.bfi.fragmented_clusters;
499 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
500 check->compressed_clusters = result.bfi.compressed_clusters;
501 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
502
503 return 0;
504 }
505
506 /*
507 * Checks an image for consistency. Exit codes:
508 *
509 * 0 - Check completed, image is good
510 * 1 - Check not completed because of internal errors
511 * 2 - Check completed, image is corrupted
512 * 3 - Check completed, image has leaked clusters, but is good otherwise
513 */
514 static int img_check(int argc, char **argv)
515 {
516 int c, ret;
517 OutputFormat output_format = OFORMAT_HUMAN;
518 const char *filename, *fmt, *output;
519 BlockDriverState *bs;
520 int fix = 0;
521 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
522 ImageCheck *check;
523 bool quiet = false;
524
525 fmt = NULL;
526 output = NULL;
527 for(;;) {
528 int option_index = 0;
529 static const struct option long_options[] = {
530 {"help", no_argument, 0, 'h'},
531 {"format", required_argument, 0, 'f'},
532 {"repair", no_argument, 0, 'r'},
533 {"output", required_argument, 0, OPTION_OUTPUT},
534 {0, 0, 0, 0}
535 };
536 c = getopt_long(argc, argv, "f:hr:q",
537 long_options, &option_index);
538 if (c == -1) {
539 break;
540 }
541 switch(c) {
542 case '?':
543 case 'h':
544 help();
545 break;
546 case 'f':
547 fmt = optarg;
548 break;
549 case 'r':
550 flags |= BDRV_O_RDWR;
551
552 if (!strcmp(optarg, "leaks")) {
553 fix = BDRV_FIX_LEAKS;
554 } else if (!strcmp(optarg, "all")) {
555 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
556 } else {
557 help();
558 }
559 break;
560 case OPTION_OUTPUT:
561 output = optarg;
562 break;
563 case 'q':
564 quiet = true;
565 break;
566 }
567 }
568 if (optind >= argc) {
569 help();
570 }
571 filename = argv[optind++];
572
573 if (output && !strcmp(output, "json")) {
574 output_format = OFORMAT_JSON;
575 } else if (output && !strcmp(output, "human")) {
576 output_format = OFORMAT_HUMAN;
577 } else if (output) {
578 error_report("--output must be used with human or json as argument.");
579 return 1;
580 }
581
582 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
583 if (!bs) {
584 return 1;
585 }
586
587 check = g_new0(ImageCheck, 1);
588 ret = collect_image_check(bs, check, filename, fmt, fix);
589
590 if (ret == -ENOTSUP) {
591 if (output_format == OFORMAT_HUMAN) {
592 error_report("This image format does not support checks");
593 }
594 ret = 1;
595 goto fail;
596 }
597
598 if (check->corruptions_fixed || check->leaks_fixed) {
599 int corruptions_fixed, leaks_fixed;
600
601 leaks_fixed = check->leaks_fixed;
602 corruptions_fixed = check->corruptions_fixed;
603
604 if (output_format == OFORMAT_HUMAN) {
605 qprintf(quiet,
606 "The following inconsistencies were found and repaired:\n\n"
607 " %" PRId64 " leaked clusters\n"
608 " %" PRId64 " corruptions\n\n"
609 "Double checking the fixed image now...\n",
610 check->leaks_fixed,
611 check->corruptions_fixed);
612 }
613
614 ret = collect_image_check(bs, check, filename, fmt, 0);
615
616 check->leaks_fixed = leaks_fixed;
617 check->corruptions_fixed = corruptions_fixed;
618 }
619
620 switch (output_format) {
621 case OFORMAT_HUMAN:
622 dump_human_image_check(check, quiet);
623 break;
624 case OFORMAT_JSON:
625 dump_json_image_check(check, quiet);
626 break;
627 }
628
629 if (ret || check->check_errors) {
630 ret = 1;
631 goto fail;
632 }
633
634 if (check->corruptions) {
635 ret = 2;
636 } else if (check->leaks) {
637 ret = 3;
638 } else {
639 ret = 0;
640 }
641
642 fail:
643 qapi_free_ImageCheck(check);
644 bdrv_delete(bs);
645
646 return ret;
647 }
648
649 static int img_commit(int argc, char **argv)
650 {
651 int c, ret, flags;
652 const char *filename, *fmt, *cache;
653 BlockDriverState *bs;
654 bool quiet = false;
655
656 fmt = NULL;
657 cache = BDRV_DEFAULT_CACHE;
658 for(;;) {
659 c = getopt(argc, argv, "f:ht:q");
660 if (c == -1) {
661 break;
662 }
663 switch(c) {
664 case '?':
665 case 'h':
666 help();
667 break;
668 case 'f':
669 fmt = optarg;
670 break;
671 case 't':
672 cache = optarg;
673 break;
674 case 'q':
675 quiet = true;
676 break;
677 }
678 }
679 if (optind >= argc) {
680 help();
681 }
682 filename = argv[optind++];
683
684 flags = BDRV_O_RDWR;
685 ret = bdrv_parse_cache_flags(cache, &flags);
686 if (ret < 0) {
687 error_report("Invalid cache option: %s", cache);
688 return -1;
689 }
690
691 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
692 if (!bs) {
693 return 1;
694 }
695 ret = bdrv_commit(bs);
696 switch(ret) {
697 case 0:
698 qprintf(quiet, "Image committed.\n");
699 break;
700 case -ENOENT:
701 error_report("No disk inserted");
702 break;
703 case -EACCES:
704 error_report("Image is read-only");
705 break;
706 case -ENOTSUP:
707 error_report("Image is already committed");
708 break;
709 default:
710 error_report("Error while committing image");
711 break;
712 }
713
714 bdrv_delete(bs);
715 if (ret) {
716 return 1;
717 }
718 return 0;
719 }
720
721 /*
722 * Returns true iff the first sector pointed to by 'buf' contains at least
723 * a non-NUL byte.
724 *
725 * 'pnum' is set to the number of sectors (including and immediately following
726 * the first one) that are known to be in the same allocated/unallocated state.
727 */
728 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
729 {
730 bool is_zero;
731 int i;
732
733 if (n <= 0) {
734 *pnum = 0;
735 return 0;
736 }
737 is_zero = buffer_is_zero(buf, 512);
738 for(i = 1; i < n; i++) {
739 buf += 512;
740 if (is_zero != buffer_is_zero(buf, 512)) {
741 break;
742 }
743 }
744 *pnum = i;
745 return !is_zero;
746 }
747
748 /*
749 * Like is_allocated_sectors, but if the buffer starts with a used sector,
750 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
751 * breaking up write requests for only small sparse areas.
752 */
753 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
754 int min)
755 {
756 int ret;
757 int num_checked, num_used;
758
759 if (n < min) {
760 min = n;
761 }
762
763 ret = is_allocated_sectors(buf, n, pnum);
764 if (!ret) {
765 return ret;
766 }
767
768 num_used = *pnum;
769 buf += BDRV_SECTOR_SIZE * *pnum;
770 n -= *pnum;
771 num_checked = num_used;
772
773 while (n > 0) {
774 ret = is_allocated_sectors(buf, n, pnum);
775
776 buf += BDRV_SECTOR_SIZE * *pnum;
777 n -= *pnum;
778 num_checked += *pnum;
779 if (ret) {
780 num_used = num_checked;
781 } else if (*pnum >= min) {
782 break;
783 }
784 }
785
786 *pnum = num_used;
787 return 1;
788 }
789
790 /*
791 * Compares two buffers sector by sector. Returns 0 if the first sector of both
792 * buffers matches, non-zero otherwise.
793 *
794 * pnum is set to the number of sectors (including and immediately following
795 * the first one) that are known to have the same comparison result
796 */
797 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
798 int *pnum)
799 {
800 int res, i;
801
802 if (n <= 0) {
803 *pnum = 0;
804 return 0;
805 }
806
807 res = !!memcmp(buf1, buf2, 512);
808 for(i = 1; i < n; i++) {
809 buf1 += 512;
810 buf2 += 512;
811
812 if (!!memcmp(buf1, buf2, 512) != res) {
813 break;
814 }
815 }
816
817 *pnum = i;
818 return res;
819 }
820
821 #define IO_BUF_SIZE (2 * 1024 * 1024)
822
823 static int img_convert(int argc, char **argv)
824 {
825 int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
826 int progress = 0, flags;
827 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
828 BlockDriver *drv, *proto_drv;
829 BlockDriverState **bs = NULL, *out_bs = NULL;
830 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
831 uint64_t bs_sectors;
832 uint8_t * buf = NULL;
833 const uint8_t *buf1;
834 BlockDriverInfo bdi;
835 QEMUOptionParameter *param = NULL, *create_options = NULL;
836 QEMUOptionParameter *out_baseimg_param;
837 char *options = NULL;
838 const char *snapshot_name = NULL;
839 float local_progress = 0;
840 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
841 bool quiet = false;
842
843 fmt = NULL;
844 out_fmt = "raw";
845 cache = "unsafe";
846 out_baseimg = NULL;
847 compress = 0;
848 for(;;) {
849 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:q");
850 if (c == -1) {
851 break;
852 }
853 switch(c) {
854 case '?':
855 case 'h':
856 help();
857 break;
858 case 'f':
859 fmt = optarg;
860 break;
861 case 'O':
862 out_fmt = optarg;
863 break;
864 case 'B':
865 out_baseimg = optarg;
866 break;
867 case 'c':
868 compress = 1;
869 break;
870 case 'e':
871 error_report("option -e is deprecated, please use \'-o "
872 "encryption\' instead!");
873 return 1;
874 case '6':
875 error_report("option -6 is deprecated, please use \'-o "
876 "compat6\' instead!");
877 return 1;
878 case 'o':
879 options = optarg;
880 break;
881 case 's':
882 snapshot_name = optarg;
883 break;
884 case 'S':
885 {
886 int64_t sval;
887 char *end;
888 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
889 if (sval < 0 || *end) {
890 error_report("Invalid minimum zero buffer size for sparse output specified");
891 return 1;
892 }
893
894 min_sparse = sval / BDRV_SECTOR_SIZE;
895 break;
896 }
897 case 'p':
898 progress = 1;
899 break;
900 case 't':
901 cache = optarg;
902 break;
903 case 'q':
904 quiet = true;
905 break;
906 }
907 }
908
909 if (quiet) {
910 progress = 0;
911 }
912
913 bs_n = argc - optind - 1;
914 if (bs_n < 1) {
915 help();
916 }
917
918 out_filename = argv[argc - 1];
919
920 /* Initialize before goto out */
921 qemu_progress_init(progress, 2.0);
922
923 if (options && is_help_option(options)) {
924 ret = print_block_option_help(out_filename, out_fmt);
925 goto out;
926 }
927
928 if (bs_n > 1 && out_baseimg) {
929 error_report("-B makes no sense when concatenating multiple input "
930 "images");
931 ret = -1;
932 goto out;
933 }
934
935 qemu_progress_print(0, 100);
936
937 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
938
939 total_sectors = 0;
940 for (bs_i = 0; bs_i < bs_n; bs_i++) {
941 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
942 quiet);
943 if (!bs[bs_i]) {
944 error_report("Could not open '%s'", argv[optind + bs_i]);
945 ret = -1;
946 goto out;
947 }
948 bdrv_get_geometry(bs[bs_i], &bs_sectors);
949 total_sectors += bs_sectors;
950 }
951
952 if (snapshot_name != NULL) {
953 if (bs_n > 1) {
954 error_report("No support for concatenating multiple snapshot");
955 ret = -1;
956 goto out;
957 }
958 if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
959 error_report("Failed to load snapshot");
960 ret = -1;
961 goto out;
962 }
963 }
964
965 /* Find driver and parse its options */
966 drv = bdrv_find_format(out_fmt);
967 if (!drv) {
968 error_report("Unknown file format '%s'", out_fmt);
969 ret = -1;
970 goto out;
971 }
972
973 proto_drv = bdrv_find_protocol(out_filename);
974 if (!proto_drv) {
975 error_report("Unknown protocol '%s'", out_filename);
976 ret = -1;
977 goto out;
978 }
979
980 create_options = append_option_parameters(create_options,
981 drv->create_options);
982 create_options = append_option_parameters(create_options,
983 proto_drv->create_options);
984
985 if (options) {
986 param = parse_option_parameters(options, create_options, param);
987 if (param == NULL) {
988 error_report("Invalid options for file format '%s'.", out_fmt);
989 ret = -1;
990 goto out;
991 }
992 } else {
993 param = parse_option_parameters("", create_options, param);
994 }
995
996 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
997 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
998 if (ret < 0) {
999 goto out;
1000 }
1001
1002 /* Get backing file name if -o backing_file was used */
1003 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
1004 if (out_baseimg_param) {
1005 out_baseimg = out_baseimg_param->value.s;
1006 }
1007
1008 /* Check if compression is supported */
1009 if (compress) {
1010 QEMUOptionParameter *encryption =
1011 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
1012 QEMUOptionParameter *preallocation =
1013 get_option_parameter(param, BLOCK_OPT_PREALLOC);
1014
1015 if (!drv->bdrv_write_compressed) {
1016 error_report("Compression not supported for this file format");
1017 ret = -1;
1018 goto out;
1019 }
1020
1021 if (encryption && encryption->value.n) {
1022 error_report("Compression and encryption not supported at "
1023 "the same time");
1024 ret = -1;
1025 goto out;
1026 }
1027
1028 if (preallocation && preallocation->value.s
1029 && strcmp(preallocation->value.s, "off"))
1030 {
1031 error_report("Compression and preallocation not supported at "
1032 "the same time");
1033 ret = -1;
1034 goto out;
1035 }
1036 }
1037
1038 /* Create the new image */
1039 ret = bdrv_create(drv, out_filename, param);
1040 if (ret < 0) {
1041 if (ret == -ENOTSUP) {
1042 error_report("Formatting not supported for file format '%s'",
1043 out_fmt);
1044 } else if (ret == -EFBIG) {
1045 error_report("The image size is too large for file format '%s'",
1046 out_fmt);
1047 } else {
1048 error_report("%s: error while converting %s: %s",
1049 out_filename, out_fmt, strerror(-ret));
1050 }
1051 goto out;
1052 }
1053
1054 flags = BDRV_O_RDWR;
1055 ret = bdrv_parse_cache_flags(cache, &flags);
1056 if (ret < 0) {
1057 error_report("Invalid cache option: %s", cache);
1058 return -1;
1059 }
1060
1061 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
1062 if (!out_bs) {
1063 ret = -1;
1064 goto out;
1065 }
1066
1067 bs_i = 0;
1068 bs_offset = 0;
1069 bdrv_get_geometry(bs[0], &bs_sectors);
1070 buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
1071
1072 if (compress) {
1073 ret = bdrv_get_info(out_bs, &bdi);
1074 if (ret < 0) {
1075 error_report("could not get block driver info");
1076 goto out;
1077 }
1078 cluster_size = bdi.cluster_size;
1079 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
1080 error_report("invalid cluster size");
1081 ret = -1;
1082 goto out;
1083 }
1084 cluster_sectors = cluster_size >> 9;
1085 sector_num = 0;
1086
1087 nb_sectors = total_sectors;
1088 if (nb_sectors != 0) {
1089 local_progress = (float)100 /
1090 (nb_sectors / MIN(nb_sectors, cluster_sectors));
1091 }
1092
1093 for(;;) {
1094 int64_t bs_num;
1095 int remainder;
1096 uint8_t *buf2;
1097
1098 nb_sectors = total_sectors - sector_num;
1099 if (nb_sectors <= 0)
1100 break;
1101 if (nb_sectors >= cluster_sectors)
1102 n = cluster_sectors;
1103 else
1104 n = nb_sectors;
1105
1106 bs_num = sector_num - bs_offset;
1107 assert (bs_num >= 0);
1108 remainder = n;
1109 buf2 = buf;
1110 while (remainder > 0) {
1111 int nlow;
1112 while (bs_num == bs_sectors) {
1113 bs_i++;
1114 assert (bs_i < bs_n);
1115 bs_offset += bs_sectors;
1116 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1117 bs_num = 0;
1118 /* printf("changing part: sector_num=%" PRId64 ", "
1119 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1120 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1121 }
1122 assert (bs_num < bs_sectors);
1123
1124 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1125
1126 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1127 if (ret < 0) {
1128 error_report("error while reading sector %" PRId64 ": %s",
1129 bs_num, strerror(-ret));
1130 goto out;
1131 }
1132
1133 buf2 += nlow * 512;
1134 bs_num += nlow;
1135
1136 remainder -= nlow;
1137 }
1138 assert (remainder == 0);
1139
1140 if (n < cluster_sectors) {
1141 memset(buf + n * 512, 0, cluster_size - n * 512);
1142 }
1143 if (!buffer_is_zero(buf, cluster_size)) {
1144 ret = bdrv_write_compressed(out_bs, sector_num, buf,
1145 cluster_sectors);
1146 if (ret != 0) {
1147 error_report("error while compressing sector %" PRId64
1148 ": %s", sector_num, strerror(-ret));
1149 goto out;
1150 }
1151 }
1152 sector_num += n;
1153 qemu_progress_print(local_progress, 100);
1154 }
1155 /* signal EOF to align */
1156 bdrv_write_compressed(out_bs, 0, NULL, 0);
1157 } else {
1158 int has_zero_init = bdrv_has_zero_init(out_bs);
1159
1160 sector_num = 0; // total number of sectors converted so far
1161 nb_sectors = total_sectors - sector_num;
1162 if (nb_sectors != 0) {
1163 local_progress = (float)100 /
1164 (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
1165 }
1166
1167 for(;;) {
1168 nb_sectors = total_sectors - sector_num;
1169 if (nb_sectors <= 0) {
1170 break;
1171 }
1172 if (nb_sectors >= (IO_BUF_SIZE / 512)) {
1173 n = (IO_BUF_SIZE / 512);
1174 } else {
1175 n = nb_sectors;
1176 }
1177
1178 while (sector_num - bs_offset >= bs_sectors) {
1179 bs_i ++;
1180 assert (bs_i < bs_n);
1181 bs_offset += bs_sectors;
1182 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1183 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1184 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1185 sector_num, bs_i, bs_offset, bs_sectors); */
1186 }
1187
1188 if (n > bs_offset + bs_sectors - sector_num) {
1189 n = bs_offset + bs_sectors - sector_num;
1190 }
1191
1192 if (has_zero_init) {
1193 /* If the output image is being created as a copy on write image,
1194 assume that sectors which are unallocated in the input image
1195 are present in both the output's and input's base images (no
1196 need to copy them). */
1197 if (out_baseimg) {
1198 if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
1199 n, &n1)) {
1200 sector_num += n1;
1201 continue;
1202 }
1203 /* The next 'n1' sectors are allocated in the input image. Copy
1204 only those as they may be followed by unallocated sectors. */
1205 n = n1;
1206 }
1207 } else {
1208 n1 = n;
1209 }
1210
1211 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1212 if (ret < 0) {
1213 error_report("error while reading sector %" PRId64 ": %s",
1214 sector_num - bs_offset, strerror(-ret));
1215 goto out;
1216 }
1217 /* NOTE: at the same time we convert, we do not write zero
1218 sectors to have a chance to compress the image. Ideally, we
1219 should add a specific call to have the info to go faster */
1220 buf1 = buf;
1221 while (n > 0) {
1222 /* If the output image is being created as a copy on write image,
1223 copy all sectors even the ones containing only NUL bytes,
1224 because they may differ from the sectors in the base image.
1225
1226 If the output is to a host device, we also write out
1227 sectors that are entirely 0, since whatever data was
1228 already there is garbage, not 0s. */
1229 if (!has_zero_init || out_baseimg ||
1230 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
1231 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1232 if (ret < 0) {
1233 error_report("error while writing sector %" PRId64
1234 ": %s", sector_num, strerror(-ret));
1235 goto out;
1236 }
1237 }
1238 sector_num += n1;
1239 n -= n1;
1240 buf1 += n1 * 512;
1241 }
1242 qemu_progress_print(local_progress, 100);
1243 }
1244 }
1245 out:
1246 qemu_progress_end();
1247 free_option_parameters(create_options);
1248 free_option_parameters(param);
1249 qemu_vfree(buf);
1250 if (out_bs) {
1251 bdrv_delete(out_bs);
1252 }
1253 if (bs) {
1254 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1255 if (bs[bs_i]) {
1256 bdrv_delete(bs[bs_i]);
1257 }
1258 }
1259 g_free(bs);
1260 }
1261 if (ret) {
1262 return 1;
1263 }
1264 return 0;
1265 }
1266
1267
1268 static void dump_snapshots(BlockDriverState *bs)
1269 {
1270 QEMUSnapshotInfo *sn_tab, *sn;
1271 int nb_sns, i;
1272 char buf[256];
1273
1274 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1275 if (nb_sns <= 0)
1276 return;
1277 printf("Snapshot list:\n");
1278 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1279 for(i = 0; i < nb_sns; i++) {
1280 sn = &sn_tab[i];
1281 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
1282 }
1283 g_free(sn_tab);
1284 }
1285
1286 static void dump_json_image_info_list(ImageInfoList *list)
1287 {
1288 Error *errp = NULL;
1289 QString *str;
1290 QmpOutputVisitor *ov = qmp_output_visitor_new();
1291 QObject *obj;
1292 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1293 &list, NULL, &errp);
1294 obj = qmp_output_get_qobject(ov);
1295 str = qobject_to_json_pretty(obj);
1296 assert(str != NULL);
1297 printf("%s\n", qstring_get_str(str));
1298 qobject_decref(obj);
1299 qmp_output_visitor_cleanup(ov);
1300 QDECREF(str);
1301 }
1302
1303 static void collect_snapshots(BlockDriverState *bs , ImageInfo *info)
1304 {
1305 int i, sn_count;
1306 QEMUSnapshotInfo *sn_tab = NULL;
1307 SnapshotInfoList *info_list, *cur_item = NULL;
1308 sn_count = bdrv_snapshot_list(bs, &sn_tab);
1309
1310 for (i = 0; i < sn_count; i++) {
1311 info->has_snapshots = true;
1312 info_list = g_new0(SnapshotInfoList, 1);
1313
1314 info_list->value = g_new0(SnapshotInfo, 1);
1315 info_list->value->id = g_strdup(sn_tab[i].id_str);
1316 info_list->value->name = g_strdup(sn_tab[i].name);
1317 info_list->value->vm_state_size = sn_tab[i].vm_state_size;
1318 info_list->value->date_sec = sn_tab[i].date_sec;
1319 info_list->value->date_nsec = sn_tab[i].date_nsec;
1320 info_list->value->vm_clock_sec = sn_tab[i].vm_clock_nsec / 1000000000;
1321 info_list->value->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
1322
1323 /* XXX: waiting for the qapi to support qemu-queue.h types */
1324 if (!cur_item) {
1325 info->snapshots = cur_item = info_list;
1326 } else {
1327 cur_item->next = info_list;
1328 cur_item = info_list;
1329 }
1330
1331 }
1332
1333 g_free(sn_tab);
1334 }
1335
1336 static void dump_json_image_info(ImageInfo *info)
1337 {
1338 Error *errp = NULL;
1339 QString *str;
1340 QmpOutputVisitor *ov = qmp_output_visitor_new();
1341 QObject *obj;
1342 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1343 &info, NULL, &errp);
1344 obj = qmp_output_get_qobject(ov);
1345 str = qobject_to_json_pretty(obj);
1346 assert(str != NULL);
1347 printf("%s\n", qstring_get_str(str));
1348 qobject_decref(obj);
1349 qmp_output_visitor_cleanup(ov);
1350 QDECREF(str);
1351 }
1352
1353 static void collect_image_info(BlockDriverState *bs,
1354 ImageInfo *info,
1355 const char *filename,
1356 const char *fmt)
1357 {
1358 uint64_t total_sectors;
1359 char backing_filename[1024];
1360 char backing_filename2[1024];
1361 BlockDriverInfo bdi;
1362
1363 bdrv_get_geometry(bs, &total_sectors);
1364
1365 info->filename = g_strdup(filename);
1366 info->format = g_strdup(bdrv_get_format_name(bs));
1367 info->virtual_size = total_sectors * 512;
1368 info->actual_size = bdrv_get_allocated_file_size(bs);
1369 info->has_actual_size = info->actual_size >= 0;
1370 if (bdrv_is_encrypted(bs)) {
1371 info->encrypted = true;
1372 info->has_encrypted = true;
1373 }
1374 if (bdrv_get_info(bs, &bdi) >= 0) {
1375 if (bdi.cluster_size != 0) {
1376 info->cluster_size = bdi.cluster_size;
1377 info->has_cluster_size = true;
1378 }
1379 info->dirty_flag = bdi.is_dirty;
1380 info->has_dirty_flag = true;
1381 }
1382 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
1383 if (backing_filename[0] != '\0') {
1384 info->backing_filename = g_strdup(backing_filename);
1385 info->has_backing_filename = true;
1386 bdrv_get_full_backing_filename(bs, backing_filename2,
1387 sizeof(backing_filename2));
1388
1389 if (strcmp(backing_filename, backing_filename2) != 0) {
1390 info->full_backing_filename =
1391 g_strdup(backing_filename2);
1392 info->has_full_backing_filename = true;
1393 }
1394
1395 if (bs->backing_format[0]) {
1396 info->backing_filename_format = g_strdup(bs->backing_format);
1397 info->has_backing_filename_format = true;
1398 }
1399 }
1400 }
1401
1402 static void dump_human_image_info(ImageInfo *info)
1403 {
1404 char size_buf[128], dsize_buf[128];
1405 if (!info->has_actual_size) {
1406 snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
1407 } else {
1408 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
1409 info->actual_size);
1410 }
1411 get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
1412 printf("image: %s\n"
1413 "file format: %s\n"
1414 "virtual size: %s (%" PRId64 " bytes)\n"
1415 "disk size: %s\n",
1416 info->filename, info->format, size_buf,
1417 info->virtual_size,
1418 dsize_buf);
1419
1420 if (info->has_encrypted && info->encrypted) {
1421 printf("encrypted: yes\n");
1422 }
1423
1424 if (info->has_cluster_size) {
1425 printf("cluster_size: %" PRId64 "\n", info->cluster_size);
1426 }
1427
1428 if (info->has_dirty_flag && info->dirty_flag) {
1429 printf("cleanly shut down: no\n");
1430 }
1431
1432 if (info->has_backing_filename) {
1433 printf("backing file: %s", info->backing_filename);
1434 if (info->has_full_backing_filename) {
1435 printf(" (actual path: %s)", info->full_backing_filename);
1436 }
1437 putchar('\n');
1438 if (info->has_backing_filename_format) {
1439 printf("backing file format: %s\n", info->backing_filename_format);
1440 }
1441 }
1442
1443 if (info->has_snapshots) {
1444 SnapshotInfoList *elem;
1445 char buf[256];
1446
1447 printf("Snapshot list:\n");
1448 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1449
1450 /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
1451 * we convert to the block layer's native QEMUSnapshotInfo for now.
1452 */
1453 for (elem = info->snapshots; elem; elem = elem->next) {
1454 QEMUSnapshotInfo sn = {
1455 .vm_state_size = elem->value->vm_state_size,
1456 .date_sec = elem->value->date_sec,
1457 .date_nsec = elem->value->date_nsec,
1458 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
1459 elem->value->vm_clock_nsec,
1460 };
1461
1462 pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
1463 pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
1464 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), &sn));
1465 }
1466 }
1467 }
1468
1469 static void dump_human_image_info_list(ImageInfoList *list)
1470 {
1471 ImageInfoList *elem;
1472 bool delim = false;
1473
1474 for (elem = list; elem; elem = elem->next) {
1475 if (delim) {
1476 printf("\n");
1477 }
1478 delim = true;
1479
1480 dump_human_image_info(elem->value);
1481 }
1482 }
1483
1484 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1485 {
1486 return strcmp(a, b) == 0;
1487 }
1488
1489 /**
1490 * Open an image file chain and return an ImageInfoList
1491 *
1492 * @filename: topmost image filename
1493 * @fmt: topmost image format (may be NULL to autodetect)
1494 * @chain: true - enumerate entire backing file chain
1495 * false - only topmost image file
1496 *
1497 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1498 * image file. If there was an error a message will have been printed to
1499 * stderr.
1500 */
1501 static ImageInfoList *collect_image_info_list(const char *filename,
1502 const char *fmt,
1503 bool chain)
1504 {
1505 ImageInfoList *head = NULL;
1506 ImageInfoList **last = &head;
1507 GHashTable *filenames;
1508
1509 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1510
1511 while (filename) {
1512 BlockDriverState *bs;
1513 ImageInfo *info;
1514 ImageInfoList *elem;
1515
1516 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1517 error_report("Backing file '%s' creates an infinite loop.",
1518 filename);
1519 goto err;
1520 }
1521 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1522
1523 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
1524 false, false);
1525 if (!bs) {
1526 goto err;
1527 }
1528
1529 info = g_new0(ImageInfo, 1);
1530 collect_image_info(bs, info, filename, fmt);
1531 collect_snapshots(bs, info);
1532
1533 elem = g_new0(ImageInfoList, 1);
1534 elem->value = info;
1535 *last = elem;
1536 last = &elem->next;
1537
1538 bdrv_delete(bs);
1539
1540 filename = fmt = NULL;
1541 if (chain) {
1542 if (info->has_full_backing_filename) {
1543 filename = info->full_backing_filename;
1544 } else if (info->has_backing_filename) {
1545 filename = info->backing_filename;
1546 }
1547 if (info->has_backing_filename_format) {
1548 fmt = info->backing_filename_format;
1549 }
1550 }
1551 }
1552 g_hash_table_destroy(filenames);
1553 return head;
1554
1555 err:
1556 qapi_free_ImageInfoList(head);
1557 g_hash_table_destroy(filenames);
1558 return NULL;
1559 }
1560
1561 static int img_info(int argc, char **argv)
1562 {
1563 int c;
1564 OutputFormat output_format = OFORMAT_HUMAN;
1565 bool chain = false;
1566 const char *filename, *fmt, *output;
1567 ImageInfoList *list;
1568
1569 fmt = NULL;
1570 output = NULL;
1571 for(;;) {
1572 int option_index = 0;
1573 static const struct option long_options[] = {
1574 {"help", no_argument, 0, 'h'},
1575 {"format", required_argument, 0, 'f'},
1576 {"output", required_argument, 0, OPTION_OUTPUT},
1577 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
1578 {0, 0, 0, 0}
1579 };
1580 c = getopt_long(argc, argv, "f:h",
1581 long_options, &option_index);
1582 if (c == -1) {
1583 break;
1584 }
1585 switch(c) {
1586 case '?':
1587 case 'h':
1588 help();
1589 break;
1590 case 'f':
1591 fmt = optarg;
1592 break;
1593 case OPTION_OUTPUT:
1594 output = optarg;
1595 break;
1596 case OPTION_BACKING_CHAIN:
1597 chain = true;
1598 break;
1599 }
1600 }
1601 if (optind >= argc) {
1602 help();
1603 }
1604 filename = argv[optind++];
1605
1606 if (output && !strcmp(output, "json")) {
1607 output_format = OFORMAT_JSON;
1608 } else if (output && !strcmp(output, "human")) {
1609 output_format = OFORMAT_HUMAN;
1610 } else if (output) {
1611 error_report("--output must be used with human or json as argument.");
1612 return 1;
1613 }
1614
1615 list = collect_image_info_list(filename, fmt, chain);
1616 if (!list) {
1617 return 1;
1618 }
1619
1620 switch (output_format) {
1621 case OFORMAT_HUMAN:
1622 dump_human_image_info_list(list);
1623 break;
1624 case OFORMAT_JSON:
1625 if (chain) {
1626 dump_json_image_info_list(list);
1627 } else {
1628 dump_json_image_info(list->value);
1629 }
1630 break;
1631 }
1632
1633 qapi_free_ImageInfoList(list);
1634 return 0;
1635 }
1636
1637 #define SNAPSHOT_LIST 1
1638 #define SNAPSHOT_CREATE 2
1639 #define SNAPSHOT_APPLY 3
1640 #define SNAPSHOT_DELETE 4
1641
1642 static int img_snapshot(int argc, char **argv)
1643 {
1644 BlockDriverState *bs;
1645 QEMUSnapshotInfo sn;
1646 char *filename, *snapshot_name = NULL;
1647 int c, ret = 0, bdrv_oflags;
1648 int action = 0;
1649 qemu_timeval tv;
1650 bool quiet = false;
1651
1652 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
1653 /* Parse commandline parameters */
1654 for(;;) {
1655 c = getopt(argc, argv, "la:c:d:hq");
1656 if (c == -1) {
1657 break;
1658 }
1659 switch(c) {
1660 case '?':
1661 case 'h':
1662 help();
1663 return 0;
1664 case 'l':
1665 if (action) {
1666 help();
1667 return 0;
1668 }
1669 action = SNAPSHOT_LIST;
1670 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
1671 break;
1672 case 'a':
1673 if (action) {
1674 help();
1675 return 0;
1676 }
1677 action = SNAPSHOT_APPLY;
1678 snapshot_name = optarg;
1679 break;
1680 case 'c':
1681 if (action) {
1682 help();
1683 return 0;
1684 }
1685 action = SNAPSHOT_CREATE;
1686 snapshot_name = optarg;
1687 break;
1688 case 'd':
1689 if (action) {
1690 help();
1691 return 0;
1692 }
1693 action = SNAPSHOT_DELETE;
1694 snapshot_name = optarg;
1695 break;
1696 case 'q':
1697 quiet = true;
1698 break;
1699 }
1700 }
1701
1702 if (optind >= argc) {
1703 help();
1704 }
1705 filename = argv[optind++];
1706
1707 /* Open the image */
1708 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
1709 if (!bs) {
1710 return 1;
1711 }
1712
1713 /* Perform the requested action */
1714 switch(action) {
1715 case SNAPSHOT_LIST:
1716 dump_snapshots(bs);
1717 break;
1718
1719 case SNAPSHOT_CREATE:
1720 memset(&sn, 0, sizeof(sn));
1721 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
1722
1723 qemu_gettimeofday(&tv);
1724 sn.date_sec = tv.tv_sec;
1725 sn.date_nsec = tv.tv_usec * 1000;
1726
1727 ret = bdrv_snapshot_create(bs, &sn);
1728 if (ret) {
1729 error_report("Could not create snapshot '%s': %d (%s)",
1730 snapshot_name, ret, strerror(-ret));
1731 }
1732 break;
1733
1734 case SNAPSHOT_APPLY:
1735 ret = bdrv_snapshot_goto(bs, snapshot_name);
1736 if (ret) {
1737 error_report("Could not apply snapshot '%s': %d (%s)",
1738 snapshot_name, ret, strerror(-ret));
1739 }
1740 break;
1741
1742 case SNAPSHOT_DELETE:
1743 ret = bdrv_snapshot_delete(bs, snapshot_name);
1744 if (ret) {
1745 error_report("Could not delete snapshot '%s': %d (%s)",
1746 snapshot_name, ret, strerror(-ret));
1747 }
1748 break;
1749 }
1750
1751 /* Cleanup */
1752 bdrv_delete(bs);
1753 if (ret) {
1754 return 1;
1755 }
1756 return 0;
1757 }
1758
1759 static int img_rebase(int argc, char **argv)
1760 {
1761 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
1762 BlockDriver *old_backing_drv, *new_backing_drv;
1763 char *filename;
1764 const char *fmt, *cache, *out_basefmt, *out_baseimg;
1765 int c, flags, ret;
1766 int unsafe = 0;
1767 int progress = 0;
1768 bool quiet = false;
1769
1770 /* Parse commandline parameters */
1771 fmt = NULL;
1772 cache = BDRV_DEFAULT_CACHE;
1773 out_baseimg = NULL;
1774 out_basefmt = NULL;
1775 for(;;) {
1776 c = getopt(argc, argv, "uhf:F:b:pt:q");
1777 if (c == -1) {
1778 break;
1779 }
1780 switch(c) {
1781 case '?':
1782 case 'h':
1783 help();
1784 return 0;
1785 case 'f':
1786 fmt = optarg;
1787 break;
1788 case 'F':
1789 out_basefmt = optarg;
1790 break;
1791 case 'b':
1792 out_baseimg = optarg;
1793 break;
1794 case 'u':
1795 unsafe = 1;
1796 break;
1797 case 'p':
1798 progress = 1;
1799 break;
1800 case 't':
1801 cache = optarg;
1802 break;
1803 case 'q':
1804 quiet = true;
1805 break;
1806 }
1807 }
1808
1809 if (quiet) {
1810 progress = 0;
1811 }
1812
1813 if ((optind >= argc) || (!unsafe && !out_baseimg)) {
1814 help();
1815 }
1816 filename = argv[optind++];
1817
1818 qemu_progress_init(progress, 2.0);
1819 qemu_progress_print(0, 100);
1820
1821 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
1822 ret = bdrv_parse_cache_flags(cache, &flags);
1823 if (ret < 0) {
1824 error_report("Invalid cache option: %s", cache);
1825 return -1;
1826 }
1827
1828 /*
1829 * Open the images.
1830 *
1831 * Ignore the old backing file for unsafe rebase in case we want to correct
1832 * the reference to a renamed or moved backing file.
1833 */
1834 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
1835 if (!bs) {
1836 return 1;
1837 }
1838
1839 /* Find the right drivers for the backing files */
1840 old_backing_drv = NULL;
1841 new_backing_drv = NULL;
1842
1843 if (!unsafe && bs->backing_format[0] != '\0') {
1844 old_backing_drv = bdrv_find_format(bs->backing_format);
1845 if (old_backing_drv == NULL) {
1846 error_report("Invalid format name: '%s'", bs->backing_format);
1847 ret = -1;
1848 goto out;
1849 }
1850 }
1851
1852 if (out_basefmt != NULL) {
1853 new_backing_drv = bdrv_find_format(out_basefmt);
1854 if (new_backing_drv == NULL) {
1855 error_report("Invalid format name: '%s'", out_basefmt);
1856 ret = -1;
1857 goto out;
1858 }
1859 }
1860
1861 /* For safe rebasing we need to compare old and new backing file */
1862 if (unsafe) {
1863 /* Make the compiler happy */
1864 bs_old_backing = NULL;
1865 bs_new_backing = NULL;
1866 } else {
1867 char backing_name[1024];
1868
1869 bs_old_backing = bdrv_new("old_backing");
1870 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
1871 ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
1872 old_backing_drv);
1873 if (ret) {
1874 error_report("Could not open old backing file '%s'", backing_name);
1875 goto out;
1876 }
1877 if (out_baseimg[0]) {
1878 bs_new_backing = bdrv_new("new_backing");
1879 ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
1880 new_backing_drv);
1881 if (ret) {
1882 error_report("Could not open new backing file '%s'",
1883 out_baseimg);
1884 goto out;
1885 }
1886 }
1887 }
1888
1889 /*
1890 * Check each unallocated cluster in the COW file. If it is unallocated,
1891 * accesses go to the backing file. We must therefore compare this cluster
1892 * in the old and new backing file, and if they differ we need to copy it
1893 * from the old backing file into the COW file.
1894 *
1895 * If qemu-img crashes during this step, no harm is done. The content of
1896 * the image is the same as the original one at any time.
1897 */
1898 if (!unsafe) {
1899 uint64_t num_sectors;
1900 uint64_t old_backing_num_sectors;
1901 uint64_t new_backing_num_sectors = 0;
1902 uint64_t sector;
1903 int n;
1904 uint8_t * buf_old;
1905 uint8_t * buf_new;
1906 float local_progress = 0;
1907
1908 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
1909 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
1910
1911 bdrv_get_geometry(bs, &num_sectors);
1912 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
1913 if (bs_new_backing) {
1914 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
1915 }
1916
1917 if (num_sectors != 0) {
1918 local_progress = (float)100 /
1919 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
1920 }
1921
1922 for (sector = 0; sector < num_sectors; sector += n) {
1923
1924 /* How many sectors can we handle with the next read? */
1925 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
1926 n = (IO_BUF_SIZE / 512);
1927 } else {
1928 n = num_sectors - sector;
1929 }
1930
1931 /* If the cluster is allocated, we don't need to take action */
1932 ret = bdrv_is_allocated(bs, sector, n, &n);
1933 if (ret) {
1934 continue;
1935 }
1936
1937 /*
1938 * Read old and new backing file and take into consideration that
1939 * backing files may be smaller than the COW image.
1940 */
1941 if (sector >= old_backing_num_sectors) {
1942 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
1943 } else {
1944 if (sector + n > old_backing_num_sectors) {
1945 n = old_backing_num_sectors - sector;
1946 }
1947
1948 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
1949 if (ret < 0) {
1950 error_report("error while reading from old backing file");
1951 goto out;
1952 }
1953 }
1954
1955 if (sector >= new_backing_num_sectors || !bs_new_backing) {
1956 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
1957 } else {
1958 if (sector + n > new_backing_num_sectors) {
1959 n = new_backing_num_sectors - sector;
1960 }
1961
1962 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
1963 if (ret < 0) {
1964 error_report("error while reading from new backing file");
1965 goto out;
1966 }
1967 }
1968
1969 /* If they differ, we need to write to the COW file */
1970 uint64_t written = 0;
1971
1972 while (written < n) {
1973 int pnum;
1974
1975 if (compare_sectors(buf_old + written * 512,
1976 buf_new + written * 512, n - written, &pnum))
1977 {
1978 ret = bdrv_write(bs, sector + written,
1979 buf_old + written * 512, pnum);
1980 if (ret < 0) {
1981 error_report("Error while writing to COW image: %s",
1982 strerror(-ret));
1983 goto out;
1984 }
1985 }
1986
1987 written += pnum;
1988 }
1989 qemu_progress_print(local_progress, 100);
1990 }
1991
1992 qemu_vfree(buf_old);
1993 qemu_vfree(buf_new);
1994 }
1995
1996 /*
1997 * Change the backing file. All clusters that are different from the old
1998 * backing file are overwritten in the COW file now, so the visible content
1999 * doesn't change when we switch the backing file.
2000 */
2001 if (out_baseimg && *out_baseimg) {
2002 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2003 } else {
2004 ret = bdrv_change_backing_file(bs, NULL, NULL);
2005 }
2006
2007 if (ret == -ENOSPC) {
2008 error_report("Could not change the backing file to '%s': No "
2009 "space left in the file header", out_baseimg);
2010 } else if (ret < 0) {
2011 error_report("Could not change the backing file to '%s': %s",
2012 out_baseimg, strerror(-ret));
2013 }
2014
2015 qemu_progress_print(100, 0);
2016 /*
2017 * TODO At this point it is possible to check if any clusters that are
2018 * allocated in the COW file are the same in the backing file. If so, they
2019 * could be dropped from the COW file. Don't do this before switching the
2020 * backing file, in case of a crash this would lead to corruption.
2021 */
2022 out:
2023 qemu_progress_end();
2024 /* Cleanup */
2025 if (!unsafe) {
2026 if (bs_old_backing != NULL) {
2027 bdrv_delete(bs_old_backing);
2028 }
2029 if (bs_new_backing != NULL) {
2030 bdrv_delete(bs_new_backing);
2031 }
2032 }
2033
2034 bdrv_delete(bs);
2035 if (ret) {
2036 return 1;
2037 }
2038 return 0;
2039 }
2040
2041 static int img_resize(int argc, char **argv)
2042 {
2043 int c, ret, relative;
2044 const char *filename, *fmt, *size;
2045 int64_t n, total_size;
2046 bool quiet = false;
2047 BlockDriverState *bs = NULL;
2048 QemuOpts *param;
2049 static QemuOptsList resize_options = {
2050 .name = "resize_options",
2051 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2052 .desc = {
2053 {
2054 .name = BLOCK_OPT_SIZE,
2055 .type = QEMU_OPT_SIZE,
2056 .help = "Virtual disk size"
2057 }, {
2058 /* end of list */
2059 }
2060 },
2061 };
2062
2063 /* Remove size from argv manually so that negative numbers are not treated
2064 * as options by getopt. */
2065 if (argc < 3) {
2066 help();
2067 return 1;
2068 }
2069
2070 size = argv[--argc];
2071
2072 /* Parse getopt arguments */
2073 fmt = NULL;
2074 for(;;) {
2075 c = getopt(argc, argv, "f:hq");
2076 if (c == -1) {
2077 break;
2078 }
2079 switch(c) {
2080 case '?':
2081 case 'h':
2082 help();
2083 break;
2084 case 'f':
2085 fmt = optarg;
2086 break;
2087 case 'q':
2088 quiet = true;
2089 break;
2090 }
2091 }
2092 if (optind >= argc) {
2093 help();
2094 }
2095 filename = argv[optind++];
2096
2097 /* Choose grow, shrink, or absolute resize mode */
2098 switch (size[0]) {
2099 case '+':
2100 relative = 1;
2101 size++;
2102 break;
2103 case '-':
2104 relative = -1;
2105 size++;
2106 break;
2107 default:
2108 relative = 0;
2109 break;
2110 }
2111
2112 /* Parse size */
2113 param = qemu_opts_create_nofail(&resize_options);
2114 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
2115 /* Error message already printed when size parsing fails */
2116 ret = -1;
2117 qemu_opts_del(param);
2118 goto out;
2119 }
2120 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2121 qemu_opts_del(param);
2122
2123 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
2124 if (!bs) {
2125 ret = -1;
2126 goto out;
2127 }
2128
2129 if (relative) {
2130 total_size = bdrv_getlength(bs) + n * relative;
2131 } else {
2132 total_size = n;
2133 }
2134 if (total_size <= 0) {
2135 error_report("New image size must be positive");
2136 ret = -1;
2137 goto out;
2138 }
2139
2140 ret = bdrv_truncate(bs, total_size);
2141 switch (ret) {
2142 case 0:
2143 qprintf(quiet, "Image resized.\n");
2144 break;
2145 case -ENOTSUP:
2146 error_report("This image does not support resize");
2147 break;
2148 case -EACCES:
2149 error_report("Image is read-only");
2150 break;
2151 default:
2152 error_report("Error resizing image (%d)", -ret);
2153 break;
2154 }
2155 out:
2156 if (bs) {
2157 bdrv_delete(bs);
2158 }
2159 if (ret) {
2160 return 1;
2161 }
2162 return 0;
2163 }
2164
2165 static const img_cmd_t img_cmds[] = {
2166 #define DEF(option, callback, arg_string) \
2167 { option, callback },
2168 #include "qemu-img-cmds.h"
2169 #undef DEF
2170 #undef GEN_DOCS
2171 { NULL, NULL, },
2172 };
2173
2174 int main(int argc, char **argv)
2175 {
2176 const img_cmd_t *cmd;
2177 const char *cmdname;
2178
2179 error_set_progname(argv[0]);
2180
2181 qemu_init_main_loop();
2182 bdrv_init();
2183 if (argc < 2)
2184 help();
2185 cmdname = argv[1];
2186 argc--; argv++;
2187
2188 /* find the command */
2189 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2190 if (!strcmp(cmdname, cmd->name)) {
2191 return cmd->handler(argc, argv);
2192 }
2193 }
2194
2195 /* not found */
2196 help();
2197 return 0;
2198 }