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/osdep.h"
27 #include "qapi/error.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qemu/error-report.h"
32 #include "qemu/module.h"
33 #include "qemu/option.h"
34 #include "qemu/bswap.h"
35 #include "migration/blocker.h"
36 #include "qemu/cutils.h"
39 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
40 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
41 #define VMDK4_COMPRESSION_DEFLATE 1
42 #define VMDK4_FLAG_NL_DETECT (1 << 0)
43 #define VMDK4_FLAG_RGD (1 << 1)
44 /* Zeroed-grain enable bit */
45 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
46 #define VMDK4_FLAG_COMPRESS (1 << 16)
47 #define VMDK4_FLAG_MARKER (1 << 17)
48 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
50 #define VMDK_EXTENT_MAX_SECTORS (1ULL << 32)
52 #define VMDK_GTE_ZEROED 0x1
54 /* VMDK internal error codes */
56 #define VMDK_ERROR (-1)
57 /* Cluster not allocated */
58 #define VMDK_UNALLOC (-2)
59 #define VMDK_ZEROED (-3)
61 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
66 uint32_t disk_sectors;
68 uint32_t l1dir_offset;
70 uint32_t file_sectors;
73 uint32_t sectors_per_track;
74 } QEMU_PACKED VMDK3Header;
83 /* Number of GrainTableEntries per GrainTable */
84 uint32_t num_gtes_per_gt;
87 uint64_t grain_offset;
90 uint16_t compressAlgorithm;
91 } QEMU_PACKED VMDK4Header;
93 #define L2_CACHE_SIZE 16
95 typedef struct VmdkExtent {
104 int64_t flat_start_offset;
105 int64_t l1_table_offset;
106 int64_t l1_backup_table_offset;
108 uint32_t *l1_backup_table;
109 unsigned int l1_size;
110 uint32_t l1_entry_sectors;
112 unsigned int l2_size;
114 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
115 uint32_t l2_cache_counts[L2_CACHE_SIZE];
117 int64_t cluster_sectors;
118 int64_t next_cluster_sector;
122 typedef struct BDRVVmdkState {
124 uint64_t desc_offset;
130 /* Extent array with num_extents entries, ascend ordered by address */
132 Error *migration_blocker;
136 typedef struct VmdkMetaData {
137 unsigned int l1_index;
138 unsigned int l2_index;
139 unsigned int l2_offset;
141 uint32_t *l2_cache_entry;
144 typedef struct VmdkGrainMarker {
148 } QEMU_PACKED VmdkGrainMarker;
151 MARKER_END_OF_STREAM = 0,
152 MARKER_GRAIN_TABLE = 1,
153 MARKER_GRAIN_DIRECTORY = 2,
157 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
164 magic = be32_to_cpu(*(uint32_t *)buf);
165 if (magic == VMDK3_MAGIC ||
166 magic == VMDK4_MAGIC) {
169 const char *p = (const char *)buf;
170 const char *end = p + buf_size;
173 /* skip comment line */
174 while (p < end && *p != '\n') {
181 while (p < end && *p == ' ') {
184 /* skip '\r' if windows line endings used. */
185 if (p < end && *p == '\r') {
188 /* only accept blank lines before 'version=' line */
189 if (p == end || *p != '\n') {
195 if (end - p >= strlen("version=X\n")) {
196 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
197 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
201 if (end - p >= strlen("version=X\r\n")) {
202 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
203 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
213 #define SECTOR_SIZE 512
214 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
215 #define BUF_SIZE 4096
216 #define HEADER_SIZE 512 /* first sector of 512 bytes */
218 static void vmdk_free_extents(BlockDriverState *bs)
221 BDRVVmdkState *s = bs->opaque;
224 for (i = 0; i < s->num_extents; i++) {
228 g_free(e->l1_backup_table);
230 if (e->file != bs->file) {
231 bdrv_unref_child(bs, e->file);
237 static void vmdk_free_last_extent(BlockDriverState *bs)
239 BDRVVmdkState *s = bs->opaque;
241 if (s->num_extents == 0) {
245 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
248 /* Return -ve errno, or 0 on success and write CID into *pcid. */
249 static int vmdk_read_cid(BlockDriverState *bs, int parent, uint32_t *pcid)
253 const char *p_name, *cid_str;
255 BDRVVmdkState *s = bs->opaque;
258 desc = g_malloc0(DESC_SIZE);
259 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
265 cid_str = "parentCID";
266 cid_str_size = sizeof("parentCID");
269 cid_str_size = sizeof("CID");
272 desc[DESC_SIZE - 1] = '\0';
273 p_name = strstr(desc, cid_str);
274 if (p_name == NULL) {
278 p_name += cid_str_size;
279 if (sscanf(p_name, "%" SCNx32, &cid) != 1) {
291 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
293 char *desc, *tmp_desc;
294 char *p_name, *tmp_str;
295 BDRVVmdkState *s = bs->opaque;
298 desc = g_malloc0(DESC_SIZE);
299 tmp_desc = g_malloc0(DESC_SIZE);
300 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
305 desc[DESC_SIZE - 1] = '\0';
306 tmp_str = strstr(desc, "parentCID");
307 if (tmp_str == NULL) {
312 pstrcpy(tmp_desc, DESC_SIZE, tmp_str);
313 p_name = strstr(desc, "CID");
314 if (p_name != NULL) {
315 p_name += sizeof("CID");
316 snprintf(p_name, DESC_SIZE - (p_name - desc), "%" PRIx32 "\n", cid);
317 pstrcat(desc, DESC_SIZE, tmp_desc);
320 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
328 static int vmdk_is_cid_valid(BlockDriverState *bs)
330 BDRVVmdkState *s = bs->opaque;
333 if (!s->cid_checked && bs->backing) {
334 BlockDriverState *p_bs = bs->backing->bs;
336 if (strcmp(p_bs->drv->format_name, "vmdk")) {
337 /* Backing file is not in vmdk format, so it does not have
338 * a CID, which makes the overlay's parent CID invalid */
342 if (vmdk_read_cid(p_bs, 0, &cur_pcid) != 0) {
343 /* read failure: report as not valid */
346 if (s->parent_cid != cur_pcid) {
351 s->cid_checked = true;
356 /* We have nothing to do for VMDK reopen, stubs just return success */
357 static int vmdk_reopen_prepare(BDRVReopenState *state,
358 BlockReopenQueue *queue, Error **errp)
360 assert(state != NULL);
361 assert(state->bs != NULL);
365 static int vmdk_parent_open(BlockDriverState *bs)
369 BDRVVmdkState *s = bs->opaque;
372 desc = g_malloc0(DESC_SIZE + 1);
373 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
379 p_name = strstr(desc, "parentFileNameHint");
380 if (p_name != NULL) {
383 p_name += sizeof("parentFileNameHint") + 1;
384 end_name = strchr(p_name, '\"');
385 if (end_name == NULL) {
389 if ((end_name - p_name) > sizeof(bs->auto_backing_file) - 1) {
394 pstrcpy(bs->auto_backing_file, end_name - p_name + 1, p_name);
395 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
396 bs->auto_backing_file);
404 /* Create and append extent to the extent array. Return the added VmdkExtent
405 * address. return NULL if allocation failed. */
406 static int vmdk_add_extent(BlockDriverState *bs,
407 BdrvChild *file, bool flat, int64_t sectors,
408 int64_t l1_offset, int64_t l1_backup_offset,
410 int l2_size, uint64_t cluster_sectors,
411 VmdkExtent **new_extent,
415 BDRVVmdkState *s = bs->opaque;
418 if (cluster_sectors > 0x200000) {
419 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
420 error_setg(errp, "Invalid granularity, image may be corrupt");
423 if (l1_size > 512 * 1024 * 1024) {
424 /* Although with big capacity and small l1_entry_sectors, we can get a
425 * big l1_size, we don't want unbounded value to allocate the table.
426 * Limit it to 512M, which is 16PB for default cluster and L2 table
428 error_setg(errp, "L1 size too big");
432 nb_sectors = bdrv_nb_sectors(file->bs);
433 if (nb_sectors < 0) {
437 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
438 extent = &s->extents[s->num_extents];
441 memset(extent, 0, sizeof(VmdkExtent));
444 extent->sectors = sectors;
445 extent->l1_table_offset = l1_offset;
446 extent->l1_backup_table_offset = l1_backup_offset;
447 extent->l1_size = l1_size;
448 extent->l1_entry_sectors = l2_size * cluster_sectors;
449 extent->l2_size = l2_size;
450 extent->cluster_sectors = flat ? sectors : cluster_sectors;
451 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
453 if (s->num_extents > 1) {
454 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
456 extent->end_sector = extent->sectors;
458 bs->total_sectors = extent->end_sector;
460 *new_extent = extent;
465 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
472 /* read the L1 table */
473 l1_size = extent->l1_size * sizeof(uint32_t);
474 extent->l1_table = g_try_malloc(l1_size);
475 if (l1_size && extent->l1_table == NULL) {
479 ret = bdrv_pread(extent->file,
480 extent->l1_table_offset,
484 bdrv_refresh_filename(extent->file->bs);
485 error_setg_errno(errp, -ret,
486 "Could not read l1 table from extent '%s'",
487 extent->file->bs->filename);
490 for (i = 0; i < extent->l1_size; i++) {
491 le32_to_cpus(&extent->l1_table[i]);
494 if (extent->l1_backup_table_offset) {
495 extent->l1_backup_table = g_try_malloc(l1_size);
496 if (l1_size && extent->l1_backup_table == NULL) {
500 ret = bdrv_pread(extent->file,
501 extent->l1_backup_table_offset,
502 extent->l1_backup_table,
505 bdrv_refresh_filename(extent->file->bs);
506 error_setg_errno(errp, -ret,
507 "Could not read l1 backup table from extent '%s'",
508 extent->file->bs->filename);
511 for (i = 0; i < extent->l1_size; i++) {
512 le32_to_cpus(&extent->l1_backup_table[i]);
517 g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
520 g_free(extent->l1_backup_table);
522 g_free(extent->l1_table);
526 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
528 int flags, Error **errp)
535 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
537 bdrv_refresh_filename(file->bs);
538 error_setg_errno(errp, -ret,
539 "Could not read header from file '%s'",
543 ret = vmdk_add_extent(bs, file, false,
544 le32_to_cpu(header.disk_sectors),
545 (int64_t)le32_to_cpu(header.l1dir_offset) << 9,
547 le32_to_cpu(header.l1dir_size),
549 le32_to_cpu(header.granularity),
555 ret = vmdk_init_tables(bs, extent, errp);
557 /* free extent allocated by vmdk_add_extent */
558 vmdk_free_last_extent(bs);
563 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
564 QDict *options, Error **errp);
566 static char *vmdk_read_desc(BdrvChild *file, uint64_t desc_offset, Error **errp)
572 size = bdrv_getlength(file->bs);
574 error_setg_errno(errp, -size, "Could not access file");
579 /* Both descriptor file and sparse image must be much larger than 4
580 * bytes, also callers of vmdk_read_desc want to compare the first 4
581 * bytes with VMDK4_MAGIC, let's error out if less is read. */
582 error_setg(errp, "File is too small, not a valid image");
586 size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */
587 buf = g_malloc(size + 1);
589 ret = bdrv_pread(file, desc_offset, buf, size);
591 error_setg_errno(errp, -ret, "Could not read from file");
600 static int vmdk_open_vmdk4(BlockDriverState *bs,
602 int flags, QDict *options, Error **errp)
606 uint32_t l1_size, l1_entry_sectors;
609 BDRVVmdkState *s = bs->opaque;
610 int64_t l1_backup_offset = 0;
613 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
615 bdrv_refresh_filename(file->bs);
616 error_setg_errno(errp, -ret,
617 "Could not read header from file '%s'",
621 if (header.capacity == 0) {
622 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
624 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
628 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
634 if (!s->create_type) {
635 s->create_type = g_strdup("monolithicSparse");
638 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
640 * The footer takes precedence over the header, so read it in. The
641 * footer starts at offset -1024 from the end: One sector for the
642 * footer, and another one for the end-of-stream marker.
649 uint8_t pad[512 - 16];
650 } QEMU_PACKED footer_marker;
654 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
660 uint8_t pad[512 - 16];
661 } QEMU_PACKED eos_marker;
662 } QEMU_PACKED footer;
664 ret = bdrv_pread(file,
665 bs->file->bs->total_sectors * 512 - 1536,
666 &footer, sizeof(footer));
668 error_setg_errno(errp, -ret, "Failed to read footer");
672 /* Some sanity checks for the footer */
673 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
674 le32_to_cpu(footer.footer_marker.size) != 0 ||
675 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
676 le64_to_cpu(footer.eos_marker.val) != 0 ||
677 le32_to_cpu(footer.eos_marker.size) != 0 ||
678 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
680 error_setg(errp, "Invalid footer");
684 header = footer.header;
688 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
689 if (le32_to_cpu(header.version) > 3) {
690 error_setg(errp, "Unsupported VMDK version %" PRIu32,
691 le32_to_cpu(header.version));
693 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR) &&
695 /* VMware KB 2064959 explains that version 3 added support for
696 * persistent changed block tracking (CBT), and backup software can
697 * read it as version=1 if it doesn't care about the changed area
698 * information. So we are safe to enable read only. */
699 error_setg(errp, "VMDK version 3 must be read only");
703 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
704 error_setg(errp, "L2 table size too big");
708 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
709 * le64_to_cpu(header.granularity);
710 if (l1_entry_sectors == 0) {
711 error_setg(errp, "L1 entry size is invalid");
714 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
716 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
717 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
719 if (bdrv_nb_sectors(file->bs) < le64_to_cpu(header.grain_offset)) {
720 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
721 (int64_t)(le64_to_cpu(header.grain_offset)
722 * BDRV_SECTOR_SIZE));
726 ret = vmdk_add_extent(bs, file, false,
727 le64_to_cpu(header.capacity),
728 le64_to_cpu(header.gd_offset) << 9,
731 le32_to_cpu(header.num_gtes_per_gt),
732 le64_to_cpu(header.granularity),
739 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
740 if (extent->compressed) {
741 g_free(s->create_type);
742 s->create_type = g_strdup("streamOptimized");
744 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
745 extent->version = le32_to_cpu(header.version);
746 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
747 ret = vmdk_init_tables(bs, extent, errp);
749 /* free extent allocated by vmdk_add_extent */
750 vmdk_free_last_extent(bs);
755 /* find an option value out of descriptor file */
756 static int vmdk_parse_description(const char *desc, const char *opt_name,
757 char *buf, int buf_size)
759 char *opt_pos, *opt_end;
760 const char *end = desc + strlen(desc);
762 opt_pos = strstr(desc, opt_name);
766 /* Skip "=\"" following opt_name */
767 opt_pos += strlen(opt_name) + 2;
768 if (opt_pos >= end) {
772 while (opt_end < end && *opt_end != '"') {
775 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
778 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
782 /* Open an extent file and append to bs array */
783 static int vmdk_open_sparse(BlockDriverState *bs, BdrvChild *file, int flags,
784 char *buf, QDict *options, Error **errp)
788 magic = ldl_be_p(buf);
791 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
794 return vmdk_open_vmdk4(bs, file, flags, options, errp);
797 error_setg(errp, "Image not in VMDK format");
803 static const char *next_line(const char *s)
814 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
815 const char *desc_file_path, QDict *options,
827 BdrvChild *extent_file;
828 BDRVVmdkState *s = bs->opaque;
830 char extent_opt_prefix[32];
831 Error *local_err = NULL;
833 for (p = desc; *p; p = next_line(p)) {
834 /* parse extent line in one of below formats:
836 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
837 * RW [size in sectors] SPARSE "file-name.vmdk"
838 * RW [size in sectors] VMFS "file-name.vmdk"
839 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
842 matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
843 access, §ors, type, fname, &flat_offset);
844 if (matches < 4 || strcmp(access, "RW")) {
846 } else if (!strcmp(type, "FLAT")) {
847 if (matches != 5 || flat_offset < 0) {
850 } else if (!strcmp(type, "VMFS")) {
856 } else if (matches != 4) {
861 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
862 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
863 (strcmp(access, "RW"))) {
867 if (!path_is_absolute(fname) && !path_has_protocol(fname) &&
870 bdrv_refresh_filename(bs->file->bs);
871 error_setg(errp, "Cannot use relative extent paths with VMDK "
872 "descriptor file '%s'", bs->file->bs->filename);
876 extent_path = path_combine(desc_file_path, fname);
878 ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents);
881 extent_file = bdrv_open_child(extent_path, options, extent_opt_prefix,
882 bs, &child_file, false, &local_err);
885 error_propagate(errp, local_err);
889 /* save to extents array */
890 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
893 ret = vmdk_add_extent(bs, extent_file, true, sectors,
894 0, 0, 0, 0, 0, &extent, errp);
896 bdrv_unref_child(bs, extent_file);
899 extent->flat_start_offset = flat_offset << 9;
900 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
901 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
902 char *buf = vmdk_read_desc(extent_file, 0, errp);
906 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf,
911 bdrv_unref_child(bs, extent_file);
914 extent = &s->extents[s->num_extents - 1];
916 error_setg(errp, "Unsupported extent type '%s'", type);
917 bdrv_unref_child(bs, extent_file);
920 extent->type = g_strdup(type);
927 if (np[-1] == '\n') {
930 error_setg(errp, "Invalid extent line: %.*s", (int)(np - p), p);
934 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
935 QDict *options, Error **errp)
939 BDRVVmdkState *s = bs->opaque;
941 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
942 error_setg(errp, "invalid VMDK image descriptor");
946 if (strcmp(ct, "monolithicFlat") &&
947 strcmp(ct, "vmfs") &&
948 strcmp(ct, "vmfsSparse") &&
949 strcmp(ct, "twoGbMaxExtentSparse") &&
950 strcmp(ct, "twoGbMaxExtentFlat")) {
951 error_setg(errp, "Unsupported image type '%s'", ct);
955 s->create_type = g_strdup(ct);
957 ret = vmdk_parse_extents(buf, bs, bs->file->bs->exact_filename, options,
963 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
968 BDRVVmdkState *s = bs->opaque;
970 Error *local_err = NULL;
972 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
978 buf = vmdk_read_desc(bs->file, 0, errp);
983 magic = ldl_be_p(buf);
987 ret = vmdk_open_sparse(bs, bs->file, flags, buf, options,
989 s->desc_offset = 0x200;
992 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
999 /* try to open parent images, if exist */
1000 ret = vmdk_parent_open(bs);
1004 ret = vmdk_read_cid(bs, 0, &s->cid);
1008 ret = vmdk_read_cid(bs, 1, &s->parent_cid);
1012 qemu_co_mutex_init(&s->lock);
1014 /* Disable migration when VMDK images are used */
1015 error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "
1016 "does not support live migration",
1017 bdrv_get_device_or_node_name(bs));
1018 ret = migrate_add_blocker(s->migration_blocker, &local_err);
1020 error_propagate(errp, local_err);
1021 error_free(s->migration_blocker);
1030 g_free(s->create_type);
1031 s->create_type = NULL;
1032 vmdk_free_extents(bs);
1037 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
1039 BDRVVmdkState *s = bs->opaque;
1042 for (i = 0; i < s->num_extents; i++) {
1043 if (!s->extents[i].flat) {
1044 bs->bl.pwrite_zeroes_alignment =
1045 MAX(bs->bl.pwrite_zeroes_alignment,
1046 s->extents[i].cluster_sectors << BDRV_SECTOR_BITS);
1054 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1055 * to the cluster at @cluster_sector_num.
1057 * If @skip_start_sector < @skip_end_sector, the relative range
1058 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1059 * it for call to write user data in the request.
1061 static int get_whole_cluster(BlockDriverState *bs,
1063 uint64_t cluster_offset,
1065 uint64_t skip_start_bytes,
1066 uint64_t skip_end_bytes)
1069 int64_t cluster_bytes;
1070 uint8_t *whole_grain;
1072 /* For COW, align request sector_num to cluster start */
1073 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
1074 offset = QEMU_ALIGN_DOWN(offset, cluster_bytes);
1075 whole_grain = qemu_blockalign(bs, cluster_bytes);
1078 memset(whole_grain, 0, skip_start_bytes);
1079 memset(whole_grain + skip_end_bytes, 0, cluster_bytes - skip_end_bytes);
1082 assert(skip_end_bytes <= cluster_bytes);
1083 /* we will be here if it's first write on non-exist grain(cluster).
1084 * try to read from parent image, if exist */
1085 if (bs->backing && !vmdk_is_cid_valid(bs)) {
1090 /* Read backing data before skip range */
1091 if (skip_start_bytes > 0) {
1093 /* qcow2 emits this on bs->file instead of bs->backing */
1094 BLKDBG_EVENT(extent->file, BLKDBG_COW_READ);
1095 ret = bdrv_pread(bs->backing, offset, whole_grain,
1102 BLKDBG_EVENT(extent->file, BLKDBG_COW_WRITE);
1103 ret = bdrv_pwrite(extent->file, cluster_offset, whole_grain,
1110 /* Read backing data after skip range */
1111 if (skip_end_bytes < cluster_bytes) {
1113 /* qcow2 emits this on bs->file instead of bs->backing */
1114 BLKDBG_EVENT(extent->file, BLKDBG_COW_READ);
1115 ret = bdrv_pread(bs->backing, offset + skip_end_bytes,
1116 whole_grain + skip_end_bytes,
1117 cluster_bytes - skip_end_bytes);
1123 BLKDBG_EVENT(extent->file, BLKDBG_COW_WRITE);
1124 ret = bdrv_pwrite(extent->file, cluster_offset + skip_end_bytes,
1125 whole_grain + skip_end_bytes,
1126 cluster_bytes - skip_end_bytes);
1135 qemu_vfree(whole_grain);
1139 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1142 offset = cpu_to_le32(offset);
1143 /* update L2 table */
1144 BLKDBG_EVENT(extent->file, BLKDBG_L2_UPDATE);
1145 if (bdrv_pwrite_sync(extent->file,
1146 ((int64_t)m_data->l2_offset * 512)
1147 + (m_data->l2_index * sizeof(offset)),
1148 &offset, sizeof(offset)) < 0) {
1151 /* update backup L2 table */
1152 if (extent->l1_backup_table_offset != 0) {
1153 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1154 if (bdrv_pwrite_sync(extent->file,
1155 ((int64_t)m_data->l2_offset * 512)
1156 + (m_data->l2_index * sizeof(offset)),
1157 &offset, sizeof(offset)) < 0) {
1161 if (m_data->l2_cache_entry) {
1162 *m_data->l2_cache_entry = offset;
1169 * get_cluster_offset
1171 * Look up cluster offset in extent file by sector number, and store in
1174 * For flat extents, the start offset as parsed from the description file is
1177 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1178 * offset for a new cluster and update L2 cache. If there is a backing file,
1179 * COW is done before returning; otherwise, zeroes are written to the allocated
1180 * cluster. Both COW and zero writing skips the sector range
1181 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1182 * has new data to write there.
1184 * Returns: VMDK_OK if cluster exists and mapped in the image.
1185 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1186 * VMDK_ERROR if failed.
1188 static int get_cluster_offset(BlockDriverState *bs,
1190 VmdkMetaData *m_data,
1193 uint64_t *cluster_offset,
1194 uint64_t skip_start_bytes,
1195 uint64_t skip_end_bytes)
1197 unsigned int l1_index, l2_offset, l2_index;
1198 int min_index, i, j;
1199 uint32_t min_count, *l2_table;
1200 bool zeroed = false;
1202 int64_t cluster_sector;
1208 *cluster_offset = extent->flat_start_offset;
1212 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1213 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1214 if (l1_index >= extent->l1_size) {
1217 l2_offset = extent->l1_table[l1_index];
1219 return VMDK_UNALLOC;
1221 for (i = 0; i < L2_CACHE_SIZE; i++) {
1222 if (l2_offset == extent->l2_cache_offsets[i]) {
1223 /* increment the hit count */
1224 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1225 for (j = 0; j < L2_CACHE_SIZE; j++) {
1226 extent->l2_cache_counts[j] >>= 1;
1229 l2_table = extent->l2_cache + (i * extent->l2_size);
1233 /* not found: load a new entry in the least used one */
1235 min_count = 0xffffffff;
1236 for (i = 0; i < L2_CACHE_SIZE; i++) {
1237 if (extent->l2_cache_counts[i] < min_count) {
1238 min_count = extent->l2_cache_counts[i];
1242 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1243 BLKDBG_EVENT(extent->file, BLKDBG_L2_LOAD);
1244 if (bdrv_pread(extent->file,
1245 (int64_t)l2_offset * 512,
1247 extent->l2_size * sizeof(uint32_t)
1248 ) != extent->l2_size * sizeof(uint32_t)) {
1252 extent->l2_cache_offsets[min_index] = l2_offset;
1253 extent->l2_cache_counts[min_index] = 1;
1255 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1256 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1258 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1262 if (!cluster_sector || zeroed) {
1264 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1267 if (extent->next_cluster_sector >= VMDK_EXTENT_MAX_SECTORS) {
1271 cluster_sector = extent->next_cluster_sector;
1272 extent->next_cluster_sector += extent->cluster_sectors;
1274 /* First of all we write grain itself, to avoid race condition
1275 * that may to corrupt the image.
1276 * This problem may occur because of insufficient space on host disk
1277 * or inappropriate VM shutdown.
1279 ret = get_whole_cluster(bs, extent, cluster_sector * BDRV_SECTOR_SIZE,
1280 offset, skip_start_bytes, skip_end_bytes);
1286 m_data->l1_index = l1_index;
1287 m_data->l2_index = l2_index;
1288 m_data->l2_offset = l2_offset;
1289 m_data->l2_cache_entry = &l2_table[l2_index];
1292 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1296 static VmdkExtent *find_extent(BDRVVmdkState *s,
1297 int64_t sector_num, VmdkExtent *start_hint)
1299 VmdkExtent *extent = start_hint;
1302 extent = &s->extents[0];
1304 while (extent < &s->extents[s->num_extents]) {
1305 if (sector_num < extent->end_sector) {
1313 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent *extent,
1316 uint64_t extent_begin_offset, extent_relative_offset;
1317 uint64_t cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1319 extent_begin_offset =
1320 (extent->end_sector - extent->sectors) * BDRV_SECTOR_SIZE;
1321 extent_relative_offset = offset - extent_begin_offset;
1322 return extent_relative_offset % cluster_size;
1325 static int coroutine_fn vmdk_co_block_status(BlockDriverState *bs,
1327 int64_t offset, int64_t bytes,
1328 int64_t *pnum, int64_t *map,
1329 BlockDriverState **file)
1331 BDRVVmdkState *s = bs->opaque;
1332 int64_t index_in_cluster, n, ret;
1333 uint64_t cluster_offset;
1336 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, NULL);
1340 qemu_co_mutex_lock(&s->lock);
1341 ret = get_cluster_offset(bs, extent, NULL, offset, false, &cluster_offset,
1343 qemu_co_mutex_unlock(&s->lock);
1345 index_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1354 ret = BDRV_BLOCK_ZERO;
1357 ret = BDRV_BLOCK_DATA;
1358 if (!extent->compressed) {
1359 ret |= BDRV_BLOCK_OFFSET_VALID;
1360 *map = cluster_offset + index_in_cluster;
1362 *file = extent->file->bs;
1366 n = extent->cluster_sectors * BDRV_SECTOR_SIZE - index_in_cluster;
1367 *pnum = MIN(n, bytes);
1371 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1372 int64_t offset_in_cluster, QEMUIOVector *qiov,
1373 uint64_t qiov_offset, uint64_t n_bytes,
1377 VmdkGrainMarker *data = NULL;
1379 QEMUIOVector local_qiov;
1381 int64_t write_offset;
1382 int64_t write_end_sector;
1384 if (extent->compressed) {
1385 void *compressed_data;
1387 if (!extent->has_marker) {
1391 buf_len = (extent->cluster_sectors << 9) * 2;
1392 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1394 compressed_data = g_malloc(n_bytes);
1395 qemu_iovec_to_buf(qiov, qiov_offset, compressed_data, n_bytes);
1396 ret = compress(data->data, &buf_len, compressed_data, n_bytes);
1397 g_free(compressed_data);
1399 if (ret != Z_OK || buf_len == 0) {
1404 data->lba = cpu_to_le64(offset >> BDRV_SECTOR_BITS);
1405 data->size = cpu_to_le32(buf_len);
1407 n_bytes = buf_len + sizeof(VmdkGrainMarker);
1408 iov = (struct iovec) {
1412 qemu_iovec_init_external(&local_qiov, &iov, 1);
1414 BLKDBG_EVENT(extent->file, BLKDBG_WRITE_COMPRESSED);
1416 qemu_iovec_init(&local_qiov, qiov->niov);
1417 qemu_iovec_concat(&local_qiov, qiov, qiov_offset, n_bytes);
1419 BLKDBG_EVENT(extent->file, BLKDBG_WRITE_AIO);
1422 write_offset = cluster_offset + offset_in_cluster;
1423 ret = bdrv_co_pwritev(extent->file, write_offset, n_bytes,
1426 write_end_sector = DIV_ROUND_UP(write_offset + n_bytes, BDRV_SECTOR_SIZE);
1428 if (extent->compressed) {
1429 extent->next_cluster_sector = write_end_sector;
1431 extent->next_cluster_sector = MAX(extent->next_cluster_sector,
1441 if (!extent->compressed) {
1442 qemu_iovec_destroy(&local_qiov);
1447 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1448 int64_t offset_in_cluster, QEMUIOVector *qiov,
1452 int cluster_bytes, buf_bytes;
1453 uint8_t *cluster_buf, *compressed_data;
1454 uint8_t *uncomp_buf;
1456 VmdkGrainMarker *marker;
1460 if (!extent->compressed) {
1461 BLKDBG_EVENT(extent->file, BLKDBG_READ_AIO);
1462 ret = bdrv_co_preadv(extent->file,
1463 cluster_offset + offset_in_cluster, bytes,
1470 cluster_bytes = extent->cluster_sectors * 512;
1471 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1472 buf_bytes = cluster_bytes * 2;
1473 cluster_buf = g_malloc(buf_bytes);
1474 uncomp_buf = g_malloc(cluster_bytes);
1475 BLKDBG_EVENT(extent->file, BLKDBG_READ_COMPRESSED);
1476 ret = bdrv_pread(extent->file,
1478 cluster_buf, buf_bytes);
1482 compressed_data = cluster_buf;
1483 buf_len = cluster_bytes;
1484 data_len = cluster_bytes;
1485 if (extent->has_marker) {
1486 marker = (VmdkGrainMarker *)cluster_buf;
1487 compressed_data = marker->data;
1488 data_len = le32_to_cpu(marker->size);
1490 if (!data_len || data_len > buf_bytes) {
1494 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1500 if (offset_in_cluster < 0 ||
1501 offset_in_cluster + bytes > buf_len) {
1505 qemu_iovec_from_buf(qiov, 0, uncomp_buf + offset_in_cluster, bytes);
1510 g_free(cluster_buf);
1514 static int coroutine_fn
1515 vmdk_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1516 QEMUIOVector *qiov, int flags)
1518 BDRVVmdkState *s = bs->opaque;
1520 uint64_t n_bytes, offset_in_cluster;
1521 VmdkExtent *extent = NULL;
1522 QEMUIOVector local_qiov;
1523 uint64_t cluster_offset;
1524 uint64_t bytes_done = 0;
1526 qemu_iovec_init(&local_qiov, qiov->niov);
1527 qemu_co_mutex_lock(&s->lock);
1530 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1535 ret = get_cluster_offset(bs, extent, NULL,
1536 offset, false, &cluster_offset, 0, 0);
1537 offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1539 n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1540 - offset_in_cluster);
1542 if (ret != VMDK_OK) {
1543 /* if not allocated, try to read from parent image, if exist */
1544 if (bs->backing && ret != VMDK_ZEROED) {
1545 if (!vmdk_is_cid_valid(bs)) {
1550 qemu_iovec_reset(&local_qiov);
1551 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1553 /* qcow2 emits this on bs->file instead of bs->backing */
1554 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1555 ret = bdrv_co_preadv(bs->backing, offset, n_bytes,
1561 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
1564 qemu_iovec_reset(&local_qiov);
1565 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1567 ret = vmdk_read_extent(extent, cluster_offset, offset_in_cluster,
1568 &local_qiov, n_bytes);
1575 bytes_done += n_bytes;
1580 qemu_co_mutex_unlock(&s->lock);
1581 qemu_iovec_destroy(&local_qiov);
1588 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1589 * if possible, otherwise return -ENOTSUP.
1590 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1591 * with each cluster. By dry run we can find if the zero write
1592 * is possible without modifying image data.
1594 * Returns: error code with 0 for success.
1596 static int vmdk_pwritev(BlockDriverState *bs, uint64_t offset,
1597 uint64_t bytes, QEMUIOVector *qiov,
1598 bool zeroed, bool zero_dry_run)
1600 BDRVVmdkState *s = bs->opaque;
1601 VmdkExtent *extent = NULL;
1603 int64_t offset_in_cluster, n_bytes;
1604 uint64_t cluster_offset;
1605 uint64_t bytes_done = 0;
1606 VmdkMetaData m_data;
1608 if (DIV_ROUND_UP(offset, BDRV_SECTOR_SIZE) > bs->total_sectors) {
1609 error_report("Wrong offset: offset=0x%" PRIx64
1610 " total_sectors=0x%" PRIx64,
1611 offset, bs->total_sectors);
1616 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1620 offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1621 n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1622 - offset_in_cluster);
1624 ret = get_cluster_offset(bs, extent, &m_data, offset,
1625 !(extent->compressed || zeroed),
1626 &cluster_offset, offset_in_cluster,
1627 offset_in_cluster + n_bytes);
1628 if (extent->compressed) {
1629 if (ret == VMDK_OK) {
1630 /* Refuse write to allocated cluster for streamOptimized */
1631 error_report("Could not write to allocated cluster"
1632 " for streamOptimized");
1636 ret = get_cluster_offset(bs, extent, &m_data, offset,
1637 true, &cluster_offset, 0, 0);
1640 if (ret == VMDK_ERROR) {
1644 /* Do zeroed write, buf is ignored */
1645 if (extent->has_zero_grain &&
1646 offset_in_cluster == 0 &&
1647 n_bytes >= extent->cluster_sectors * BDRV_SECTOR_SIZE) {
1648 n_bytes = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1649 if (!zero_dry_run) {
1650 /* update L2 tables */
1651 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1660 ret = vmdk_write_extent(extent, cluster_offset, offset_in_cluster,
1661 qiov, bytes_done, n_bytes, offset);
1666 /* update L2 tables */
1667 if (vmdk_L2update(extent, &m_data,
1668 cluster_offset >> BDRV_SECTOR_BITS)
1676 bytes_done += n_bytes;
1678 /* update CID on the first write every time the virtual disk is
1680 if (!s->cid_updated) {
1681 ret = vmdk_write_cid(bs, g_random_int());
1685 s->cid_updated = true;
1691 static int coroutine_fn
1692 vmdk_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1693 QEMUIOVector *qiov, int flags)
1696 BDRVVmdkState *s = bs->opaque;
1697 qemu_co_mutex_lock(&s->lock);
1698 ret = vmdk_pwritev(bs, offset, bytes, qiov, false, false);
1699 qemu_co_mutex_unlock(&s->lock);
1703 static int coroutine_fn
1704 vmdk_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1705 uint64_t bytes, QEMUIOVector *qiov)
1708 /* The caller will write bytes 0 to signal EOF.
1709 * When receive it, we align EOF to a sector boundary. */
1710 BDRVVmdkState *s = bs->opaque;
1714 for (i = 0; i < s->num_extents; i++) {
1715 length = bdrv_getlength(s->extents[i].file->bs);
1719 length = QEMU_ALIGN_UP(length, BDRV_SECTOR_SIZE);
1720 ret = bdrv_truncate(s->extents[i].file, length,
1721 PREALLOC_MODE_OFF, NULL);
1728 return vmdk_co_pwritev(bs, offset, bytes, qiov, 0);
1731 static int coroutine_fn vmdk_co_pwrite_zeroes(BlockDriverState *bs,
1734 BdrvRequestFlags flags)
1737 BDRVVmdkState *s = bs->opaque;
1739 qemu_co_mutex_lock(&s->lock);
1740 /* write zeroes could fail if sectors not aligned to cluster, test it with
1741 * dry_run == true before really updating image */
1742 ret = vmdk_pwritev(bs, offset, bytes, NULL, true, true);
1744 ret = vmdk_pwritev(bs, offset, bytes, NULL, true, false);
1746 qemu_co_mutex_unlock(&s->lock);
1750 static int vmdk_init_extent(BlockBackend *blk,
1751 int64_t filesize, bool flat,
1752 bool compress, bool zeroed_grain,
1757 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1758 uint32_t *gd_buf = NULL;
1762 ret = blk_truncate(blk, filesize, PREALLOC_MODE_OFF, errp);
1765 magic = cpu_to_be32(VMDK4_MAGIC);
1766 memset(&header, 0, sizeof(header));
1769 } else if (zeroed_grain) {
1774 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1775 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1776 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1777 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1778 header.capacity = filesize / BDRV_SECTOR_SIZE;
1779 header.granularity = 128;
1780 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1782 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1783 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1785 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1786 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1788 header.desc_offset = 1;
1789 header.desc_size = 20;
1790 header.rgd_offset = header.desc_offset + header.desc_size;
1791 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1792 header.grain_offset =
1793 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1794 header.granularity);
1795 /* swap endianness for all header fields */
1796 header.version = cpu_to_le32(header.version);
1797 header.flags = cpu_to_le32(header.flags);
1798 header.capacity = cpu_to_le64(header.capacity);
1799 header.granularity = cpu_to_le64(header.granularity);
1800 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1801 header.desc_offset = cpu_to_le64(header.desc_offset);
1802 header.desc_size = cpu_to_le64(header.desc_size);
1803 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1804 header.gd_offset = cpu_to_le64(header.gd_offset);
1805 header.grain_offset = cpu_to_le64(header.grain_offset);
1806 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1808 header.check_bytes[0] = 0xa;
1809 header.check_bytes[1] = 0x20;
1810 header.check_bytes[2] = 0xd;
1811 header.check_bytes[3] = 0xa;
1813 /* write all the data */
1814 ret = blk_pwrite(blk, 0, &magic, sizeof(magic), 0);
1816 error_setg(errp, QERR_IO_ERROR);
1819 ret = blk_pwrite(blk, sizeof(magic), &header, sizeof(header), 0);
1821 error_setg(errp, QERR_IO_ERROR);
1825 ret = blk_truncate(blk, le64_to_cpu(header.grain_offset) << 9,
1826 PREALLOC_MODE_OFF, errp);
1831 /* write grain directory */
1832 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1833 gd_buf = g_malloc0(gd_buf_size);
1834 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1835 i < gt_count; i++, tmp += gt_size) {
1836 gd_buf[i] = cpu_to_le32(tmp);
1838 ret = blk_pwrite(blk, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1839 gd_buf, gd_buf_size, 0);
1841 error_setg(errp, QERR_IO_ERROR);
1845 /* write backup grain directory */
1846 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1847 i < gt_count; i++, tmp += gt_size) {
1848 gd_buf[i] = cpu_to_le32(tmp);
1850 ret = blk_pwrite(blk, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1851 gd_buf, gd_buf_size, 0);
1853 error_setg(errp, QERR_IO_ERROR);
1862 static int vmdk_create_extent(const char *filename, int64_t filesize,
1863 bool flat, bool compress, bool zeroed_grain,
1865 QemuOpts *opts, Error **errp)
1868 BlockBackend *blk = NULL;
1869 Error *local_err = NULL;
1871 ret = bdrv_create_file(filename, opts, &local_err);
1873 error_propagate(errp, local_err);
1877 blk = blk_new_open(filename, NULL, NULL,
1878 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
1881 error_propagate(errp, local_err);
1886 blk_set_allow_write_beyond_eof(blk, true);
1888 ret = vmdk_init_extent(blk, filesize, flat, compress, zeroed_grain, errp);
1901 static int filename_decompose(const char *filename, char *path, char *prefix,
1902 char *postfix, size_t buf_len, Error **errp)
1906 if (filename == NULL || !strlen(filename)) {
1907 error_setg(errp, "No filename provided");
1910 p = strrchr(filename, '/');
1912 p = strrchr(filename, '\\');
1915 p = strrchr(filename, ':');
1919 if (p - filename >= buf_len) {
1922 pstrcpy(path, p - filename + 1, filename);
1927 q = strrchr(p, '.');
1929 pstrcpy(prefix, buf_len, p);
1932 if (q - p >= buf_len) {
1935 pstrcpy(prefix, q - p + 1, p);
1936 pstrcpy(postfix, buf_len, q);
1942 * idx == 0: get or create the descriptor file (also the image file if in a
1944 * idx >= 1: get the n-th extent if in a split subformat
1946 typedef BlockBackend *(*vmdk_create_extent_fn)(int64_t size,
1955 static void vmdk_desc_add_extent(GString *desc,
1956 const char *extent_line_fmt,
1957 int64_t size, const char *filename)
1959 char *basename = g_path_get_basename(filename);
1961 g_string_append_printf(desc, extent_line_fmt,
1962 DIV_ROUND_UP(size, BDRV_SECTOR_SIZE), basename);
1966 static int coroutine_fn vmdk_co_do_create(int64_t size,
1967 BlockdevVmdkSubformat subformat,
1968 BlockdevVmdkAdapterType adapter_type,
1969 const char *backing_file,
1970 const char *hw_version,
1973 vmdk_create_extent_fn extent_fn,
1978 BlockBackend *blk = NULL;
1979 BlockBackend *extent_blk;
1980 Error *local_err = NULL;
1983 bool flat, split, compress;
1984 GString *ext_desc_lines;
1985 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1986 int64_t extent_size;
1987 int64_t created_size = 0;
1988 const char *extent_line_fmt;
1989 char *parent_desc_line = g_malloc0(BUF_SIZE);
1990 uint32_t parent_cid = 0xffffffff;
1991 uint32_t number_heads = 16;
1992 uint32_t desc_offset = 0, desc_len;
1993 const char desc_template[] =
1994 "# Disk DescriptorFile\n"
1997 "parentCID=%" PRIx32 "\n"
1998 "createType=\"%s\"\n"
2001 "# Extent description\n"
2004 "# The Disk Data Base\n"
2007 "ddb.virtualHWVersion = \"%s\"\n"
2008 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
2009 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
2010 "ddb.geometry.sectors = \"63\"\n"
2011 "ddb.adapterType = \"%s\"\n";
2013 ext_desc_lines = g_string_new(NULL);
2015 /* Read out options */
2019 "compat6 cannot be enabled with hwversion set");
2029 if (adapter_type != BLOCKDEV_VMDK_ADAPTER_TYPE_IDE) {
2030 /* that's the number of heads with which vmware operates when
2031 creating, exporting, etc. vmdk files with a non-ide adapter type */
2034 split = (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT) ||
2035 (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTSPARSE);
2036 flat = (subformat == BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICFLAT) ||
2037 (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT);
2038 compress = subformat == BLOCKDEV_VMDK_SUBFORMAT_STREAMOPTIMIZED;
2041 extent_line_fmt = "RW %" PRId64 " FLAT \"%s\" 0\n";
2043 extent_line_fmt = "RW %" PRId64 " SPARSE \"%s\"\n";
2045 if (flat && backing_file) {
2046 error_setg(errp, "Flat image can't have backing file");
2050 if (flat && zeroed_grain) {
2051 error_setg(errp, "Flat image can't enable zeroed grain");
2056 /* Create extents */
2058 extent_size = split_size;
2062 if (!split && !flat) {
2063 created_size = extent_size;
2067 /* Get the descriptor file BDS */
2068 blk = extent_fn(created_size, 0, flat, split, compress, zeroed_grain,
2074 if (!split && !flat) {
2075 vmdk_desc_add_extent(ext_desc_lines, extent_line_fmt, created_size,
2076 blk_bs(blk)->filename);
2080 BlockBackend *backing;
2081 char *full_backing =
2082 bdrv_get_full_backing_filename_from_filename(blk_bs(blk)->filename,
2086 error_propagate(errp, local_err);
2090 assert(full_backing);
2092 backing = blk_new_open(full_backing, NULL, NULL,
2093 BDRV_O_NO_BACKING, errp);
2094 g_free(full_backing);
2095 if (backing == NULL) {
2099 if (strcmp(blk_bs(backing)->drv->format_name, "vmdk")) {
2100 error_setg(errp, "Invalid backing file format: %s. Must be vmdk",
2101 blk_bs(backing)->drv->format_name);
2106 ret = vmdk_read_cid(blk_bs(backing), 0, &parent_cid);
2109 error_setg(errp, "Failed to read parent CID");
2112 snprintf(parent_desc_line, BUF_SIZE,
2113 "parentFileNameHint=\"%s\"", backing_file);
2116 while (created_size < size) {
2117 int64_t cur_size = MIN(size - created_size, extent_size);
2118 extent_blk = extent_fn(cur_size, extent_idx, flat, split, compress,
2119 zeroed_grain, opaque, errp);
2124 vmdk_desc_add_extent(ext_desc_lines, extent_line_fmt, cur_size,
2125 blk_bs(extent_blk)->filename);
2126 created_size += cur_size;
2128 blk_unref(extent_blk);
2131 /* Check whether we got excess extents */
2132 extent_blk = extent_fn(-1, extent_idx, flat, split, compress, zeroed_grain,
2135 blk_unref(extent_blk);
2136 error_setg(errp, "List of extents contains unused extents");
2141 /* generate descriptor file */
2142 desc = g_strdup_printf(desc_template,
2145 BlockdevVmdkSubformat_str(subformat),
2147 ext_desc_lines->str,
2150 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
2152 BlockdevVmdkAdapterType_str(adapter_type));
2153 desc_len = strlen(desc);
2154 /* the descriptor offset = 0x200 */
2155 if (!split && !flat) {
2156 desc_offset = 0x200;
2159 ret = blk_pwrite(blk, desc_offset, desc, desc_len, 0);
2161 error_setg_errno(errp, -ret, "Could not write description");
2164 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2165 * for description file */
2166 if (desc_offset == 0) {
2167 ret = blk_truncate(blk, desc_len, PREALLOC_MODE_OFF, errp);
2178 g_free(parent_desc_line);
2179 g_string_free(ext_desc_lines, true);
2188 } VMDKCreateOptsData;
2190 static BlockBackend *vmdk_co_create_opts_cb(int64_t size, int idx,
2191 bool flat, bool split, bool compress,
2192 bool zeroed_grain, void *opaque,
2195 BlockBackend *blk = NULL;
2196 BlockDriverState *bs = NULL;
2197 VMDKCreateOptsData *data = opaque;
2198 char *ext_filename = NULL;
2199 char *rel_filename = NULL;
2201 /* We're done, don't create excess extents. */
2203 assert(errp == NULL);
2208 rel_filename = g_strdup_printf("%s%s", data->prefix, data->postfix);
2210 rel_filename = g_strdup_printf("%s-%c%03d%s",
2212 flat ? 'f' : 's', idx, data->postfix);
2215 rel_filename = g_strdup_printf("%s-flat%s", data->prefix, data->postfix);
2218 ext_filename = g_strdup_printf("%s%s", data->path, rel_filename);
2219 g_free(rel_filename);
2221 if (vmdk_create_extent(ext_filename, size,
2222 flat, compress, zeroed_grain, &blk, data->opts,
2228 g_free(ext_filename);
2232 static int coroutine_fn vmdk_co_create_opts(const char *filename, QemuOpts *opts,
2235 Error *local_err = NULL;
2237 int64_t total_size = 0;
2238 char *adapter_type = NULL;
2239 BlockdevVmdkAdapterType adapter_type_enum;
2240 char *backing_file = NULL;
2241 char *hw_version = NULL;
2243 BlockdevVmdkSubformat subformat;
2245 char *path = g_malloc0(PATH_MAX);
2246 char *prefix = g_malloc0(PATH_MAX);
2247 char *postfix = g_malloc0(PATH_MAX);
2248 char *desc_line = g_malloc0(BUF_SIZE);
2249 char *ext_filename = g_malloc0(PATH_MAX);
2250 char *desc_filename = g_malloc0(PATH_MAX);
2251 char *parent_desc_line = g_malloc0(BUF_SIZE);
2254 VMDKCreateOptsData data;
2256 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
2260 /* Read out options */
2261 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2263 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
2264 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2265 hw_version = qemu_opt_get_del(opts, BLOCK_OPT_HWVERSION);
2266 compat6 = qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false);
2267 if (strcmp(hw_version, "undefined") == 0) {
2269 hw_version = g_strdup("4");
2271 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
2272 zeroed_grain = qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false);
2275 adapter_type_enum = qapi_enum_parse(&BlockdevVmdkAdapterType_lookup,
2277 BLOCKDEV_VMDK_ADAPTER_TYPE_IDE,
2280 error_propagate(errp, local_err);
2285 adapter_type_enum = BLOCKDEV_VMDK_ADAPTER_TYPE_IDE;
2289 /* Default format to monolithicSparse */
2290 subformat = BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE;
2292 subformat = qapi_enum_parse(&BlockdevVmdkSubformat_lookup,
2294 BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE,
2297 error_propagate(errp, local_err);
2302 data = (VMDKCreateOptsData){
2308 ret = vmdk_co_do_create(total_size, subformat, adapter_type_enum,
2309 backing_file, hw_version, compat6, zeroed_grain,
2310 vmdk_co_create_opts_cb, &data, errp);
2313 g_free(adapter_type);
2314 g_free(backing_file);
2322 g_free(ext_filename);
2323 g_free(desc_filename);
2324 g_free(parent_desc_line);
2328 static BlockBackend *vmdk_co_create_cb(int64_t size, int idx,
2329 bool flat, bool split, bool compress,
2330 bool zeroed_grain, void *opaque,
2334 BlockDriverState *bs;
2336 BlockdevCreateOptionsVmdk *opts = opaque;
2339 bs = bdrv_open_blockdev_ref(opts->file, errp);
2342 BlockdevRefList *list = opts->extents;
2343 for (i = 1; i < idx; i++) {
2344 if (!list || !list->next) {
2345 error_setg(errp, "Extent [%d] not specified", i);
2351 error_setg(errp, "Extent [%d] not specified", idx - 1);
2354 bs = bdrv_open_blockdev_ref(list->value, errp);
2359 blk = blk_new(BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE | BLK_PERM_RESIZE,
2361 if (blk_insert_bs(blk, bs, errp)) {
2365 blk_set_allow_write_beyond_eof(blk, true);
2369 ret = vmdk_init_extent(blk, size, flat, compress, zeroed_grain, errp);
2378 static int coroutine_fn vmdk_co_create(BlockdevCreateOptions *create_options,
2382 BlockdevCreateOptionsVmdk *opts;
2384 opts = &create_options->u.vmdk;
2386 /* Validate options */
2387 if (!QEMU_IS_ALIGNED(opts->size, BDRV_SECTOR_SIZE)) {
2388 error_setg(errp, "Image size must be a multiple of 512 bytes");
2393 ret = vmdk_co_do_create(opts->size,
2408 static void vmdk_close(BlockDriverState *bs)
2410 BDRVVmdkState *s = bs->opaque;
2412 vmdk_free_extents(bs);
2413 g_free(s->create_type);
2415 migrate_del_blocker(s->migration_blocker);
2416 error_free(s->migration_blocker);
2419 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
2421 BDRVVmdkState *s = bs->opaque;
2425 for (i = 0; i < s->num_extents; i++) {
2426 err = bdrv_co_flush(s->extents[i].file->bs);
2434 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2439 BDRVVmdkState *s = bs->opaque;
2441 ret = bdrv_get_allocated_file_size(bs->file->bs);
2445 for (i = 0; i < s->num_extents; i++) {
2446 if (s->extents[i].file == bs->file) {
2449 r = bdrv_get_allocated_file_size(s->extents[i].file->bs);
2458 static int vmdk_has_zero_init(BlockDriverState *bs)
2461 BDRVVmdkState *s = bs->opaque;
2463 /* If has a flat extent and its underlying storage doesn't have zero init,
2465 for (i = 0; i < s->num_extents; i++) {
2466 if (s->extents[i].flat) {
2467 if (!bdrv_has_zero_init(s->extents[i].file->bs)) {
2475 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2477 ImageInfo *info = g_new0(ImageInfo, 1);
2479 bdrv_refresh_filename(extent->file->bs);
2480 *info = (ImageInfo){
2481 .filename = g_strdup(extent->file->bs->filename),
2482 .format = g_strdup(extent->type),
2483 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2484 .compressed = extent->compressed,
2485 .has_compressed = extent->compressed,
2486 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2487 .has_cluster_size = !extent->flat,
2493 static int coroutine_fn vmdk_co_check(BlockDriverState *bs,
2494 BdrvCheckResult *result,
2497 BDRVVmdkState *s = bs->opaque;
2498 VmdkExtent *extent = NULL;
2499 int64_t sector_num = 0;
2500 int64_t total_sectors = bdrv_nb_sectors(bs);
2502 uint64_t cluster_offset;
2509 if (sector_num >= total_sectors) {
2512 extent = find_extent(s, sector_num, extent);
2515 "ERROR: could not find extent for sector %" PRId64 "\n",
2520 ret = get_cluster_offset(bs, extent, NULL,
2521 sector_num << BDRV_SECTOR_BITS,
2522 false, &cluster_offset, 0, 0);
2523 if (ret == VMDK_ERROR) {
2525 "ERROR: could not get cluster_offset for sector %"
2526 PRId64 "\n", sector_num);
2529 if (ret == VMDK_OK) {
2530 int64_t extent_len = bdrv_getlength(extent->file->bs);
2531 if (extent_len < 0) {
2533 "ERROR: could not get extent file length for sector %"
2534 PRId64 "\n", sector_num);
2538 if (cluster_offset >= extent_len) {
2540 "ERROR: cluster offset for sector %"
2541 PRId64 " points after EOF\n", sector_num);
2546 sector_num += extent->cluster_sectors;
2549 result->corruptions++;
2553 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs,
2557 BDRVVmdkState *s = bs->opaque;
2558 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2559 ImageInfoList **next;
2561 *spec_info = (ImageInfoSpecific){
2562 .type = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2564 .vmdk.data = g_new0(ImageInfoSpecificVmdk, 1),
2568 *spec_info->u.vmdk.data = (ImageInfoSpecificVmdk) {
2569 .create_type = g_strdup(s->create_type),
2571 .parent_cid = s->parent_cid,
2574 next = &spec_info->u.vmdk.data->extents;
2575 for (i = 0; i < s->num_extents; i++) {
2576 *next = g_new0(ImageInfoList, 1);
2577 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2578 (*next)->next = NULL;
2579 next = &(*next)->next;
2585 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2587 return a->flat == b->flat &&
2588 a->compressed == b->compressed &&
2589 (a->flat || a->cluster_sectors == b->cluster_sectors);
2592 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2595 BDRVVmdkState *s = bs->opaque;
2596 assert(s->num_extents);
2598 /* See if we have multiple extents but they have different cases */
2599 for (i = 1; i < s->num_extents; i++) {
2600 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2604 bdi->needs_compressed_writes = s->extents[0].compressed;
2605 if (!s->extents[0].flat) {
2606 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2611 static QemuOptsList vmdk_create_opts = {
2612 .name = "vmdk-create-opts",
2613 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2616 .name = BLOCK_OPT_SIZE,
2617 .type = QEMU_OPT_SIZE,
2618 .help = "Virtual disk size"
2621 .name = BLOCK_OPT_ADAPTER_TYPE,
2622 .type = QEMU_OPT_STRING,
2623 .help = "Virtual adapter type, can be one of "
2624 "ide (default), lsilogic, buslogic or legacyESX"
2627 .name = BLOCK_OPT_BACKING_FILE,
2628 .type = QEMU_OPT_STRING,
2629 .help = "File name of a base image"
2632 .name = BLOCK_OPT_COMPAT6,
2633 .type = QEMU_OPT_BOOL,
2634 .help = "VMDK version 6 image",
2635 .def_value_str = "off"
2638 .name = BLOCK_OPT_HWVERSION,
2639 .type = QEMU_OPT_STRING,
2640 .help = "VMDK hardware version",
2641 .def_value_str = "undefined"
2644 .name = BLOCK_OPT_SUBFMT,
2645 .type = QEMU_OPT_STRING,
2647 "VMDK flat extent format, can be one of "
2648 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2651 .name = BLOCK_OPT_ZEROED_GRAIN,
2652 .type = QEMU_OPT_BOOL,
2653 .help = "Enable efficient zero writes "
2654 "using the zeroed-grain GTE feature"
2656 { /* end of list */ }
2660 static BlockDriver bdrv_vmdk = {
2661 .format_name = "vmdk",
2662 .instance_size = sizeof(BDRVVmdkState),
2663 .bdrv_probe = vmdk_probe,
2664 .bdrv_open = vmdk_open,
2665 .bdrv_co_check = vmdk_co_check,
2666 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2667 .bdrv_child_perm = bdrv_format_default_perms,
2668 .bdrv_co_preadv = vmdk_co_preadv,
2669 .bdrv_co_pwritev = vmdk_co_pwritev,
2670 .bdrv_co_pwritev_compressed = vmdk_co_pwritev_compressed,
2671 .bdrv_co_pwrite_zeroes = vmdk_co_pwrite_zeroes,
2672 .bdrv_close = vmdk_close,
2673 .bdrv_co_create_opts = vmdk_co_create_opts,
2674 .bdrv_co_create = vmdk_co_create,
2675 .bdrv_co_flush_to_disk = vmdk_co_flush,
2676 .bdrv_co_block_status = vmdk_co_block_status,
2677 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2678 .bdrv_has_zero_init = vmdk_has_zero_init,
2679 .bdrv_get_specific_info = vmdk_get_specific_info,
2680 .bdrv_refresh_limits = vmdk_refresh_limits,
2681 .bdrv_get_info = vmdk_get_info,
2683 .supports_backing = true,
2684 .create_opts = &vmdk_create_opts,
2687 static void bdrv_vmdk_init(void)
2689 bdrv_register(&bdrv_vmdk);
2692 block_init(bdrv_vmdk_init);