Device hot-remove
[qemu-kvm/fedora.git] / qemu-img.c
blob38736a4c7509d5c67be61d62179af4a3d8c151e2
1 /*
2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "qemu-common.h"
25 #include "block_int.h"
26 #include <assert.h>
28 #ifdef _WIN32
29 #define WIN32_LEAN_AND_MEAN
30 #include <windows.h>
31 #endif
33 void *get_mmap_addr(unsigned long size)
35 return NULL;
38 void qemu_free(void *ptr)
40 free(ptr);
43 void *qemu_malloc(size_t size)
45 return malloc(size);
48 void *qemu_mallocz(size_t size)
50 void *ptr;
51 ptr = qemu_malloc(size);
52 if (!ptr)
53 return NULL;
54 memset(ptr, 0, size);
55 return ptr;
58 #ifdef _WIN32
60 void *qemu_memalign(size_t alignment, size_t size)
62 return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
65 #else
67 void *qemu_memalign(size_t alignment, size_t size)
69 #if defined(_POSIX_C_SOURCE)
70 int ret;
71 void *ptr;
72 ret = posix_memalign(&ptr, alignment, size);
73 if (ret != 0)
74 return NULL;
75 return ptr;
76 #elif defined(_BSD)
77 return valloc(size);
78 #else
79 return memalign(alignment, size);
80 #endif
83 #endif
85 char *qemu_strdup(const char *str)
87 char *ptr;
88 ptr = qemu_malloc(strlen(str) + 1);
89 if (!ptr)
90 return NULL;
91 strcpy(ptr, str);
92 return ptr;
95 static void __attribute__((noreturn)) error(const char *fmt, ...)
97 va_list ap;
98 va_start(ap, fmt);
99 fprintf(stderr, "qemu-img: ");
100 vfprintf(stderr, fmt, ap);
101 fprintf(stderr, "\n");
102 exit(1);
103 va_end(ap);
106 static void format_print(void *opaque, const char *name)
108 printf(" %s", name);
111 static void help(void)
113 printf("qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
114 "usage: qemu-img command [command options]\n"
115 "QEMU disk image utility\n"
116 "\n"
117 "Command syntax:\n"
118 " create [-e] [-6] [-b base_image] [-f fmt] filename [size]\n"
119 " commit [-f fmt] filename\n"
120 " convert [-c] [-e] [-6] [-f fmt] [-O output_fmt] filename [filename2 [...]] output_filename\n"
121 " info [-f fmt] filename\n"
122 "\n"
123 "Command parameters:\n"
124 " 'filename' is a disk image filename\n"
125 " 'base_image' is the read-only disk image which is used as base for a copy on\n"
126 " write image; the copy on write image only stores the modified data\n"
127 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
128 " 'size' is the disk image size in kilobytes. Optional suffixes 'M' (megabyte)\n"
129 " and 'G' (gigabyte) are supported\n"
130 " 'output_filename' is the destination disk image filename\n"
131 " 'output_fmt' is the destination format\n"
132 " '-c' indicates that target image must be compressed (qcow format only)\n"
133 " '-e' indicates that the target image must be encrypted (qcow format only)\n"
134 " '-6' indicates that the target image must use compatibility level 6 (vmdk format only)\n"
136 printf("\nSupported format:");
137 bdrv_iterate_format(format_print, NULL);
138 printf("\n");
139 exit(1);
142 #if defined(WIN32)
143 /* XXX: put correct support for win32 */
144 static int read_password(char *buf, int buf_size)
146 int c, i;
147 printf("Password: ");
148 fflush(stdout);
149 i = 0;
150 for(;;) {
151 c = getchar();
152 if (c == '\n')
153 break;
154 if (i < (buf_size - 1))
155 buf[i++] = c;
157 buf[i] = '\0';
158 return 0;
161 #else
163 #include <termios.h>
165 static struct termios oldtty;
167 static void term_exit(void)
169 tcsetattr (0, TCSANOW, &oldtty);
172 static void term_init(void)
174 struct termios tty;
176 tcgetattr (0, &tty);
177 oldtty = tty;
179 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
180 |INLCR|IGNCR|ICRNL|IXON);
181 tty.c_oflag |= OPOST;
182 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
183 tty.c_cflag &= ~(CSIZE|PARENB);
184 tty.c_cflag |= CS8;
185 tty.c_cc[VMIN] = 1;
186 tty.c_cc[VTIME] = 0;
188 tcsetattr (0, TCSANOW, &tty);
190 atexit(term_exit);
193 static int read_password(char *buf, int buf_size)
195 uint8_t ch;
196 int i, ret;
198 printf("password: ");
199 fflush(stdout);
200 term_init();
201 i = 0;
202 for(;;) {
203 ret = read(0, &ch, 1);
204 if (ret == -1) {
205 if (errno == EAGAIN || errno == EINTR) {
206 continue;
207 } else {
208 ret = -1;
209 break;
211 } else if (ret == 0) {
212 ret = -1;
213 break;
214 } else {
215 if (ch == '\r') {
216 ret = 0;
217 break;
219 if (i < (buf_size - 1))
220 buf[i++] = ch;
223 term_exit();
224 buf[i] = '\0';
225 printf("\n");
226 return ret;
228 #endif
230 static BlockDriverState *bdrv_new_open(const char *filename,
231 const char *fmt)
233 BlockDriverState *bs;
234 BlockDriver *drv;
235 char password[256];
237 bs = bdrv_new("");
238 if (!bs)
239 error("Not enough memory");
240 if (fmt) {
241 drv = bdrv_find_format(fmt);
242 if (!drv)
243 error("Unknown file format '%s'", fmt);
244 } else {
245 drv = NULL;
247 if (bdrv_open2(bs, filename, 0, drv) < 0) {
248 error("Could not open '%s'", filename);
250 if (bdrv_is_encrypted(bs)) {
251 printf("Disk image '%s' is encrypted.\n", filename);
252 if (read_password(password, sizeof(password)) < 0)
253 error("No password given");
254 if (bdrv_set_key(bs, password) < 0)
255 error("invalid password");
257 return bs;
260 static int img_create(int argc, char **argv)
262 int c, ret, flags;
263 const char *fmt = "raw";
264 const char *filename;
265 const char *base_filename = NULL;
266 uint64_t size;
267 const char *p;
268 BlockDriver *drv;
270 flags = 0;
271 for(;;) {
272 c = getopt(argc, argv, "b:f:he6");
273 if (c == -1)
274 break;
275 switch(c) {
276 case 'h':
277 help();
278 break;
279 case 'b':
280 base_filename = optarg;
281 break;
282 case 'f':
283 fmt = optarg;
284 break;
285 case 'e':
286 flags |= BLOCK_FLAG_ENCRYPT;
287 break;
288 case '6':
289 flags |= BLOCK_FLAG_COMPAT6;
290 break;
293 if (optind >= argc)
294 help();
295 filename = argv[optind++];
296 size = 0;
297 if (base_filename) {
298 BlockDriverState *bs;
299 bs = bdrv_new_open(base_filename, NULL);
300 bdrv_get_geometry(bs, &size);
301 size *= 512;
302 bdrv_delete(bs);
303 } else {
304 if (optind >= argc)
305 help();
306 p = argv[optind];
307 size = strtoul(p, (char **)&p, 0);
308 if (*p == 'M') {
309 size *= 1024 * 1024;
310 } else if (*p == 'G') {
311 size *= 1024 * 1024 * 1024;
312 } else if (*p == 'k' || *p == 'K' || *p == '\0') {
313 size *= 1024;
314 } else {
315 help();
318 drv = bdrv_find_format(fmt);
319 if (!drv)
320 error("Unknown file format '%s'", fmt);
321 printf("Formatting '%s', fmt=%s",
322 filename, fmt);
323 if (flags & BLOCK_FLAG_ENCRYPT)
324 printf(", encrypted");
325 if (flags & BLOCK_FLAG_COMPAT6)
326 printf(", compatibility level=6");
327 if (base_filename) {
328 printf(", backing_file=%s",
329 base_filename);
331 printf(", size=%" PRIu64 " kB\n", size / 1024);
332 ret = bdrv_create(drv, filename, size / 512, base_filename, flags);
333 if (ret < 0) {
334 if (ret == -ENOTSUP) {
335 error("Formatting or formatting option not supported for file format '%s'", fmt);
336 } else {
337 error("Error while formatting");
340 return 0;
343 static int img_commit(int argc, char **argv)
345 int c, ret;
346 const char *filename, *fmt;
347 BlockDriver *drv;
348 BlockDriverState *bs;
350 fmt = NULL;
351 for(;;) {
352 c = getopt(argc, argv, "f:h");
353 if (c == -1)
354 break;
355 switch(c) {
356 case 'h':
357 help();
358 break;
359 case 'f':
360 fmt = optarg;
361 break;
364 if (optind >= argc)
365 help();
366 filename = argv[optind++];
368 bs = bdrv_new("");
369 if (!bs)
370 error("Not enough memory");
371 if (fmt) {
372 drv = bdrv_find_format(fmt);
373 if (!drv)
374 error("Unknown file format '%s'", fmt);
375 } else {
376 drv = NULL;
378 if (bdrv_open2(bs, filename, 0, drv) < 0) {
379 error("Could not open '%s'", filename);
381 ret = bdrv_commit(bs);
382 switch(ret) {
383 case 0:
384 printf("Image committed.\n");
385 break;
386 case -ENOENT:
387 error("No disk inserted");
388 break;
389 case -EACCES:
390 error("Image is read-only");
391 break;
392 case -ENOTSUP:
393 error("Image is already committed");
394 break;
395 default:
396 error("Error while committing image");
397 break;
400 bdrv_delete(bs);
401 return 0;
404 static int is_not_zero(const uint8_t *sector, int len)
406 int i;
407 len >>= 2;
408 for(i = 0;i < len; i++) {
409 if (((uint32_t *)sector)[i] != 0)
410 return 1;
412 return 0;
415 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
417 int v, i;
419 if (n <= 0) {
420 *pnum = 0;
421 return 0;
423 v = is_not_zero(buf, 512);
424 for(i = 1; i < n; i++) {
425 buf += 512;
426 if (v != is_not_zero(buf, 512))
427 break;
429 *pnum = i;
430 return v;
433 #define IO_BUF_SIZE 65536
435 static int img_convert(int argc, char **argv)
437 int c, ret, n, n1, bs_n, bs_i, flags, cluster_size, cluster_sectors;
438 const char *fmt, *out_fmt, *out_filename;
439 BlockDriver *drv;
440 BlockDriverState **bs, *out_bs;
441 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
442 uint64_t bs_sectors;
443 uint8_t buf[IO_BUF_SIZE];
444 const uint8_t *buf1;
445 BlockDriverInfo bdi;
447 fmt = NULL;
448 out_fmt = "raw";
449 flags = 0;
450 for(;;) {
451 c = getopt(argc, argv, "f:O:hce6");
452 if (c == -1)
453 break;
454 switch(c) {
455 case 'h':
456 help();
457 break;
458 case 'f':
459 fmt = optarg;
460 break;
461 case 'O':
462 out_fmt = optarg;
463 break;
464 case 'c':
465 flags |= BLOCK_FLAG_COMPRESS;
466 break;
467 case 'e':
468 flags |= BLOCK_FLAG_ENCRYPT;
469 break;
470 case '6':
471 flags |= BLOCK_FLAG_COMPAT6;
472 break;
476 bs_n = argc - optind - 1;
477 if (bs_n < 1) help();
479 out_filename = argv[argc - 1];
481 bs = calloc(bs_n, sizeof(BlockDriverState *));
482 if (!bs)
483 error("Out of memory");
485 total_sectors = 0;
486 for (bs_i = 0; bs_i < bs_n; bs_i++) {
487 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt);
488 if (!bs[bs_i])
489 error("Could not open '%s'", argv[optind + bs_i]);
490 bdrv_get_geometry(bs[bs_i], &bs_sectors);
491 total_sectors += bs_sectors;
494 drv = bdrv_find_format(out_fmt);
495 if (!drv)
496 error("Unknown file format '%s'", out_fmt);
497 if (flags & BLOCK_FLAG_COMPRESS && drv != &bdrv_qcow && drv != &bdrv_qcow2)
498 error("Compression not supported for this file format");
499 if (flags & BLOCK_FLAG_ENCRYPT && drv != &bdrv_qcow && drv != &bdrv_qcow2)
500 error("Encryption not supported for this file format");
501 if (flags & BLOCK_FLAG_COMPAT6 && drv != &bdrv_vmdk)
502 error("Alternative compatibility level not supported for this file format");
503 if (flags & BLOCK_FLAG_ENCRYPT && flags & BLOCK_FLAG_COMPRESS)
504 error("Compression and encryption not supported at the same time");
506 ret = bdrv_create(drv, out_filename, total_sectors, NULL, flags);
507 if (ret < 0) {
508 if (ret == -ENOTSUP) {
509 error("Formatting not supported for file format '%s'", fmt);
510 } else {
511 error("Error while formatting '%s'", out_filename);
515 out_bs = bdrv_new_open(out_filename, out_fmt);
517 bs_i = 0;
518 bs_offset = 0;
519 bdrv_get_geometry(bs[0], &bs_sectors);
521 if (flags & BLOCK_FLAG_COMPRESS) {
522 if (bdrv_get_info(out_bs, &bdi) < 0)
523 error("could not get block driver info");
524 cluster_size = bdi.cluster_size;
525 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE)
526 error("invalid cluster size");
527 cluster_sectors = cluster_size >> 9;
528 sector_num = 0;
529 for(;;) {
530 int64_t bs_num;
531 int remainder;
532 uint8_t *buf2;
534 nb_sectors = total_sectors - sector_num;
535 if (nb_sectors <= 0)
536 break;
537 if (nb_sectors >= cluster_sectors)
538 n = cluster_sectors;
539 else
540 n = nb_sectors;
542 bs_num = sector_num - bs_offset;
543 assert (bs_num >= 0);
544 remainder = n;
545 buf2 = buf;
546 while (remainder > 0) {
547 int nlow;
548 while (bs_num == bs_sectors) {
549 bs_i++;
550 assert (bs_i < bs_n);
551 bs_offset += bs_sectors;
552 bdrv_get_geometry(bs[bs_i], &bs_sectors);
553 bs_num = 0;
554 /* printf("changing part: sector_num=%lld, "
555 "bs_i=%d, bs_offset=%lld, bs_sectors=%lld\n",
556 sector_num, bs_i, bs_offset, bs_sectors); */
558 assert (bs_num < bs_sectors);
560 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
562 if (bdrv_read(bs[bs_i], bs_num, buf2, nlow) < 0)
563 error("error while reading");
565 buf2 += nlow * 512;
566 bs_num += nlow;
568 remainder -= nlow;
570 assert (remainder == 0);
572 if (n < cluster_sectors)
573 memset(buf + n * 512, 0, cluster_size - n * 512);
574 if (is_not_zero(buf, cluster_size)) {
575 if (bdrv_write_compressed(out_bs, sector_num, buf,
576 cluster_sectors) != 0)
577 error("error while compressing sector %" PRId64,
578 sector_num);
580 sector_num += n;
582 /* signal EOF to align */
583 bdrv_write_compressed(out_bs, 0, NULL, 0);
584 } else {
585 sector_num = 0;
586 for(;;) {
587 nb_sectors = total_sectors - sector_num;
588 if (nb_sectors <= 0)
589 break;
590 if (nb_sectors >= (IO_BUF_SIZE / 512))
591 n = (IO_BUF_SIZE / 512);
592 else
593 n = nb_sectors;
595 while (sector_num - bs_offset >= bs_sectors) {
596 bs_i ++;
597 assert (bs_i < bs_n);
598 bs_offset += bs_sectors;
599 bdrv_get_geometry(bs[bs_i], &bs_sectors);
600 /* printf("changing part: sector_num=%lld, bs_i=%d, "
601 "bs_offset=%lld, bs_sectors=%lld\n",
602 sector_num, bs_i, bs_offset, bs_sectors); */
605 if (n > bs_offset + bs_sectors - sector_num)
606 n = bs_offset + bs_sectors - sector_num;
608 if (bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n) < 0)
609 error("error while reading");
610 /* NOTE: at the same time we convert, we do not write zero
611 sectors to have a chance to compress the image. Ideally, we
612 should add a specific call to have the info to go faster */
613 buf1 = buf;
614 while (n > 0) {
615 if (is_allocated_sectors(buf1, n, &n1)) {
616 if (bdrv_write(out_bs, sector_num, buf1, n1) < 0)
617 error("error while writing");
619 sector_num += n1;
620 n -= n1;
621 buf1 += n1 * 512;
625 bdrv_delete(out_bs);
626 for (bs_i = 0; bs_i < bs_n; bs_i++)
627 bdrv_delete(bs[bs_i]);
628 free(bs);
629 return 0;
632 #ifdef _WIN32
633 static int64_t get_allocated_file_size(const char *filename)
635 typedef DWORD (WINAPI * get_compressed_t)(const char *filename, DWORD *high);
636 get_compressed_t get_compressed;
637 struct _stati64 st;
639 /* WinNT support GetCompressedFileSize to determine allocate size */
640 get_compressed = (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"), "GetCompressedFileSizeA");
641 if (get_compressed) {
642 DWORD high, low;
643 low = get_compressed(filename, &high);
644 if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR)
645 return (((int64_t) high) << 32) + low;
648 if (_stati64(filename, &st) < 0)
649 return -1;
650 return st.st_size;
652 #else
653 static int64_t get_allocated_file_size(const char *filename)
655 struct stat st;
656 if (stat(filename, &st) < 0)
657 return -1;
658 return (int64_t)st.st_blocks * 512;
660 #endif
662 static void dump_snapshots(BlockDriverState *bs)
664 QEMUSnapshotInfo *sn_tab, *sn;
665 int nb_sns, i;
666 char buf[256];
668 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
669 if (nb_sns <= 0)
670 return;
671 printf("Snapshot list:\n");
672 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
673 for(i = 0; i < nb_sns; i++) {
674 sn = &sn_tab[i];
675 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
677 qemu_free(sn_tab);
680 static int img_info(int argc, char **argv)
682 int c;
683 const char *filename, *fmt;
684 BlockDriver *drv;
685 BlockDriverState *bs;
686 char fmt_name[128], size_buf[128], dsize_buf[128];
687 uint64_t total_sectors;
688 int64_t allocated_size;
689 char backing_filename[1024];
690 char backing_filename2[1024];
691 BlockDriverInfo bdi;
693 fmt = NULL;
694 for(;;) {
695 c = getopt(argc, argv, "f:h");
696 if (c == -1)
697 break;
698 switch(c) {
699 case 'h':
700 help();
701 break;
702 case 'f':
703 fmt = optarg;
704 break;
707 if (optind >= argc)
708 help();
709 filename = argv[optind++];
711 bs = bdrv_new("");
712 if (!bs)
713 error("Not enough memory");
714 if (fmt) {
715 drv = bdrv_find_format(fmt);
716 if (!drv)
717 error("Unknown file format '%s'", fmt);
718 } else {
719 drv = NULL;
721 if (bdrv_open2(bs, filename, 0, drv) < 0) {
722 error("Could not open '%s'", filename);
724 bdrv_get_format(bs, fmt_name, sizeof(fmt_name));
725 bdrv_get_geometry(bs, &total_sectors);
726 get_human_readable_size(size_buf, sizeof(size_buf), total_sectors * 512);
727 allocated_size = get_allocated_file_size(filename);
728 if (allocated_size < 0)
729 sprintf(dsize_buf, "unavailable");
730 else
731 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
732 allocated_size);
733 printf("image: %s\n"
734 "file format: %s\n"
735 "virtual size: %s (%" PRId64 " bytes)\n"
736 "disk size: %s\n",
737 filename, fmt_name, size_buf,
738 (total_sectors * 512),
739 dsize_buf);
740 if (bdrv_is_encrypted(bs))
741 printf("encrypted: yes\n");
742 if (bdrv_get_info(bs, &bdi) >= 0) {
743 if (bdi.cluster_size != 0)
744 printf("cluster_size: %d\n", bdi.cluster_size);
746 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
747 if (backing_filename[0] != '\0') {
748 path_combine(backing_filename2, sizeof(backing_filename2),
749 filename, backing_filename);
750 printf("backing file: %s (actual path: %s)\n",
751 backing_filename,
752 backing_filename2);
754 dump_snapshots(bs);
755 bdrv_delete(bs);
756 return 0;
759 int main(int argc, char **argv)
761 const char *cmd;
763 bdrv_init();
764 if (argc < 2)
765 help();
766 cmd = argv[1];
767 optind++;
768 if (!strcmp(cmd, "create")) {
769 img_create(argc, argv);
770 } else if (!strcmp(cmd, "commit")) {
771 img_commit(argc, argv);
772 } else if (!strcmp(cmd, "convert")) {
773 img_convert(argc, argv);
774 } else if (!strcmp(cmd, "info")) {
775 img_info(argc, argv);
776 } else {
777 help();
779 return 0;