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;
127 uint32_t *l2_cache_entry;
130 typedef struct VmdkGrainMarker {
137 MARKER_END_OF_STREAM = 0,
138 MARKER_GRAIN_TABLE = 1,
139 MARKER_GRAIN_DIRECTORY = 2,
143 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
150 magic = be32_to_cpu(*(uint32_t *)buf);
151 if (magic == VMDK3_MAGIC ||
152 magic == VMDK4_MAGIC) {
155 const char *p = (const char *)buf;
156 const char *end = p + buf_size;
159 /* skip comment line */
160 while (p < end && *p != '\n') {
167 while (p < end && *p == ' ') {
170 /* skip '\r' if windows line endings used. */
171 if (p < end && *p == '\r') {
174 /* only accept blank lines before 'version=' line */
175 if (p == end || *p != '\n') {
181 if (end - p >= strlen("version=X\n")) {
182 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
183 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
187 if (end - p >= strlen("version=X\r\n")) {
188 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
189 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
201 #define SECTOR_SIZE 512
202 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
203 #define BUF_SIZE 4096
204 #define HEADER_SIZE 512 /* first sector of 512 bytes */
206 static void vmdk_free_extents(BlockDriverState *bs)
209 BDRVVmdkState *s = bs->opaque;
212 for (i = 0; i < s->num_extents; i++) {
216 g_free(e->l1_backup_table);
217 if (e->file != bs->file) {
218 bdrv_delete(e->file);
224 static void vmdk_free_last_extent(BlockDriverState *bs)
226 BDRVVmdkState *s = bs->opaque;
228 if (s->num_extents == 0) {
232 s->extents = g_realloc(s->extents, s->num_extents * sizeof(VmdkExtent));
235 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
237 char desc[DESC_SIZE];
238 uint32_t cid = 0xffffffff;
239 const char *p_name, *cid_str;
241 BDRVVmdkState *s = bs->opaque;
244 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
250 cid_str = "parentCID";
251 cid_str_size = sizeof("parentCID");
254 cid_str_size = sizeof("CID");
257 desc[DESC_SIZE - 1] = '\0';
258 p_name = strstr(desc, cid_str);
259 if (p_name != NULL) {
260 p_name += cid_str_size;
261 sscanf(p_name, "%x", &cid);
267 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
269 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
270 char *p_name, *tmp_str;
271 BDRVVmdkState *s = bs->opaque;
274 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
279 desc[DESC_SIZE - 1] = '\0';
280 tmp_str = strstr(desc, "parentCID");
281 if (tmp_str == NULL) {
285 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
286 p_name = strstr(desc, "CID");
287 if (p_name != NULL) {
288 p_name += sizeof("CID");
289 snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);
290 pstrcat(desc, sizeof(desc), tmp_desc);
293 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
301 static int vmdk_is_cid_valid(BlockDriverState *bs)
304 BDRVVmdkState *s = bs->opaque;
305 BlockDriverState *p_bs = bs->backing_hd;
309 cur_pcid = vmdk_read_cid(p_bs, 0);
310 if (s->parent_cid != cur_pcid) {
320 /* Queue extents, if any, for reopen() */
321 static int vmdk_reopen_prepare(BDRVReopenState *state,
322 BlockReopenQueue *queue, Error **errp)
329 assert(state != NULL);
330 assert(state->bs != NULL);
333 error_set(errp, ERROR_CLASS_GENERIC_ERROR,
334 "No reopen queue for VMDK extents");
338 s = state->bs->opaque;
342 for (i = 0; i < s->num_extents; i++) {
344 if (e->file != state->bs->file) {
345 bdrv_reopen_queue(queue, e->file, state->flags);
354 static int vmdk_parent_open(BlockDriverState *bs)
357 char desc[DESC_SIZE + 1];
358 BDRVVmdkState *s = bs->opaque;
361 desc[DESC_SIZE] = '\0';
362 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
367 p_name = strstr(desc, "parentFileNameHint");
368 if (p_name != NULL) {
371 p_name += sizeof("parentFileNameHint") + 1;
372 end_name = strchr(p_name, '\"');
373 if (end_name == NULL) {
376 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
380 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
386 /* Create and append extent to the extent array. Return the added VmdkExtent
387 * address. return NULL if allocation failed. */
388 static VmdkExtent *vmdk_add_extent(BlockDriverState *bs,
389 BlockDriverState *file, bool flat, int64_t sectors,
390 int64_t l1_offset, int64_t l1_backup_offset,
392 int l2_size, unsigned int cluster_sectors)
395 BDRVVmdkState *s = bs->opaque;
397 s->extents = g_realloc(s->extents,
398 (s->num_extents + 1) * sizeof(VmdkExtent));
399 extent = &s->extents[s->num_extents];
402 memset(extent, 0, sizeof(VmdkExtent));
405 extent->sectors = sectors;
406 extent->l1_table_offset = l1_offset;
407 extent->l1_backup_table_offset = l1_backup_offset;
408 extent->l1_size = l1_size;
409 extent->l1_entry_sectors = l2_size * cluster_sectors;
410 extent->l2_size = l2_size;
411 extent->cluster_sectors = cluster_sectors;
413 if (s->num_extents > 1) {
414 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
416 extent->end_sector = extent->sectors;
418 bs->total_sectors = extent->end_sector;
422 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent)
427 /* read the L1 table */
428 l1_size = extent->l1_size * sizeof(uint32_t);
429 extent->l1_table = g_malloc(l1_size);
430 ret = bdrv_pread(extent->file,
431 extent->l1_table_offset,
437 for (i = 0; i < extent->l1_size; i++) {
438 le32_to_cpus(&extent->l1_table[i]);
441 if (extent->l1_backup_table_offset) {
442 extent->l1_backup_table = g_malloc(l1_size);
443 ret = bdrv_pread(extent->file,
444 extent->l1_backup_table_offset,
445 extent->l1_backup_table,
450 for (i = 0; i < extent->l1_size; i++) {
451 le32_to_cpus(&extent->l1_backup_table[i]);
456 g_malloc(extent->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
459 g_free(extent->l1_backup_table);
461 g_free(extent->l1_table);
465 static int vmdk_open_vmdk3(BlockDriverState *bs,
466 BlockDriverState *file,
474 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
478 extent = vmdk_add_extent(bs,
480 le32_to_cpu(header.disk_sectors),
481 le32_to_cpu(header.l1dir_offset) << 9,
483 le32_to_cpu(header.granularity));
484 ret = vmdk_init_tables(bs, extent);
486 /* free extent allocated by vmdk_add_extent */
487 vmdk_free_last_extent(bs);
492 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
493 int64_t desc_offset);
495 static int vmdk_open_vmdk4(BlockDriverState *bs,
496 BlockDriverState *file,
501 uint32_t l1_size, l1_entry_sectors;
504 int64_t l1_backup_offset = 0;
506 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
510 if (header.capacity == 0) {
511 int64_t desc_offset = le64_to_cpu(header.desc_offset);
513 return vmdk_open_desc_file(bs, flags, desc_offset << 9);
517 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
519 * The footer takes precedence over the header, so read it in. The
520 * footer starts at offset -1024 from the end: One sector for the
521 * footer, and another one for the end-of-stream marker.
528 uint8_t pad[512 - 16];
529 } QEMU_PACKED footer_marker;
533 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
539 uint8_t pad[512 - 16];
540 } QEMU_PACKED eos_marker;
541 } QEMU_PACKED footer;
543 ret = bdrv_pread(file,
544 bs->file->total_sectors * 512 - 1536,
545 &footer, sizeof(footer));
550 /* Some sanity checks for the footer */
551 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
552 le32_to_cpu(footer.footer_marker.size) != 0 ||
553 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
554 le64_to_cpu(footer.eos_marker.val) != 0 ||
555 le32_to_cpu(footer.eos_marker.size) != 0 ||
556 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
561 header = footer.header;
564 if (le32_to_cpu(header.version) >= 3) {
566 snprintf(buf, sizeof(buf), "VMDK version %d",
567 le32_to_cpu(header.version));
568 qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
569 bs->device_name, "vmdk", buf);
573 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gte)
574 * le64_to_cpu(header.granularity);
575 if (l1_entry_sectors == 0) {
578 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
580 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
581 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
583 extent = vmdk_add_extent(bs, file, false,
584 le64_to_cpu(header.capacity),
585 le64_to_cpu(header.gd_offset) << 9,
588 le32_to_cpu(header.num_gtes_per_gte),
589 le64_to_cpu(header.granularity));
591 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
592 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
593 extent->version = le32_to_cpu(header.version);
594 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
595 ret = vmdk_init_tables(bs, extent);
597 /* free extent allocated by vmdk_add_extent */
598 vmdk_free_last_extent(bs);
603 /* find an option value out of descriptor file */
604 static int vmdk_parse_description(const char *desc, const char *opt_name,
605 char *buf, int buf_size)
607 char *opt_pos, *opt_end;
608 const char *end = desc + strlen(desc);
610 opt_pos = strstr(desc, opt_name);
614 /* Skip "=\"" following opt_name */
615 opt_pos += strlen(opt_name) + 2;
616 if (opt_pos >= end) {
620 while (opt_end < end && *opt_end != '"') {
623 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
626 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
630 /* Open an extent file and append to bs array */
631 static int vmdk_open_sparse(BlockDriverState *bs,
632 BlockDriverState *file,
637 if (bdrv_pread(file, 0, &magic, sizeof(magic)) != sizeof(magic)) {
641 magic = be32_to_cpu(magic);
644 return vmdk_open_vmdk3(bs, file, flags);
647 return vmdk_open_vmdk4(bs, file, flags);
655 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
656 const char *desc_file_path)
662 const char *p = desc;
665 char extent_path[PATH_MAX];
666 BlockDriverState *extent_file;
669 /* parse extent line:
670 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
672 * RW [size in sectors] SPARSE "file-name.vmdk"
675 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
676 access, §ors, type, fname, &flat_offset);
677 if (ret < 4 || strcmp(access, "RW")) {
679 } else if (!strcmp(type, "FLAT")) {
680 if (ret != 5 || flat_offset < 0) {
683 } else if (ret != 4) {
688 (strcmp(type, "FLAT") && strcmp(type, "SPARSE")) ||
689 (strcmp(access, "RW"))) {
693 path_combine(extent_path, sizeof(extent_path),
694 desc_file_path, fname);
695 ret = bdrv_file_open(&extent_file, extent_path, NULL, bs->open_flags);
700 /* save to extents array */
701 if (!strcmp(type, "FLAT")) {
705 extent = vmdk_add_extent(bs, extent_file, true, sectors,
706 0, 0, 0, 0, sectors);
707 extent->flat_start_offset = flat_offset << 9;
708 } else if (!strcmp(type, "SPARSE")) {
710 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags);
712 bdrv_delete(extent_file);
717 "VMDK: Not supported extent type \"%s\""".\n", type);
721 /* move to next line */
722 while (*p && *p != '\n') {
730 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
736 BDRVVmdkState *s = bs->opaque;
739 size = bdrv_getlength(bs->file);
744 size = MIN(size, 1 << 20); /* avoid unbounded allocation */
745 buf = g_malloc0(size + 1);
747 ret = bdrv_pread(bs->file, desc_offset, buf, size);
751 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
755 if (strcmp(ct, "monolithicFlat") &&
756 strcmp(ct, "twoGbMaxExtentSparse") &&
757 strcmp(ct, "twoGbMaxExtentFlat")) {
759 "VMDK: Not supported image type \"%s\""".\n", ct);
764 ret = vmdk_parse_extents(buf, bs, bs->file->filename);
770 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags)
773 BDRVVmdkState *s = bs->opaque;
775 if (vmdk_open_sparse(bs, bs->file, flags) == 0) {
776 s->desc_offset = 0x200;
778 ret = vmdk_open_desc_file(bs, flags, 0);
783 /* try to open parent images, if exist */
784 ret = vmdk_parent_open(bs);
788 s->parent_cid = vmdk_read_cid(bs, 1);
789 qemu_co_mutex_init(&s->lock);
791 /* Disable migration when VMDK images are used */
792 error_set(&s->migration_blocker,
793 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
794 "vmdk", bs->device_name, "live migration");
795 migrate_add_blocker(s->migration_blocker);
800 vmdk_free_extents(bs);
804 static int get_whole_cluster(BlockDriverState *bs,
806 uint64_t cluster_offset,
810 /* 128 sectors * 512 bytes each = grain size 64KB */
811 uint8_t whole_grain[extent->cluster_sectors * 512];
813 /* we will be here if it's first write on non-exist grain(cluster).
814 * try to read from parent image, if exist */
815 if (bs->backing_hd) {
818 if (!vmdk_is_cid_valid(bs)) {
822 /* floor offset to cluster */
823 offset -= offset % (extent->cluster_sectors * 512);
824 ret = bdrv_read(bs->backing_hd, offset >> 9, whole_grain,
825 extent->cluster_sectors);
830 /* Write grain only into the active image */
831 ret = bdrv_write(extent->file, cluster_offset, whole_grain,
832 extent->cluster_sectors);
840 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data)
843 QEMU_BUILD_BUG_ON(sizeof(offset) != sizeof(m_data->offset));
844 offset = cpu_to_le32(m_data->offset);
845 /* update L2 table */
846 if (bdrv_pwrite_sync(
848 ((int64_t)m_data->l2_offset * 512)
849 + (m_data->l2_index * sizeof(m_data->offset)),
850 &offset, sizeof(offset)) < 0) {
853 /* update backup L2 table */
854 if (extent->l1_backup_table_offset != 0) {
855 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
856 if (bdrv_pwrite_sync(
858 ((int64_t)m_data->l2_offset * 512)
859 + (m_data->l2_index * sizeof(m_data->offset)),
860 &offset, sizeof(offset)) < 0) {
864 if (m_data->l2_cache_entry) {
865 *m_data->l2_cache_entry = offset;
871 static int get_cluster_offset(BlockDriverState *bs,
873 VmdkMetaData *m_data,
876 uint64_t *cluster_offset)
878 unsigned int l1_index, l2_offset, l2_index;
880 uint32_t min_count, *l2_table;
887 *cluster_offset = extent->flat_start_offset;
891 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
892 l1_index = (offset >> 9) / extent->l1_entry_sectors;
893 if (l1_index >= extent->l1_size) {
896 l2_offset = extent->l1_table[l1_index];
900 for (i = 0; i < L2_CACHE_SIZE; i++) {
901 if (l2_offset == extent->l2_cache_offsets[i]) {
902 /* increment the hit count */
903 if (++extent->l2_cache_counts[i] == 0xffffffff) {
904 for (j = 0; j < L2_CACHE_SIZE; j++) {
905 extent->l2_cache_counts[j] >>= 1;
908 l2_table = extent->l2_cache + (i * extent->l2_size);
912 /* not found: load a new entry in the least used one */
914 min_count = 0xffffffff;
915 for (i = 0; i < L2_CACHE_SIZE; i++) {
916 if (extent->l2_cache_counts[i] < min_count) {
917 min_count = extent->l2_cache_counts[i];
921 l2_table = extent->l2_cache + (min_index * extent->l2_size);
924 (int64_t)l2_offset * 512,
926 extent->l2_size * sizeof(uint32_t)
927 ) != extent->l2_size * sizeof(uint32_t)) {
931 extent->l2_cache_offsets[min_index] = l2_offset;
932 extent->l2_cache_counts[min_index] = 1;
934 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
935 *cluster_offset = le32_to_cpu(l2_table[l2_index]);
939 m_data->l1_index = l1_index;
940 m_data->l2_index = l2_index;
941 m_data->offset = *cluster_offset;
942 m_data->l2_offset = l2_offset;
943 m_data->l2_cache_entry = &l2_table[l2_index];
945 if (extent->has_zero_grain && *cluster_offset == VMDK_GTE_ZEROED) {
949 if (!*cluster_offset || zeroed) {
951 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
954 /* Avoid the L2 tables update for the images that have snapshots. */
955 *cluster_offset = bdrv_getlength(extent->file);
956 if (!extent->compressed) {
959 *cluster_offset + (extent->cluster_sectors << 9)
963 *cluster_offset >>= 9;
964 l2_table[l2_index] = cpu_to_le32(*cluster_offset);
966 /* First of all we write grain itself, to avoid race condition
967 * that may to corrupt the image.
968 * This problem may occur because of insufficient space on host disk
969 * or inappropriate VM shutdown.
971 if (get_whole_cluster(
972 bs, extent, *cluster_offset, offset, allocate) == -1) {
977 m_data->offset = *cluster_offset;
980 *cluster_offset <<= 9;
984 static VmdkExtent *find_extent(BDRVVmdkState *s,
985 int64_t sector_num, VmdkExtent *start_hint)
987 VmdkExtent *extent = start_hint;
990 extent = &s->extents[0];
992 while (extent < &s->extents[s->num_extents]) {
993 if (sector_num < extent->end_sector) {
1001 static int coroutine_fn vmdk_co_is_allocated(BlockDriverState *bs,
1002 int64_t sector_num, int nb_sectors, int *pnum)
1004 BDRVVmdkState *s = bs->opaque;
1005 int64_t index_in_cluster, n, ret;
1009 extent = find_extent(s, sector_num, NULL);
1013 qemu_co_mutex_lock(&s->lock);
1014 ret = get_cluster_offset(bs, extent, NULL,
1015 sector_num * 512, 0, &offset);
1016 qemu_co_mutex_unlock(&s->lock);
1018 ret = (ret == VMDK_OK || ret == VMDK_ZEROED);
1020 index_in_cluster = sector_num % extent->cluster_sectors;
1021 n = extent->cluster_sectors - index_in_cluster;
1022 if (n > nb_sectors) {
1029 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1030 int64_t offset_in_cluster, const uint8_t *buf,
1031 int nb_sectors, int64_t sector_num)
1034 VmdkGrainMarker *data = NULL;
1036 const uint8_t *write_buf = buf;
1037 int write_len = nb_sectors * 512;
1039 if (extent->compressed) {
1040 if (!extent->has_marker) {
1044 buf_len = (extent->cluster_sectors << 9) * 2;
1045 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1046 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1051 data->lba = sector_num;
1052 data->size = buf_len;
1053 write_buf = (uint8_t *)data;
1054 write_len = buf_len + sizeof(VmdkGrainMarker);
1056 ret = bdrv_pwrite(extent->file,
1057 cluster_offset + offset_in_cluster,
1060 if (ret != write_len) {
1061 ret = ret < 0 ? ret : -EIO;
1070 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1071 int64_t offset_in_cluster, uint8_t *buf,
1075 int cluster_bytes, buf_bytes;
1076 uint8_t *cluster_buf, *compressed_data;
1077 uint8_t *uncomp_buf;
1079 VmdkGrainMarker *marker;
1083 if (!extent->compressed) {
1084 ret = bdrv_pread(extent->file,
1085 cluster_offset + offset_in_cluster,
1086 buf, nb_sectors * 512);
1087 if (ret == nb_sectors * 512) {
1093 cluster_bytes = extent->cluster_sectors * 512;
1094 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1095 buf_bytes = cluster_bytes * 2;
1096 cluster_buf = g_malloc(buf_bytes);
1097 uncomp_buf = g_malloc(cluster_bytes);
1098 ret = bdrv_pread(extent->file,
1100 cluster_buf, buf_bytes);
1104 compressed_data = cluster_buf;
1105 buf_len = cluster_bytes;
1106 data_len = cluster_bytes;
1107 if (extent->has_marker) {
1108 marker = (VmdkGrainMarker *)cluster_buf;
1109 compressed_data = marker->data;
1110 data_len = le32_to_cpu(marker->size);
1112 if (!data_len || data_len > buf_bytes) {
1116 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1122 if (offset_in_cluster < 0 ||
1123 offset_in_cluster + nb_sectors * 512 > buf_len) {
1127 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1132 g_free(cluster_buf);
1136 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1137 uint8_t *buf, int nb_sectors)
1139 BDRVVmdkState *s = bs->opaque;
1141 uint64_t n, index_in_cluster;
1142 uint64_t extent_begin_sector, extent_relative_sector_num;
1143 VmdkExtent *extent = NULL;
1144 uint64_t cluster_offset;
1146 while (nb_sectors > 0) {
1147 extent = find_extent(s, sector_num, extent);
1151 ret = get_cluster_offset(
1153 sector_num << 9, 0, &cluster_offset);
1154 extent_begin_sector = extent->end_sector - extent->sectors;
1155 extent_relative_sector_num = sector_num - extent_begin_sector;
1156 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1157 n = extent->cluster_sectors - index_in_cluster;
1158 if (n > nb_sectors) {
1161 if (ret != VMDK_OK) {
1162 /* if not allocated, try to read from parent image, if exist */
1163 if (bs->backing_hd && ret != VMDK_ZEROED) {
1164 if (!vmdk_is_cid_valid(bs)) {
1167 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1172 memset(buf, 0, 512 * n);
1175 ret = vmdk_read_extent(extent,
1176 cluster_offset, index_in_cluster * 512,
1189 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1190 uint8_t *buf, int nb_sectors)
1193 BDRVVmdkState *s = bs->opaque;
1194 qemu_co_mutex_lock(&s->lock);
1195 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1196 qemu_co_mutex_unlock(&s->lock);
1202 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1203 * if possible, otherwise return -ENOTSUP.
1204 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just
1206 * Returns: error code with 0 for success.
1208 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1209 const uint8_t *buf, int nb_sectors,
1210 bool zeroed, bool zero_dry_run)
1212 BDRVVmdkState *s = bs->opaque;
1213 VmdkExtent *extent = NULL;
1215 int64_t index_in_cluster;
1216 uint64_t extent_begin_sector, extent_relative_sector_num;
1217 uint64_t cluster_offset;
1218 VmdkMetaData m_data;
1220 if (sector_num > bs->total_sectors) {
1222 "(VMDK) Wrong offset: sector_num=0x%" PRIx64
1223 " total_sectors=0x%" PRIx64 "\n",
1224 sector_num, bs->total_sectors);
1228 while (nb_sectors > 0) {
1229 extent = find_extent(s, sector_num, extent);
1233 ret = get_cluster_offset(
1237 sector_num << 9, !extent->compressed,
1239 if (extent->compressed) {
1240 if (ret == VMDK_OK) {
1241 /* Refuse write to allocated cluster for streamOptimized */
1243 "VMDK: can't write to allocated cluster"
1244 " for streamOptimized\n");
1248 ret = get_cluster_offset(
1256 if (ret == VMDK_ERROR) {
1259 extent_begin_sector = extent->end_sector - extent->sectors;
1260 extent_relative_sector_num = sector_num - extent_begin_sector;
1261 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1262 n = extent->cluster_sectors - index_in_cluster;
1263 if (n > nb_sectors) {
1267 /* Do zeroed write, buf is ignored */
1268 if (extent->has_zero_grain &&
1269 index_in_cluster == 0 &&
1270 n >= extent->cluster_sectors) {
1271 n = extent->cluster_sectors;
1272 if (!zero_dry_run) {
1273 m_data.offset = VMDK_GTE_ZEROED;
1274 /* update L2 tables */
1275 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1283 ret = vmdk_write_extent(extent,
1284 cluster_offset, index_in_cluster * 512,
1285 buf, n, sector_num);
1290 /* update L2 tables */
1291 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1300 /* update CID on the first write every time the virtual disk is
1302 if (!s->cid_updated) {
1303 ret = vmdk_write_cid(bs, time(NULL));
1307 s->cid_updated = true;
1313 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1314 const uint8_t *buf, int nb_sectors)
1317 BDRVVmdkState *s = bs->opaque;
1318 qemu_co_mutex_lock(&s->lock);
1319 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1320 qemu_co_mutex_unlock(&s->lock);
1324 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1329 BDRVVmdkState *s = bs->opaque;
1330 qemu_co_mutex_lock(&s->lock);
1331 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1333 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1335 qemu_co_mutex_unlock(&s->lock);
1340 static int vmdk_create_extent(const char *filename, int64_t filesize,
1341 bool flat, bool compress, bool zeroed_grain)
1346 uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
1348 fd = qemu_open(filename,
1349 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1355 ret = ftruncate(fd, filesize);
1361 magic = cpu_to_be32(VMDK4_MAGIC);
1362 memset(&header, 0, sizeof(header));
1363 header.version = zeroed_grain ? 2 : 1;
1364 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1365 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1366 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1367 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1368 header.capacity = filesize / 512;
1369 header.granularity = 128;
1370 header.num_gtes_per_gte = 512;
1372 grains = (filesize / 512 + header.granularity - 1) / header.granularity;
1373 gt_size = ((header.num_gtes_per_gte * sizeof(uint32_t)) + 511) >> 9;
1375 (grains + header.num_gtes_per_gte - 1) / header.num_gtes_per_gte;
1376 gd_size = (gt_count * sizeof(uint32_t) + 511) >> 9;
1378 header.desc_offset = 1;
1379 header.desc_size = 20;
1380 header.rgd_offset = header.desc_offset + header.desc_size;
1381 header.gd_offset = header.rgd_offset + gd_size + (gt_size * gt_count);
1382 header.grain_offset =
1383 ((header.gd_offset + gd_size + (gt_size * gt_count) +
1384 header.granularity - 1) / header.granularity) *
1386 /* swap endianness for all header fields */
1387 header.version = cpu_to_le32(header.version);
1388 header.flags = cpu_to_le32(header.flags);
1389 header.capacity = cpu_to_le64(header.capacity);
1390 header.granularity = cpu_to_le64(header.granularity);
1391 header.num_gtes_per_gte = cpu_to_le32(header.num_gtes_per_gte);
1392 header.desc_offset = cpu_to_le64(header.desc_offset);
1393 header.desc_size = cpu_to_le64(header.desc_size);
1394 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1395 header.gd_offset = cpu_to_le64(header.gd_offset);
1396 header.grain_offset = cpu_to_le64(header.grain_offset);
1397 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1399 header.check_bytes[0] = 0xa;
1400 header.check_bytes[1] = 0x20;
1401 header.check_bytes[2] = 0xd;
1402 header.check_bytes[3] = 0xa;
1404 /* write all the data */
1405 ret = qemu_write_full(fd, &magic, sizeof(magic));
1406 if (ret != sizeof(magic)) {
1410 ret = qemu_write_full(fd, &header, sizeof(header));
1411 if (ret != sizeof(header)) {
1416 ret = ftruncate(fd, le64_to_cpu(header.grain_offset) << 9);
1422 /* write grain directory */
1423 lseek(fd, le64_to_cpu(header.rgd_offset) << 9, SEEK_SET);
1424 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_size;
1425 i < gt_count; i++, tmp += gt_size) {
1426 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1427 if (ret != sizeof(tmp)) {
1433 /* write backup grain directory */
1434 lseek(fd, le64_to_cpu(header.gd_offset) << 9, SEEK_SET);
1435 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_size;
1436 i < gt_count; i++, tmp += gt_size) {
1437 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1438 if (ret != sizeof(tmp)) {
1450 static int filename_decompose(const char *filename, char *path, char *prefix,
1451 char *postfix, size_t buf_len)
1455 if (filename == NULL || !strlen(filename)) {
1456 fprintf(stderr, "Vmdk: no filename provided.\n");
1459 p = strrchr(filename, '/');
1461 p = strrchr(filename, '\\');
1464 p = strrchr(filename, ':');
1468 if (p - filename >= buf_len) {
1471 pstrcpy(path, p - filename + 1, filename);
1476 q = strrchr(p, '.');
1478 pstrcpy(prefix, buf_len, p);
1481 if (q - p >= buf_len) {
1484 pstrcpy(prefix, q - p + 1, p);
1485 pstrcpy(postfix, buf_len, q);
1490 static int vmdk_create(const char *filename, QEMUOptionParameter *options)
1493 char desc[BUF_SIZE];
1494 int64_t total_size = 0, filesize;
1495 const char *adapter_type = NULL;
1496 const char *backing_file = NULL;
1497 const char *fmt = NULL;
1500 bool flat, split, compress;
1501 char ext_desc_lines[BUF_SIZE] = "";
1502 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1503 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1504 const char *desc_extent_line;
1505 char parent_desc_line[BUF_SIZE] = "";
1506 uint32_t parent_cid = 0xffffffff;
1507 uint32_t number_heads = 16;
1508 bool zeroed_grain = false;
1509 const char desc_template[] =
1510 "# Disk DescriptorFile\n"
1514 "createType=\"%s\"\n"
1517 "# Extent description\n"
1520 "# The Disk Data Base\n"
1523 "ddb.virtualHWVersion = \"%d\"\n"
1524 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1525 "ddb.geometry.heads = \"%d\"\n"
1526 "ddb.geometry.sectors = \"63\"\n"
1527 "ddb.adapterType = \"%s\"\n";
1529 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX)) {
1532 /* Read out options */
1533 while (options && options->name) {
1534 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1535 total_size = options->value.n;
1536 } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {
1537 adapter_type = options->value.s;
1538 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1539 backing_file = options->value.s;
1540 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
1541 flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;
1542 } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {
1543 fmt = options->value.s;
1544 } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {
1545 zeroed_grain |= options->value.n;
1549 if (!adapter_type) {
1550 adapter_type = "ide";
1551 } else if (strcmp(adapter_type, "ide") &&
1552 strcmp(adapter_type, "buslogic") &&
1553 strcmp(adapter_type, "lsilogic") &&
1554 strcmp(adapter_type, "legacyESX")) {
1555 fprintf(stderr, "VMDK: Unknown adapter type: '%s'.\n", adapter_type);
1558 if (strcmp(adapter_type, "ide") != 0) {
1559 /* that's the number of heads with which vmware operates when
1560 creating, exporting, etc. vmdk files with a non-ide adapter type */
1564 /* Default format to monolithicSparse */
1565 fmt = "monolithicSparse";
1566 } else if (strcmp(fmt, "monolithicFlat") &&
1567 strcmp(fmt, "monolithicSparse") &&
1568 strcmp(fmt, "twoGbMaxExtentSparse") &&
1569 strcmp(fmt, "twoGbMaxExtentFlat") &&
1570 strcmp(fmt, "streamOptimized")) {
1571 fprintf(stderr, "VMDK: Unknown subformat: %s\n", fmt);
1574 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1575 strcmp(fmt, "twoGbMaxExtentSparse"));
1576 flat = !(strcmp(fmt, "monolithicFlat") &&
1577 strcmp(fmt, "twoGbMaxExtentFlat"));
1578 compress = !strcmp(fmt, "streamOptimized");
1580 desc_extent_line = "RW %lld FLAT \"%s\" 0\n";
1582 desc_extent_line = "RW %lld SPARSE \"%s\"\n";
1584 if (flat && backing_file) {
1585 /* not supporting backing file for flat image */
1589 BlockDriverState *bs = bdrv_new("");
1590 ret = bdrv_open(bs, backing_file, NULL, 0, NULL);
1595 if (strcmp(bs->drv->format_name, "vmdk")) {
1599 parent_cid = vmdk_read_cid(bs, 0);
1601 snprintf(parent_desc_line, sizeof(parent_desc_line),
1602 "parentFileNameHint=\"%s\"", backing_file);
1605 /* Create extents */
1606 filesize = total_size;
1607 while (filesize > 0) {
1608 char desc_line[BUF_SIZE];
1609 char ext_filename[PATH_MAX];
1610 char desc_filename[PATH_MAX];
1611 int64_t size = filesize;
1613 if (split && size > split_size) {
1617 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1618 prefix, flat ? 'f' : 's', ++idx, postfix);
1620 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1623 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1626 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1627 path, desc_filename);
1629 if (vmdk_create_extent(ext_filename, size,
1630 flat, compress, zeroed_grain)) {
1635 /* Format description line */
1636 snprintf(desc_line, sizeof(desc_line),
1637 desc_extent_line, size / 512, desc_filename);
1638 pstrcat(ext_desc_lines, sizeof(ext_desc_lines), desc_line);
1640 /* generate descriptor file */
1641 snprintf(desc, sizeof(desc), desc_template,
1642 (unsigned int)time(NULL),
1647 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1648 total_size / (int64_t)(63 * number_heads * 512), number_heads,
1650 if (split || flat) {
1651 fd = qemu_open(filename,
1652 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1655 fd = qemu_open(filename,
1656 O_WRONLY | O_BINARY | O_LARGEFILE,
1662 /* the descriptor offset = 0x200 */
1663 if (!split && !flat && 0x200 != lseek(fd, 0x200, SEEK_SET)) {
1667 ret = qemu_write_full(fd, desc, strlen(desc));
1668 if (ret != strlen(desc)) {
1678 static void vmdk_close(BlockDriverState *bs)
1680 BDRVVmdkState *s = bs->opaque;
1682 vmdk_free_extents(bs);
1684 migrate_del_blocker(s->migration_blocker);
1685 error_free(s->migration_blocker);
1688 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1690 BDRVVmdkState *s = bs->opaque;
1694 for (i = 0; i < s->num_extents; i++) {
1695 err = bdrv_co_flush(s->extents[i].file);
1703 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
1708 BDRVVmdkState *s = bs->opaque;
1710 ret = bdrv_get_allocated_file_size(bs->file);
1714 for (i = 0; i < s->num_extents; i++) {
1715 if (s->extents[i].file == bs->file) {
1718 r = bdrv_get_allocated_file_size(s->extents[i].file);
1727 static QEMUOptionParameter vmdk_create_options[] = {
1729 .name = BLOCK_OPT_SIZE,
1731 .help = "Virtual disk size"
1734 .name = BLOCK_OPT_ADAPTER_TYPE,
1736 .help = "Virtual adapter type, can be one of "
1737 "ide (default), lsilogic, buslogic or legacyESX"
1740 .name = BLOCK_OPT_BACKING_FILE,
1742 .help = "File name of a base image"
1745 .name = BLOCK_OPT_COMPAT6,
1747 .help = "VMDK version 6 image"
1750 .name = BLOCK_OPT_SUBFMT,
1753 "VMDK flat extent format, can be one of "
1754 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
1757 .name = BLOCK_OPT_ZEROED_GRAIN,
1759 .help = "Enable efficient zero writes using the zeroed-grain GTE feature"
1764 static BlockDriver bdrv_vmdk = {
1765 .format_name = "vmdk",
1766 .instance_size = sizeof(BDRVVmdkState),
1767 .bdrv_probe = vmdk_probe,
1768 .bdrv_open = vmdk_open,
1769 .bdrv_reopen_prepare = vmdk_reopen_prepare,
1770 .bdrv_read = vmdk_co_read,
1771 .bdrv_write = vmdk_co_write,
1772 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
1773 .bdrv_close = vmdk_close,
1774 .bdrv_create = vmdk_create,
1775 .bdrv_co_flush_to_disk = vmdk_co_flush,
1776 .bdrv_co_is_allocated = vmdk_co_is_allocated,
1777 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
1779 .create_options = vmdk_create_options,
1782 static void bdrv_vmdk_init(void)
1784 bdrv_register(&bdrv_vmdk);
1787 block_init(bdrv_vmdk_init);