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
,
456 /* read the L1 table */
457 l1_size
= extent
->l1_size
* sizeof(uint32_t);
458 extent
->l1_table
= g_try_malloc(l1_size
);
459 if (l1_size
&& extent
->l1_table
== NULL
) {
463 ret
= bdrv_pread(extent
->file
,
464 extent
->l1_table_offset
,
468 error_setg_errno(errp
, -ret
,
469 "Could not read l1 table from extent '%s'",
470 extent
->file
->filename
);
473 for (i
= 0; i
< extent
->l1_size
; i
++) {
474 le32_to_cpus(&extent
->l1_table
[i
]);
477 if (extent
->l1_backup_table_offset
) {
478 extent
->l1_backup_table
= g_try_malloc(l1_size
);
479 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
483 ret
= bdrv_pread(extent
->file
,
484 extent
->l1_backup_table_offset
,
485 extent
->l1_backup_table
,
488 error_setg_errno(errp
, -ret
,
489 "Could not read l1 backup table from extent '%s'",
490 extent
->file
->filename
);
493 for (i
= 0; i
< extent
->l1_size
; i
++) {
494 le32_to_cpus(&extent
->l1_backup_table
[i
]);
499 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
502 g_free(extent
->l1_backup_table
);
504 g_free(extent
->l1_table
);
508 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
509 BlockDriverState
*file
,
510 int flags
, Error
**errp
)
517 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
519 error_setg_errno(errp
, -ret
,
520 "Could not read header from file '%s'",
524 ret
= vmdk_add_extent(bs
, file
, false,
525 le32_to_cpu(header
.disk_sectors
),
526 le32_to_cpu(header
.l1dir_offset
) << 9,
528 le32_to_cpu(header
.l1dir_size
),
530 le32_to_cpu(header
.granularity
),
536 ret
= vmdk_init_tables(bs
, extent
, errp
);
538 /* free extent allocated by vmdk_add_extent */
539 vmdk_free_last_extent(bs
);
544 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
547 static char *vmdk_read_desc(BlockDriverState
*file
, uint64_t desc_offset
,
554 size
= bdrv_getlength(file
);
556 error_setg_errno(errp
, -size
, "Could not access file");
561 /* Both descriptor file and sparse image must be much larger than 4
562 * bytes, also callers of vmdk_read_desc want to compare the first 4
563 * bytes with VMDK4_MAGIC, let's error out if less is read. */
564 error_setg(errp
, "File is too small, not a valid image");
568 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
569 buf
= g_malloc(size
+ 1);
571 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
573 error_setg_errno(errp
, -ret
, "Could not read from file");
582 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
583 BlockDriverState
*file
,
584 int flags
, Error
**errp
)
588 uint32_t l1_size
, l1_entry_sectors
;
591 BDRVVmdkState
*s
= bs
->opaque
;
592 int64_t l1_backup_offset
= 0;
594 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
596 error_setg_errno(errp
, -ret
,
597 "Could not read header from file '%s'",
601 if (header
.capacity
== 0) {
602 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
604 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
608 ret
= vmdk_open_desc_file(bs
, flags
, buf
, errp
);
614 if (!s
->create_type
) {
615 s
->create_type
= g_strdup("monolithicSparse");
618 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
620 * The footer takes precedence over the header, so read it in. The
621 * footer starts at offset -1024 from the end: One sector for the
622 * footer, and another one for the end-of-stream marker.
629 uint8_t pad
[512 - 16];
630 } QEMU_PACKED footer_marker
;
634 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
640 uint8_t pad
[512 - 16];
641 } QEMU_PACKED eos_marker
;
642 } QEMU_PACKED footer
;
644 ret
= bdrv_pread(file
,
645 bs
->file
->total_sectors
* 512 - 1536,
646 &footer
, sizeof(footer
));
648 error_setg_errno(errp
, -ret
, "Failed to read footer");
652 /* Some sanity checks for the footer */
653 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
654 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
655 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
656 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
657 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
658 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
660 error_setg(errp
, "Invalid footer");
664 header
= footer
.header
;
667 if (le32_to_cpu(header
.version
) > 3) {
669 snprintf(buf
, sizeof(buf
), "VMDK version %" PRId32
,
670 le32_to_cpu(header
.version
));
671 error_set(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
,
672 bdrv_get_device_name(bs
), "vmdk", buf
);
674 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
)) {
675 /* VMware KB 2064959 explains that version 3 added support for
676 * persistent changed block tracking (CBT), and backup software can
677 * read it as version=1 if it doesn't care about the changed area
678 * information. So we are safe to enable read only. */
679 error_setg(errp
, "VMDK version 3 must be read only");
683 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
684 error_setg(errp
, "L2 table size too big");
688 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
689 * le64_to_cpu(header
.granularity
);
690 if (l1_entry_sectors
== 0) {
691 error_setg(errp
, "L1 entry size is invalid");
694 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
696 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
697 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
699 if (bdrv_nb_sectors(file
) < le64_to_cpu(header
.grain_offset
)) {
700 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
701 (int64_t)(le64_to_cpu(header
.grain_offset
)
702 * BDRV_SECTOR_SIZE
));
706 ret
= vmdk_add_extent(bs
, file
, false,
707 le64_to_cpu(header
.capacity
),
708 le64_to_cpu(header
.gd_offset
) << 9,
711 le32_to_cpu(header
.num_gtes_per_gt
),
712 le64_to_cpu(header
.granularity
),
719 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
720 if (extent
->compressed
) {
721 g_free(s
->create_type
);
722 s
->create_type
= g_strdup("streamOptimized");
724 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
725 extent
->version
= le32_to_cpu(header
.version
);
726 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
727 ret
= vmdk_init_tables(bs
, extent
, errp
);
729 /* free extent allocated by vmdk_add_extent */
730 vmdk_free_last_extent(bs
);
735 /* find an option value out of descriptor file */
736 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
737 char *buf
, int buf_size
)
739 char *opt_pos
, *opt_end
;
740 const char *end
= desc
+ strlen(desc
);
742 opt_pos
= strstr(desc
, opt_name
);
746 /* Skip "=\"" following opt_name */
747 opt_pos
+= strlen(opt_name
) + 2;
748 if (opt_pos
>= end
) {
752 while (opt_end
< end
&& *opt_end
!= '"') {
755 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
758 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
762 /* Open an extent file and append to bs array */
763 static int vmdk_open_sparse(BlockDriverState
*bs
,
764 BlockDriverState
*file
, int flags
,
765 char *buf
, Error
**errp
)
769 magic
= ldl_be_p(buf
);
772 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
775 return vmdk_open_vmdk4(bs
, file
, flags
, errp
);
778 error_setg(errp
, "Image not in VMDK format");
784 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
785 const char *desc_file_path
, Error
**errp
)
791 const char *p
= desc
;
794 char extent_path
[PATH_MAX
];
795 BlockDriverState
*extent_file
;
796 BDRVVmdkState
*s
= bs
->opaque
;
800 /* parse extent line in one of below formats:
802 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
803 * RW [size in sectors] SPARSE "file-name.vmdk"
804 * RW [size in sectors] VMFS "file-name.vmdk"
805 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
808 ret
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
809 access
, §ors
, type
, fname
, &flat_offset
);
810 if (ret
< 4 || strcmp(access
, "RW")) {
812 } else if (!strcmp(type
, "FLAT")) {
813 if (ret
!= 5 || flat_offset
< 0) {
814 error_setg(errp
, "Invalid extent lines: \n%s", p
);
817 } else if (!strcmp(type
, "VMFS")) {
821 error_setg(errp
, "Invalid extent lines:\n%s", p
);
824 } else if (ret
!= 4) {
825 error_setg(errp
, "Invalid extent lines:\n%s", p
);
830 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
831 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
832 (strcmp(access
, "RW"))) {
836 path_combine(extent_path
, sizeof(extent_path
),
837 desc_file_path
, fname
);
839 ret
= bdrv_open(&extent_file
, extent_path
, NULL
, NULL
,
840 bs
->open_flags
| BDRV_O_PROTOCOL
, NULL
, errp
);
845 /* save to extents array */
846 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
849 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
850 0, 0, 0, 0, 0, &extent
, errp
);
852 bdrv_unref(extent_file
);
855 extent
->flat_start_offset
= flat_offset
<< 9;
856 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
857 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
858 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
862 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
, errp
);
866 bdrv_unref(extent_file
);
869 extent
= &s
->extents
[s
->num_extents
- 1];
871 error_setg(errp
, "Unsupported extent type '%s'", type
);
872 bdrv_unref(extent_file
);
875 extent
->type
= g_strdup(type
);
877 /* move to next line */
889 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
894 BDRVVmdkState
*s
= bs
->opaque
;
896 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
897 error_setg(errp
, "invalid VMDK image descriptor");
901 if (strcmp(ct
, "monolithicFlat") &&
902 strcmp(ct
, "vmfs") &&
903 strcmp(ct
, "vmfsSparse") &&
904 strcmp(ct
, "twoGbMaxExtentSparse") &&
905 strcmp(ct
, "twoGbMaxExtentFlat")) {
906 error_setg(errp
, "Unsupported image type '%s'", ct
);
910 s
->create_type
= g_strdup(ct
);
912 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->filename
, errp
);
917 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
922 BDRVVmdkState
*s
= bs
->opaque
;
925 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
930 magic
= ldl_be_p(buf
);
934 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, errp
);
935 s
->desc_offset
= 0x200;
938 ret
= vmdk_open_desc_file(bs
, flags
, buf
, errp
);
945 /* try to open parent images, if exist */
946 ret
= vmdk_parent_open(bs
);
950 s
->cid
= vmdk_read_cid(bs
, 0);
951 s
->parent_cid
= vmdk_read_cid(bs
, 1);
952 qemu_co_mutex_init(&s
->lock
);
954 /* Disable migration when VMDK images are used */
955 error_set(&s
->migration_blocker
,
956 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED
,
957 "vmdk", bdrv_get_device_name(bs
), "live migration");
958 migrate_add_blocker(s
->migration_blocker
);
964 g_free(s
->create_type
);
965 s
->create_type
= NULL
;
966 vmdk_free_extents(bs
);
971 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
973 BDRVVmdkState
*s
= bs
->opaque
;
976 for (i
= 0; i
< s
->num_extents
; i
++) {
977 if (!s
->extents
[i
].flat
) {
978 bs
->bl
.write_zeroes_alignment
=
979 MAX(bs
->bl
.write_zeroes_alignment
,
980 s
->extents
[i
].cluster_sectors
);
988 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
989 * to the cluster at @cluster_sector_num.
991 * If @skip_start_sector < @skip_end_sector, the relative range
992 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
993 * it for call to write user data in the request.
995 static int get_whole_cluster(BlockDriverState
*bs
,
997 uint64_t cluster_sector_num
,
999 uint64_t skip_start_sector
,
1000 uint64_t skip_end_sector
)
1003 int64_t cluster_bytes
;
1004 uint8_t *whole_grain
;
1006 /* For COW, align request sector_num to cluster start */
1007 sector_num
= QEMU_ALIGN_DOWN(sector_num
, extent
->cluster_sectors
);
1008 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1009 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1011 if (!bs
->backing_hd
) {
1012 memset(whole_grain
, 0, skip_start_sector
<< BDRV_SECTOR_BITS
);
1013 memset(whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
), 0,
1014 cluster_bytes
- (skip_end_sector
<< BDRV_SECTOR_BITS
));
1017 assert(skip_end_sector
<= extent
->cluster_sectors
);
1018 /* we will be here if it's first write on non-exist grain(cluster).
1019 * try to read from parent image, if exist */
1020 if (bs
->backing_hd
&& !vmdk_is_cid_valid(bs
)) {
1025 /* Read backing data before skip range */
1026 if (skip_start_sector
> 0) {
1027 if (bs
->backing_hd
) {
1028 ret
= bdrv_read(bs
->backing_hd
, sector_num
,
1029 whole_grain
, skip_start_sector
);
1035 ret
= bdrv_write(extent
->file
, cluster_sector_num
, whole_grain
,
1042 /* Read backing data after skip range */
1043 if (skip_end_sector
< extent
->cluster_sectors
) {
1044 if (bs
->backing_hd
) {
1045 ret
= bdrv_read(bs
->backing_hd
, sector_num
+ skip_end_sector
,
1046 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1047 extent
->cluster_sectors
- skip_end_sector
);
1053 ret
= bdrv_write(extent
->file
, cluster_sector_num
+ skip_end_sector
,
1054 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1055 extent
->cluster_sectors
- skip_end_sector
);
1063 qemu_vfree(whole_grain
);
1067 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1070 offset
= cpu_to_le32(offset
);
1071 /* update L2 table */
1072 if (bdrv_pwrite_sync(
1074 ((int64_t)m_data
->l2_offset
* 512)
1075 + (m_data
->l2_index
* sizeof(offset
)),
1076 &offset
, sizeof(offset
)) < 0) {
1079 /* update backup L2 table */
1080 if (extent
->l1_backup_table_offset
!= 0) {
1081 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1082 if (bdrv_pwrite_sync(
1084 ((int64_t)m_data
->l2_offset
* 512)
1085 + (m_data
->l2_index
* sizeof(offset
)),
1086 &offset
, sizeof(offset
)) < 0) {
1090 if (m_data
->l2_cache_entry
) {
1091 *m_data
->l2_cache_entry
= offset
;
1098 * get_cluster_offset
1100 * Look up cluster offset in extent file by sector number, and store in
1103 * For flat extents, the start offset as parsed from the description file is
1106 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1107 * offset for a new cluster and update L2 cache. If there is a backing file,
1108 * COW is done before returning; otherwise, zeroes are written to the allocated
1109 * cluster. Both COW and zero writing skips the sector range
1110 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1111 * has new data to write there.
1113 * Returns: VMDK_OK if cluster exists and mapped in the image.
1114 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1115 * VMDK_ERROR if failed.
1117 static int get_cluster_offset(BlockDriverState
*bs
,
1119 VmdkMetaData
*m_data
,
1122 uint64_t *cluster_offset
,
1123 uint64_t skip_start_sector
,
1124 uint64_t skip_end_sector
)
1126 unsigned int l1_index
, l2_offset
, l2_index
;
1127 int min_index
, i
, j
;
1128 uint32_t min_count
, *l2_table
;
1129 bool zeroed
= false;
1131 int64_t cluster_sector
;
1137 *cluster_offset
= extent
->flat_start_offset
;
1141 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1142 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1143 if (l1_index
>= extent
->l1_size
) {
1146 l2_offset
= extent
->l1_table
[l1_index
];
1148 return VMDK_UNALLOC
;
1150 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1151 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1152 /* increment the hit count */
1153 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1154 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1155 extent
->l2_cache_counts
[j
] >>= 1;
1158 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1162 /* not found: load a new entry in the least used one */
1164 min_count
= 0xffffffff;
1165 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1166 if (extent
->l2_cache_counts
[i
] < min_count
) {
1167 min_count
= extent
->l2_cache_counts
[i
];
1171 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1174 (int64_t)l2_offset
* 512,
1176 extent
->l2_size
* sizeof(uint32_t)
1177 ) != extent
->l2_size
* sizeof(uint32_t)) {
1181 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1182 extent
->l2_cache_counts
[min_index
] = 1;
1184 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1185 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1189 m_data
->l1_index
= l1_index
;
1190 m_data
->l2_index
= l2_index
;
1191 m_data
->l2_offset
= l2_offset
;
1192 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1194 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1198 if (!cluster_sector
|| zeroed
) {
1200 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1203 cluster_sector
= extent
->next_cluster_sector
;
1204 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1206 /* First of all we write grain itself, to avoid race condition
1207 * that may to corrupt the image.
1208 * This problem may occur because of insufficient space on host disk
1209 * or inappropriate VM shutdown.
1211 ret
= get_whole_cluster(bs
, extent
,
1213 offset
>> BDRV_SECTOR_BITS
,
1214 skip_start_sector
, skip_end_sector
);
1219 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1223 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1224 int64_t sector_num
, VmdkExtent
*start_hint
)
1226 VmdkExtent
*extent
= start_hint
;
1229 extent
= &s
->extents
[0];
1231 while (extent
< &s
->extents
[s
->num_extents
]) {
1232 if (sector_num
< extent
->end_sector
) {
1240 static int64_t coroutine_fn
vmdk_co_get_block_status(BlockDriverState
*bs
,
1241 int64_t sector_num
, int nb_sectors
, int *pnum
)
1243 BDRVVmdkState
*s
= bs
->opaque
;
1244 int64_t index_in_cluster
, n
, ret
;
1248 extent
= find_extent(s
, sector_num
, NULL
);
1252 qemu_co_mutex_lock(&s
->lock
);
1253 ret
= get_cluster_offset(bs
, extent
, NULL
,
1254 sector_num
* 512, false, &offset
,
1256 qemu_co_mutex_unlock(&s
->lock
);
1266 ret
= BDRV_BLOCK_ZERO
;
1269 ret
= BDRV_BLOCK_DATA
;
1270 if (extent
->file
== bs
->file
&& !extent
->compressed
) {
1271 ret
|= BDRV_BLOCK_OFFSET_VALID
| offset
;
1277 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
1278 n
= extent
->cluster_sectors
- index_in_cluster
;
1279 if (n
> nb_sectors
) {
1286 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1287 int64_t offset_in_cluster
, const uint8_t *buf
,
1288 int nb_sectors
, int64_t sector_num
)
1291 VmdkGrainMarker
*data
= NULL
;
1293 const uint8_t *write_buf
= buf
;
1294 int write_len
= nb_sectors
* 512;
1296 if (extent
->compressed
) {
1297 if (!extent
->has_marker
) {
1301 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1302 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1303 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
1308 data
->lba
= sector_num
;
1309 data
->size
= buf_len
;
1310 write_buf
= (uint8_t *)data
;
1311 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
1313 ret
= bdrv_pwrite(extent
->file
,
1314 cluster_offset
+ offset_in_cluster
,
1317 if (ret
!= write_len
) {
1318 ret
= ret
< 0 ? ret
: -EIO
;
1327 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1328 int64_t offset_in_cluster
, uint8_t *buf
,
1332 int cluster_bytes
, buf_bytes
;
1333 uint8_t *cluster_buf
, *compressed_data
;
1334 uint8_t *uncomp_buf
;
1336 VmdkGrainMarker
*marker
;
1340 if (!extent
->compressed
) {
1341 ret
= bdrv_pread(extent
->file
,
1342 cluster_offset
+ offset_in_cluster
,
1343 buf
, nb_sectors
* 512);
1344 if (ret
== nb_sectors
* 512) {
1350 cluster_bytes
= extent
->cluster_sectors
* 512;
1351 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1352 buf_bytes
= cluster_bytes
* 2;
1353 cluster_buf
= g_malloc(buf_bytes
);
1354 uncomp_buf
= g_malloc(cluster_bytes
);
1355 ret
= bdrv_pread(extent
->file
,
1357 cluster_buf
, buf_bytes
);
1361 compressed_data
= cluster_buf
;
1362 buf_len
= cluster_bytes
;
1363 data_len
= cluster_bytes
;
1364 if (extent
->has_marker
) {
1365 marker
= (VmdkGrainMarker
*)cluster_buf
;
1366 compressed_data
= marker
->data
;
1367 data_len
= le32_to_cpu(marker
->size
);
1369 if (!data_len
|| data_len
> buf_bytes
) {
1373 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1379 if (offset_in_cluster
< 0 ||
1380 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
1384 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
1389 g_free(cluster_buf
);
1393 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
1394 uint8_t *buf
, int nb_sectors
)
1396 BDRVVmdkState
*s
= bs
->opaque
;
1398 uint64_t n
, index_in_cluster
;
1399 uint64_t extent_begin_sector
, extent_relative_sector_num
;
1400 VmdkExtent
*extent
= NULL
;
1401 uint64_t cluster_offset
;
1403 while (nb_sectors
> 0) {
1404 extent
= find_extent(s
, sector_num
, extent
);
1408 ret
= get_cluster_offset(bs
, extent
, NULL
,
1409 sector_num
<< 9, false, &cluster_offset
,
1411 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1412 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1413 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1414 n
= extent
->cluster_sectors
- index_in_cluster
;
1415 if (n
> nb_sectors
) {
1418 if (ret
!= VMDK_OK
) {
1419 /* if not allocated, try to read from parent image, if exist */
1420 if (bs
->backing_hd
&& ret
!= VMDK_ZEROED
) {
1421 if (!vmdk_is_cid_valid(bs
)) {
1424 ret
= bdrv_read(bs
->backing_hd
, sector_num
, buf
, n
);
1429 memset(buf
, 0, 512 * n
);
1432 ret
= vmdk_read_extent(extent
,
1433 cluster_offset
, index_in_cluster
* 512,
1446 static coroutine_fn
int vmdk_co_read(BlockDriverState
*bs
, int64_t sector_num
,
1447 uint8_t *buf
, int nb_sectors
)
1450 BDRVVmdkState
*s
= bs
->opaque
;
1451 qemu_co_mutex_lock(&s
->lock
);
1452 ret
= vmdk_read(bs
, sector_num
, buf
, nb_sectors
);
1453 qemu_co_mutex_unlock(&s
->lock
);
1459 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1460 * if possible, otherwise return -ENOTSUP.
1461 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1462 * with each cluster. By dry run we can find if the zero write
1463 * is possible without modifying image data.
1465 * Returns: error code with 0 for success.
1467 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1468 const uint8_t *buf
, int nb_sectors
,
1469 bool zeroed
, bool zero_dry_run
)
1471 BDRVVmdkState
*s
= bs
->opaque
;
1472 VmdkExtent
*extent
= NULL
;
1474 int64_t index_in_cluster
, n
;
1475 uint64_t extent_begin_sector
, extent_relative_sector_num
;
1476 uint64_t cluster_offset
;
1477 VmdkMetaData m_data
;
1479 if (sector_num
> bs
->total_sectors
) {
1480 error_report("Wrong offset: sector_num=0x%" PRIx64
1481 " total_sectors=0x%" PRIx64
"\n",
1482 sector_num
, bs
->total_sectors
);
1486 while (nb_sectors
> 0) {
1487 extent
= find_extent(s
, sector_num
, extent
);
1491 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1492 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1493 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1494 n
= extent
->cluster_sectors
- index_in_cluster
;
1495 if (n
> nb_sectors
) {
1498 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1499 !(extent
->compressed
|| zeroed
),
1501 index_in_cluster
, index_in_cluster
+ n
);
1502 if (extent
->compressed
) {
1503 if (ret
== VMDK_OK
) {
1504 /* Refuse write to allocated cluster for streamOptimized */
1505 error_report("Could not write to allocated cluster"
1506 " for streamOptimized");
1510 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1511 true, &cluster_offset
, 0, 0);
1514 if (ret
== VMDK_ERROR
) {
1518 /* Do zeroed write, buf is ignored */
1519 if (extent
->has_zero_grain
&&
1520 index_in_cluster
== 0 &&
1521 n
>= extent
->cluster_sectors
) {
1522 n
= extent
->cluster_sectors
;
1523 if (!zero_dry_run
) {
1524 /* update L2 tables */
1525 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1534 ret
= vmdk_write_extent(extent
,
1535 cluster_offset
, index_in_cluster
* 512,
1536 buf
, n
, sector_num
);
1541 /* update L2 tables */
1542 if (vmdk_L2update(extent
, &m_data
,
1543 cluster_offset
>> BDRV_SECTOR_BITS
)
1553 /* update CID on the first write every time the virtual disk is
1555 if (!s
->cid_updated
) {
1556 ret
= vmdk_write_cid(bs
, g_random_int());
1560 s
->cid_updated
= true;
1566 static coroutine_fn
int vmdk_co_write(BlockDriverState
*bs
, int64_t sector_num
,
1567 const uint8_t *buf
, int nb_sectors
)
1570 BDRVVmdkState
*s
= bs
->opaque
;
1571 qemu_co_mutex_lock(&s
->lock
);
1572 ret
= vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1573 qemu_co_mutex_unlock(&s
->lock
);
1577 static int vmdk_write_compressed(BlockDriverState
*bs
,
1582 BDRVVmdkState
*s
= bs
->opaque
;
1583 if (s
->num_extents
== 1 && s
->extents
[0].compressed
) {
1584 return vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1590 static int coroutine_fn
vmdk_co_write_zeroes(BlockDriverState
*bs
,
1593 BdrvRequestFlags flags
)
1596 BDRVVmdkState
*s
= bs
->opaque
;
1597 qemu_co_mutex_lock(&s
->lock
);
1598 /* write zeroes could fail if sectors not aligned to cluster, test it with
1599 * dry_run == true before really updating image */
1600 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, true);
1602 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, false);
1604 qemu_co_mutex_unlock(&s
->lock
);
1608 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1609 bool flat
, bool compress
, bool zeroed_grain
,
1610 QemuOpts
*opts
, Error
**errp
)
1613 BlockDriverState
*bs
= NULL
;
1615 Error
*local_err
= NULL
;
1616 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1617 uint32_t *gd_buf
= NULL
;
1620 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1622 error_propagate(errp
, local_err
);
1627 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, BDRV_O_RDWR
| BDRV_O_PROTOCOL
,
1630 error_propagate(errp
, local_err
);
1635 ret
= bdrv_truncate(bs
, filesize
);
1637 error_setg_errno(errp
, -ret
, "Could not truncate file");
1641 magic
= cpu_to_be32(VMDK4_MAGIC
);
1642 memset(&header
, 0, sizeof(header
));
1643 header
.version
= zeroed_grain
? 2 : 1;
1644 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1645 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1646 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1647 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1648 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1649 header
.granularity
= 128;
1650 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1652 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1653 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1655 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1656 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1658 header
.desc_offset
= 1;
1659 header
.desc_size
= 20;
1660 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1661 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1662 header
.grain_offset
=
1663 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1664 header
.granularity
);
1665 /* swap endianness for all header fields */
1666 header
.version
= cpu_to_le32(header
.version
);
1667 header
.flags
= cpu_to_le32(header
.flags
);
1668 header
.capacity
= cpu_to_le64(header
.capacity
);
1669 header
.granularity
= cpu_to_le64(header
.granularity
);
1670 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1671 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1672 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1673 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1674 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1675 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1676 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1678 header
.check_bytes
[0] = 0xa;
1679 header
.check_bytes
[1] = 0x20;
1680 header
.check_bytes
[2] = 0xd;
1681 header
.check_bytes
[3] = 0xa;
1683 /* write all the data */
1684 ret
= bdrv_pwrite(bs
, 0, &magic
, sizeof(magic
));
1686 error_set(errp
, QERR_IO_ERROR
);
1689 ret
= bdrv_pwrite(bs
, sizeof(magic
), &header
, sizeof(header
));
1691 error_set(errp
, QERR_IO_ERROR
);
1695 ret
= bdrv_truncate(bs
, le64_to_cpu(header
.grain_offset
) << 9);
1697 error_setg_errno(errp
, -ret
, "Could not truncate file");
1701 /* write grain directory */
1702 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1703 gd_buf
= g_malloc0(gd_buf_size
);
1704 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1705 i
< gt_count
; i
++, tmp
+= gt_size
) {
1706 gd_buf
[i
] = cpu_to_le32(tmp
);
1708 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1709 gd_buf
, gd_buf_size
);
1711 error_set(errp
, QERR_IO_ERROR
);
1715 /* write backup grain directory */
1716 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1717 i
< gt_count
; i
++, tmp
+= gt_size
) {
1718 gd_buf
[i
] = cpu_to_le32(tmp
);
1720 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1721 gd_buf
, gd_buf_size
);
1723 error_set(errp
, QERR_IO_ERROR
);
1736 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1737 char *postfix
, size_t buf_len
, Error
**errp
)
1741 if (filename
== NULL
|| !strlen(filename
)) {
1742 error_setg(errp
, "No filename provided");
1745 p
= strrchr(filename
, '/');
1747 p
= strrchr(filename
, '\\');
1750 p
= strrchr(filename
, ':');
1754 if (p
- filename
>= buf_len
) {
1757 pstrcpy(path
, p
- filename
+ 1, filename
);
1762 q
= strrchr(p
, '.');
1764 pstrcpy(prefix
, buf_len
, p
);
1767 if (q
- p
>= buf_len
) {
1770 pstrcpy(prefix
, q
- p
+ 1, p
);
1771 pstrcpy(postfix
, buf_len
, q
);
1776 static int vmdk_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1779 BlockDriverState
*new_bs
= NULL
;
1780 Error
*local_err
= NULL
;
1782 int64_t total_size
= 0, filesize
;
1783 char *adapter_type
= NULL
;
1784 char *backing_file
= NULL
;
1788 bool flat
, split
, compress
;
1789 GString
*ext_desc_lines
;
1790 char path
[PATH_MAX
], prefix
[PATH_MAX
], postfix
[PATH_MAX
];
1791 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1792 const char *desc_extent_line
;
1793 char parent_desc_line
[BUF_SIZE
] = "";
1794 uint32_t parent_cid
= 0xffffffff;
1795 uint32_t number_heads
= 16;
1796 bool zeroed_grain
= false;
1797 uint32_t desc_offset
= 0, desc_len
;
1798 const char desc_template
[] =
1799 "# Disk DescriptorFile\n"
1802 "parentCID=%" PRIx32
"\n"
1803 "createType=\"%s\"\n"
1806 "# Extent description\n"
1809 "# The Disk Data Base\n"
1812 "ddb.virtualHWVersion = \"%d\"\n"
1813 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1814 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1815 "ddb.geometry.sectors = \"63\"\n"
1816 "ddb.adapterType = \"%s\"\n";
1818 ext_desc_lines
= g_string_new(NULL
);
1820 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1824 /* Read out options */
1825 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1827 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1828 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1829 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1830 flags
|= BLOCK_FLAG_COMPAT6
;
1832 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1833 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1834 zeroed_grain
= true;
1837 if (!adapter_type
) {
1838 adapter_type
= g_strdup("ide");
1839 } else if (strcmp(adapter_type
, "ide") &&
1840 strcmp(adapter_type
, "buslogic") &&
1841 strcmp(adapter_type
, "lsilogic") &&
1842 strcmp(adapter_type
, "legacyESX")) {
1843 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1847 if (strcmp(adapter_type
, "ide") != 0) {
1848 /* that's the number of heads with which vmware operates when
1849 creating, exporting, etc. vmdk files with a non-ide adapter type */
1853 /* Default format to monolithicSparse */
1854 fmt
= g_strdup("monolithicSparse");
1855 } else if (strcmp(fmt
, "monolithicFlat") &&
1856 strcmp(fmt
, "monolithicSparse") &&
1857 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1858 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1859 strcmp(fmt
, "streamOptimized")) {
1860 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1864 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1865 strcmp(fmt
, "twoGbMaxExtentSparse"));
1866 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1867 strcmp(fmt
, "twoGbMaxExtentFlat"));
1868 compress
= !strcmp(fmt
, "streamOptimized");
1870 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
1872 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
1874 if (flat
&& backing_file
) {
1875 error_setg(errp
, "Flat image can't have backing file");
1879 if (flat
&& zeroed_grain
) {
1880 error_setg(errp
, "Flat image can't enable zeroed grain");
1885 BlockDriverState
*bs
= NULL
;
1886 ret
= bdrv_open(&bs
, backing_file
, NULL
, NULL
, BDRV_O_NO_BACKING
, NULL
,
1891 if (strcmp(bs
->drv
->format_name
, "vmdk")) {
1896 parent_cid
= vmdk_read_cid(bs
, 0);
1898 snprintf(parent_desc_line
, sizeof(parent_desc_line
),
1899 "parentFileNameHint=\"%s\"", backing_file
);
1902 /* Create extents */
1903 filesize
= total_size
;
1904 while (filesize
> 0) {
1905 char desc_line
[BUF_SIZE
];
1906 char ext_filename
[PATH_MAX
];
1907 char desc_filename
[PATH_MAX
];
1908 int64_t size
= filesize
;
1910 if (split
&& size
> split_size
) {
1914 snprintf(desc_filename
, sizeof(desc_filename
), "%s-%c%03d%s",
1915 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1917 snprintf(desc_filename
, sizeof(desc_filename
), "%s-flat%s",
1920 snprintf(desc_filename
, sizeof(desc_filename
), "%s%s",
1923 snprintf(ext_filename
, sizeof(ext_filename
), "%s%s",
1924 path
, desc_filename
);
1926 if (vmdk_create_extent(ext_filename
, size
,
1927 flat
, compress
, zeroed_grain
, opts
, errp
)) {
1933 /* Format description line */
1934 snprintf(desc_line
, sizeof(desc_line
),
1935 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
1936 g_string_append(ext_desc_lines
, desc_line
);
1938 /* generate descriptor file */
1939 desc
= g_strdup_printf(desc_template
,
1944 ext_desc_lines
->str
,
1945 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
1947 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
1950 desc_len
= strlen(desc
);
1951 /* the descriptor offset = 0x200 */
1952 if (!split
&& !flat
) {
1953 desc_offset
= 0x200;
1955 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1957 error_propagate(errp
, local_err
);
1961 assert(new_bs
== NULL
);
1962 ret
= bdrv_open(&new_bs
, filename
, NULL
, NULL
,
1963 BDRV_O_RDWR
| BDRV_O_PROTOCOL
, NULL
, &local_err
);
1965 error_propagate(errp
, local_err
);
1968 ret
= bdrv_pwrite(new_bs
, desc_offset
, desc
, desc_len
);
1970 error_setg_errno(errp
, -ret
, "Could not write description");
1973 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1974 * for description file */
1975 if (desc_offset
== 0) {
1976 ret
= bdrv_truncate(new_bs
, desc_len
);
1978 error_setg_errno(errp
, -ret
, "Could not truncate file");
1985 g_free(adapter_type
);
1986 g_free(backing_file
);
1989 g_string_free(ext_desc_lines
, true);
1993 static void vmdk_close(BlockDriverState
*bs
)
1995 BDRVVmdkState
*s
= bs
->opaque
;
1997 vmdk_free_extents(bs
);
1998 g_free(s
->create_type
);
2000 migrate_del_blocker(s
->migration_blocker
);
2001 error_free(s
->migration_blocker
);
2004 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
2006 BDRVVmdkState
*s
= bs
->opaque
;
2010 for (i
= 0; i
< s
->num_extents
; i
++) {
2011 err
= bdrv_co_flush(s
->extents
[i
].file
);
2019 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2024 BDRVVmdkState
*s
= bs
->opaque
;
2026 ret
= bdrv_get_allocated_file_size(bs
->file
);
2030 for (i
= 0; i
< s
->num_extents
; i
++) {
2031 if (s
->extents
[i
].file
== bs
->file
) {
2034 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
);
2043 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2046 BDRVVmdkState
*s
= bs
->opaque
;
2048 /* If has a flat extent and its underlying storage doesn't have zero init,
2050 for (i
= 0; i
< s
->num_extents
; i
++) {
2051 if (s
->extents
[i
].flat
) {
2052 if (!bdrv_has_zero_init(s
->extents
[i
].file
)) {
2060 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2062 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2064 *info
= (ImageInfo
){
2065 .filename
= g_strdup(extent
->file
->filename
),
2066 .format
= g_strdup(extent
->type
),
2067 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2068 .compressed
= extent
->compressed
,
2069 .has_compressed
= extent
->compressed
,
2070 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2071 .has_cluster_size
= !extent
->flat
,
2077 static int vmdk_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
2080 BDRVVmdkState
*s
= bs
->opaque
;
2081 VmdkExtent
*extent
= NULL
;
2082 int64_t sector_num
= 0;
2083 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2085 uint64_t cluster_offset
;
2092 if (sector_num
>= total_sectors
) {
2095 extent
= find_extent(s
, sector_num
, extent
);
2098 "ERROR: could not find extent for sector %" PRId64
"\n",
2102 ret
= get_cluster_offset(bs
, extent
, NULL
,
2103 sector_num
<< BDRV_SECTOR_BITS
,
2104 false, &cluster_offset
, 0, 0);
2105 if (ret
== VMDK_ERROR
) {
2107 "ERROR: could not get cluster_offset for sector %"
2108 PRId64
"\n", sector_num
);
2111 if (ret
== VMDK_OK
&& cluster_offset
>= bdrv_getlength(extent
->file
)) {
2113 "ERROR: cluster offset for sector %"
2114 PRId64
" points after EOF\n", sector_num
);
2117 sector_num
+= extent
->cluster_sectors
;
2120 result
->corruptions
++;
2124 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2127 BDRVVmdkState
*s
= bs
->opaque
;
2128 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2129 ImageInfoList
**next
;
2131 *spec_info
= (ImageInfoSpecific
){
2132 .kind
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2134 .vmdk
= g_new0(ImageInfoSpecificVmdk
, 1),
2138 *spec_info
->vmdk
= (ImageInfoSpecificVmdk
) {
2139 .create_type
= g_strdup(s
->create_type
),
2141 .parent_cid
= s
->parent_cid
,
2144 next
= &spec_info
->vmdk
->extents
;
2145 for (i
= 0; i
< s
->num_extents
; i
++) {
2146 *next
= g_new0(ImageInfoList
, 1);
2147 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2148 (*next
)->next
= NULL
;
2149 next
= &(*next
)->next
;
2155 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
2157 return a
->flat
== b
->flat
&&
2158 a
->compressed
== b
->compressed
&&
2159 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
2162 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2165 BDRVVmdkState
*s
= bs
->opaque
;
2166 assert(s
->num_extents
);
2168 /* See if we have multiple extents but they have different cases */
2169 for (i
= 1; i
< s
->num_extents
; i
++) {
2170 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
2174 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2175 if (!s
->extents
[0].flat
) {
2176 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2181 static void vmdk_detach_aio_context(BlockDriverState
*bs
)
2183 BDRVVmdkState
*s
= bs
->opaque
;
2186 for (i
= 0; i
< s
->num_extents
; i
++) {
2187 bdrv_detach_aio_context(s
->extents
[i
].file
);
2191 static void vmdk_attach_aio_context(BlockDriverState
*bs
,
2192 AioContext
*new_context
)
2194 BDRVVmdkState
*s
= bs
->opaque
;
2197 for (i
= 0; i
< s
->num_extents
; i
++) {
2198 bdrv_attach_aio_context(s
->extents
[i
].file
, new_context
);
2202 static QemuOptsList vmdk_create_opts
= {
2203 .name
= "vmdk-create-opts",
2204 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2207 .name
= BLOCK_OPT_SIZE
,
2208 .type
= QEMU_OPT_SIZE
,
2209 .help
= "Virtual disk size"
2212 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2213 .type
= QEMU_OPT_STRING
,
2214 .help
= "Virtual adapter type, can be one of "
2215 "ide (default), lsilogic, buslogic or legacyESX"
2218 .name
= BLOCK_OPT_BACKING_FILE
,
2219 .type
= QEMU_OPT_STRING
,
2220 .help
= "File name of a base image"
2223 .name
= BLOCK_OPT_COMPAT6
,
2224 .type
= QEMU_OPT_BOOL
,
2225 .help
= "VMDK version 6 image",
2226 .def_value_str
= "off"
2229 .name
= BLOCK_OPT_SUBFMT
,
2230 .type
= QEMU_OPT_STRING
,
2232 "VMDK flat extent format, can be one of "
2233 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2236 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2237 .type
= QEMU_OPT_BOOL
,
2238 .help
= "Enable efficient zero writes "
2239 "using the zeroed-grain GTE feature"
2241 { /* end of list */ }
2245 static BlockDriver bdrv_vmdk
= {
2246 .format_name
= "vmdk",
2247 .instance_size
= sizeof(BDRVVmdkState
),
2248 .bdrv_probe
= vmdk_probe
,
2249 .bdrv_open
= vmdk_open
,
2250 .bdrv_check
= vmdk_check
,
2251 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2252 .bdrv_read
= vmdk_co_read
,
2253 .bdrv_write
= vmdk_co_write
,
2254 .bdrv_write_compressed
= vmdk_write_compressed
,
2255 .bdrv_co_write_zeroes
= vmdk_co_write_zeroes
,
2256 .bdrv_close
= vmdk_close
,
2257 .bdrv_create
= vmdk_create
,
2258 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2259 .bdrv_co_get_block_status
= vmdk_co_get_block_status
,
2260 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2261 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2262 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2263 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2264 .bdrv_get_info
= vmdk_get_info
,
2265 .bdrv_detach_aio_context
= vmdk_detach_aio_context
,
2266 .bdrv_attach_aio_context
= vmdk_attach_aio_context
,
2268 .supports_backing
= true,
2269 .create_opts
= &vmdk_create_opts
,
2272 static void bdrv_vmdk_init(void)
2274 bdrv_register(&bdrv_vmdk
);
2277 block_init(bdrv_vmdk_init
);