2 * Block driver for the VMDK format
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu-common.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "migration/migration.h"
32 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
33 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
34 #define VMDK4_COMPRESSION_DEFLATE 1
35 #define VMDK4_FLAG_NL_DETECT (1 << 0)
36 #define VMDK4_FLAG_RGD (1 << 1)
37 /* Zeroed-grain enable bit */
38 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
39 #define VMDK4_FLAG_COMPRESS (1 << 16)
40 #define VMDK4_FLAG_MARKER (1 << 17)
41 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
43 #define VMDK_GTE_ZEROED 0x1
45 /* VMDK internal error codes */
47 #define VMDK_ERROR (-1)
48 /* Cluster not allocated */
49 #define VMDK_UNALLOC (-2)
50 #define VMDK_ZEROED (-3)
52 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
57 uint32_t disk_sectors;
59 uint32_t l1dir_offset;
61 uint32_t file_sectors;
64 uint32_t sectors_per_track;
74 int32_t num_gtes_per_gte;
80 uint16_t compressAlgorithm;
81 } QEMU_PACKED VMDK4Header;
83 #define L2_CACHE_SIZE 16
85 typedef struct VmdkExtent {
86 BlockDriverState *file;
94 int64_t flat_start_offset;
95 int64_t l1_table_offset;
96 int64_t l1_backup_table_offset;
98 uint32_t *l1_backup_table;
100 uint32_t l1_entry_sectors;
102 unsigned int l2_size;
104 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
105 uint32_t l2_cache_counts[L2_CACHE_SIZE];
107 unsigned int cluster_sectors;
110 typedef struct BDRVVmdkState {
116 /* Extent array with num_extents entries, ascend ordered by address */
118 Error *migration_blocker;
121 typedef struct VmdkMetaData {
123 unsigned int l1_index;
124 unsigned int l2_index;
125 unsigned int l2_offset;
129 typedef struct VmdkGrainMarker {
136 MARKER_END_OF_STREAM = 0,
137 MARKER_GRAIN_TABLE = 1,
138 MARKER_GRAIN_DIRECTORY = 2,
142 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
149 magic = be32_to_cpu(*(uint32_t *)buf);
150 if (magic == VMDK3_MAGIC ||
151 magic == VMDK4_MAGIC) {
154 const char *p = (const char *)buf;
155 const char *end = p + buf_size;
158 /* skip comment line */
159 while (p < end && *p != '\n') {
166 while (p < end && *p == ' ') {
169 /* skip '\r' if windows line endings used. */
170 if (p < end && *p == '\r') {
173 /* only accept blank lines before 'version=' line */
174 if (p == end || *p != '\n') {
180 if (end - p >= strlen("version=X\n")) {
181 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
182 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
186 if (end - p >= strlen("version=X\r\n")) {
187 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
188 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
200 #define SECTOR_SIZE 512
201 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
202 #define BUF_SIZE 4096
203 #define HEADER_SIZE 512 /* first sector of 512 bytes */
205 static void vmdk_free_extents(BlockDriverState *bs)
208 BDRVVmdkState *s = bs->opaque;
211 for (i = 0; i < s->num_extents; i++) {
215 g_free(e->l1_backup_table);
216 if (e->file != bs->file) {
217 bdrv_delete(e->file);
223 static void vmdk_free_last_extent(BlockDriverState *bs)
225 BDRVVmdkState *s = bs->opaque;
227 if (s->num_extents == 0) {
231 s->extents = g_realloc(s->extents, s->num_extents * sizeof(VmdkExtent));
234 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
236 char desc[DESC_SIZE];
237 uint32_t cid = 0xffffffff;
238 const char *p_name, *cid_str;
240 BDRVVmdkState *s = bs->opaque;
243 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
249 cid_str = "parentCID";
250 cid_str_size = sizeof("parentCID");
253 cid_str_size = sizeof("CID");
256 desc[DESC_SIZE - 1] = '\0';
257 p_name = strstr(desc, cid_str);
258 if (p_name != NULL) {
259 p_name += cid_str_size;
260 sscanf(p_name, "%x", &cid);
266 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
268 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
269 char *p_name, *tmp_str;
270 BDRVVmdkState *s = bs->opaque;
273 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
278 desc[DESC_SIZE - 1] = '\0';
279 tmp_str = strstr(desc, "parentCID");
280 if (tmp_str == NULL) {
284 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
285 p_name = strstr(desc, "CID");
286 if (p_name != NULL) {
287 p_name += sizeof("CID");
288 snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);
289 pstrcat(desc, sizeof(desc), tmp_desc);
292 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
300 static int vmdk_is_cid_valid(BlockDriverState *bs)
303 BDRVVmdkState *s = bs->opaque;
304 BlockDriverState *p_bs = bs->backing_hd;
308 cur_pcid = vmdk_read_cid(p_bs, 0);
309 if (s->parent_cid != cur_pcid) {
319 /* Queue extents, if any, for reopen() */
320 static int vmdk_reopen_prepare(BDRVReopenState *state,
321 BlockReopenQueue *queue, Error **errp)
328 assert(state != NULL);
329 assert(state->bs != NULL);
332 error_set(errp, ERROR_CLASS_GENERIC_ERROR,
333 "No reopen queue for VMDK extents");
337 s = state->bs->opaque;
341 for (i = 0; i < s->num_extents; i++) {
343 if (e->file != state->bs->file) {
344 bdrv_reopen_queue(queue, e->file, state->flags);
353 static int vmdk_parent_open(BlockDriverState *bs)
356 char desc[DESC_SIZE + 1];
357 BDRVVmdkState *s = bs->opaque;
360 desc[DESC_SIZE] = '\0';
361 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
366 p_name = strstr(desc, "parentFileNameHint");
367 if (p_name != NULL) {
370 p_name += sizeof("parentFileNameHint") + 1;
371 end_name = strchr(p_name, '\"');
372 if (end_name == NULL) {
375 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
379 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
385 /* Create and append extent to the extent array. Return the added VmdkExtent
386 * address. return NULL if allocation failed. */
387 static VmdkExtent *vmdk_add_extent(BlockDriverState *bs,
388 BlockDriverState *file, bool flat, int64_t sectors,
389 int64_t l1_offset, int64_t l1_backup_offset,
391 int l2_size, unsigned int cluster_sectors)
394 BDRVVmdkState *s = bs->opaque;
396 s->extents = g_realloc(s->extents,
397 (s->num_extents + 1) * sizeof(VmdkExtent));
398 extent = &s->extents[s->num_extents];
401 memset(extent, 0, sizeof(VmdkExtent));
404 extent->sectors = sectors;
405 extent->l1_table_offset = l1_offset;
406 extent->l1_backup_table_offset = l1_backup_offset;
407 extent->l1_size = l1_size;
408 extent->l1_entry_sectors = l2_size * cluster_sectors;
409 extent->l2_size = l2_size;
410 extent->cluster_sectors = cluster_sectors;
412 if (s->num_extents > 1) {
413 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
415 extent->end_sector = extent->sectors;
417 bs->total_sectors = extent->end_sector;
421 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent)
426 /* read the L1 table */
427 l1_size = extent->l1_size * sizeof(uint32_t);
428 extent->l1_table = g_malloc(l1_size);
429 ret = bdrv_pread(extent->file,
430 extent->l1_table_offset,
436 for (i = 0; i < extent->l1_size; i++) {
437 le32_to_cpus(&extent->l1_table[i]);
440 if (extent->l1_backup_table_offset) {
441 extent->l1_backup_table = g_malloc(l1_size);
442 ret = bdrv_pread(extent->file,
443 extent->l1_backup_table_offset,
444 extent->l1_backup_table,
449 for (i = 0; i < extent->l1_size; i++) {
450 le32_to_cpus(&extent->l1_backup_table[i]);
455 g_malloc(extent->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
458 g_free(extent->l1_backup_table);
460 g_free(extent->l1_table);
464 static int vmdk_open_vmdk3(BlockDriverState *bs,
465 BlockDriverState *file,
473 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
477 extent = vmdk_add_extent(bs,
479 le32_to_cpu(header.disk_sectors),
480 le32_to_cpu(header.l1dir_offset) << 9,
482 le32_to_cpu(header.granularity));
483 ret = vmdk_init_tables(bs, extent);
485 /* free extent allocated by vmdk_add_extent */
486 vmdk_free_last_extent(bs);
491 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
492 int64_t desc_offset);
494 static int vmdk_open_vmdk4(BlockDriverState *bs,
495 BlockDriverState *file,
500 uint32_t l1_size, l1_entry_sectors;
503 int64_t l1_backup_offset = 0;
505 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
509 if (header.capacity == 0 && header.desc_offset) {
510 return vmdk_open_desc_file(bs, flags, header.desc_offset << 9);
513 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
515 * The footer takes precedence over the header, so read it in. The
516 * footer starts at offset -1024 from the end: One sector for the
517 * footer, and another one for the end-of-stream marker.
524 uint8_t pad[512 - 16];
525 } QEMU_PACKED footer_marker;
529 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
535 uint8_t pad[512 - 16];
536 } QEMU_PACKED eos_marker;
537 } QEMU_PACKED footer;
539 ret = bdrv_pread(file,
540 bs->file->total_sectors * 512 - 1536,
541 &footer, sizeof(footer));
546 /* Some sanity checks for the footer */
547 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
548 le32_to_cpu(footer.footer_marker.size) != 0 ||
549 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
550 le64_to_cpu(footer.eos_marker.val) != 0 ||
551 le32_to_cpu(footer.eos_marker.size) != 0 ||
552 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
557 header = footer.header;
560 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gte)
561 * le64_to_cpu(header.granularity);
562 if (l1_entry_sectors == 0) {
565 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
567 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
568 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
570 extent = vmdk_add_extent(bs, file, false,
571 le64_to_cpu(header.capacity),
572 le64_to_cpu(header.gd_offset) << 9,
575 le32_to_cpu(header.num_gtes_per_gte),
576 le64_to_cpu(header.granularity));
578 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
579 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
580 extent->version = le32_to_cpu(header.version);
581 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
582 ret = vmdk_init_tables(bs, extent);
584 /* free extent allocated by vmdk_add_extent */
585 vmdk_free_last_extent(bs);
590 /* find an option value out of descriptor file */
591 static int vmdk_parse_description(const char *desc, const char *opt_name,
592 char *buf, int buf_size)
594 char *opt_pos, *opt_end;
595 const char *end = desc + strlen(desc);
597 opt_pos = strstr(desc, opt_name);
601 /* Skip "=\"" following opt_name */
602 opt_pos += strlen(opt_name) + 2;
603 if (opt_pos >= end) {
607 while (opt_end < end && *opt_end != '"') {
610 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
613 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
617 /* Open an extent file and append to bs array */
618 static int vmdk_open_sparse(BlockDriverState *bs,
619 BlockDriverState *file,
624 if (bdrv_pread(file, 0, &magic, sizeof(magic)) != sizeof(magic)) {
628 magic = be32_to_cpu(magic);
631 return vmdk_open_vmdk3(bs, file, flags);
634 return vmdk_open_vmdk4(bs, file, flags);
642 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
643 const char *desc_file_path)
649 const char *p = desc;
652 char extent_path[PATH_MAX];
653 BlockDriverState *extent_file;
656 /* parse extent line:
657 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
659 * RW [size in sectors] SPARSE "file-name.vmdk"
662 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
663 access, §ors, type, fname, &flat_offset);
664 if (ret < 4 || strcmp(access, "RW")) {
666 } else if (!strcmp(type, "FLAT")) {
667 if (ret != 5 || flat_offset < 0) {
670 } else if (ret != 4) {
675 (strcmp(type, "FLAT") && strcmp(type, "SPARSE")) ||
676 (strcmp(access, "RW"))) {
680 path_combine(extent_path, sizeof(extent_path),
681 desc_file_path, fname);
682 ret = bdrv_file_open(&extent_file, extent_path, NULL, bs->open_flags);
687 /* save to extents array */
688 if (!strcmp(type, "FLAT")) {
692 extent = vmdk_add_extent(bs, extent_file, true, sectors,
693 0, 0, 0, 0, sectors);
694 extent->flat_start_offset = flat_offset << 9;
695 } else if (!strcmp(type, "SPARSE")) {
697 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags);
699 bdrv_delete(extent_file);
704 "VMDK: Not supported extent type \"%s\""".\n", type);
708 /* move to next line */
709 while (*p && *p != '\n') {
717 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
723 BDRVVmdkState *s = bs->opaque;
725 ret = bdrv_pread(bs->file, desc_offset, buf, sizeof(buf));
730 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
733 if (strcmp(ct, "monolithicFlat") &&
734 strcmp(ct, "twoGbMaxExtentSparse") &&
735 strcmp(ct, "twoGbMaxExtentFlat")) {
737 "VMDK: Not supported image type \"%s\""".\n", ct);
741 return vmdk_parse_extents(buf, bs, bs->file->filename);
744 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags)
747 BDRVVmdkState *s = bs->opaque;
749 if (vmdk_open_sparse(bs, bs->file, flags) == 0) {
750 s->desc_offset = 0x200;
752 ret = vmdk_open_desc_file(bs, flags, 0);
757 /* try to open parent images, if exist */
758 ret = vmdk_parent_open(bs);
762 s->parent_cid = vmdk_read_cid(bs, 1);
763 qemu_co_mutex_init(&s->lock);
765 /* Disable migration when VMDK images are used */
766 error_set(&s->migration_blocker,
767 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
768 "vmdk", bs->device_name, "live migration");
769 migrate_add_blocker(s->migration_blocker);
774 vmdk_free_extents(bs);
778 static int get_whole_cluster(BlockDriverState *bs,
780 uint64_t cluster_offset,
784 /* 128 sectors * 512 bytes each = grain size 64KB */
785 uint8_t whole_grain[extent->cluster_sectors * 512];
787 /* we will be here if it's first write on non-exist grain(cluster).
788 * try to read from parent image, if exist */
789 if (bs->backing_hd) {
792 if (!vmdk_is_cid_valid(bs)) {
796 /* floor offset to cluster */
797 offset -= offset % (extent->cluster_sectors * 512);
798 ret = bdrv_read(bs->backing_hd, offset >> 9, whole_grain,
799 extent->cluster_sectors);
804 /* Write grain only into the active image */
805 ret = bdrv_write(extent->file, cluster_offset, whole_grain,
806 extent->cluster_sectors);
814 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data)
817 QEMU_BUILD_BUG_ON(sizeof(offset) != sizeof(m_data->offset));
818 offset = cpu_to_le32(m_data->offset);
819 /* update L2 table */
820 if (bdrv_pwrite_sync(
822 ((int64_t)m_data->l2_offset * 512)
823 + (m_data->l2_index * sizeof(m_data->offset)),
824 &offset, sizeof(offset)) < 0) {
827 /* update backup L2 table */
828 if (extent->l1_backup_table_offset != 0) {
829 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
830 if (bdrv_pwrite_sync(
832 ((int64_t)m_data->l2_offset * 512)
833 + (m_data->l2_index * sizeof(m_data->offset)),
834 &offset, sizeof(offset)) < 0) {
842 static int get_cluster_offset(BlockDriverState *bs,
844 VmdkMetaData *m_data,
847 uint64_t *cluster_offset)
849 unsigned int l1_index, l2_offset, l2_index;
851 uint32_t min_count, *l2_table;
858 *cluster_offset = extent->flat_start_offset;
862 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
863 l1_index = (offset >> 9) / extent->l1_entry_sectors;
864 if (l1_index >= extent->l1_size) {
867 l2_offset = extent->l1_table[l1_index];
871 for (i = 0; i < L2_CACHE_SIZE; i++) {
872 if (l2_offset == extent->l2_cache_offsets[i]) {
873 /* increment the hit count */
874 if (++extent->l2_cache_counts[i] == 0xffffffff) {
875 for (j = 0; j < L2_CACHE_SIZE; j++) {
876 extent->l2_cache_counts[j] >>= 1;
879 l2_table = extent->l2_cache + (i * extent->l2_size);
883 /* not found: load a new entry in the least used one */
885 min_count = 0xffffffff;
886 for (i = 0; i < L2_CACHE_SIZE; i++) {
887 if (extent->l2_cache_counts[i] < min_count) {
888 min_count = extent->l2_cache_counts[i];
892 l2_table = extent->l2_cache + (min_index * extent->l2_size);
895 (int64_t)l2_offset * 512,
897 extent->l2_size * sizeof(uint32_t)
898 ) != extent->l2_size * sizeof(uint32_t)) {
902 extent->l2_cache_offsets[min_index] = l2_offset;
903 extent->l2_cache_counts[min_index] = 1;
905 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
906 *cluster_offset = le32_to_cpu(l2_table[l2_index]);
908 if (extent->has_zero_grain && *cluster_offset == VMDK_GTE_ZEROED) {
912 if (!*cluster_offset || zeroed) {
914 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
917 /* Avoid the L2 tables update for the images that have snapshots. */
918 *cluster_offset = bdrv_getlength(extent->file);
919 if (!extent->compressed) {
922 *cluster_offset + (extent->cluster_sectors << 9)
926 *cluster_offset >>= 9;
927 l2_table[l2_index] = cpu_to_le32(*cluster_offset);
929 /* First of all we write grain itself, to avoid race condition
930 * that may to corrupt the image.
931 * This problem may occur because of insufficient space on host disk
932 * or inappropriate VM shutdown.
934 if (get_whole_cluster(
935 bs, extent, *cluster_offset, offset, allocate) == -1) {
940 m_data->offset = *cluster_offset;
941 m_data->l1_index = l1_index;
942 m_data->l2_index = l2_index;
943 m_data->l2_offset = l2_offset;
947 *cluster_offset <<= 9;
951 static VmdkExtent *find_extent(BDRVVmdkState *s,
952 int64_t sector_num, VmdkExtent *start_hint)
954 VmdkExtent *extent = start_hint;
957 extent = &s->extents[0];
959 while (extent < &s->extents[s->num_extents]) {
960 if (sector_num < extent->end_sector) {
968 static int coroutine_fn vmdk_co_is_allocated(BlockDriverState *bs,
969 int64_t sector_num, int nb_sectors, int *pnum)
971 BDRVVmdkState *s = bs->opaque;
972 int64_t index_in_cluster, n, ret;
976 extent = find_extent(s, sector_num, NULL);
980 qemu_co_mutex_lock(&s->lock);
981 ret = get_cluster_offset(bs, extent, NULL,
982 sector_num * 512, 0, &offset);
983 qemu_co_mutex_unlock(&s->lock);
985 ret = (ret == VMDK_OK || ret == VMDK_ZEROED);
987 index_in_cluster = sector_num % extent->cluster_sectors;
988 n = extent->cluster_sectors - index_in_cluster;
989 if (n > nb_sectors) {
996 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
997 int64_t offset_in_cluster, const uint8_t *buf,
998 int nb_sectors, int64_t sector_num)
1001 VmdkGrainMarker *data = NULL;
1003 const uint8_t *write_buf = buf;
1004 int write_len = nb_sectors * 512;
1006 if (extent->compressed) {
1007 if (!extent->has_marker) {
1011 buf_len = (extent->cluster_sectors << 9) * 2;
1012 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1013 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1018 data->lba = sector_num;
1019 data->size = buf_len;
1020 write_buf = (uint8_t *)data;
1021 write_len = buf_len + sizeof(VmdkGrainMarker);
1023 ret = bdrv_pwrite(extent->file,
1024 cluster_offset + offset_in_cluster,
1027 if (ret != write_len) {
1028 ret = ret < 0 ? ret : -EIO;
1037 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1038 int64_t offset_in_cluster, uint8_t *buf,
1042 int cluster_bytes, buf_bytes;
1043 uint8_t *cluster_buf, *compressed_data;
1044 uint8_t *uncomp_buf;
1046 VmdkGrainMarker *marker;
1050 if (!extent->compressed) {
1051 ret = bdrv_pread(extent->file,
1052 cluster_offset + offset_in_cluster,
1053 buf, nb_sectors * 512);
1054 if (ret == nb_sectors * 512) {
1060 cluster_bytes = extent->cluster_sectors * 512;
1061 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1062 buf_bytes = cluster_bytes * 2;
1063 cluster_buf = g_malloc(buf_bytes);
1064 uncomp_buf = g_malloc(cluster_bytes);
1065 ret = bdrv_pread(extent->file,
1067 cluster_buf, buf_bytes);
1071 compressed_data = cluster_buf;
1072 buf_len = cluster_bytes;
1073 data_len = cluster_bytes;
1074 if (extent->has_marker) {
1075 marker = (VmdkGrainMarker *)cluster_buf;
1076 compressed_data = marker->data;
1077 data_len = le32_to_cpu(marker->size);
1079 if (!data_len || data_len > buf_bytes) {
1083 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1089 if (offset_in_cluster < 0 ||
1090 offset_in_cluster + nb_sectors * 512 > buf_len) {
1094 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1099 g_free(cluster_buf);
1103 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1104 uint8_t *buf, int nb_sectors)
1106 BDRVVmdkState *s = bs->opaque;
1108 uint64_t n, index_in_cluster;
1109 uint64_t extent_begin_sector, extent_relative_sector_num;
1110 VmdkExtent *extent = NULL;
1111 uint64_t cluster_offset;
1113 while (nb_sectors > 0) {
1114 extent = find_extent(s, sector_num, extent);
1118 ret = get_cluster_offset(
1120 sector_num << 9, 0, &cluster_offset);
1121 extent_begin_sector = extent->end_sector - extent->sectors;
1122 extent_relative_sector_num = sector_num - extent_begin_sector;
1123 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1124 n = extent->cluster_sectors - index_in_cluster;
1125 if (n > nb_sectors) {
1128 if (ret != VMDK_OK) {
1129 /* if not allocated, try to read from parent image, if exist */
1130 if (bs->backing_hd && ret != VMDK_ZEROED) {
1131 if (!vmdk_is_cid_valid(bs)) {
1134 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1139 memset(buf, 0, 512 * n);
1142 ret = vmdk_read_extent(extent,
1143 cluster_offset, index_in_cluster * 512,
1156 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1157 uint8_t *buf, int nb_sectors)
1160 BDRVVmdkState *s = bs->opaque;
1161 qemu_co_mutex_lock(&s->lock);
1162 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1163 qemu_co_mutex_unlock(&s->lock);
1167 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1168 const uint8_t *buf, int nb_sectors)
1170 BDRVVmdkState *s = bs->opaque;
1171 VmdkExtent *extent = NULL;
1173 int64_t index_in_cluster;
1174 uint64_t extent_begin_sector, extent_relative_sector_num;
1175 uint64_t cluster_offset;
1176 VmdkMetaData m_data;
1178 if (sector_num > bs->total_sectors) {
1180 "(VMDK) Wrong offset: sector_num=0x%" PRIx64
1181 " total_sectors=0x%" PRIx64 "\n",
1182 sector_num, bs->total_sectors);
1186 while (nb_sectors > 0) {
1187 extent = find_extent(s, sector_num, extent);
1191 ret = get_cluster_offset(
1195 sector_num << 9, !extent->compressed,
1197 if (extent->compressed) {
1198 if (ret == VMDK_OK) {
1199 /* Refuse write to allocated cluster for streamOptimized */
1201 "VMDK: can't write to allocated cluster"
1202 " for streamOptimized\n");
1206 ret = get_cluster_offset(
1217 extent_begin_sector = extent->end_sector - extent->sectors;
1218 extent_relative_sector_num = sector_num - extent_begin_sector;
1219 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1220 n = extent->cluster_sectors - index_in_cluster;
1221 if (n > nb_sectors) {
1225 ret = vmdk_write_extent(extent,
1226 cluster_offset, index_in_cluster * 512,
1227 buf, n, sector_num);
1232 /* update L2 tables */
1233 if (vmdk_L2update(extent, &m_data) == -1) {
1241 /* update CID on the first write every time the virtual disk is
1243 if (!s->cid_updated) {
1244 ret = vmdk_write_cid(bs, time(NULL));
1248 s->cid_updated = true;
1254 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1255 const uint8_t *buf, int nb_sectors)
1258 BDRVVmdkState *s = bs->opaque;
1259 qemu_co_mutex_lock(&s->lock);
1260 ret = vmdk_write(bs, sector_num, buf, nb_sectors);
1261 qemu_co_mutex_unlock(&s->lock);
1266 static int vmdk_create_extent(const char *filename, int64_t filesize,
1267 bool flat, bool compress, bool zeroed_grain)
1272 uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
1274 fd = qemu_open(filename,
1275 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1281 ret = ftruncate(fd, filesize);
1287 magic = cpu_to_be32(VMDK4_MAGIC);
1288 memset(&header, 0, sizeof(header));
1289 header.version = zeroed_grain ? 2 : 1;
1290 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1291 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1292 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1293 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1294 header.capacity = filesize / 512;
1295 header.granularity = 128;
1296 header.num_gtes_per_gte = 512;
1298 grains = (filesize / 512 + header.granularity - 1) / header.granularity;
1299 gt_size = ((header.num_gtes_per_gte * sizeof(uint32_t)) + 511) >> 9;
1301 (grains + header.num_gtes_per_gte - 1) / header.num_gtes_per_gte;
1302 gd_size = (gt_count * sizeof(uint32_t) + 511) >> 9;
1304 header.desc_offset = 1;
1305 header.desc_size = 20;
1306 header.rgd_offset = header.desc_offset + header.desc_size;
1307 header.gd_offset = header.rgd_offset + gd_size + (gt_size * gt_count);
1308 header.grain_offset =
1309 ((header.gd_offset + gd_size + (gt_size * gt_count) +
1310 header.granularity - 1) / header.granularity) *
1312 /* swap endianness for all header fields */
1313 header.version = cpu_to_le32(header.version);
1314 header.flags = cpu_to_le32(header.flags);
1315 header.capacity = cpu_to_le64(header.capacity);
1316 header.granularity = cpu_to_le64(header.granularity);
1317 header.num_gtes_per_gte = cpu_to_le32(header.num_gtes_per_gte);
1318 header.desc_offset = cpu_to_le64(header.desc_offset);
1319 header.desc_size = cpu_to_le64(header.desc_size);
1320 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1321 header.gd_offset = cpu_to_le64(header.gd_offset);
1322 header.grain_offset = cpu_to_le64(header.grain_offset);
1323 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1325 header.check_bytes[0] = 0xa;
1326 header.check_bytes[1] = 0x20;
1327 header.check_bytes[2] = 0xd;
1328 header.check_bytes[3] = 0xa;
1330 /* write all the data */
1331 ret = qemu_write_full(fd, &magic, sizeof(magic));
1332 if (ret != sizeof(magic)) {
1336 ret = qemu_write_full(fd, &header, sizeof(header));
1337 if (ret != sizeof(header)) {
1342 ret = ftruncate(fd, le64_to_cpu(header.grain_offset) << 9);
1348 /* write grain directory */
1349 lseek(fd, le64_to_cpu(header.rgd_offset) << 9, SEEK_SET);
1350 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_size;
1351 i < gt_count; i++, tmp += gt_size) {
1352 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1353 if (ret != sizeof(tmp)) {
1359 /* write backup grain directory */
1360 lseek(fd, le64_to_cpu(header.gd_offset) << 9, SEEK_SET);
1361 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_size;
1362 i < gt_count; i++, tmp += gt_size) {
1363 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1364 if (ret != sizeof(tmp)) {
1376 static int filename_decompose(const char *filename, char *path, char *prefix,
1377 char *postfix, size_t buf_len)
1381 if (filename == NULL || !strlen(filename)) {
1382 fprintf(stderr, "Vmdk: no filename provided.\n");
1385 p = strrchr(filename, '/');
1387 p = strrchr(filename, '\\');
1390 p = strrchr(filename, ':');
1394 if (p - filename >= buf_len) {
1397 pstrcpy(path, p - filename + 1, filename);
1402 q = strrchr(p, '.');
1404 pstrcpy(prefix, buf_len, p);
1407 if (q - p >= buf_len) {
1410 pstrcpy(prefix, q - p + 1, p);
1411 pstrcpy(postfix, buf_len, q);
1416 static int relative_path(char *dest, int dest_size,
1417 const char *base, const char *target)
1423 const char *sep = "\\";
1425 const char *sep = "/";
1428 if (!(dest && base && target)) {
1431 if (path_is_absolute(target)) {
1432 pstrcpy(dest, dest_size, target);
1435 while (base[i] == target[i]) {
1448 pstrcat(dest, dest_size, "..");
1449 pstrcat(dest, dest_size, sep);
1451 pstrcat(dest, dest_size, q);
1455 static int vmdk_create(const char *filename, QEMUOptionParameter *options)
1458 char desc[BUF_SIZE];
1459 int64_t total_size = 0, filesize;
1460 const char *adapter_type = NULL;
1461 const char *backing_file = NULL;
1462 const char *fmt = NULL;
1465 bool flat, split, compress;
1466 char ext_desc_lines[BUF_SIZE] = "";
1467 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1468 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1469 const char *desc_extent_line;
1470 char parent_desc_line[BUF_SIZE] = "";
1471 uint32_t parent_cid = 0xffffffff;
1472 uint32_t number_heads = 16;
1473 bool zeroed_grain = false;
1474 const char desc_template[] =
1475 "# Disk DescriptorFile\n"
1479 "createType=\"%s\"\n"
1482 "# Extent description\n"
1485 "# The Disk Data Base\n"
1488 "ddb.virtualHWVersion = \"%d\"\n"
1489 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1490 "ddb.geometry.heads = \"%d\"\n"
1491 "ddb.geometry.sectors = \"63\"\n"
1492 "ddb.adapterType = \"%s\"\n";
1494 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX)) {
1497 /* Read out options */
1498 while (options && options->name) {
1499 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1500 total_size = options->value.n;
1501 } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {
1502 adapter_type = options->value.s;
1503 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1504 backing_file = options->value.s;
1505 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
1506 flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;
1507 } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {
1508 fmt = options->value.s;
1509 } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {
1510 zeroed_grain |= options->value.n;
1514 if (!adapter_type) {
1515 adapter_type = "ide";
1516 } else if (strcmp(adapter_type, "ide") &&
1517 strcmp(adapter_type, "buslogic") &&
1518 strcmp(adapter_type, "lsilogic") &&
1519 strcmp(adapter_type, "legacyESX")) {
1520 fprintf(stderr, "VMDK: Unknown adapter type: '%s'.\n", adapter_type);
1523 if (strcmp(adapter_type, "ide") != 0) {
1524 /* that's the number of heads with which vmware operates when
1525 creating, exporting, etc. vmdk files with a non-ide adapter type */
1529 /* Default format to monolithicSparse */
1530 fmt = "monolithicSparse";
1531 } else if (strcmp(fmt, "monolithicFlat") &&
1532 strcmp(fmt, "monolithicSparse") &&
1533 strcmp(fmt, "twoGbMaxExtentSparse") &&
1534 strcmp(fmt, "twoGbMaxExtentFlat") &&
1535 strcmp(fmt, "streamOptimized")) {
1536 fprintf(stderr, "VMDK: Unknown subformat: %s\n", fmt);
1539 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1540 strcmp(fmt, "twoGbMaxExtentSparse"));
1541 flat = !(strcmp(fmt, "monolithicFlat") &&
1542 strcmp(fmt, "twoGbMaxExtentFlat"));
1543 compress = !strcmp(fmt, "streamOptimized");
1545 desc_extent_line = "RW %lld FLAT \"%s\" 0\n";
1547 desc_extent_line = "RW %lld SPARSE \"%s\"\n";
1549 if (flat && backing_file) {
1550 /* not supporting backing file for flat image */
1554 char parent_filename[PATH_MAX];
1555 BlockDriverState *bs = bdrv_new("");
1556 ret = bdrv_open(bs, backing_file, NULL, 0, NULL);
1561 if (strcmp(bs->drv->format_name, "vmdk")) {
1565 parent_cid = vmdk_read_cid(bs, 0);
1567 relative_path(parent_filename, sizeof(parent_filename),
1568 filename, backing_file);
1569 snprintf(parent_desc_line, sizeof(parent_desc_line),
1570 "parentFileNameHint=\"%s\"", parent_filename);
1573 /* Create extents */
1574 filesize = total_size;
1575 while (filesize > 0) {
1576 char desc_line[BUF_SIZE];
1577 char ext_filename[PATH_MAX];
1578 char desc_filename[PATH_MAX];
1579 int64_t size = filesize;
1581 if (split && size > split_size) {
1585 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1586 prefix, flat ? 'f' : 's', ++idx, postfix);
1588 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1591 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1594 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1595 path, desc_filename);
1597 if (vmdk_create_extent(ext_filename, size,
1598 flat, compress, zeroed_grain)) {
1603 /* Format description line */
1604 snprintf(desc_line, sizeof(desc_line),
1605 desc_extent_line, size / 512, desc_filename);
1606 pstrcat(ext_desc_lines, sizeof(ext_desc_lines), desc_line);
1608 /* generate descriptor file */
1609 snprintf(desc, sizeof(desc), desc_template,
1610 (unsigned int)time(NULL),
1615 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1616 total_size / (int64_t)(63 * number_heads * 512), number_heads,
1618 if (split || flat) {
1619 fd = qemu_open(filename,
1620 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1623 fd = qemu_open(filename,
1624 O_WRONLY | O_BINARY | O_LARGEFILE,
1630 /* the descriptor offset = 0x200 */
1631 if (!split && !flat && 0x200 != lseek(fd, 0x200, SEEK_SET)) {
1635 ret = qemu_write_full(fd, desc, strlen(desc));
1636 if (ret != strlen(desc)) {
1646 static void vmdk_close(BlockDriverState *bs)
1648 BDRVVmdkState *s = bs->opaque;
1650 vmdk_free_extents(bs);
1652 migrate_del_blocker(s->migration_blocker);
1653 error_free(s->migration_blocker);
1656 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1658 BDRVVmdkState *s = bs->opaque;
1662 for (i = 0; i < s->num_extents; i++) {
1663 err = bdrv_co_flush(s->extents[i].file);
1671 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
1676 BDRVVmdkState *s = bs->opaque;
1678 ret = bdrv_get_allocated_file_size(bs->file);
1682 for (i = 0; i < s->num_extents; i++) {
1683 if (s->extents[i].file == bs->file) {
1686 r = bdrv_get_allocated_file_size(s->extents[i].file);
1695 static QEMUOptionParameter vmdk_create_options[] = {
1697 .name = BLOCK_OPT_SIZE,
1699 .help = "Virtual disk size"
1702 .name = BLOCK_OPT_ADAPTER_TYPE,
1704 .help = "Virtual adapter type, can be one of "
1705 "ide (default), lsilogic, buslogic or legacyESX"
1708 .name = BLOCK_OPT_BACKING_FILE,
1710 .help = "File name of a base image"
1713 .name = BLOCK_OPT_COMPAT6,
1715 .help = "VMDK version 6 image"
1718 .name = BLOCK_OPT_SUBFMT,
1721 "VMDK flat extent format, can be one of "
1722 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
1725 .name = BLOCK_OPT_ZEROED_GRAIN,
1727 .help = "Enable efficient zero writes using the zeroed-grain GTE feature"
1732 static BlockDriver bdrv_vmdk = {
1733 .format_name = "vmdk",
1734 .instance_size = sizeof(BDRVVmdkState),
1735 .bdrv_probe = vmdk_probe,
1736 .bdrv_open = vmdk_open,
1737 .bdrv_reopen_prepare = vmdk_reopen_prepare,
1738 .bdrv_read = vmdk_co_read,
1739 .bdrv_write = vmdk_co_write,
1740 .bdrv_close = vmdk_close,
1741 .bdrv_create = vmdk_create,
1742 .bdrv_co_flush_to_disk = vmdk_co_flush,
1743 .bdrv_co_is_allocated = vmdk_co_is_allocated,
1744 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
1746 .create_options = vmdk_create_options,
1749 static void bdrv_vmdk_init(void)
1751 bdrv_register(&bdrv_vmdk);
1754 block_init(bdrv_vmdk_init);