2 * Block driver for the VMDK format
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu/osdep.h"
27 #include "qemu-common.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qemu/error-report.h"
32 #include "qemu/module.h"
33 #include "migration/migration.h"
37 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
38 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
39 #define VMDK4_COMPRESSION_DEFLATE 1
40 #define VMDK4_FLAG_NL_DETECT (1 << 0)
41 #define VMDK4_FLAG_RGD (1 << 1)
42 /* Zeroed-grain enable bit */
43 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
44 #define VMDK4_FLAG_COMPRESS (1 << 16)
45 #define VMDK4_FLAG_MARKER (1 << 17)
46 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
48 #define VMDK_GTE_ZEROED 0x1
50 /* VMDK internal error codes */
52 #define VMDK_ERROR (-1)
53 /* Cluster not allocated */
54 #define VMDK_UNALLOC (-2)
55 #define VMDK_ZEROED (-3)
57 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
62 uint32_t disk_sectors
;
64 uint32_t l1dir_offset
;
66 uint32_t file_sectors
;
69 uint32_t sectors_per_track
;
70 } QEMU_PACKED VMDK3Header
;
79 /* Number of GrainTableEntries per GrainTable */
80 uint32_t num_gtes_per_gt
;
83 uint64_t grain_offset
;
86 uint16_t compressAlgorithm
;
87 } QEMU_PACKED VMDK4Header
;
89 #define L2_CACHE_SIZE 16
91 typedef struct VmdkExtent
{
100 int64_t flat_start_offset
;
101 int64_t l1_table_offset
;
102 int64_t l1_backup_table_offset
;
104 uint32_t *l1_backup_table
;
105 unsigned int l1_size
;
106 uint32_t l1_entry_sectors
;
108 unsigned int l2_size
;
110 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
111 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
113 int64_t cluster_sectors
;
114 int64_t next_cluster_sector
;
118 typedef struct BDRVVmdkState
{
120 uint64_t desc_offset
;
126 /* Extent array with num_extents entries, ascend ordered by address */
128 Error
*migration_blocker
;
132 typedef struct VmdkMetaData
{
133 unsigned int l1_index
;
134 unsigned int l2_index
;
135 unsigned int l2_offset
;
137 uint32_t *l2_cache_entry
;
140 typedef struct VmdkGrainMarker
{
144 } QEMU_PACKED VmdkGrainMarker
;
147 MARKER_END_OF_STREAM
= 0,
148 MARKER_GRAIN_TABLE
= 1,
149 MARKER_GRAIN_DIRECTORY
= 2,
153 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
160 magic
= be32_to_cpu(*(uint32_t *)buf
);
161 if (magic
== VMDK3_MAGIC
||
162 magic
== VMDK4_MAGIC
) {
165 const char *p
= (const char *)buf
;
166 const char *end
= p
+ buf_size
;
169 /* skip comment line */
170 while (p
< end
&& *p
!= '\n') {
177 while (p
< end
&& *p
== ' ') {
180 /* skip '\r' if windows line endings used. */
181 if (p
< end
&& *p
== '\r') {
184 /* only accept blank lines before 'version=' line */
185 if (p
== end
|| *p
!= '\n') {
191 if (end
- p
>= strlen("version=X\n")) {
192 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
193 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
197 if (end
- p
>= strlen("version=X\r\n")) {
198 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
199 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
209 #define SECTOR_SIZE 512
210 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
211 #define BUF_SIZE 4096
212 #define HEADER_SIZE 512 /* first sector of 512 bytes */
214 static void vmdk_free_extents(BlockDriverState
*bs
)
217 BDRVVmdkState
*s
= bs
->opaque
;
220 for (i
= 0; i
< s
->num_extents
; i
++) {
224 g_free(e
->l1_backup_table
);
226 if (e
->file
!= bs
->file
) {
227 bdrv_unref_child(bs
, e
->file
);
233 static void vmdk_free_last_extent(BlockDriverState
*bs
)
235 BDRVVmdkState
*s
= bs
->opaque
;
237 if (s
->num_extents
== 0) {
241 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
244 static uint32_t vmdk_read_cid(BlockDriverState
*bs
, int parent
)
247 uint32_t cid
= 0xffffffff;
248 const char *p_name
, *cid_str
;
250 BDRVVmdkState
*s
= bs
->opaque
;
253 desc
= g_malloc0(DESC_SIZE
);
254 ret
= bdrv_pread(bs
->file
->bs
, s
->desc_offset
, desc
, DESC_SIZE
);
261 cid_str
= "parentCID";
262 cid_str_size
= sizeof("parentCID");
265 cid_str_size
= sizeof("CID");
268 desc
[DESC_SIZE
- 1] = '\0';
269 p_name
= strstr(desc
, cid_str
);
270 if (p_name
!= NULL
) {
271 p_name
+= cid_str_size
;
272 sscanf(p_name
, "%" SCNx32
, &cid
);
279 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
281 char *desc
, *tmp_desc
;
282 char *p_name
, *tmp_str
;
283 BDRVVmdkState
*s
= bs
->opaque
;
286 desc
= g_malloc0(DESC_SIZE
);
287 tmp_desc
= g_malloc0(DESC_SIZE
);
288 ret
= bdrv_pread(bs
->file
->bs
, s
->desc_offset
, desc
, DESC_SIZE
);
293 desc
[DESC_SIZE
- 1] = '\0';
294 tmp_str
= strstr(desc
, "parentCID");
295 if (tmp_str
== NULL
) {
300 pstrcpy(tmp_desc
, DESC_SIZE
, tmp_str
);
301 p_name
= strstr(desc
, "CID");
302 if (p_name
!= NULL
) {
303 p_name
+= sizeof("CID");
304 snprintf(p_name
, DESC_SIZE
- (p_name
- desc
), "%" PRIx32
"\n", cid
);
305 pstrcat(desc
, DESC_SIZE
, tmp_desc
);
308 ret
= bdrv_pwrite_sync(bs
->file
->bs
, s
->desc_offset
, desc
, DESC_SIZE
);
316 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
318 BDRVVmdkState
*s
= bs
->opaque
;
321 if (!s
->cid_checked
&& bs
->backing
) {
322 BlockDriverState
*p_bs
= bs
->backing
->bs
;
324 cur_pcid
= vmdk_read_cid(p_bs
, 0);
325 if (s
->parent_cid
!= cur_pcid
) {
330 s
->cid_checked
= true;
335 /* We have nothing to do for VMDK reopen, stubs just return success */
336 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
337 BlockReopenQueue
*queue
, Error
**errp
)
339 assert(state
!= NULL
);
340 assert(state
->bs
!= NULL
);
344 static int vmdk_parent_open(BlockDriverState
*bs
)
348 BDRVVmdkState
*s
= bs
->opaque
;
351 desc
= g_malloc0(DESC_SIZE
+ 1);
352 ret
= bdrv_pread(bs
->file
->bs
, s
->desc_offset
, desc
, DESC_SIZE
);
358 p_name
= strstr(desc
, "parentFileNameHint");
359 if (p_name
!= NULL
) {
362 p_name
+= sizeof("parentFileNameHint") + 1;
363 end_name
= strchr(p_name
, '\"');
364 if (end_name
== NULL
) {
368 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
373 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
381 /* Create and append extent to the extent array. Return the added VmdkExtent
382 * address. return NULL if allocation failed. */
383 static int vmdk_add_extent(BlockDriverState
*bs
,
384 BdrvChild
*file
, bool flat
, int64_t sectors
,
385 int64_t l1_offset
, int64_t l1_backup_offset
,
387 int l2_size
, uint64_t cluster_sectors
,
388 VmdkExtent
**new_extent
,
392 BDRVVmdkState
*s
= bs
->opaque
;
395 if (cluster_sectors
> 0x200000) {
396 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
397 error_setg(errp
, "Invalid granularity, image may be corrupt");
400 if (l1_size
> 512 * 1024 * 1024) {
401 /* Although with big capacity and small l1_entry_sectors, we can get a
402 * big l1_size, we don't want unbounded value to allocate the table.
403 * Limit it to 512M, which is 16PB for default cluster and L2 table
405 error_setg(errp
, "L1 size too big");
409 nb_sectors
= bdrv_nb_sectors(file
->bs
);
410 if (nb_sectors
< 0) {
414 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
415 extent
= &s
->extents
[s
->num_extents
];
418 memset(extent
, 0, sizeof(VmdkExtent
));
421 extent
->sectors
= sectors
;
422 extent
->l1_table_offset
= l1_offset
;
423 extent
->l1_backup_table_offset
= l1_backup_offset
;
424 extent
->l1_size
= l1_size
;
425 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
426 extent
->l2_size
= l2_size
;
427 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
428 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
430 if (s
->num_extents
> 1) {
431 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
433 extent
->end_sector
= extent
->sectors
;
435 bs
->total_sectors
= extent
->end_sector
;
437 *new_extent
= extent
;
442 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
449 /* read the L1 table */
450 l1_size
= extent
->l1_size
* sizeof(uint32_t);
451 extent
->l1_table
= g_try_malloc(l1_size
);
452 if (l1_size
&& extent
->l1_table
== NULL
) {
456 ret
= bdrv_pread(extent
->file
->bs
,
457 extent
->l1_table_offset
,
461 error_setg_errno(errp
, -ret
,
462 "Could not read l1 table from extent '%s'",
463 extent
->file
->bs
->filename
);
466 for (i
= 0; i
< extent
->l1_size
; i
++) {
467 le32_to_cpus(&extent
->l1_table
[i
]);
470 if (extent
->l1_backup_table_offset
) {
471 extent
->l1_backup_table
= g_try_malloc(l1_size
);
472 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
476 ret
= bdrv_pread(extent
->file
->bs
,
477 extent
->l1_backup_table_offset
,
478 extent
->l1_backup_table
,
481 error_setg_errno(errp
, -ret
,
482 "Could not read l1 backup table from extent '%s'",
483 extent
->file
->bs
->filename
);
486 for (i
= 0; i
< extent
->l1_size
; i
++) {
487 le32_to_cpus(&extent
->l1_backup_table
[i
]);
492 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
495 g_free(extent
->l1_backup_table
);
497 g_free(extent
->l1_table
);
501 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
503 int flags
, Error
**errp
)
510 ret
= bdrv_pread(file
->bs
, sizeof(magic
), &header
, sizeof(header
));
512 error_setg_errno(errp
, -ret
,
513 "Could not read header from file '%s'",
517 ret
= vmdk_add_extent(bs
, file
, false,
518 le32_to_cpu(header
.disk_sectors
),
519 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
521 le32_to_cpu(header
.l1dir_size
),
523 le32_to_cpu(header
.granularity
),
529 ret
= vmdk_init_tables(bs
, extent
, errp
);
531 /* free extent allocated by vmdk_add_extent */
532 vmdk_free_last_extent(bs
);
537 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
538 QDict
*options
, Error
**errp
);
540 static char *vmdk_read_desc(BlockDriverState
*file
, uint64_t desc_offset
,
547 size
= bdrv_getlength(file
);
549 error_setg_errno(errp
, -size
, "Could not access file");
554 /* Both descriptor file and sparse image must be much larger than 4
555 * bytes, also callers of vmdk_read_desc want to compare the first 4
556 * bytes with VMDK4_MAGIC, let's error out if less is read. */
557 error_setg(errp
, "File is too small, not a valid image");
561 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
562 buf
= g_malloc(size
+ 1);
564 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
566 error_setg_errno(errp
, -ret
, "Could not read from file");
575 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
577 int flags
, QDict
*options
, Error
**errp
)
581 uint32_t l1_size
, l1_entry_sectors
;
584 BDRVVmdkState
*s
= bs
->opaque
;
585 int64_t l1_backup_offset
= 0;
588 ret
= bdrv_pread(file
->bs
, sizeof(magic
), &header
, sizeof(header
));
590 error_setg_errno(errp
, -ret
,
591 "Could not read header from file '%s'",
595 if (header
.capacity
== 0) {
596 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
598 char *buf
= vmdk_read_desc(file
->bs
, desc_offset
<< 9, errp
);
602 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
608 if (!s
->create_type
) {
609 s
->create_type
= g_strdup("monolithicSparse");
612 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
614 * The footer takes precedence over the header, so read it in. The
615 * footer starts at offset -1024 from the end: One sector for the
616 * footer, and another one for the end-of-stream marker.
623 uint8_t pad
[512 - 16];
624 } QEMU_PACKED footer_marker
;
628 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
634 uint8_t pad
[512 - 16];
635 } QEMU_PACKED eos_marker
;
636 } QEMU_PACKED footer
;
638 ret
= bdrv_pread(file
->bs
,
639 bs
->file
->bs
->total_sectors
* 512 - 1536,
640 &footer
, sizeof(footer
));
642 error_setg_errno(errp
, -ret
, "Failed to read footer");
646 /* Some sanity checks for the footer */
647 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
648 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
649 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
650 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
651 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
652 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
654 error_setg(errp
, "Invalid footer");
658 header
= footer
.header
;
662 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
663 if (le32_to_cpu(header
.version
) > 3) {
665 snprintf(buf
, sizeof(buf
), "VMDK version %" PRId32
,
666 le32_to_cpu(header
.version
));
667 error_setg(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
,
668 bdrv_get_device_or_node_name(bs
), "vmdk", buf
);
670 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
) &&
672 /* VMware KB 2064959 explains that version 3 added support for
673 * persistent changed block tracking (CBT), and backup software can
674 * read it as version=1 if it doesn't care about the changed area
675 * information. So we are safe to enable read only. */
676 error_setg(errp
, "VMDK version 3 must be read only");
680 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
681 error_setg(errp
, "L2 table size too big");
685 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
686 * le64_to_cpu(header
.granularity
);
687 if (l1_entry_sectors
== 0) {
688 error_setg(errp
, "L1 entry size is invalid");
691 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
693 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
694 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
696 if (bdrv_nb_sectors(file
->bs
) < le64_to_cpu(header
.grain_offset
)) {
697 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
698 (int64_t)(le64_to_cpu(header
.grain_offset
)
699 * BDRV_SECTOR_SIZE
));
703 ret
= vmdk_add_extent(bs
, file
, false,
704 le64_to_cpu(header
.capacity
),
705 le64_to_cpu(header
.gd_offset
) << 9,
708 le32_to_cpu(header
.num_gtes_per_gt
),
709 le64_to_cpu(header
.granularity
),
716 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
717 if (extent
->compressed
) {
718 g_free(s
->create_type
);
719 s
->create_type
= g_strdup("streamOptimized");
721 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
722 extent
->version
= le32_to_cpu(header
.version
);
723 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
724 ret
= vmdk_init_tables(bs
, extent
, errp
);
726 /* free extent allocated by vmdk_add_extent */
727 vmdk_free_last_extent(bs
);
732 /* find an option value out of descriptor file */
733 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
734 char *buf
, int buf_size
)
736 char *opt_pos
, *opt_end
;
737 const char *end
= desc
+ strlen(desc
);
739 opt_pos
= strstr(desc
, opt_name
);
743 /* Skip "=\"" following opt_name */
744 opt_pos
+= strlen(opt_name
) + 2;
745 if (opt_pos
>= end
) {
749 while (opt_end
< end
&& *opt_end
!= '"') {
752 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
755 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
759 /* Open an extent file and append to bs array */
760 static int vmdk_open_sparse(BlockDriverState
*bs
, BdrvChild
*file
, int flags
,
761 char *buf
, QDict
*options
, Error
**errp
)
765 magic
= ldl_be_p(buf
);
768 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
771 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
774 error_setg(errp
, "Image not in VMDK format");
780 static const char *next_line(const char *s
)
791 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
792 const char *desc_file_path
, QDict
*options
,
804 BdrvChild
*extent_file
;
805 BDRVVmdkState
*s
= bs
->opaque
;
807 char extent_opt_prefix
[32];
808 Error
*local_err
= NULL
;
810 for (p
= desc
; *p
; p
= next_line(p
)) {
811 /* parse extent line in one of below formats:
813 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
814 * RW [size in sectors] SPARSE "file-name.vmdk"
815 * RW [size in sectors] VMFS "file-name.vmdk"
816 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
819 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
820 access
, §ors
, type
, fname
, &flat_offset
);
821 if (matches
< 4 || strcmp(access
, "RW")) {
823 } else if (!strcmp(type
, "FLAT")) {
824 if (matches
!= 5 || flat_offset
< 0) {
827 } else if (!strcmp(type
, "VMFS")) {
833 } else if (matches
!= 4) {
838 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
839 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
840 (strcmp(access
, "RW"))) {
844 if (!path_is_absolute(fname
) && !path_has_protocol(fname
) &&
847 error_setg(errp
, "Cannot use relative extent paths with VMDK "
848 "descriptor file '%s'", bs
->file
->bs
->filename
);
852 extent_path
= g_malloc0(PATH_MAX
);
853 path_combine(extent_path
, PATH_MAX
, desc_file_path
, fname
);
855 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
858 extent_file
= bdrv_open_child(extent_path
, options
, extent_opt_prefix
,
859 bs
, &child_file
, false, &local_err
);
862 error_propagate(errp
, local_err
);
866 /* save to extents array */
867 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
870 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
871 0, 0, 0, 0, 0, &extent
, errp
);
873 bdrv_unref_child(bs
, extent_file
);
876 extent
->flat_start_offset
= flat_offset
<< 9;
877 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
878 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
879 char *buf
= vmdk_read_desc(extent_file
->bs
, 0, errp
);
883 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
888 bdrv_unref_child(bs
, extent_file
);
891 extent
= &s
->extents
[s
->num_extents
- 1];
893 error_setg(errp
, "Unsupported extent type '%s'", type
);
894 bdrv_unref_child(bs
, extent_file
);
897 extent
->type
= g_strdup(type
);
904 if (np
[-1] == '\n') {
907 error_setg(errp
, "Invalid extent line: %.*s", (int)(np
- p
), p
);
911 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
912 QDict
*options
, Error
**errp
)
916 BDRVVmdkState
*s
= bs
->opaque
;
918 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
919 error_setg(errp
, "invalid VMDK image descriptor");
923 if (strcmp(ct
, "monolithicFlat") &&
924 strcmp(ct
, "vmfs") &&
925 strcmp(ct
, "vmfsSparse") &&
926 strcmp(ct
, "twoGbMaxExtentSparse") &&
927 strcmp(ct
, "twoGbMaxExtentFlat")) {
928 error_setg(errp
, "Unsupported image type '%s'", ct
);
932 s
->create_type
= g_strdup(ct
);
934 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->bs
->exact_filename
, options
,
940 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
945 BDRVVmdkState
*s
= bs
->opaque
;
948 buf
= vmdk_read_desc(bs
->file
->bs
, 0, errp
);
953 magic
= ldl_be_p(buf
);
957 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
,
959 s
->desc_offset
= 0x200;
962 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
969 /* try to open parent images, if exist */
970 ret
= vmdk_parent_open(bs
);
974 s
->cid
= vmdk_read_cid(bs
, 0);
975 s
->parent_cid
= vmdk_read_cid(bs
, 1);
976 qemu_co_mutex_init(&s
->lock
);
978 /* Disable migration when VMDK images are used */
979 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
980 "does not support live migration",
981 bdrv_get_device_or_node_name(bs
));
982 migrate_add_blocker(s
->migration_blocker
);
988 g_free(s
->create_type
);
989 s
->create_type
= NULL
;
990 vmdk_free_extents(bs
);
995 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
997 BDRVVmdkState
*s
= bs
->opaque
;
1000 for (i
= 0; i
< s
->num_extents
; i
++) {
1001 if (!s
->extents
[i
].flat
) {
1002 bs
->bl
.write_zeroes_alignment
=
1003 MAX(bs
->bl
.write_zeroes_alignment
,
1004 s
->extents
[i
].cluster_sectors
);
1012 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1013 * to the cluster at @cluster_sector_num.
1015 * If @skip_start_sector < @skip_end_sector, the relative range
1016 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1017 * it for call to write user data in the request.
1019 static int get_whole_cluster(BlockDriverState
*bs
,
1021 uint64_t cluster_sector_num
,
1022 uint64_t sector_num
,
1023 uint64_t skip_start_sector
,
1024 uint64_t skip_end_sector
)
1027 int64_t cluster_bytes
;
1028 uint8_t *whole_grain
;
1030 /* For COW, align request sector_num to cluster start */
1031 sector_num
= QEMU_ALIGN_DOWN(sector_num
, extent
->cluster_sectors
);
1032 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1033 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1036 memset(whole_grain
, 0, skip_start_sector
<< BDRV_SECTOR_BITS
);
1037 memset(whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
), 0,
1038 cluster_bytes
- (skip_end_sector
<< BDRV_SECTOR_BITS
));
1041 assert(skip_end_sector
<= extent
->cluster_sectors
);
1042 /* we will be here if it's first write on non-exist grain(cluster).
1043 * try to read from parent image, if exist */
1044 if (bs
->backing
&& !vmdk_is_cid_valid(bs
)) {
1049 /* Read backing data before skip range */
1050 if (skip_start_sector
> 0) {
1052 ret
= bdrv_read(bs
->backing
->bs
, sector_num
,
1053 whole_grain
, skip_start_sector
);
1059 ret
= bdrv_write(extent
->file
->bs
, cluster_sector_num
, whole_grain
,
1066 /* Read backing data after skip range */
1067 if (skip_end_sector
< extent
->cluster_sectors
) {
1069 ret
= bdrv_read(bs
->backing
->bs
, sector_num
+ skip_end_sector
,
1070 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1071 extent
->cluster_sectors
- skip_end_sector
);
1077 ret
= bdrv_write(extent
->file
->bs
, cluster_sector_num
+ skip_end_sector
,
1078 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1079 extent
->cluster_sectors
- skip_end_sector
);
1087 qemu_vfree(whole_grain
);
1091 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1094 offset
= cpu_to_le32(offset
);
1095 /* update L2 table */
1096 if (bdrv_pwrite_sync(
1098 ((int64_t)m_data
->l2_offset
* 512)
1099 + (m_data
->l2_index
* sizeof(offset
)),
1100 &offset
, sizeof(offset
)) < 0) {
1103 /* update backup L2 table */
1104 if (extent
->l1_backup_table_offset
!= 0) {
1105 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1106 if (bdrv_pwrite_sync(
1108 ((int64_t)m_data
->l2_offset
* 512)
1109 + (m_data
->l2_index
* sizeof(offset
)),
1110 &offset
, sizeof(offset
)) < 0) {
1114 if (m_data
->l2_cache_entry
) {
1115 *m_data
->l2_cache_entry
= offset
;
1122 * get_cluster_offset
1124 * Look up cluster offset in extent file by sector number, and store in
1127 * For flat extents, the start offset as parsed from the description file is
1130 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1131 * offset for a new cluster and update L2 cache. If there is a backing file,
1132 * COW is done before returning; otherwise, zeroes are written to the allocated
1133 * cluster. Both COW and zero writing skips the sector range
1134 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1135 * has new data to write there.
1137 * Returns: VMDK_OK if cluster exists and mapped in the image.
1138 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1139 * VMDK_ERROR if failed.
1141 static int get_cluster_offset(BlockDriverState
*bs
,
1143 VmdkMetaData
*m_data
,
1146 uint64_t *cluster_offset
,
1147 uint64_t skip_start_sector
,
1148 uint64_t skip_end_sector
)
1150 unsigned int l1_index
, l2_offset
, l2_index
;
1151 int min_index
, i
, j
;
1152 uint32_t min_count
, *l2_table
;
1153 bool zeroed
= false;
1155 int64_t cluster_sector
;
1161 *cluster_offset
= extent
->flat_start_offset
;
1165 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1166 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1167 if (l1_index
>= extent
->l1_size
) {
1170 l2_offset
= extent
->l1_table
[l1_index
];
1172 return VMDK_UNALLOC
;
1174 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1175 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1176 /* increment the hit count */
1177 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1178 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1179 extent
->l2_cache_counts
[j
] >>= 1;
1182 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1186 /* not found: load a new entry in the least used one */
1188 min_count
= 0xffffffff;
1189 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1190 if (extent
->l2_cache_counts
[i
] < min_count
) {
1191 min_count
= extent
->l2_cache_counts
[i
];
1195 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1198 (int64_t)l2_offset
* 512,
1200 extent
->l2_size
* sizeof(uint32_t)
1201 ) != extent
->l2_size
* sizeof(uint32_t)) {
1205 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1206 extent
->l2_cache_counts
[min_index
] = 1;
1208 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1209 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1213 m_data
->l1_index
= l1_index
;
1214 m_data
->l2_index
= l2_index
;
1215 m_data
->l2_offset
= l2_offset
;
1216 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1218 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1222 if (!cluster_sector
|| zeroed
) {
1224 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1227 cluster_sector
= extent
->next_cluster_sector
;
1228 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1230 /* First of all we write grain itself, to avoid race condition
1231 * that may to corrupt the image.
1232 * This problem may occur because of insufficient space on host disk
1233 * or inappropriate VM shutdown.
1235 ret
= get_whole_cluster(bs
, extent
,
1237 offset
>> BDRV_SECTOR_BITS
,
1238 skip_start_sector
, skip_end_sector
);
1243 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1247 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1248 int64_t sector_num
, VmdkExtent
*start_hint
)
1250 VmdkExtent
*extent
= start_hint
;
1253 extent
= &s
->extents
[0];
1255 while (extent
< &s
->extents
[s
->num_extents
]) {
1256 if (sector_num
< extent
->end_sector
) {
1264 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent
*extent
,
1267 uint64_t index_in_cluster
, extent_begin_sector
, extent_relative_sector_num
;
1269 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1270 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1271 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1272 return index_in_cluster
;
1275 static int64_t coroutine_fn
vmdk_co_get_block_status(BlockDriverState
*bs
,
1276 int64_t sector_num
, int nb_sectors
, int *pnum
, BlockDriverState
**file
)
1278 BDRVVmdkState
*s
= bs
->opaque
;
1279 int64_t index_in_cluster
, n
, ret
;
1283 extent
= find_extent(s
, sector_num
, NULL
);
1287 qemu_co_mutex_lock(&s
->lock
);
1288 ret
= get_cluster_offset(bs
, extent
, NULL
,
1289 sector_num
* 512, false, &offset
,
1291 qemu_co_mutex_unlock(&s
->lock
);
1293 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1302 ret
= BDRV_BLOCK_ZERO
;
1305 ret
= BDRV_BLOCK_DATA
;
1306 if (!extent
->compressed
) {
1307 ret
|= BDRV_BLOCK_OFFSET_VALID
;
1308 ret
|= (offset
+ (index_in_cluster
<< BDRV_SECTOR_BITS
))
1309 & BDRV_BLOCK_OFFSET_MASK
;
1311 *file
= extent
->file
->bs
;
1315 n
= extent
->cluster_sectors
- index_in_cluster
;
1316 if (n
> nb_sectors
) {
1323 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1324 int64_t offset_in_cluster
, const uint8_t *buf
,
1325 int nb_sectors
, int64_t sector_num
)
1328 VmdkGrainMarker
*data
= NULL
;
1330 const uint8_t *write_buf
= buf
;
1331 int write_len
= nb_sectors
* 512;
1332 int64_t write_offset
;
1333 int64_t write_end_sector
;
1335 if (extent
->compressed
) {
1336 if (!extent
->has_marker
) {
1340 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1341 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1342 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
1347 data
->lba
= sector_num
;
1348 data
->size
= buf_len
;
1349 write_buf
= (uint8_t *)data
;
1350 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
1352 write_offset
= cluster_offset
+ offset_in_cluster
,
1353 ret
= bdrv_pwrite(extent
->file
->bs
, write_offset
, write_buf
, write_len
);
1355 write_end_sector
= DIV_ROUND_UP(write_offset
+ write_len
, BDRV_SECTOR_SIZE
);
1357 if (extent
->compressed
) {
1358 extent
->next_cluster_sector
= write_end_sector
;
1360 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1364 if (ret
!= write_len
) {
1365 ret
= ret
< 0 ? ret
: -EIO
;
1374 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1375 int64_t offset_in_cluster
, uint8_t *buf
,
1379 int cluster_bytes
, buf_bytes
;
1380 uint8_t *cluster_buf
, *compressed_data
;
1381 uint8_t *uncomp_buf
;
1383 VmdkGrainMarker
*marker
;
1387 if (!extent
->compressed
) {
1388 ret
= bdrv_pread(extent
->file
->bs
,
1389 cluster_offset
+ offset_in_cluster
,
1390 buf
, nb_sectors
* 512);
1391 if (ret
== nb_sectors
* 512) {
1397 cluster_bytes
= extent
->cluster_sectors
* 512;
1398 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1399 buf_bytes
= cluster_bytes
* 2;
1400 cluster_buf
= g_malloc(buf_bytes
);
1401 uncomp_buf
= g_malloc(cluster_bytes
);
1402 ret
= bdrv_pread(extent
->file
->bs
,
1404 cluster_buf
, buf_bytes
);
1408 compressed_data
= cluster_buf
;
1409 buf_len
= cluster_bytes
;
1410 data_len
= cluster_bytes
;
1411 if (extent
->has_marker
) {
1412 marker
= (VmdkGrainMarker
*)cluster_buf
;
1413 compressed_data
= marker
->data
;
1414 data_len
= le32_to_cpu(marker
->size
);
1416 if (!data_len
|| data_len
> buf_bytes
) {
1420 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1426 if (offset_in_cluster
< 0 ||
1427 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
1431 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
1436 g_free(cluster_buf
);
1440 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
1441 uint8_t *buf
, int nb_sectors
)
1443 BDRVVmdkState
*s
= bs
->opaque
;
1445 uint64_t n
, index_in_cluster
;
1446 VmdkExtent
*extent
= NULL
;
1447 uint64_t cluster_offset
;
1449 while (nb_sectors
> 0) {
1450 extent
= find_extent(s
, sector_num
, extent
);
1454 ret
= get_cluster_offset(bs
, extent
, NULL
,
1455 sector_num
<< 9, false, &cluster_offset
,
1457 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1458 n
= extent
->cluster_sectors
- index_in_cluster
;
1459 if (n
> nb_sectors
) {
1462 if (ret
!= VMDK_OK
) {
1463 /* if not allocated, try to read from parent image, if exist */
1464 if (bs
->backing
&& ret
!= VMDK_ZEROED
) {
1465 if (!vmdk_is_cid_valid(bs
)) {
1468 ret
= bdrv_read(bs
->backing
->bs
, sector_num
, buf
, n
);
1473 memset(buf
, 0, 512 * n
);
1476 ret
= vmdk_read_extent(extent
,
1477 cluster_offset
, index_in_cluster
* 512,
1490 static coroutine_fn
int vmdk_co_read(BlockDriverState
*bs
, int64_t sector_num
,
1491 uint8_t *buf
, int nb_sectors
)
1494 BDRVVmdkState
*s
= bs
->opaque
;
1495 qemu_co_mutex_lock(&s
->lock
);
1496 ret
= vmdk_read(bs
, sector_num
, buf
, nb_sectors
);
1497 qemu_co_mutex_unlock(&s
->lock
);
1503 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1504 * if possible, otherwise return -ENOTSUP.
1505 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1506 * with each cluster. By dry run we can find if the zero write
1507 * is possible without modifying image data.
1509 * Returns: error code with 0 for success.
1511 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1512 const uint8_t *buf
, int nb_sectors
,
1513 bool zeroed
, bool zero_dry_run
)
1515 BDRVVmdkState
*s
= bs
->opaque
;
1516 VmdkExtent
*extent
= NULL
;
1518 int64_t index_in_cluster
, n
;
1519 uint64_t cluster_offset
;
1520 VmdkMetaData m_data
;
1522 if (sector_num
> bs
->total_sectors
) {
1523 error_report("Wrong offset: sector_num=0x%" PRIx64
1524 " total_sectors=0x%" PRIx64
,
1525 sector_num
, bs
->total_sectors
);
1529 while (nb_sectors
> 0) {
1530 extent
= find_extent(s
, sector_num
, extent
);
1534 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1535 n
= extent
->cluster_sectors
- index_in_cluster
;
1536 if (n
> nb_sectors
) {
1539 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1540 !(extent
->compressed
|| zeroed
),
1542 index_in_cluster
, index_in_cluster
+ n
);
1543 if (extent
->compressed
) {
1544 if (ret
== VMDK_OK
) {
1545 /* Refuse write to allocated cluster for streamOptimized */
1546 error_report("Could not write to allocated cluster"
1547 " for streamOptimized");
1551 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1552 true, &cluster_offset
, 0, 0);
1555 if (ret
== VMDK_ERROR
) {
1559 /* Do zeroed write, buf is ignored */
1560 if (extent
->has_zero_grain
&&
1561 index_in_cluster
== 0 &&
1562 n
>= extent
->cluster_sectors
) {
1563 n
= extent
->cluster_sectors
;
1564 if (!zero_dry_run
) {
1565 /* update L2 tables */
1566 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1575 ret
= vmdk_write_extent(extent
,
1576 cluster_offset
, index_in_cluster
* 512,
1577 buf
, n
, sector_num
);
1582 /* update L2 tables */
1583 if (vmdk_L2update(extent
, &m_data
,
1584 cluster_offset
>> BDRV_SECTOR_BITS
)
1594 /* update CID on the first write every time the virtual disk is
1596 if (!s
->cid_updated
) {
1597 ret
= vmdk_write_cid(bs
, g_random_int());
1601 s
->cid_updated
= true;
1607 static coroutine_fn
int vmdk_co_write(BlockDriverState
*bs
, int64_t sector_num
,
1608 const uint8_t *buf
, int nb_sectors
)
1611 BDRVVmdkState
*s
= bs
->opaque
;
1612 qemu_co_mutex_lock(&s
->lock
);
1613 ret
= vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1614 qemu_co_mutex_unlock(&s
->lock
);
1618 static int vmdk_write_compressed(BlockDriverState
*bs
,
1623 BDRVVmdkState
*s
= bs
->opaque
;
1624 if (s
->num_extents
== 1 && s
->extents
[0].compressed
) {
1625 return vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1631 static int coroutine_fn
vmdk_co_write_zeroes(BlockDriverState
*bs
,
1634 BdrvRequestFlags flags
)
1637 BDRVVmdkState
*s
= bs
->opaque
;
1638 qemu_co_mutex_lock(&s
->lock
);
1639 /* write zeroes could fail if sectors not aligned to cluster, test it with
1640 * dry_run == true before really updating image */
1641 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, true);
1643 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, false);
1645 qemu_co_mutex_unlock(&s
->lock
);
1649 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1650 bool flat
, bool compress
, bool zeroed_grain
,
1651 QemuOpts
*opts
, Error
**errp
)
1654 BlockBackend
*blk
= NULL
;
1656 Error
*local_err
= NULL
;
1657 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1658 uint32_t *gd_buf
= NULL
;
1661 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1663 error_propagate(errp
, local_err
);
1667 blk
= blk_new_open("extent", filename
, NULL
, NULL
,
1668 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_PROTOCOL
,
1671 error_propagate(errp
, local_err
);
1676 blk_set_allow_write_beyond_eof(blk
, true);
1679 ret
= blk_truncate(blk
, filesize
);
1681 error_setg_errno(errp
, -ret
, "Could not truncate file");
1685 magic
= cpu_to_be32(VMDK4_MAGIC
);
1686 memset(&header
, 0, sizeof(header
));
1689 } else if (zeroed_grain
) {
1694 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1695 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1696 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1697 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1698 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1699 header
.granularity
= 128;
1700 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1702 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1703 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1705 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1706 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1708 header
.desc_offset
= 1;
1709 header
.desc_size
= 20;
1710 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1711 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1712 header
.grain_offset
=
1713 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1714 header
.granularity
);
1715 /* swap endianness for all header fields */
1716 header
.version
= cpu_to_le32(header
.version
);
1717 header
.flags
= cpu_to_le32(header
.flags
);
1718 header
.capacity
= cpu_to_le64(header
.capacity
);
1719 header
.granularity
= cpu_to_le64(header
.granularity
);
1720 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1721 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1722 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1723 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1724 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1725 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1726 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1728 header
.check_bytes
[0] = 0xa;
1729 header
.check_bytes
[1] = 0x20;
1730 header
.check_bytes
[2] = 0xd;
1731 header
.check_bytes
[3] = 0xa;
1733 /* write all the data */
1734 ret
= blk_pwrite(blk
, 0, &magic
, sizeof(magic
));
1736 error_setg(errp
, QERR_IO_ERROR
);
1739 ret
= blk_pwrite(blk
, sizeof(magic
), &header
, sizeof(header
));
1741 error_setg(errp
, QERR_IO_ERROR
);
1745 ret
= blk_truncate(blk
, le64_to_cpu(header
.grain_offset
) << 9);
1747 error_setg_errno(errp
, -ret
, "Could not truncate file");
1751 /* write grain directory */
1752 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1753 gd_buf
= g_malloc0(gd_buf_size
);
1754 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1755 i
< gt_count
; i
++, tmp
+= gt_size
) {
1756 gd_buf
[i
] = cpu_to_le32(tmp
);
1758 ret
= blk_pwrite(blk
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1759 gd_buf
, gd_buf_size
);
1761 error_setg(errp
, QERR_IO_ERROR
);
1765 /* write backup grain directory */
1766 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1767 i
< gt_count
; i
++, tmp
+= gt_size
) {
1768 gd_buf
[i
] = cpu_to_le32(tmp
);
1770 ret
= blk_pwrite(blk
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1771 gd_buf
, gd_buf_size
);
1773 error_setg(errp
, QERR_IO_ERROR
);
1786 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1787 char *postfix
, size_t buf_len
, Error
**errp
)
1791 if (filename
== NULL
|| !strlen(filename
)) {
1792 error_setg(errp
, "No filename provided");
1795 p
= strrchr(filename
, '/');
1797 p
= strrchr(filename
, '\\');
1800 p
= strrchr(filename
, ':');
1804 if (p
- filename
>= buf_len
) {
1807 pstrcpy(path
, p
- filename
+ 1, filename
);
1812 q
= strrchr(p
, '.');
1814 pstrcpy(prefix
, buf_len
, p
);
1817 if (q
- p
>= buf_len
) {
1820 pstrcpy(prefix
, q
- p
+ 1, p
);
1821 pstrcpy(postfix
, buf_len
, q
);
1826 static int vmdk_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1829 BlockBackend
*new_blk
= NULL
;
1830 Error
*local_err
= NULL
;
1832 int64_t total_size
= 0, filesize
;
1833 char *adapter_type
= NULL
;
1834 char *backing_file
= NULL
;
1838 bool flat
, split
, compress
;
1839 GString
*ext_desc_lines
;
1840 char *path
= g_malloc0(PATH_MAX
);
1841 char *prefix
= g_malloc0(PATH_MAX
);
1842 char *postfix
= g_malloc0(PATH_MAX
);
1843 char *desc_line
= g_malloc0(BUF_SIZE
);
1844 char *ext_filename
= g_malloc0(PATH_MAX
);
1845 char *desc_filename
= g_malloc0(PATH_MAX
);
1846 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1847 const char *desc_extent_line
;
1848 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
1849 uint32_t parent_cid
= 0xffffffff;
1850 uint32_t number_heads
= 16;
1851 bool zeroed_grain
= false;
1852 uint32_t desc_offset
= 0, desc_len
;
1853 const char desc_template
[] =
1854 "# Disk DescriptorFile\n"
1857 "parentCID=%" PRIx32
"\n"
1858 "createType=\"%s\"\n"
1861 "# Extent description\n"
1864 "# The Disk Data Base\n"
1867 "ddb.virtualHWVersion = \"%d\"\n"
1868 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1869 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1870 "ddb.geometry.sectors = \"63\"\n"
1871 "ddb.adapterType = \"%s\"\n";
1873 ext_desc_lines
= g_string_new(NULL
);
1875 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1879 /* Read out options */
1880 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1882 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1883 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1884 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1885 flags
|= BLOCK_FLAG_COMPAT6
;
1887 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1888 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1889 zeroed_grain
= true;
1892 if (!adapter_type
) {
1893 adapter_type
= g_strdup("ide");
1894 } else if (strcmp(adapter_type
, "ide") &&
1895 strcmp(adapter_type
, "buslogic") &&
1896 strcmp(adapter_type
, "lsilogic") &&
1897 strcmp(adapter_type
, "legacyESX")) {
1898 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1902 if (strcmp(adapter_type
, "ide") != 0) {
1903 /* that's the number of heads with which vmware operates when
1904 creating, exporting, etc. vmdk files with a non-ide adapter type */
1908 /* Default format to monolithicSparse */
1909 fmt
= g_strdup("monolithicSparse");
1910 } else if (strcmp(fmt
, "monolithicFlat") &&
1911 strcmp(fmt
, "monolithicSparse") &&
1912 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1913 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1914 strcmp(fmt
, "streamOptimized")) {
1915 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1919 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1920 strcmp(fmt
, "twoGbMaxExtentSparse"));
1921 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1922 strcmp(fmt
, "twoGbMaxExtentFlat"));
1923 compress
= !strcmp(fmt
, "streamOptimized");
1925 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
1927 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
1929 if (flat
&& backing_file
) {
1930 error_setg(errp
, "Flat image can't have backing file");
1934 if (flat
&& zeroed_grain
) {
1935 error_setg(errp
, "Flat image can't enable zeroed grain");
1941 char *full_backing
= g_new0(char, PATH_MAX
);
1942 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
1943 full_backing
, PATH_MAX
,
1946 g_free(full_backing
);
1947 error_propagate(errp
, local_err
);
1952 blk
= blk_new_open("backing", full_backing
, NULL
, NULL
,
1953 BDRV_O_NO_BACKING
| BDRV_O_CACHE_WB
, errp
);
1954 g_free(full_backing
);
1959 if (strcmp(blk_bs(blk
)->drv
->format_name
, "vmdk")) {
1964 parent_cid
= vmdk_read_cid(blk_bs(blk
), 0);
1966 snprintf(parent_desc_line
, BUF_SIZE
,
1967 "parentFileNameHint=\"%s\"", backing_file
);
1970 /* Create extents */
1971 filesize
= total_size
;
1972 while (filesize
> 0) {
1973 int64_t size
= filesize
;
1975 if (split
&& size
> split_size
) {
1979 snprintf(desc_filename
, PATH_MAX
, "%s-%c%03d%s",
1980 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1982 snprintf(desc_filename
, PATH_MAX
, "%s-flat%s", prefix
, postfix
);
1984 snprintf(desc_filename
, PATH_MAX
, "%s%s", prefix
, postfix
);
1986 snprintf(ext_filename
, PATH_MAX
, "%s%s", path
, desc_filename
);
1988 if (vmdk_create_extent(ext_filename
, size
,
1989 flat
, compress
, zeroed_grain
, opts
, errp
)) {
1995 /* Format description line */
1996 snprintf(desc_line
, BUF_SIZE
,
1997 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
1998 g_string_append(ext_desc_lines
, desc_line
);
2000 /* generate descriptor file */
2001 desc
= g_strdup_printf(desc_template
,
2006 ext_desc_lines
->str
,
2007 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
2009 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
2012 desc_len
= strlen(desc
);
2013 /* the descriptor offset = 0x200 */
2014 if (!split
&& !flat
) {
2015 desc_offset
= 0x200;
2017 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2019 error_propagate(errp
, local_err
);
2024 new_blk
= blk_new_open("descriptor", filename
, NULL
, NULL
,
2025 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_PROTOCOL
,
2027 if (new_blk
== NULL
) {
2028 error_propagate(errp
, local_err
);
2033 blk_set_allow_write_beyond_eof(new_blk
, true);
2035 ret
= blk_pwrite(new_blk
, desc_offset
, desc
, desc_len
);
2037 error_setg_errno(errp
, -ret
, "Could not write description");
2040 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2041 * for description file */
2042 if (desc_offset
== 0) {
2043 ret
= blk_truncate(new_blk
, desc_len
);
2045 error_setg_errno(errp
, -ret
, "Could not truncate file");
2052 g_free(adapter_type
);
2053 g_free(backing_file
);
2060 g_free(ext_filename
);
2061 g_free(desc_filename
);
2062 g_free(parent_desc_line
);
2063 g_string_free(ext_desc_lines
, true);
2067 static void vmdk_close(BlockDriverState
*bs
)
2069 BDRVVmdkState
*s
= bs
->opaque
;
2071 vmdk_free_extents(bs
);
2072 g_free(s
->create_type
);
2074 migrate_del_blocker(s
->migration_blocker
);
2075 error_free(s
->migration_blocker
);
2078 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
2080 BDRVVmdkState
*s
= bs
->opaque
;
2084 for (i
= 0; i
< s
->num_extents
; i
++) {
2085 err
= bdrv_co_flush(s
->extents
[i
].file
->bs
);
2093 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2098 BDRVVmdkState
*s
= bs
->opaque
;
2100 ret
= bdrv_get_allocated_file_size(bs
->file
->bs
);
2104 for (i
= 0; i
< s
->num_extents
; i
++) {
2105 if (s
->extents
[i
].file
== bs
->file
) {
2108 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
->bs
);
2117 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2120 BDRVVmdkState
*s
= bs
->opaque
;
2122 /* If has a flat extent and its underlying storage doesn't have zero init,
2124 for (i
= 0; i
< s
->num_extents
; i
++) {
2125 if (s
->extents
[i
].flat
) {
2126 if (!bdrv_has_zero_init(s
->extents
[i
].file
->bs
)) {
2134 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2136 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2138 *info
= (ImageInfo
){
2139 .filename
= g_strdup(extent
->file
->bs
->filename
),
2140 .format
= g_strdup(extent
->type
),
2141 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2142 .compressed
= extent
->compressed
,
2143 .has_compressed
= extent
->compressed
,
2144 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2145 .has_cluster_size
= !extent
->flat
,
2151 static int vmdk_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
2154 BDRVVmdkState
*s
= bs
->opaque
;
2155 VmdkExtent
*extent
= NULL
;
2156 int64_t sector_num
= 0;
2157 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2159 uint64_t cluster_offset
;
2166 if (sector_num
>= total_sectors
) {
2169 extent
= find_extent(s
, sector_num
, extent
);
2172 "ERROR: could not find extent for sector %" PRId64
"\n",
2176 ret
= get_cluster_offset(bs
, extent
, NULL
,
2177 sector_num
<< BDRV_SECTOR_BITS
,
2178 false, &cluster_offset
, 0, 0);
2179 if (ret
== VMDK_ERROR
) {
2181 "ERROR: could not get cluster_offset for sector %"
2182 PRId64
"\n", sector_num
);
2185 if (ret
== VMDK_OK
&&
2186 cluster_offset
>= bdrv_getlength(extent
->file
->bs
))
2189 "ERROR: cluster offset for sector %"
2190 PRId64
" points after EOF\n", sector_num
);
2193 sector_num
+= extent
->cluster_sectors
;
2196 result
->corruptions
++;
2200 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2203 BDRVVmdkState
*s
= bs
->opaque
;
2204 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2205 ImageInfoList
**next
;
2207 *spec_info
= (ImageInfoSpecific
){
2208 .type
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2210 .vmdk
= g_new0(ImageInfoSpecificVmdk
, 1),
2214 *spec_info
->u
.vmdk
= (ImageInfoSpecificVmdk
) {
2215 .create_type
= g_strdup(s
->create_type
),
2217 .parent_cid
= s
->parent_cid
,
2220 next
= &spec_info
->u
.vmdk
->extents
;
2221 for (i
= 0; i
< s
->num_extents
; i
++) {
2222 *next
= g_new0(ImageInfoList
, 1);
2223 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2224 (*next
)->next
= NULL
;
2225 next
= &(*next
)->next
;
2231 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
2233 return a
->flat
== b
->flat
&&
2234 a
->compressed
== b
->compressed
&&
2235 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
2238 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2241 BDRVVmdkState
*s
= bs
->opaque
;
2242 assert(s
->num_extents
);
2244 /* See if we have multiple extents but they have different cases */
2245 for (i
= 1; i
< s
->num_extents
; i
++) {
2246 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
2250 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2251 if (!s
->extents
[0].flat
) {
2252 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2257 static void vmdk_detach_aio_context(BlockDriverState
*bs
)
2259 BDRVVmdkState
*s
= bs
->opaque
;
2262 for (i
= 0; i
< s
->num_extents
; i
++) {
2263 bdrv_detach_aio_context(s
->extents
[i
].file
->bs
);
2267 static void vmdk_attach_aio_context(BlockDriverState
*bs
,
2268 AioContext
*new_context
)
2270 BDRVVmdkState
*s
= bs
->opaque
;
2273 for (i
= 0; i
< s
->num_extents
; i
++) {
2274 bdrv_attach_aio_context(s
->extents
[i
].file
->bs
, new_context
);
2278 static QemuOptsList vmdk_create_opts
= {
2279 .name
= "vmdk-create-opts",
2280 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2283 .name
= BLOCK_OPT_SIZE
,
2284 .type
= QEMU_OPT_SIZE
,
2285 .help
= "Virtual disk size"
2288 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2289 .type
= QEMU_OPT_STRING
,
2290 .help
= "Virtual adapter type, can be one of "
2291 "ide (default), lsilogic, buslogic or legacyESX"
2294 .name
= BLOCK_OPT_BACKING_FILE
,
2295 .type
= QEMU_OPT_STRING
,
2296 .help
= "File name of a base image"
2299 .name
= BLOCK_OPT_COMPAT6
,
2300 .type
= QEMU_OPT_BOOL
,
2301 .help
= "VMDK version 6 image",
2302 .def_value_str
= "off"
2305 .name
= BLOCK_OPT_SUBFMT
,
2306 .type
= QEMU_OPT_STRING
,
2308 "VMDK flat extent format, can be one of "
2309 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2312 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2313 .type
= QEMU_OPT_BOOL
,
2314 .help
= "Enable efficient zero writes "
2315 "using the zeroed-grain GTE feature"
2317 { /* end of list */ }
2321 static BlockDriver bdrv_vmdk
= {
2322 .format_name
= "vmdk",
2323 .instance_size
= sizeof(BDRVVmdkState
),
2324 .bdrv_probe
= vmdk_probe
,
2325 .bdrv_open
= vmdk_open
,
2326 .bdrv_check
= vmdk_check
,
2327 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2328 .bdrv_read
= vmdk_co_read
,
2329 .bdrv_write
= vmdk_co_write
,
2330 .bdrv_write_compressed
= vmdk_write_compressed
,
2331 .bdrv_co_write_zeroes
= vmdk_co_write_zeroes
,
2332 .bdrv_close
= vmdk_close
,
2333 .bdrv_create
= vmdk_create
,
2334 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2335 .bdrv_co_get_block_status
= vmdk_co_get_block_status
,
2336 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2337 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2338 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2339 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2340 .bdrv_get_info
= vmdk_get_info
,
2341 .bdrv_detach_aio_context
= vmdk_detach_aio_context
,
2342 .bdrv_attach_aio_context
= vmdk_attach_aio_context
,
2344 .supports_backing
= true,
2345 .create_opts
= &vmdk_create_opts
,
2348 static void bdrv_vmdk_init(void)
2350 bdrv_register(&bdrv_vmdk
);
2353 block_init(bdrv_vmdk_init
);