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"
33 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
34 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
35 #define VMDK4_COMPRESSION_DEFLATE 1
36 #define VMDK4_FLAG_NL_DETECT (1 << 0)
37 #define VMDK4_FLAG_RGD (1 << 1)
38 /* Zeroed-grain enable bit */
39 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
40 #define VMDK4_FLAG_COMPRESS (1 << 16)
41 #define VMDK4_FLAG_MARKER (1 << 17)
42 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
44 #define VMDK_GTE_ZEROED 0x1
46 /* VMDK internal error codes */
48 #define VMDK_ERROR (-1)
49 /* Cluster not allocated */
50 #define VMDK_UNALLOC (-2)
51 #define VMDK_ZEROED (-3)
53 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
58 uint32_t disk_sectors;
60 uint32_t l1dir_offset;
62 uint32_t file_sectors;
65 uint32_t sectors_per_track;
66 } QEMU_PACKED VMDK3Header;
75 /* Number of GrainTableEntries per GrainTable */
76 uint32_t num_gtes_per_gt;
79 uint64_t grain_offset;
82 uint16_t compressAlgorithm;
83 } QEMU_PACKED VMDK4Header;
85 #define L2_CACHE_SIZE 16
87 typedef struct VmdkExtent {
88 BlockDriverState *file;
96 int64_t flat_start_offset;
97 int64_t l1_table_offset;
98 int64_t l1_backup_table_offset;
100 uint32_t *l1_backup_table;
101 unsigned int l1_size;
102 uint32_t l1_entry_sectors;
104 unsigned int l2_size;
106 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
107 uint32_t l2_cache_counts[L2_CACHE_SIZE];
109 int64_t cluster_sectors;
110 int64_t next_cluster_sector;
114 typedef struct BDRVVmdkState {
116 uint64_t desc_offset;
122 /* Extent array with num_extents entries, ascend ordered by address */
124 Error *migration_blocker;
128 typedef struct VmdkMetaData {
129 unsigned int l1_index;
130 unsigned int l2_index;
131 unsigned int l2_offset;
133 uint32_t *l2_cache_entry;
136 typedef struct VmdkGrainMarker {
140 } QEMU_PACKED VmdkGrainMarker;
143 MARKER_END_OF_STREAM = 0,
144 MARKER_GRAIN_TABLE = 1,
145 MARKER_GRAIN_DIRECTORY = 2,
149 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
156 magic = be32_to_cpu(*(uint32_t *)buf);
157 if (magic == VMDK3_MAGIC ||
158 magic == VMDK4_MAGIC) {
161 const char *p = (const char *)buf;
162 const char *end = p + buf_size;
165 /* skip comment line */
166 while (p < end && *p != '\n') {
173 while (p < end && *p == ' ') {
176 /* skip '\r' if windows line endings used. */
177 if (p < end && *p == '\r') {
180 /* only accept blank lines before 'version=' line */
181 if (p == end || *p != '\n') {
187 if (end - p >= strlen("version=X\n")) {
188 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
189 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
193 if (end - p >= strlen("version=X\r\n")) {
194 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
195 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
205 #define SECTOR_SIZE 512
206 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
207 #define BUF_SIZE 4096
208 #define HEADER_SIZE 512 /* first sector of 512 bytes */
210 static void vmdk_free_extents(BlockDriverState *bs)
213 BDRVVmdkState *s = bs->opaque;
216 for (i = 0; i < s->num_extents; i++) {
220 g_free(e->l1_backup_table);
222 if (e->file != bs->file) {
229 static void vmdk_free_last_extent(BlockDriverState *bs)
231 BDRVVmdkState *s = bs->opaque;
233 if (s->num_extents == 0) {
237 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
240 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
242 char desc[DESC_SIZE];
243 uint32_t cid = 0xffffffff;
244 const char *p_name, *cid_str;
246 BDRVVmdkState *s = bs->opaque;
249 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
255 cid_str = "parentCID";
256 cid_str_size = sizeof("parentCID");
259 cid_str_size = sizeof("CID");
262 desc[DESC_SIZE - 1] = '\0';
263 p_name = strstr(desc, cid_str);
264 if (p_name != NULL) {
265 p_name += cid_str_size;
266 sscanf(p_name, "%" SCNx32, &cid);
272 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
274 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
275 char *p_name, *tmp_str;
276 BDRVVmdkState *s = bs->opaque;
279 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
284 desc[DESC_SIZE - 1] = '\0';
285 tmp_str = strstr(desc, "parentCID");
286 if (tmp_str == NULL) {
290 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
291 p_name = strstr(desc, "CID");
292 if (p_name != NULL) {
293 p_name += sizeof("CID");
294 snprintf(p_name, sizeof(desc) - (p_name - desc), "%" PRIx32 "\n", cid);
295 pstrcat(desc, sizeof(desc), tmp_desc);
298 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
306 static int vmdk_is_cid_valid(BlockDriverState *bs)
308 BDRVVmdkState *s = bs->opaque;
309 BlockDriverState *p_bs = bs->backing_hd;
312 if (!s->cid_checked && p_bs) {
313 cur_pcid = vmdk_read_cid(p_bs, 0);
314 if (s->parent_cid != cur_pcid) {
319 s->cid_checked = true;
324 /* Queue extents, if any, for reopen() */
325 static int vmdk_reopen_prepare(BDRVReopenState *state,
326 BlockReopenQueue *queue, Error **errp)
333 assert(state != NULL);
334 assert(state->bs != NULL);
337 error_setg(errp, "No reopen queue for VMDK extents");
341 s = state->bs->opaque;
345 for (i = 0; i < s->num_extents; i++) {
347 if (e->file != state->bs->file) {
348 bdrv_reopen_queue(queue, e->file, state->flags);
357 static int vmdk_parent_open(BlockDriverState *bs)
360 char desc[DESC_SIZE + 1];
361 BDRVVmdkState *s = bs->opaque;
364 desc[DESC_SIZE] = '\0';
365 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
370 p_name = strstr(desc, "parentFileNameHint");
371 if (p_name != NULL) {
374 p_name += sizeof("parentFileNameHint") + 1;
375 end_name = strchr(p_name, '\"');
376 if (end_name == NULL) {
379 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
383 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
389 /* Create and append extent to the extent array. Return the added VmdkExtent
390 * address. return NULL if allocation failed. */
391 static int vmdk_add_extent(BlockDriverState *bs,
392 BlockDriverState *file, bool flat, int64_t sectors,
393 int64_t l1_offset, int64_t l1_backup_offset,
395 int l2_size, uint64_t cluster_sectors,
396 VmdkExtent **new_extent,
400 BDRVVmdkState *s = bs->opaque;
403 if (cluster_sectors > 0x200000) {
404 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
405 error_setg(errp, "Invalid granularity, image may be corrupt");
408 if (l1_size > 512 * 1024 * 1024) {
409 /* Although with big capacity and small l1_entry_sectors, we can get a
410 * big l1_size, we don't want unbounded value to allocate the table.
411 * Limit it to 512M, which is 16PB for default cluster and L2 table
413 error_setg(errp, "L1 size too big");
417 nb_sectors = bdrv_nb_sectors(file);
418 if (nb_sectors < 0) {
422 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
423 extent = &s->extents[s->num_extents];
426 memset(extent, 0, sizeof(VmdkExtent));
429 extent->sectors = sectors;
430 extent->l1_table_offset = l1_offset;
431 extent->l1_backup_table_offset = l1_backup_offset;
432 extent->l1_size = l1_size;
433 extent->l1_entry_sectors = l2_size * cluster_sectors;
434 extent->l2_size = l2_size;
435 extent->cluster_sectors = flat ? sectors : cluster_sectors;
436 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
438 if (s->num_extents > 1) {
439 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
441 extent->end_sector = extent->sectors;
443 bs->total_sectors = extent->end_sector;
445 *new_extent = extent;
450 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
457 /* read the L1 table */
458 l1_size = extent->l1_size * sizeof(uint32_t);
459 extent->l1_table = g_try_malloc(l1_size);
460 if (l1_size && extent->l1_table == NULL) {
464 ret = bdrv_pread(extent->file,
465 extent->l1_table_offset,
469 error_setg_errno(errp, -ret,
470 "Could not read l1 table from extent '%s'",
471 extent->file->filename);
474 for (i = 0; i < extent->l1_size; i++) {
475 le32_to_cpus(&extent->l1_table[i]);
478 if (extent->l1_backup_table_offset) {
479 extent->l1_backup_table = g_try_malloc(l1_size);
480 if (l1_size && extent->l1_backup_table == NULL) {
484 ret = bdrv_pread(extent->file,
485 extent->l1_backup_table_offset,
486 extent->l1_backup_table,
489 error_setg_errno(errp, -ret,
490 "Could not read l1 backup table from extent '%s'",
491 extent->file->filename);
494 for (i = 0; i < extent->l1_size; i++) {
495 le32_to_cpus(&extent->l1_backup_table[i]);
500 g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
503 g_free(extent->l1_backup_table);
505 g_free(extent->l1_table);
509 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
510 BlockDriverState *file,
511 int flags, Error **errp)
518 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
520 error_setg_errno(errp, -ret,
521 "Could not read header from file '%s'",
525 ret = vmdk_add_extent(bs, file, false,
526 le32_to_cpu(header.disk_sectors),
527 (int64_t)le32_to_cpu(header.l1dir_offset) << 9,
529 le32_to_cpu(header.l1dir_size),
531 le32_to_cpu(header.granularity),
537 ret = vmdk_init_tables(bs, extent, errp);
539 /* free extent allocated by vmdk_add_extent */
540 vmdk_free_last_extent(bs);
545 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
548 static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset,
555 size = bdrv_getlength(file);
557 error_setg_errno(errp, -size, "Could not access file");
562 /* Both descriptor file and sparse image must be much larger than 4
563 * bytes, also callers of vmdk_read_desc want to compare the first 4
564 * bytes with VMDK4_MAGIC, let's error out if less is read. */
565 error_setg(errp, "File is too small, not a valid image");
569 size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */
570 buf = g_malloc(size + 1);
572 ret = bdrv_pread(file, desc_offset, buf, size);
574 error_setg_errno(errp, -ret, "Could not read from file");
583 static int vmdk_open_vmdk4(BlockDriverState *bs,
584 BlockDriverState *file,
585 int flags, Error **errp)
589 uint32_t l1_size, l1_entry_sectors;
592 BDRVVmdkState *s = bs->opaque;
593 int64_t l1_backup_offset = 0;
595 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
597 error_setg_errno(errp, -ret,
598 "Could not read header from file '%s'",
602 if (header.capacity == 0) {
603 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
605 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
609 ret = vmdk_open_desc_file(bs, flags, buf, errp);
615 if (!s->create_type) {
616 s->create_type = g_strdup("monolithicSparse");
619 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
621 * The footer takes precedence over the header, so read it in. The
622 * footer starts at offset -1024 from the end: One sector for the
623 * footer, and another one for the end-of-stream marker.
630 uint8_t pad[512 - 16];
631 } QEMU_PACKED footer_marker;
635 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
641 uint8_t pad[512 - 16];
642 } QEMU_PACKED eos_marker;
643 } QEMU_PACKED footer;
645 ret = bdrv_pread(file,
646 bs->file->total_sectors * 512 - 1536,
647 &footer, sizeof(footer));
649 error_setg_errno(errp, -ret, "Failed to read footer");
653 /* Some sanity checks for the footer */
654 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
655 le32_to_cpu(footer.footer_marker.size) != 0 ||
656 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
657 le64_to_cpu(footer.eos_marker.val) != 0 ||
658 le32_to_cpu(footer.eos_marker.size) != 0 ||
659 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
661 error_setg(errp, "Invalid footer");
665 header = footer.header;
668 if (le32_to_cpu(header.version) > 3) {
670 snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
671 le32_to_cpu(header.version));
672 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
673 bdrv_get_device_or_node_name(bs), "vmdk", buf);
675 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
676 /* VMware KB 2064959 explains that version 3 added support for
677 * persistent changed block tracking (CBT), and backup software can
678 * read it as version=1 if it doesn't care about the changed area
679 * information. So we are safe to enable read only. */
680 error_setg(errp, "VMDK version 3 must be read only");
684 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
685 error_setg(errp, "L2 table size too big");
689 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
690 * le64_to_cpu(header.granularity);
691 if (l1_entry_sectors == 0) {
692 error_setg(errp, "L1 entry size is invalid");
695 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
697 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
698 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
700 if (bdrv_nb_sectors(file) < le64_to_cpu(header.grain_offset)) {
701 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
702 (int64_t)(le64_to_cpu(header.grain_offset)
703 * BDRV_SECTOR_SIZE));
707 ret = vmdk_add_extent(bs, file, false,
708 le64_to_cpu(header.capacity),
709 le64_to_cpu(header.gd_offset) << 9,
712 le32_to_cpu(header.num_gtes_per_gt),
713 le64_to_cpu(header.granularity),
720 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
721 if (extent->compressed) {
722 g_free(s->create_type);
723 s->create_type = g_strdup("streamOptimized");
725 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
726 extent->version = le32_to_cpu(header.version);
727 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
728 ret = vmdk_init_tables(bs, extent, errp);
730 /* free extent allocated by vmdk_add_extent */
731 vmdk_free_last_extent(bs);
736 /* find an option value out of descriptor file */
737 static int vmdk_parse_description(const char *desc, const char *opt_name,
738 char *buf, int buf_size)
740 char *opt_pos, *opt_end;
741 const char *end = desc + strlen(desc);
743 opt_pos = strstr(desc, opt_name);
747 /* Skip "=\"" following opt_name */
748 opt_pos += strlen(opt_name) + 2;
749 if (opt_pos >= end) {
753 while (opt_end < end && *opt_end != '"') {
756 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
759 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
763 /* Open an extent file and append to bs array */
764 static int vmdk_open_sparse(BlockDriverState *bs,
765 BlockDriverState *file, int flags,
766 char *buf, Error **errp)
770 magic = ldl_be_p(buf);
773 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
776 return vmdk_open_vmdk4(bs, file, flags, errp);
779 error_setg(errp, "Image not in VMDK format");
785 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
786 const char *desc_file_path, Error **errp)
793 const char *p = desc;
797 BlockDriverState *extent_file;
798 BDRVVmdkState *s = bs->opaque;
802 /* parse extent line in one of below formats:
804 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
805 * RW [size in sectors] SPARSE "file-name.vmdk"
806 * RW [size in sectors] VMFS "file-name.vmdk"
807 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
810 matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
811 access, §ors, type, fname, &flat_offset);
812 if (matches < 4 || strcmp(access, "RW")) {
814 } else if (!strcmp(type, "FLAT")) {
815 if (matches != 5 || flat_offset < 0) {
816 error_setg(errp, "Invalid extent lines: \n%s", p);
819 } else if (!strcmp(type, "VMFS")) {
823 error_setg(errp, "Invalid extent lines:\n%s", p);
826 } else if (matches != 4) {
827 error_setg(errp, "Invalid extent lines:\n%s", p);
832 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
833 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
834 (strcmp(access, "RW"))) {
838 if (!path_is_absolute(fname) && !path_has_protocol(fname) &&
841 error_setg(errp, "Cannot use relative extent paths with VMDK "
842 "descriptor file '%s'", bs->file->filename);
846 extent_path = g_malloc0(PATH_MAX);
847 path_combine(extent_path, PATH_MAX, desc_file_path, fname);
849 ret = bdrv_open(&extent_file, extent_path, NULL, NULL,
850 bs->open_flags | BDRV_O_PROTOCOL, NULL, errp);
856 /* save to extents array */
857 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
860 ret = vmdk_add_extent(bs, extent_file, true, sectors,
861 0, 0, 0, 0, 0, &extent, errp);
863 bdrv_unref(extent_file);
866 extent->flat_start_offset = flat_offset << 9;
867 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
868 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
869 char *buf = vmdk_read_desc(extent_file, 0, errp);
873 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf, errp);
877 bdrv_unref(extent_file);
880 extent = &s->extents[s->num_extents - 1];
882 error_setg(errp, "Unsupported extent type '%s'", type);
883 bdrv_unref(extent_file);
886 extent->type = g_strdup(type);
888 /* move to next line */
900 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
905 BDRVVmdkState *s = bs->opaque;
907 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
908 error_setg(errp, "invalid VMDK image descriptor");
912 if (strcmp(ct, "monolithicFlat") &&
913 strcmp(ct, "vmfs") &&
914 strcmp(ct, "vmfsSparse") &&
915 strcmp(ct, "twoGbMaxExtentSparse") &&
916 strcmp(ct, "twoGbMaxExtentFlat")) {
917 error_setg(errp, "Unsupported image type '%s'", ct);
921 s->create_type = g_strdup(ct);
923 ret = vmdk_parse_extents(buf, bs, bs->file->exact_filename, errp);
928 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
933 BDRVVmdkState *s = bs->opaque;
936 buf = vmdk_read_desc(bs->file, 0, errp);
941 magic = ldl_be_p(buf);
945 ret = vmdk_open_sparse(bs, bs->file, flags, buf, errp);
946 s->desc_offset = 0x200;
949 ret = vmdk_open_desc_file(bs, flags, buf, errp);
956 /* try to open parent images, if exist */
957 ret = vmdk_parent_open(bs);
961 s->cid = vmdk_read_cid(bs, 0);
962 s->parent_cid = vmdk_read_cid(bs, 1);
963 qemu_co_mutex_init(&s->lock);
965 /* Disable migration when VMDK images are used */
966 error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "
967 "does not support live migration",
968 bdrv_get_device_or_node_name(bs));
969 migrate_add_blocker(s->migration_blocker);
975 g_free(s->create_type);
976 s->create_type = NULL;
977 vmdk_free_extents(bs);
982 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
984 BDRVVmdkState *s = bs->opaque;
987 for (i = 0; i < s->num_extents; i++) {
988 if (!s->extents[i].flat) {
989 bs->bl.write_zeroes_alignment =
990 MAX(bs->bl.write_zeroes_alignment,
991 s->extents[i].cluster_sectors);
999 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1000 * to the cluster at @cluster_sector_num.
1002 * If @skip_start_sector < @skip_end_sector, the relative range
1003 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1004 * it for call to write user data in the request.
1006 static int get_whole_cluster(BlockDriverState *bs,
1008 uint64_t cluster_sector_num,
1009 uint64_t sector_num,
1010 uint64_t skip_start_sector,
1011 uint64_t skip_end_sector)
1014 int64_t cluster_bytes;
1015 uint8_t *whole_grain;
1017 /* For COW, align request sector_num to cluster start */
1018 sector_num = QEMU_ALIGN_DOWN(sector_num, extent->cluster_sectors);
1019 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
1020 whole_grain = qemu_blockalign(bs, cluster_bytes);
1022 if (!bs->backing_hd) {
1023 memset(whole_grain, 0, skip_start_sector << BDRV_SECTOR_BITS);
1024 memset(whole_grain + (skip_end_sector << BDRV_SECTOR_BITS), 0,
1025 cluster_bytes - (skip_end_sector << BDRV_SECTOR_BITS));
1028 assert(skip_end_sector <= extent->cluster_sectors);
1029 /* we will be here if it's first write on non-exist grain(cluster).
1030 * try to read from parent image, if exist */
1031 if (bs->backing_hd && !vmdk_is_cid_valid(bs)) {
1036 /* Read backing data before skip range */
1037 if (skip_start_sector > 0) {
1038 if (bs->backing_hd) {
1039 ret = bdrv_read(bs->backing_hd, sector_num,
1040 whole_grain, skip_start_sector);
1046 ret = bdrv_write(extent->file, cluster_sector_num, whole_grain,
1053 /* Read backing data after skip range */
1054 if (skip_end_sector < extent->cluster_sectors) {
1055 if (bs->backing_hd) {
1056 ret = bdrv_read(bs->backing_hd, sector_num + skip_end_sector,
1057 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1058 extent->cluster_sectors - skip_end_sector);
1064 ret = bdrv_write(extent->file, cluster_sector_num + skip_end_sector,
1065 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1066 extent->cluster_sectors - skip_end_sector);
1074 qemu_vfree(whole_grain);
1078 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1081 offset = cpu_to_le32(offset);
1082 /* update L2 table */
1083 if (bdrv_pwrite_sync(
1085 ((int64_t)m_data->l2_offset * 512)
1086 + (m_data->l2_index * sizeof(offset)),
1087 &offset, sizeof(offset)) < 0) {
1090 /* update backup L2 table */
1091 if (extent->l1_backup_table_offset != 0) {
1092 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1093 if (bdrv_pwrite_sync(
1095 ((int64_t)m_data->l2_offset * 512)
1096 + (m_data->l2_index * sizeof(offset)),
1097 &offset, sizeof(offset)) < 0) {
1101 if (m_data->l2_cache_entry) {
1102 *m_data->l2_cache_entry = offset;
1109 * get_cluster_offset
1111 * Look up cluster offset in extent file by sector number, and store in
1114 * For flat extents, the start offset as parsed from the description file is
1117 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1118 * offset for a new cluster and update L2 cache. If there is a backing file,
1119 * COW is done before returning; otherwise, zeroes are written to the allocated
1120 * cluster. Both COW and zero writing skips the sector range
1121 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1122 * has new data to write there.
1124 * Returns: VMDK_OK if cluster exists and mapped in the image.
1125 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1126 * VMDK_ERROR if failed.
1128 static int get_cluster_offset(BlockDriverState *bs,
1130 VmdkMetaData *m_data,
1133 uint64_t *cluster_offset,
1134 uint64_t skip_start_sector,
1135 uint64_t skip_end_sector)
1137 unsigned int l1_index, l2_offset, l2_index;
1138 int min_index, i, j;
1139 uint32_t min_count, *l2_table;
1140 bool zeroed = false;
1142 int64_t cluster_sector;
1148 *cluster_offset = extent->flat_start_offset;
1152 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1153 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1154 if (l1_index >= extent->l1_size) {
1157 l2_offset = extent->l1_table[l1_index];
1159 return VMDK_UNALLOC;
1161 for (i = 0; i < L2_CACHE_SIZE; i++) {
1162 if (l2_offset == extent->l2_cache_offsets[i]) {
1163 /* increment the hit count */
1164 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1165 for (j = 0; j < L2_CACHE_SIZE; j++) {
1166 extent->l2_cache_counts[j] >>= 1;
1169 l2_table = extent->l2_cache + (i * extent->l2_size);
1173 /* not found: load a new entry in the least used one */
1175 min_count = 0xffffffff;
1176 for (i = 0; i < L2_CACHE_SIZE; i++) {
1177 if (extent->l2_cache_counts[i] < min_count) {
1178 min_count = extent->l2_cache_counts[i];
1182 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1185 (int64_t)l2_offset * 512,
1187 extent->l2_size * sizeof(uint32_t)
1188 ) != extent->l2_size * sizeof(uint32_t)) {
1192 extent->l2_cache_offsets[min_index] = l2_offset;
1193 extent->l2_cache_counts[min_index] = 1;
1195 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1196 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1200 m_data->l1_index = l1_index;
1201 m_data->l2_index = l2_index;
1202 m_data->l2_offset = l2_offset;
1203 m_data->l2_cache_entry = &l2_table[l2_index];
1205 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1209 if (!cluster_sector || zeroed) {
1211 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1214 cluster_sector = extent->next_cluster_sector;
1215 extent->next_cluster_sector += extent->cluster_sectors;
1217 /* First of all we write grain itself, to avoid race condition
1218 * that may to corrupt the image.
1219 * This problem may occur because of insufficient space on host disk
1220 * or inappropriate VM shutdown.
1222 ret = get_whole_cluster(bs, extent,
1224 offset >> BDRV_SECTOR_BITS,
1225 skip_start_sector, skip_end_sector);
1230 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1234 static VmdkExtent *find_extent(BDRVVmdkState *s,
1235 int64_t sector_num, VmdkExtent *start_hint)
1237 VmdkExtent *extent = start_hint;
1240 extent = &s->extents[0];
1242 while (extent < &s->extents[s->num_extents]) {
1243 if (sector_num < extent->end_sector) {
1251 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1252 int64_t sector_num, int nb_sectors, int *pnum)
1254 BDRVVmdkState *s = bs->opaque;
1255 int64_t index_in_cluster, n, ret;
1259 extent = find_extent(s, sector_num, NULL);
1263 qemu_co_mutex_lock(&s->lock);
1264 ret = get_cluster_offset(bs, extent, NULL,
1265 sector_num * 512, false, &offset,
1267 qemu_co_mutex_unlock(&s->lock);
1277 ret = BDRV_BLOCK_ZERO;
1280 ret = BDRV_BLOCK_DATA;
1281 if (extent->file == bs->file && !extent->compressed) {
1282 ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1288 index_in_cluster = sector_num % extent->cluster_sectors;
1289 n = extent->cluster_sectors - index_in_cluster;
1290 if (n > nb_sectors) {
1297 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1298 int64_t offset_in_cluster, const uint8_t *buf,
1299 int nb_sectors, int64_t sector_num)
1302 VmdkGrainMarker *data = NULL;
1304 const uint8_t *write_buf = buf;
1305 int write_len = nb_sectors * 512;
1306 int64_t write_offset;
1307 int64_t write_end_sector;
1309 if (extent->compressed) {
1310 if (!extent->has_marker) {
1314 buf_len = (extent->cluster_sectors << 9) * 2;
1315 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1316 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1321 data->lba = sector_num;
1322 data->size = buf_len;
1323 write_buf = (uint8_t *)data;
1324 write_len = buf_len + sizeof(VmdkGrainMarker);
1326 write_offset = cluster_offset + offset_in_cluster,
1327 ret = bdrv_pwrite(extent->file, write_offset, write_buf, write_len);
1329 write_end_sector = DIV_ROUND_UP(write_offset + write_len, BDRV_SECTOR_SIZE);
1331 extent->next_cluster_sector = MAX(extent->next_cluster_sector,
1334 if (ret != write_len) {
1335 ret = ret < 0 ? ret : -EIO;
1344 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1345 int64_t offset_in_cluster, uint8_t *buf,
1349 int cluster_bytes, buf_bytes;
1350 uint8_t *cluster_buf, *compressed_data;
1351 uint8_t *uncomp_buf;
1353 VmdkGrainMarker *marker;
1357 if (!extent->compressed) {
1358 ret = bdrv_pread(extent->file,
1359 cluster_offset + offset_in_cluster,
1360 buf, nb_sectors * 512);
1361 if (ret == nb_sectors * 512) {
1367 cluster_bytes = extent->cluster_sectors * 512;
1368 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1369 buf_bytes = cluster_bytes * 2;
1370 cluster_buf = g_malloc(buf_bytes);
1371 uncomp_buf = g_malloc(cluster_bytes);
1372 ret = bdrv_pread(extent->file,
1374 cluster_buf, buf_bytes);
1378 compressed_data = cluster_buf;
1379 buf_len = cluster_bytes;
1380 data_len = cluster_bytes;
1381 if (extent->has_marker) {
1382 marker = (VmdkGrainMarker *)cluster_buf;
1383 compressed_data = marker->data;
1384 data_len = le32_to_cpu(marker->size);
1386 if (!data_len || data_len > buf_bytes) {
1390 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1396 if (offset_in_cluster < 0 ||
1397 offset_in_cluster + nb_sectors * 512 > buf_len) {
1401 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1406 g_free(cluster_buf);
1410 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1411 uint8_t *buf, int nb_sectors)
1413 BDRVVmdkState *s = bs->opaque;
1415 uint64_t n, index_in_cluster;
1416 uint64_t extent_begin_sector, extent_relative_sector_num;
1417 VmdkExtent *extent = NULL;
1418 uint64_t cluster_offset;
1420 while (nb_sectors > 0) {
1421 extent = find_extent(s, sector_num, extent);
1425 ret = get_cluster_offset(bs, extent, NULL,
1426 sector_num << 9, false, &cluster_offset,
1428 extent_begin_sector = extent->end_sector - extent->sectors;
1429 extent_relative_sector_num = sector_num - extent_begin_sector;
1430 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1431 n = extent->cluster_sectors - index_in_cluster;
1432 if (n > nb_sectors) {
1435 if (ret != VMDK_OK) {
1436 /* if not allocated, try to read from parent image, if exist */
1437 if (bs->backing_hd && ret != VMDK_ZEROED) {
1438 if (!vmdk_is_cid_valid(bs)) {
1441 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1446 memset(buf, 0, 512 * n);
1449 ret = vmdk_read_extent(extent,
1450 cluster_offset, index_in_cluster * 512,
1463 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1464 uint8_t *buf, int nb_sectors)
1467 BDRVVmdkState *s = bs->opaque;
1468 qemu_co_mutex_lock(&s->lock);
1469 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1470 qemu_co_mutex_unlock(&s->lock);
1476 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1477 * if possible, otherwise return -ENOTSUP.
1478 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1479 * with each cluster. By dry run we can find if the zero write
1480 * is possible without modifying image data.
1482 * Returns: error code with 0 for success.
1484 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1485 const uint8_t *buf, int nb_sectors,
1486 bool zeroed, bool zero_dry_run)
1488 BDRVVmdkState *s = bs->opaque;
1489 VmdkExtent *extent = NULL;
1491 int64_t index_in_cluster, n;
1492 uint64_t extent_begin_sector, extent_relative_sector_num;
1493 uint64_t cluster_offset;
1494 VmdkMetaData m_data;
1496 if (sector_num > bs->total_sectors) {
1497 error_report("Wrong offset: sector_num=0x%" PRIx64
1498 " total_sectors=0x%" PRIx64 "\n",
1499 sector_num, bs->total_sectors);
1503 while (nb_sectors > 0) {
1504 extent = find_extent(s, sector_num, extent);
1508 extent_begin_sector = extent->end_sector - extent->sectors;
1509 extent_relative_sector_num = sector_num - extent_begin_sector;
1510 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1511 n = extent->cluster_sectors - index_in_cluster;
1512 if (n > nb_sectors) {
1515 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1516 !(extent->compressed || zeroed),
1518 index_in_cluster, index_in_cluster + n);
1519 if (extent->compressed) {
1520 if (ret == VMDK_OK) {
1521 /* Refuse write to allocated cluster for streamOptimized */
1522 error_report("Could not write to allocated cluster"
1523 " for streamOptimized");
1527 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1528 true, &cluster_offset, 0, 0);
1531 if (ret == VMDK_ERROR) {
1535 /* Do zeroed write, buf is ignored */
1536 if (extent->has_zero_grain &&
1537 index_in_cluster == 0 &&
1538 n >= extent->cluster_sectors) {
1539 n = extent->cluster_sectors;
1540 if (!zero_dry_run) {
1541 /* update L2 tables */
1542 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1551 ret = vmdk_write_extent(extent,
1552 cluster_offset, index_in_cluster * 512,
1553 buf, n, sector_num);
1558 /* update L2 tables */
1559 if (vmdk_L2update(extent, &m_data,
1560 cluster_offset >> BDRV_SECTOR_BITS)
1570 /* update CID on the first write every time the virtual disk is
1572 if (!s->cid_updated) {
1573 ret = vmdk_write_cid(bs, g_random_int());
1577 s->cid_updated = true;
1583 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1584 const uint8_t *buf, int nb_sectors)
1587 BDRVVmdkState *s = bs->opaque;
1588 qemu_co_mutex_lock(&s->lock);
1589 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1590 qemu_co_mutex_unlock(&s->lock);
1594 static int vmdk_write_compressed(BlockDriverState *bs,
1599 BDRVVmdkState *s = bs->opaque;
1600 if (s->num_extents == 1 && s->extents[0].compressed) {
1601 return vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1607 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1610 BdrvRequestFlags flags)
1613 BDRVVmdkState *s = bs->opaque;
1614 qemu_co_mutex_lock(&s->lock);
1615 /* write zeroes could fail if sectors not aligned to cluster, test it with
1616 * dry_run == true before really updating image */
1617 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1619 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1621 qemu_co_mutex_unlock(&s->lock);
1625 static int vmdk_create_extent(const char *filename, int64_t filesize,
1626 bool flat, bool compress, bool zeroed_grain,
1627 QemuOpts *opts, Error **errp)
1630 BlockDriverState *bs = NULL;
1632 Error *local_err = NULL;
1633 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1634 uint32_t *gd_buf = NULL;
1637 ret = bdrv_create_file(filename, opts, &local_err);
1639 error_propagate(errp, local_err);
1644 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1647 error_propagate(errp, local_err);
1652 ret = bdrv_truncate(bs, filesize);
1654 error_setg_errno(errp, -ret, "Could not truncate file");
1658 magic = cpu_to_be32(VMDK4_MAGIC);
1659 memset(&header, 0, sizeof(header));
1660 header.version = zeroed_grain ? 2 : 1;
1661 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1662 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1663 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1664 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1665 header.capacity = filesize / BDRV_SECTOR_SIZE;
1666 header.granularity = 128;
1667 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1669 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1670 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1672 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1673 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1675 header.desc_offset = 1;
1676 header.desc_size = 20;
1677 header.rgd_offset = header.desc_offset + header.desc_size;
1678 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1679 header.grain_offset =
1680 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1681 header.granularity);
1682 /* swap endianness for all header fields */
1683 header.version = cpu_to_le32(header.version);
1684 header.flags = cpu_to_le32(header.flags);
1685 header.capacity = cpu_to_le64(header.capacity);
1686 header.granularity = cpu_to_le64(header.granularity);
1687 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1688 header.desc_offset = cpu_to_le64(header.desc_offset);
1689 header.desc_size = cpu_to_le64(header.desc_size);
1690 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1691 header.gd_offset = cpu_to_le64(header.gd_offset);
1692 header.grain_offset = cpu_to_le64(header.grain_offset);
1693 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1695 header.check_bytes[0] = 0xa;
1696 header.check_bytes[1] = 0x20;
1697 header.check_bytes[2] = 0xd;
1698 header.check_bytes[3] = 0xa;
1700 /* write all the data */
1701 ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1703 error_set(errp, QERR_IO_ERROR);
1706 ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1708 error_set(errp, QERR_IO_ERROR);
1712 ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1714 error_setg_errno(errp, -ret, "Could not truncate file");
1718 /* write grain directory */
1719 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1720 gd_buf = g_malloc0(gd_buf_size);
1721 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1722 i < gt_count; i++, tmp += gt_size) {
1723 gd_buf[i] = cpu_to_le32(tmp);
1725 ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1726 gd_buf, gd_buf_size);
1728 error_set(errp, QERR_IO_ERROR);
1732 /* write backup grain directory */
1733 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1734 i < gt_count; i++, tmp += gt_size) {
1735 gd_buf[i] = cpu_to_le32(tmp);
1737 ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1738 gd_buf, gd_buf_size);
1740 error_set(errp, QERR_IO_ERROR);
1753 static int filename_decompose(const char *filename, char *path, char *prefix,
1754 char *postfix, size_t buf_len, Error **errp)
1758 if (filename == NULL || !strlen(filename)) {
1759 error_setg(errp, "No filename provided");
1762 p = strrchr(filename, '/');
1764 p = strrchr(filename, '\\');
1767 p = strrchr(filename, ':');
1771 if (p - filename >= buf_len) {
1774 pstrcpy(path, p - filename + 1, filename);
1779 q = strrchr(p, '.');
1781 pstrcpy(prefix, buf_len, p);
1784 if (q - p >= buf_len) {
1787 pstrcpy(prefix, q - p + 1, p);
1788 pstrcpy(postfix, buf_len, q);
1793 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1796 BlockDriverState *new_bs = NULL;
1797 Error *local_err = NULL;
1799 int64_t total_size = 0, filesize;
1800 char *adapter_type = NULL;
1801 char *backing_file = NULL;
1805 bool flat, split, compress;
1806 GString *ext_desc_lines;
1807 char *path = g_malloc0(PATH_MAX);
1808 char *prefix = g_malloc0(PATH_MAX);
1809 char *postfix = g_malloc0(PATH_MAX);
1810 char *desc_line = g_malloc0(BUF_SIZE);
1811 char *ext_filename = g_malloc0(PATH_MAX);
1812 char *desc_filename = g_malloc0(PATH_MAX);
1813 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1814 const char *desc_extent_line;
1815 char *parent_desc_line = g_malloc0(BUF_SIZE);
1816 uint32_t parent_cid = 0xffffffff;
1817 uint32_t number_heads = 16;
1818 bool zeroed_grain = false;
1819 uint32_t desc_offset = 0, desc_len;
1820 const char desc_template[] =
1821 "# Disk DescriptorFile\n"
1824 "parentCID=%" PRIx32 "\n"
1825 "createType=\"%s\"\n"
1828 "# Extent description\n"
1831 "# The Disk Data Base\n"
1834 "ddb.virtualHWVersion = \"%d\"\n"
1835 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1836 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1837 "ddb.geometry.sectors = \"63\"\n"
1838 "ddb.adapterType = \"%s\"\n";
1840 ext_desc_lines = g_string_new(NULL);
1842 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1846 /* Read out options */
1847 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1849 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1850 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1851 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1852 flags |= BLOCK_FLAG_COMPAT6;
1854 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1855 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1856 zeroed_grain = true;
1859 if (!adapter_type) {
1860 adapter_type = g_strdup("ide");
1861 } else if (strcmp(adapter_type, "ide") &&
1862 strcmp(adapter_type, "buslogic") &&
1863 strcmp(adapter_type, "lsilogic") &&
1864 strcmp(adapter_type, "legacyESX")) {
1865 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1869 if (strcmp(adapter_type, "ide") != 0) {
1870 /* that's the number of heads with which vmware operates when
1871 creating, exporting, etc. vmdk files with a non-ide adapter type */
1875 /* Default format to monolithicSparse */
1876 fmt = g_strdup("monolithicSparse");
1877 } else if (strcmp(fmt, "monolithicFlat") &&
1878 strcmp(fmt, "monolithicSparse") &&
1879 strcmp(fmt, "twoGbMaxExtentSparse") &&
1880 strcmp(fmt, "twoGbMaxExtentFlat") &&
1881 strcmp(fmt, "streamOptimized")) {
1882 error_setg(errp, "Unknown subformat: '%s'", fmt);
1886 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1887 strcmp(fmt, "twoGbMaxExtentSparse"));
1888 flat = !(strcmp(fmt, "monolithicFlat") &&
1889 strcmp(fmt, "twoGbMaxExtentFlat"));
1890 compress = !strcmp(fmt, "streamOptimized");
1892 desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1894 desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1896 if (flat && backing_file) {
1897 error_setg(errp, "Flat image can't have backing file");
1901 if (flat && zeroed_grain) {
1902 error_setg(errp, "Flat image can't enable zeroed grain");
1907 BlockDriverState *bs = NULL;
1908 char *full_backing = g_new0(char, PATH_MAX);
1909 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
1910 full_backing, PATH_MAX,
1913 g_free(full_backing);
1914 error_propagate(errp, local_err);
1918 ret = bdrv_open(&bs, full_backing, NULL, NULL, BDRV_O_NO_BACKING, NULL,
1920 g_free(full_backing);
1924 if (strcmp(bs->drv->format_name, "vmdk")) {
1929 parent_cid = vmdk_read_cid(bs, 0);
1931 snprintf(parent_desc_line, BUF_SIZE,
1932 "parentFileNameHint=\"%s\"", backing_file);
1935 /* Create extents */
1936 filesize = total_size;
1937 while (filesize > 0) {
1938 int64_t size = filesize;
1940 if (split && size > split_size) {
1944 snprintf(desc_filename, PATH_MAX, "%s-%c%03d%s",
1945 prefix, flat ? 'f' : 's', ++idx, postfix);
1947 snprintf(desc_filename, PATH_MAX, "%s-flat%s", prefix, postfix);
1949 snprintf(desc_filename, PATH_MAX, "%s%s", prefix, postfix);
1951 snprintf(ext_filename, PATH_MAX, "%s%s", path, desc_filename);
1953 if (vmdk_create_extent(ext_filename, size,
1954 flat, compress, zeroed_grain, opts, errp)) {
1960 /* Format description line */
1961 snprintf(desc_line, BUF_SIZE,
1962 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1963 g_string_append(ext_desc_lines, desc_line);
1965 /* generate descriptor file */
1966 desc = g_strdup_printf(desc_template,
1971 ext_desc_lines->str,
1972 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1974 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1977 desc_len = strlen(desc);
1978 /* the descriptor offset = 0x200 */
1979 if (!split && !flat) {
1980 desc_offset = 0x200;
1982 ret = bdrv_create_file(filename, opts, &local_err);
1984 error_propagate(errp, local_err);
1988 assert(new_bs == NULL);
1989 ret = bdrv_open(&new_bs, filename, NULL, NULL,
1990 BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
1992 error_propagate(errp, local_err);
1995 ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1997 error_setg_errno(errp, -ret, "Could not write description");
2000 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2001 * for description file */
2002 if (desc_offset == 0) {
2003 ret = bdrv_truncate(new_bs, desc_len);
2005 error_setg_errno(errp, -ret, "Could not truncate file");
2012 g_free(adapter_type);
2013 g_free(backing_file);
2020 g_free(ext_filename);
2021 g_free(desc_filename);
2022 g_free(parent_desc_line);
2023 g_string_free(ext_desc_lines, true);
2027 static void vmdk_close(BlockDriverState *bs)
2029 BDRVVmdkState *s = bs->opaque;
2031 vmdk_free_extents(bs);
2032 g_free(s->create_type);
2034 migrate_del_blocker(s->migration_blocker);
2035 error_free(s->migration_blocker);
2038 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
2040 BDRVVmdkState *s = bs->opaque;
2044 for (i = 0; i < s->num_extents; i++) {
2045 err = bdrv_co_flush(s->extents[i].file);
2053 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2058 BDRVVmdkState *s = bs->opaque;
2060 ret = bdrv_get_allocated_file_size(bs->file);
2064 for (i = 0; i < s->num_extents; i++) {
2065 if (s->extents[i].file == bs->file) {
2068 r = bdrv_get_allocated_file_size(s->extents[i].file);
2077 static int vmdk_has_zero_init(BlockDriverState *bs)
2080 BDRVVmdkState *s = bs->opaque;
2082 /* If has a flat extent and its underlying storage doesn't have zero init,
2084 for (i = 0; i < s->num_extents; i++) {
2085 if (s->extents[i].flat) {
2086 if (!bdrv_has_zero_init(s->extents[i].file)) {
2094 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2096 ImageInfo *info = g_new0(ImageInfo, 1);
2098 *info = (ImageInfo){
2099 .filename = g_strdup(extent->file->filename),
2100 .format = g_strdup(extent->type),
2101 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2102 .compressed = extent->compressed,
2103 .has_compressed = extent->compressed,
2104 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2105 .has_cluster_size = !extent->flat,
2111 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2114 BDRVVmdkState *s = bs->opaque;
2115 VmdkExtent *extent = NULL;
2116 int64_t sector_num = 0;
2117 int64_t total_sectors = bdrv_nb_sectors(bs);
2119 uint64_t cluster_offset;
2126 if (sector_num >= total_sectors) {
2129 extent = find_extent(s, sector_num, extent);
2132 "ERROR: could not find extent for sector %" PRId64 "\n",
2136 ret = get_cluster_offset(bs, extent, NULL,
2137 sector_num << BDRV_SECTOR_BITS,
2138 false, &cluster_offset, 0, 0);
2139 if (ret == VMDK_ERROR) {
2141 "ERROR: could not get cluster_offset for sector %"
2142 PRId64 "\n", sector_num);
2145 if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2147 "ERROR: cluster offset for sector %"
2148 PRId64 " points after EOF\n", sector_num);
2151 sector_num += extent->cluster_sectors;
2154 result->corruptions++;
2158 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2161 BDRVVmdkState *s = bs->opaque;
2162 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2163 ImageInfoList **next;
2165 *spec_info = (ImageInfoSpecific){
2166 .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2168 .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2172 *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2173 .create_type = g_strdup(s->create_type),
2175 .parent_cid = s->parent_cid,
2178 next = &spec_info->vmdk->extents;
2179 for (i = 0; i < s->num_extents; i++) {
2180 *next = g_new0(ImageInfoList, 1);
2181 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2182 (*next)->next = NULL;
2183 next = &(*next)->next;
2189 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2191 return a->flat == b->flat &&
2192 a->compressed == b->compressed &&
2193 (a->flat || a->cluster_sectors == b->cluster_sectors);
2196 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2199 BDRVVmdkState *s = bs->opaque;
2200 assert(s->num_extents);
2202 /* See if we have multiple extents but they have different cases */
2203 for (i = 1; i < s->num_extents; i++) {
2204 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2208 bdi->needs_compressed_writes = s->extents[0].compressed;
2209 if (!s->extents[0].flat) {
2210 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2215 static void vmdk_detach_aio_context(BlockDriverState *bs)
2217 BDRVVmdkState *s = bs->opaque;
2220 for (i = 0; i < s->num_extents; i++) {
2221 bdrv_detach_aio_context(s->extents[i].file);
2225 static void vmdk_attach_aio_context(BlockDriverState *bs,
2226 AioContext *new_context)
2228 BDRVVmdkState *s = bs->opaque;
2231 for (i = 0; i < s->num_extents; i++) {
2232 bdrv_attach_aio_context(s->extents[i].file, new_context);
2236 static QemuOptsList vmdk_create_opts = {
2237 .name = "vmdk-create-opts",
2238 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2241 .name = BLOCK_OPT_SIZE,
2242 .type = QEMU_OPT_SIZE,
2243 .help = "Virtual disk size"
2246 .name = BLOCK_OPT_ADAPTER_TYPE,
2247 .type = QEMU_OPT_STRING,
2248 .help = "Virtual adapter type, can be one of "
2249 "ide (default), lsilogic, buslogic or legacyESX"
2252 .name = BLOCK_OPT_BACKING_FILE,
2253 .type = QEMU_OPT_STRING,
2254 .help = "File name of a base image"
2257 .name = BLOCK_OPT_COMPAT6,
2258 .type = QEMU_OPT_BOOL,
2259 .help = "VMDK version 6 image",
2260 .def_value_str = "off"
2263 .name = BLOCK_OPT_SUBFMT,
2264 .type = QEMU_OPT_STRING,
2266 "VMDK flat extent format, can be one of "
2267 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2270 .name = BLOCK_OPT_ZEROED_GRAIN,
2271 .type = QEMU_OPT_BOOL,
2272 .help = "Enable efficient zero writes "
2273 "using the zeroed-grain GTE feature"
2275 { /* end of list */ }
2279 static BlockDriver bdrv_vmdk = {
2280 .format_name = "vmdk",
2281 .instance_size = sizeof(BDRVVmdkState),
2282 .bdrv_probe = vmdk_probe,
2283 .bdrv_open = vmdk_open,
2284 .bdrv_check = vmdk_check,
2285 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2286 .bdrv_read = vmdk_co_read,
2287 .bdrv_write = vmdk_co_write,
2288 .bdrv_write_compressed = vmdk_write_compressed,
2289 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
2290 .bdrv_close = vmdk_close,
2291 .bdrv_create = vmdk_create,
2292 .bdrv_co_flush_to_disk = vmdk_co_flush,
2293 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2294 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2295 .bdrv_has_zero_init = vmdk_has_zero_init,
2296 .bdrv_get_specific_info = vmdk_get_specific_info,
2297 .bdrv_refresh_limits = vmdk_refresh_limits,
2298 .bdrv_get_info = vmdk_get_info,
2299 .bdrv_detach_aio_context = vmdk_detach_aio_context,
2300 .bdrv_attach_aio_context = vmdk_attach_aio_context,
2302 .supports_backing = true,
2303 .create_opts = &vmdk_create_opts,
2306 static void bdrv_vmdk_init(void)
2308 bdrv_register(&bdrv_vmdk);
2311 block_init(bdrv_vmdk_init);