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 "qapi/qmp/qerror.h"
30 #include "qemu/error-report.h"
31 #include "qemu/module.h"
32 #include "migration/migration.h"
36 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
37 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
38 #define VMDK4_COMPRESSION_DEFLATE 1
39 #define VMDK4_FLAG_NL_DETECT (1 << 0)
40 #define VMDK4_FLAG_RGD (1 << 1)
41 /* Zeroed-grain enable bit */
42 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
43 #define VMDK4_FLAG_COMPRESS (1 << 16)
44 #define VMDK4_FLAG_MARKER (1 << 17)
45 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
47 #define VMDK_GTE_ZEROED 0x1
49 /* VMDK internal error codes */
51 #define VMDK_ERROR (-1)
52 /* Cluster not allocated */
53 #define VMDK_UNALLOC (-2)
54 #define VMDK_ZEROED (-3)
56 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
61 uint32_t disk_sectors
;
63 uint32_t l1dir_offset
;
65 uint32_t file_sectors
;
68 uint32_t sectors_per_track
;
69 } QEMU_PACKED VMDK3Header
;
78 /* Number of GrainTableEntries per GrainTable */
79 uint32_t num_gtes_per_gt
;
82 uint64_t grain_offset
;
85 uint16_t compressAlgorithm
;
86 } QEMU_PACKED VMDK4Header
;
88 #define L2_CACHE_SIZE 16
90 typedef struct VmdkExtent
{
99 int64_t flat_start_offset
;
100 int64_t l1_table_offset
;
101 int64_t l1_backup_table_offset
;
103 uint32_t *l1_backup_table
;
104 unsigned int l1_size
;
105 uint32_t l1_entry_sectors
;
107 unsigned int l2_size
;
109 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
110 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
112 int64_t cluster_sectors
;
113 int64_t next_cluster_sector
;
117 typedef struct BDRVVmdkState
{
119 uint64_t desc_offset
;
125 /* Extent array with num_extents entries, ascend ordered by address */
127 Error
*migration_blocker
;
131 typedef struct VmdkMetaData
{
132 unsigned int l1_index
;
133 unsigned int l2_index
;
134 unsigned int l2_offset
;
136 uint32_t *l2_cache_entry
;
139 typedef struct VmdkGrainMarker
{
143 } QEMU_PACKED VmdkGrainMarker
;
146 MARKER_END_OF_STREAM
= 0,
147 MARKER_GRAIN_TABLE
= 1,
148 MARKER_GRAIN_DIRECTORY
= 2,
152 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
159 magic
= be32_to_cpu(*(uint32_t *)buf
);
160 if (magic
== VMDK3_MAGIC
||
161 magic
== VMDK4_MAGIC
) {
164 const char *p
= (const char *)buf
;
165 const char *end
= p
+ buf_size
;
168 /* skip comment line */
169 while (p
< end
&& *p
!= '\n') {
176 while (p
< end
&& *p
== ' ') {
179 /* skip '\r' if windows line endings used. */
180 if (p
< end
&& *p
== '\r') {
183 /* only accept blank lines before 'version=' line */
184 if (p
== end
|| *p
!= '\n') {
190 if (end
- p
>= strlen("version=X\n")) {
191 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
192 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
196 if (end
- p
>= strlen("version=X\r\n")) {
197 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
198 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
208 #define SECTOR_SIZE 512
209 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
210 #define BUF_SIZE 4096
211 #define HEADER_SIZE 512 /* first sector of 512 bytes */
213 static void vmdk_free_extents(BlockDriverState
*bs
)
216 BDRVVmdkState
*s
= bs
->opaque
;
219 for (i
= 0; i
< s
->num_extents
; i
++) {
223 g_free(e
->l1_backup_table
);
225 if (e
->file
!= bs
->file
) {
226 bdrv_unref_child(bs
, e
->file
);
232 static void vmdk_free_last_extent(BlockDriverState
*bs
)
234 BDRVVmdkState
*s
= bs
->opaque
;
236 if (s
->num_extents
== 0) {
240 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
243 static uint32_t vmdk_read_cid(BlockDriverState
*bs
, int parent
)
245 char desc
[DESC_SIZE
];
246 uint32_t cid
= 0xffffffff;
247 const char *p_name
, *cid_str
;
249 BDRVVmdkState
*s
= bs
->opaque
;
252 ret
= bdrv_pread(bs
->file
->bs
, s
->desc_offset
, desc
, DESC_SIZE
);
258 cid_str
= "parentCID";
259 cid_str_size
= sizeof("parentCID");
262 cid_str_size
= sizeof("CID");
265 desc
[DESC_SIZE
- 1] = '\0';
266 p_name
= strstr(desc
, cid_str
);
267 if (p_name
!= NULL
) {
268 p_name
+= cid_str_size
;
269 sscanf(p_name
, "%" SCNx32
, &cid
);
275 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
277 char desc
[DESC_SIZE
], tmp_desc
[DESC_SIZE
];
278 char *p_name
, *tmp_str
;
279 BDRVVmdkState
*s
= bs
->opaque
;
282 ret
= bdrv_pread(bs
->file
->bs
, s
->desc_offset
, desc
, DESC_SIZE
);
287 desc
[DESC_SIZE
- 1] = '\0';
288 tmp_str
= strstr(desc
, "parentCID");
289 if (tmp_str
== NULL
) {
293 pstrcpy(tmp_desc
, sizeof(tmp_desc
), tmp_str
);
294 p_name
= strstr(desc
, "CID");
295 if (p_name
!= NULL
) {
296 p_name
+= sizeof("CID");
297 snprintf(p_name
, sizeof(desc
) - (p_name
- desc
), "%" PRIx32
"\n", cid
);
298 pstrcat(desc
, sizeof(desc
), tmp_desc
);
301 ret
= bdrv_pwrite_sync(bs
->file
->bs
, s
->desc_offset
, desc
, DESC_SIZE
);
309 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
311 BDRVVmdkState
*s
= bs
->opaque
;
314 if (!s
->cid_checked
&& bs
->backing
) {
315 BlockDriverState
*p_bs
= bs
->backing
->bs
;
317 cur_pcid
= vmdk_read_cid(p_bs
, 0);
318 if (s
->parent_cid
!= cur_pcid
) {
323 s
->cid_checked
= true;
328 /* We have nothing to do for VMDK reopen, stubs just return success */
329 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
330 BlockReopenQueue
*queue
, Error
**errp
)
332 assert(state
!= NULL
);
333 assert(state
->bs
!= NULL
);
337 static int vmdk_parent_open(BlockDriverState
*bs
)
340 char desc
[DESC_SIZE
+ 1];
341 BDRVVmdkState
*s
= bs
->opaque
;
344 desc
[DESC_SIZE
] = '\0';
345 ret
= bdrv_pread(bs
->file
->bs
, s
->desc_offset
, desc
, DESC_SIZE
);
350 p_name
= strstr(desc
, "parentFileNameHint");
351 if (p_name
!= NULL
) {
354 p_name
+= sizeof("parentFileNameHint") + 1;
355 end_name
= strchr(p_name
, '\"');
356 if (end_name
== NULL
) {
359 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
363 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
369 /* Create and append extent to the extent array. Return the added VmdkExtent
370 * address. return NULL if allocation failed. */
371 static int vmdk_add_extent(BlockDriverState
*bs
,
372 BdrvChild
*file
, bool flat
, int64_t sectors
,
373 int64_t l1_offset
, int64_t l1_backup_offset
,
375 int l2_size
, uint64_t cluster_sectors
,
376 VmdkExtent
**new_extent
,
380 BDRVVmdkState
*s
= bs
->opaque
;
383 if (cluster_sectors
> 0x200000) {
384 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
385 error_setg(errp
, "Invalid granularity, image may be corrupt");
388 if (l1_size
> 512 * 1024 * 1024) {
389 /* Although with big capacity and small l1_entry_sectors, we can get a
390 * big l1_size, we don't want unbounded value to allocate the table.
391 * Limit it to 512M, which is 16PB for default cluster and L2 table
393 error_setg(errp
, "L1 size too big");
397 nb_sectors
= bdrv_nb_sectors(file
->bs
);
398 if (nb_sectors
< 0) {
402 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
403 extent
= &s
->extents
[s
->num_extents
];
406 memset(extent
, 0, sizeof(VmdkExtent
));
409 extent
->sectors
= sectors
;
410 extent
->l1_table_offset
= l1_offset
;
411 extent
->l1_backup_table_offset
= l1_backup_offset
;
412 extent
->l1_size
= l1_size
;
413 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
414 extent
->l2_size
= l2_size
;
415 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
416 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
418 if (s
->num_extents
> 1) {
419 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
421 extent
->end_sector
= extent
->sectors
;
423 bs
->total_sectors
= extent
->end_sector
;
425 *new_extent
= extent
;
430 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
437 /* read the L1 table */
438 l1_size
= extent
->l1_size
* sizeof(uint32_t);
439 extent
->l1_table
= g_try_malloc(l1_size
);
440 if (l1_size
&& extent
->l1_table
== NULL
) {
444 ret
= bdrv_pread(extent
->file
->bs
,
445 extent
->l1_table_offset
,
449 error_setg_errno(errp
, -ret
,
450 "Could not read l1 table from extent '%s'",
451 extent
->file
->bs
->filename
);
454 for (i
= 0; i
< extent
->l1_size
; i
++) {
455 le32_to_cpus(&extent
->l1_table
[i
]);
458 if (extent
->l1_backup_table_offset
) {
459 extent
->l1_backup_table
= g_try_malloc(l1_size
);
460 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
464 ret
= bdrv_pread(extent
->file
->bs
,
465 extent
->l1_backup_table_offset
,
466 extent
->l1_backup_table
,
469 error_setg_errno(errp
, -ret
,
470 "Could not read l1 backup table from extent '%s'",
471 extent
->file
->bs
->filename
);
474 for (i
= 0; i
< extent
->l1_size
; i
++) {
475 le32_to_cpus(&extent
->l1_backup_table
[i
]);
480 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
483 g_free(extent
->l1_backup_table
);
485 g_free(extent
->l1_table
);
489 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
491 int flags
, Error
**errp
)
498 ret
= bdrv_pread(file
->bs
, sizeof(magic
), &header
, sizeof(header
));
500 error_setg_errno(errp
, -ret
,
501 "Could not read header from file '%s'",
505 ret
= vmdk_add_extent(bs
, file
, false,
506 le32_to_cpu(header
.disk_sectors
),
507 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
509 le32_to_cpu(header
.l1dir_size
),
511 le32_to_cpu(header
.granularity
),
517 ret
= vmdk_init_tables(bs
, extent
, errp
);
519 /* free extent allocated by vmdk_add_extent */
520 vmdk_free_last_extent(bs
);
525 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
526 QDict
*options
, Error
**errp
);
528 static char *vmdk_read_desc(BlockDriverState
*file
, uint64_t desc_offset
,
535 size
= bdrv_getlength(file
);
537 error_setg_errno(errp
, -size
, "Could not access file");
542 /* Both descriptor file and sparse image must be much larger than 4
543 * bytes, also callers of vmdk_read_desc want to compare the first 4
544 * bytes with VMDK4_MAGIC, let's error out if less is read. */
545 error_setg(errp
, "File is too small, not a valid image");
549 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
550 buf
= g_malloc(size
+ 1);
552 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
554 error_setg_errno(errp
, -ret
, "Could not read from file");
563 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
565 int flags
, QDict
*options
, Error
**errp
)
569 uint32_t l1_size
, l1_entry_sectors
;
572 BDRVVmdkState
*s
= bs
->opaque
;
573 int64_t l1_backup_offset
= 0;
576 ret
= bdrv_pread(file
->bs
, sizeof(magic
), &header
, sizeof(header
));
578 error_setg_errno(errp
, -ret
,
579 "Could not read header from file '%s'",
583 if (header
.capacity
== 0) {
584 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
586 char *buf
= vmdk_read_desc(file
->bs
, desc_offset
<< 9, errp
);
590 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
596 if (!s
->create_type
) {
597 s
->create_type
= g_strdup("monolithicSparse");
600 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
602 * The footer takes precedence over the header, so read it in. The
603 * footer starts at offset -1024 from the end: One sector for the
604 * footer, and another one for the end-of-stream marker.
611 uint8_t pad
[512 - 16];
612 } QEMU_PACKED footer_marker
;
616 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
622 uint8_t pad
[512 - 16];
623 } QEMU_PACKED eos_marker
;
624 } QEMU_PACKED footer
;
626 ret
= bdrv_pread(file
->bs
,
627 bs
->file
->bs
->total_sectors
* 512 - 1536,
628 &footer
, sizeof(footer
));
630 error_setg_errno(errp
, -ret
, "Failed to read footer");
634 /* Some sanity checks for the footer */
635 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
636 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
637 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
638 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
639 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
640 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
642 error_setg(errp
, "Invalid footer");
646 header
= footer
.header
;
650 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
651 if (le32_to_cpu(header
.version
) > 3) {
653 snprintf(buf
, sizeof(buf
), "VMDK version %" PRId32
,
654 le32_to_cpu(header
.version
));
655 error_setg(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
,
656 bdrv_get_device_or_node_name(bs
), "vmdk", buf
);
658 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
) &&
660 /* VMware KB 2064959 explains that version 3 added support for
661 * persistent changed block tracking (CBT), and backup software can
662 * read it as version=1 if it doesn't care about the changed area
663 * information. So we are safe to enable read only. */
664 error_setg(errp
, "VMDK version 3 must be read only");
668 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
669 error_setg(errp
, "L2 table size too big");
673 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
674 * le64_to_cpu(header
.granularity
);
675 if (l1_entry_sectors
== 0) {
676 error_setg(errp
, "L1 entry size is invalid");
679 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
681 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
682 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
684 if (bdrv_nb_sectors(file
->bs
) < le64_to_cpu(header
.grain_offset
)) {
685 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
686 (int64_t)(le64_to_cpu(header
.grain_offset
)
687 * BDRV_SECTOR_SIZE
));
691 ret
= vmdk_add_extent(bs
, file
, false,
692 le64_to_cpu(header
.capacity
),
693 le64_to_cpu(header
.gd_offset
) << 9,
696 le32_to_cpu(header
.num_gtes_per_gt
),
697 le64_to_cpu(header
.granularity
),
704 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
705 if (extent
->compressed
) {
706 g_free(s
->create_type
);
707 s
->create_type
= g_strdup("streamOptimized");
709 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
710 extent
->version
= le32_to_cpu(header
.version
);
711 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
712 ret
= vmdk_init_tables(bs
, extent
, errp
);
714 /* free extent allocated by vmdk_add_extent */
715 vmdk_free_last_extent(bs
);
720 /* find an option value out of descriptor file */
721 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
722 char *buf
, int buf_size
)
724 char *opt_pos
, *opt_end
;
725 const char *end
= desc
+ strlen(desc
);
727 opt_pos
= strstr(desc
, opt_name
);
731 /* Skip "=\"" following opt_name */
732 opt_pos
+= strlen(opt_name
) + 2;
733 if (opt_pos
>= end
) {
737 while (opt_end
< end
&& *opt_end
!= '"') {
740 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
743 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
747 /* Open an extent file and append to bs array */
748 static int vmdk_open_sparse(BlockDriverState
*bs
, BdrvChild
*file
, int flags
,
749 char *buf
, QDict
*options
, Error
**errp
)
753 magic
= ldl_be_p(buf
);
756 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
759 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
762 error_setg(errp
, "Image not in VMDK format");
768 static const char *next_line(const char *s
)
779 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
780 const char *desc_file_path
, QDict
*options
,
792 BdrvChild
*extent_file
;
793 BDRVVmdkState
*s
= bs
->opaque
;
795 char extent_opt_prefix
[32];
796 Error
*local_err
= NULL
;
798 for (p
= desc
; *p
; p
= next_line(p
)) {
799 /* parse extent line in one of below formats:
801 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
802 * RW [size in sectors] SPARSE "file-name.vmdk"
803 * RW [size in sectors] VMFS "file-name.vmdk"
804 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
807 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
808 access
, §ors
, type
, fname
, &flat_offset
);
809 if (matches
< 4 || strcmp(access
, "RW")) {
811 } else if (!strcmp(type
, "FLAT")) {
812 if (matches
!= 5 || flat_offset
< 0) {
815 } else if (!strcmp(type
, "VMFS")) {
821 } else if (matches
!= 4) {
826 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
827 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
828 (strcmp(access
, "RW"))) {
832 if (!path_is_absolute(fname
) && !path_has_protocol(fname
) &&
835 error_setg(errp
, "Cannot use relative extent paths with VMDK "
836 "descriptor file '%s'", bs
->file
->bs
->filename
);
840 extent_path
= g_malloc0(PATH_MAX
);
841 path_combine(extent_path
, PATH_MAX
, desc_file_path
, fname
);
843 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
846 extent_file
= bdrv_open_child(extent_path
, options
, extent_opt_prefix
,
847 bs
, &child_file
, false, &local_err
);
850 error_propagate(errp
, local_err
);
854 /* save to extents array */
855 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
858 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
859 0, 0, 0, 0, 0, &extent
, errp
);
861 bdrv_unref_child(bs
, extent_file
);
864 extent
->flat_start_offset
= flat_offset
<< 9;
865 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
866 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
867 char *buf
= vmdk_read_desc(extent_file
->bs
, 0, errp
);
871 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
876 bdrv_unref_child(bs
, extent_file
);
879 extent
= &s
->extents
[s
->num_extents
- 1];
881 error_setg(errp
, "Unsupported extent type '%s'", type
);
882 bdrv_unref_child(bs
, extent_file
);
885 extent
->type
= g_strdup(type
);
892 if (np
[-1] == '\n') {
895 error_setg(errp
, "Invalid extent line: %.*s", (int)(np
- p
), p
);
899 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
900 QDict
*options
, Error
**errp
)
904 BDRVVmdkState
*s
= bs
->opaque
;
906 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
907 error_setg(errp
, "invalid VMDK image descriptor");
911 if (strcmp(ct
, "monolithicFlat") &&
912 strcmp(ct
, "vmfs") &&
913 strcmp(ct
, "vmfsSparse") &&
914 strcmp(ct
, "twoGbMaxExtentSparse") &&
915 strcmp(ct
, "twoGbMaxExtentFlat")) {
916 error_setg(errp
, "Unsupported image type '%s'", ct
);
920 s
->create_type
= g_strdup(ct
);
922 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->bs
->exact_filename
, options
,
928 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
933 BDRVVmdkState
*s
= bs
->opaque
;
936 buf
= vmdk_read_desc(bs
->file
->bs
, 0, errp
);
941 magic
= ldl_be_p(buf
);
945 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
,
947 s
->desc_offset
= 0x200;
950 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
957 /* try to open parent images, if exist */
958 ret
= vmdk_parent_open(bs
);
962 s
->cid
= vmdk_read_cid(bs
, 0);
963 s
->parent_cid
= vmdk_read_cid(bs
, 1);
964 qemu_co_mutex_init(&s
->lock
);
966 /* Disable migration when VMDK images are used */
967 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
968 "does not support live migration",
969 bdrv_get_device_or_node_name(bs
));
970 migrate_add_blocker(s
->migration_blocker
);
976 g_free(s
->create_type
);
977 s
->create_type
= NULL
;
978 vmdk_free_extents(bs
);
983 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
985 BDRVVmdkState
*s
= bs
->opaque
;
988 for (i
= 0; i
< s
->num_extents
; i
++) {
989 if (!s
->extents
[i
].flat
) {
990 bs
->bl
.write_zeroes_alignment
=
991 MAX(bs
->bl
.write_zeroes_alignment
,
992 s
->extents
[i
].cluster_sectors
);
1000 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1001 * to the cluster at @cluster_sector_num.
1003 * If @skip_start_sector < @skip_end_sector, the relative range
1004 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1005 * it for call to write user data in the request.
1007 static int get_whole_cluster(BlockDriverState
*bs
,
1009 uint64_t cluster_sector_num
,
1010 uint64_t sector_num
,
1011 uint64_t skip_start_sector
,
1012 uint64_t skip_end_sector
)
1015 int64_t cluster_bytes
;
1016 uint8_t *whole_grain
;
1018 /* For COW, align request sector_num to cluster start */
1019 sector_num
= QEMU_ALIGN_DOWN(sector_num
, extent
->cluster_sectors
);
1020 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1021 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1024 memset(whole_grain
, 0, skip_start_sector
<< BDRV_SECTOR_BITS
);
1025 memset(whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
), 0,
1026 cluster_bytes
- (skip_end_sector
<< BDRV_SECTOR_BITS
));
1029 assert(skip_end_sector
<= extent
->cluster_sectors
);
1030 /* we will be here if it's first write on non-exist grain(cluster).
1031 * try to read from parent image, if exist */
1032 if (bs
->backing
&& !vmdk_is_cid_valid(bs
)) {
1037 /* Read backing data before skip range */
1038 if (skip_start_sector
> 0) {
1040 ret
= bdrv_read(bs
->backing
->bs
, sector_num
,
1041 whole_grain
, skip_start_sector
);
1047 ret
= bdrv_write(extent
->file
->bs
, cluster_sector_num
, whole_grain
,
1054 /* Read backing data after skip range */
1055 if (skip_end_sector
< extent
->cluster_sectors
) {
1057 ret
= bdrv_read(bs
->backing
->bs
, sector_num
+ skip_end_sector
,
1058 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1059 extent
->cluster_sectors
- skip_end_sector
);
1065 ret
= bdrv_write(extent
->file
->bs
, cluster_sector_num
+ skip_end_sector
,
1066 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1067 extent
->cluster_sectors
- skip_end_sector
);
1075 qemu_vfree(whole_grain
);
1079 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1082 offset
= cpu_to_le32(offset
);
1083 /* update L2 table */
1084 if (bdrv_pwrite_sync(
1086 ((int64_t)m_data
->l2_offset
* 512)
1087 + (m_data
->l2_index
* sizeof(offset
)),
1088 &offset
, sizeof(offset
)) < 0) {
1091 /* update backup L2 table */
1092 if (extent
->l1_backup_table_offset
!= 0) {
1093 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1094 if (bdrv_pwrite_sync(
1096 ((int64_t)m_data
->l2_offset
* 512)
1097 + (m_data
->l2_index
* sizeof(offset
)),
1098 &offset
, sizeof(offset
)) < 0) {
1102 if (m_data
->l2_cache_entry
) {
1103 *m_data
->l2_cache_entry
= offset
;
1110 * get_cluster_offset
1112 * Look up cluster offset in extent file by sector number, and store in
1115 * For flat extents, the start offset as parsed from the description file is
1118 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1119 * offset for a new cluster and update L2 cache. If there is a backing file,
1120 * COW is done before returning; otherwise, zeroes are written to the allocated
1121 * cluster. Both COW and zero writing skips the sector range
1122 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1123 * has new data to write there.
1125 * Returns: VMDK_OK if cluster exists and mapped in the image.
1126 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1127 * VMDK_ERROR if failed.
1129 static int get_cluster_offset(BlockDriverState
*bs
,
1131 VmdkMetaData
*m_data
,
1134 uint64_t *cluster_offset
,
1135 uint64_t skip_start_sector
,
1136 uint64_t skip_end_sector
)
1138 unsigned int l1_index
, l2_offset
, l2_index
;
1139 int min_index
, i
, j
;
1140 uint32_t min_count
, *l2_table
;
1141 bool zeroed
= false;
1143 int64_t cluster_sector
;
1149 *cluster_offset
= extent
->flat_start_offset
;
1153 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1154 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1155 if (l1_index
>= extent
->l1_size
) {
1158 l2_offset
= extent
->l1_table
[l1_index
];
1160 return VMDK_UNALLOC
;
1162 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1163 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1164 /* increment the hit count */
1165 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1166 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1167 extent
->l2_cache_counts
[j
] >>= 1;
1170 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1174 /* not found: load a new entry in the least used one */
1176 min_count
= 0xffffffff;
1177 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1178 if (extent
->l2_cache_counts
[i
] < min_count
) {
1179 min_count
= extent
->l2_cache_counts
[i
];
1183 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1186 (int64_t)l2_offset
* 512,
1188 extent
->l2_size
* sizeof(uint32_t)
1189 ) != extent
->l2_size
* sizeof(uint32_t)) {
1193 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1194 extent
->l2_cache_counts
[min_index
] = 1;
1196 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1197 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1201 m_data
->l1_index
= l1_index
;
1202 m_data
->l2_index
= l2_index
;
1203 m_data
->l2_offset
= l2_offset
;
1204 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1206 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1210 if (!cluster_sector
|| zeroed
) {
1212 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1215 cluster_sector
= extent
->next_cluster_sector
;
1216 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1218 /* First of all we write grain itself, to avoid race condition
1219 * that may to corrupt the image.
1220 * This problem may occur because of insufficient space on host disk
1221 * or inappropriate VM shutdown.
1223 ret
= get_whole_cluster(bs
, extent
,
1225 offset
>> BDRV_SECTOR_BITS
,
1226 skip_start_sector
, skip_end_sector
);
1231 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1235 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1236 int64_t sector_num
, VmdkExtent
*start_hint
)
1238 VmdkExtent
*extent
= start_hint
;
1241 extent
= &s
->extents
[0];
1243 while (extent
< &s
->extents
[s
->num_extents
]) {
1244 if (sector_num
< extent
->end_sector
) {
1252 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent
*extent
,
1255 uint64_t index_in_cluster
, extent_begin_sector
, extent_relative_sector_num
;
1257 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1258 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1259 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1260 return index_in_cluster
;
1263 static int64_t coroutine_fn
vmdk_co_get_block_status(BlockDriverState
*bs
,
1264 int64_t sector_num
, int nb_sectors
, int *pnum
, BlockDriverState
**file
)
1266 BDRVVmdkState
*s
= bs
->opaque
;
1267 int64_t index_in_cluster
, n
, ret
;
1271 extent
= find_extent(s
, sector_num
, NULL
);
1275 qemu_co_mutex_lock(&s
->lock
);
1276 ret
= get_cluster_offset(bs
, extent
, NULL
,
1277 sector_num
* 512, false, &offset
,
1279 qemu_co_mutex_unlock(&s
->lock
);
1281 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1290 ret
= BDRV_BLOCK_ZERO
;
1293 ret
= BDRV_BLOCK_DATA
;
1294 if (!extent
->compressed
) {
1295 ret
|= BDRV_BLOCK_OFFSET_VALID
;
1296 ret
|= (offset
+ (index_in_cluster
<< BDRV_SECTOR_BITS
))
1297 & BDRV_BLOCK_OFFSET_MASK
;
1299 *file
= extent
->file
->bs
;
1303 n
= extent
->cluster_sectors
- index_in_cluster
;
1304 if (n
> nb_sectors
) {
1311 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1312 int64_t offset_in_cluster
, const uint8_t *buf
,
1313 int nb_sectors
, int64_t sector_num
)
1316 VmdkGrainMarker
*data
= NULL
;
1318 const uint8_t *write_buf
= buf
;
1319 int write_len
= nb_sectors
* 512;
1320 int64_t write_offset
;
1321 int64_t write_end_sector
;
1323 if (extent
->compressed
) {
1324 if (!extent
->has_marker
) {
1328 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1329 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1330 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
1335 data
->lba
= sector_num
;
1336 data
->size
= buf_len
;
1337 write_buf
= (uint8_t *)data
;
1338 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
1340 write_offset
= cluster_offset
+ offset_in_cluster
,
1341 ret
= bdrv_pwrite(extent
->file
->bs
, write_offset
, write_buf
, write_len
);
1343 write_end_sector
= DIV_ROUND_UP(write_offset
+ write_len
, BDRV_SECTOR_SIZE
);
1345 if (extent
->compressed
) {
1346 extent
->next_cluster_sector
= write_end_sector
;
1348 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1352 if (ret
!= write_len
) {
1353 ret
= ret
< 0 ? ret
: -EIO
;
1362 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1363 int64_t offset_in_cluster
, uint8_t *buf
,
1367 int cluster_bytes
, buf_bytes
;
1368 uint8_t *cluster_buf
, *compressed_data
;
1369 uint8_t *uncomp_buf
;
1371 VmdkGrainMarker
*marker
;
1375 if (!extent
->compressed
) {
1376 ret
= bdrv_pread(extent
->file
->bs
,
1377 cluster_offset
+ offset_in_cluster
,
1378 buf
, nb_sectors
* 512);
1379 if (ret
== nb_sectors
* 512) {
1385 cluster_bytes
= extent
->cluster_sectors
* 512;
1386 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1387 buf_bytes
= cluster_bytes
* 2;
1388 cluster_buf
= g_malloc(buf_bytes
);
1389 uncomp_buf
= g_malloc(cluster_bytes
);
1390 ret
= bdrv_pread(extent
->file
->bs
,
1392 cluster_buf
, buf_bytes
);
1396 compressed_data
= cluster_buf
;
1397 buf_len
= cluster_bytes
;
1398 data_len
= cluster_bytes
;
1399 if (extent
->has_marker
) {
1400 marker
= (VmdkGrainMarker
*)cluster_buf
;
1401 compressed_data
= marker
->data
;
1402 data_len
= le32_to_cpu(marker
->size
);
1404 if (!data_len
|| data_len
> buf_bytes
) {
1408 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1414 if (offset_in_cluster
< 0 ||
1415 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
1419 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
1424 g_free(cluster_buf
);
1428 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
1429 uint8_t *buf
, int nb_sectors
)
1431 BDRVVmdkState
*s
= bs
->opaque
;
1433 uint64_t n
, index_in_cluster
;
1434 VmdkExtent
*extent
= NULL
;
1435 uint64_t cluster_offset
;
1437 while (nb_sectors
> 0) {
1438 extent
= find_extent(s
, sector_num
, extent
);
1442 ret
= get_cluster_offset(bs
, extent
, NULL
,
1443 sector_num
<< 9, false, &cluster_offset
,
1445 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1446 n
= extent
->cluster_sectors
- index_in_cluster
;
1447 if (n
> nb_sectors
) {
1450 if (ret
!= VMDK_OK
) {
1451 /* if not allocated, try to read from parent image, if exist */
1452 if (bs
->backing
&& ret
!= VMDK_ZEROED
) {
1453 if (!vmdk_is_cid_valid(bs
)) {
1456 ret
= bdrv_read(bs
->backing
->bs
, sector_num
, buf
, n
);
1461 memset(buf
, 0, 512 * n
);
1464 ret
= vmdk_read_extent(extent
,
1465 cluster_offset
, index_in_cluster
* 512,
1478 static coroutine_fn
int vmdk_co_read(BlockDriverState
*bs
, int64_t sector_num
,
1479 uint8_t *buf
, int nb_sectors
)
1482 BDRVVmdkState
*s
= bs
->opaque
;
1483 qemu_co_mutex_lock(&s
->lock
);
1484 ret
= vmdk_read(bs
, sector_num
, buf
, nb_sectors
);
1485 qemu_co_mutex_unlock(&s
->lock
);
1491 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1492 * if possible, otherwise return -ENOTSUP.
1493 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1494 * with each cluster. By dry run we can find if the zero write
1495 * is possible without modifying image data.
1497 * Returns: error code with 0 for success.
1499 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1500 const uint8_t *buf
, int nb_sectors
,
1501 bool zeroed
, bool zero_dry_run
)
1503 BDRVVmdkState
*s
= bs
->opaque
;
1504 VmdkExtent
*extent
= NULL
;
1506 int64_t index_in_cluster
, n
;
1507 uint64_t cluster_offset
;
1508 VmdkMetaData m_data
;
1510 if (sector_num
> bs
->total_sectors
) {
1511 error_report("Wrong offset: sector_num=0x%" PRIx64
1512 " total_sectors=0x%" PRIx64
,
1513 sector_num
, bs
->total_sectors
);
1517 while (nb_sectors
> 0) {
1518 extent
= find_extent(s
, sector_num
, extent
);
1522 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1523 n
= extent
->cluster_sectors
- index_in_cluster
;
1524 if (n
> nb_sectors
) {
1527 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1528 !(extent
->compressed
|| zeroed
),
1530 index_in_cluster
, index_in_cluster
+ n
);
1531 if (extent
->compressed
) {
1532 if (ret
== VMDK_OK
) {
1533 /* Refuse write to allocated cluster for streamOptimized */
1534 error_report("Could not write to allocated cluster"
1535 " for streamOptimized");
1539 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1540 true, &cluster_offset
, 0, 0);
1543 if (ret
== VMDK_ERROR
) {
1547 /* Do zeroed write, buf is ignored */
1548 if (extent
->has_zero_grain
&&
1549 index_in_cluster
== 0 &&
1550 n
>= extent
->cluster_sectors
) {
1551 n
= extent
->cluster_sectors
;
1552 if (!zero_dry_run
) {
1553 /* update L2 tables */
1554 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1563 ret
= vmdk_write_extent(extent
,
1564 cluster_offset
, index_in_cluster
* 512,
1565 buf
, n
, sector_num
);
1570 /* update L2 tables */
1571 if (vmdk_L2update(extent
, &m_data
,
1572 cluster_offset
>> BDRV_SECTOR_BITS
)
1582 /* update CID on the first write every time the virtual disk is
1584 if (!s
->cid_updated
) {
1585 ret
= vmdk_write_cid(bs
, g_random_int());
1589 s
->cid_updated
= true;
1595 static coroutine_fn
int vmdk_co_write(BlockDriverState
*bs
, int64_t sector_num
,
1596 const uint8_t *buf
, int nb_sectors
)
1599 BDRVVmdkState
*s
= bs
->opaque
;
1600 qemu_co_mutex_lock(&s
->lock
);
1601 ret
= vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1602 qemu_co_mutex_unlock(&s
->lock
);
1606 static int vmdk_write_compressed(BlockDriverState
*bs
,
1611 BDRVVmdkState
*s
= bs
->opaque
;
1612 if (s
->num_extents
== 1 && s
->extents
[0].compressed
) {
1613 return vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1619 static int coroutine_fn
vmdk_co_write_zeroes(BlockDriverState
*bs
,
1622 BdrvRequestFlags flags
)
1625 BDRVVmdkState
*s
= bs
->opaque
;
1626 qemu_co_mutex_lock(&s
->lock
);
1627 /* write zeroes could fail if sectors not aligned to cluster, test it with
1628 * dry_run == true before really updating image */
1629 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, true);
1631 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, false);
1633 qemu_co_mutex_unlock(&s
->lock
);
1637 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1638 bool flat
, bool compress
, bool zeroed_grain
,
1639 QemuOpts
*opts
, Error
**errp
)
1642 BlockDriverState
*bs
= NULL
;
1644 Error
*local_err
= NULL
;
1645 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1646 uint32_t *gd_buf
= NULL
;
1649 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1651 error_propagate(errp
, local_err
);
1656 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, BDRV_O_RDWR
| BDRV_O_PROTOCOL
,
1659 error_propagate(errp
, local_err
);
1664 ret
= bdrv_truncate(bs
, filesize
);
1666 error_setg_errno(errp
, -ret
, "Could not truncate file");
1670 magic
= cpu_to_be32(VMDK4_MAGIC
);
1671 memset(&header
, 0, sizeof(header
));
1674 } else if (zeroed_grain
) {
1679 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1680 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1681 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1682 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1683 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1684 header
.granularity
= 128;
1685 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1687 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1688 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1690 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1691 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1693 header
.desc_offset
= 1;
1694 header
.desc_size
= 20;
1695 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1696 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1697 header
.grain_offset
=
1698 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1699 header
.granularity
);
1700 /* swap endianness for all header fields */
1701 header
.version
= cpu_to_le32(header
.version
);
1702 header
.flags
= cpu_to_le32(header
.flags
);
1703 header
.capacity
= cpu_to_le64(header
.capacity
);
1704 header
.granularity
= cpu_to_le64(header
.granularity
);
1705 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1706 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1707 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1708 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1709 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1710 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1711 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1713 header
.check_bytes
[0] = 0xa;
1714 header
.check_bytes
[1] = 0x20;
1715 header
.check_bytes
[2] = 0xd;
1716 header
.check_bytes
[3] = 0xa;
1718 /* write all the data */
1719 ret
= bdrv_pwrite(bs
, 0, &magic
, sizeof(magic
));
1721 error_setg(errp
, QERR_IO_ERROR
);
1724 ret
= bdrv_pwrite(bs
, sizeof(magic
), &header
, sizeof(header
));
1726 error_setg(errp
, QERR_IO_ERROR
);
1730 ret
= bdrv_truncate(bs
, le64_to_cpu(header
.grain_offset
) << 9);
1732 error_setg_errno(errp
, -ret
, "Could not truncate file");
1736 /* write grain directory */
1737 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1738 gd_buf
= g_malloc0(gd_buf_size
);
1739 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1740 i
< gt_count
; i
++, tmp
+= gt_size
) {
1741 gd_buf
[i
] = cpu_to_le32(tmp
);
1743 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1744 gd_buf
, gd_buf_size
);
1746 error_setg(errp
, QERR_IO_ERROR
);
1750 /* write backup grain directory */
1751 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1752 i
< gt_count
; i
++, tmp
+= gt_size
) {
1753 gd_buf
[i
] = cpu_to_le32(tmp
);
1755 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1756 gd_buf
, gd_buf_size
);
1758 error_setg(errp
, QERR_IO_ERROR
);
1771 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1772 char *postfix
, size_t buf_len
, Error
**errp
)
1776 if (filename
== NULL
|| !strlen(filename
)) {
1777 error_setg(errp
, "No filename provided");
1780 p
= strrchr(filename
, '/');
1782 p
= strrchr(filename
, '\\');
1785 p
= strrchr(filename
, ':');
1789 if (p
- filename
>= buf_len
) {
1792 pstrcpy(path
, p
- filename
+ 1, filename
);
1797 q
= strrchr(p
, '.');
1799 pstrcpy(prefix
, buf_len
, p
);
1802 if (q
- p
>= buf_len
) {
1805 pstrcpy(prefix
, q
- p
+ 1, p
);
1806 pstrcpy(postfix
, buf_len
, q
);
1811 static int vmdk_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1814 BlockDriverState
*new_bs
= NULL
;
1815 Error
*local_err
= NULL
;
1817 int64_t total_size
= 0, filesize
;
1818 char *adapter_type
= NULL
;
1819 char *backing_file
= NULL
;
1823 bool flat
, split
, compress
;
1824 GString
*ext_desc_lines
;
1825 char *path
= g_malloc0(PATH_MAX
);
1826 char *prefix
= g_malloc0(PATH_MAX
);
1827 char *postfix
= g_malloc0(PATH_MAX
);
1828 char *desc_line
= g_malloc0(BUF_SIZE
);
1829 char *ext_filename
= g_malloc0(PATH_MAX
);
1830 char *desc_filename
= g_malloc0(PATH_MAX
);
1831 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1832 const char *desc_extent_line
;
1833 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
1834 uint32_t parent_cid
= 0xffffffff;
1835 uint32_t number_heads
= 16;
1836 bool zeroed_grain
= false;
1837 uint32_t desc_offset
= 0, desc_len
;
1838 const char desc_template
[] =
1839 "# Disk DescriptorFile\n"
1842 "parentCID=%" PRIx32
"\n"
1843 "createType=\"%s\"\n"
1846 "# Extent description\n"
1849 "# The Disk Data Base\n"
1852 "ddb.virtualHWVersion = \"%d\"\n"
1853 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1854 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1855 "ddb.geometry.sectors = \"63\"\n"
1856 "ddb.adapterType = \"%s\"\n";
1858 ext_desc_lines
= g_string_new(NULL
);
1860 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1864 /* Read out options */
1865 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1867 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1868 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1869 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1870 flags
|= BLOCK_FLAG_COMPAT6
;
1872 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1873 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1874 zeroed_grain
= true;
1877 if (!adapter_type
) {
1878 adapter_type
= g_strdup("ide");
1879 } else if (strcmp(adapter_type
, "ide") &&
1880 strcmp(adapter_type
, "buslogic") &&
1881 strcmp(adapter_type
, "lsilogic") &&
1882 strcmp(adapter_type
, "legacyESX")) {
1883 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1887 if (strcmp(adapter_type
, "ide") != 0) {
1888 /* that's the number of heads with which vmware operates when
1889 creating, exporting, etc. vmdk files with a non-ide adapter type */
1893 /* Default format to monolithicSparse */
1894 fmt
= g_strdup("monolithicSparse");
1895 } else if (strcmp(fmt
, "monolithicFlat") &&
1896 strcmp(fmt
, "monolithicSparse") &&
1897 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1898 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1899 strcmp(fmt
, "streamOptimized")) {
1900 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1904 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1905 strcmp(fmt
, "twoGbMaxExtentSparse"));
1906 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1907 strcmp(fmt
, "twoGbMaxExtentFlat"));
1908 compress
= !strcmp(fmt
, "streamOptimized");
1910 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
1912 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
1914 if (flat
&& backing_file
) {
1915 error_setg(errp
, "Flat image can't have backing file");
1919 if (flat
&& zeroed_grain
) {
1920 error_setg(errp
, "Flat image can't enable zeroed grain");
1925 BlockDriverState
*bs
= NULL
;
1926 char *full_backing
= g_new0(char, PATH_MAX
);
1927 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
1928 full_backing
, PATH_MAX
,
1931 g_free(full_backing
);
1932 error_propagate(errp
, local_err
);
1936 ret
= bdrv_open(&bs
, full_backing
, NULL
, NULL
, BDRV_O_NO_BACKING
, errp
);
1937 g_free(full_backing
);
1941 if (strcmp(bs
->drv
->format_name
, "vmdk")) {
1946 parent_cid
= vmdk_read_cid(bs
, 0);
1948 snprintf(parent_desc_line
, BUF_SIZE
,
1949 "parentFileNameHint=\"%s\"", backing_file
);
1952 /* Create extents */
1953 filesize
= total_size
;
1954 while (filesize
> 0) {
1955 int64_t size
= filesize
;
1957 if (split
&& size
> split_size
) {
1961 snprintf(desc_filename
, PATH_MAX
, "%s-%c%03d%s",
1962 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1964 snprintf(desc_filename
, PATH_MAX
, "%s-flat%s", prefix
, postfix
);
1966 snprintf(desc_filename
, PATH_MAX
, "%s%s", prefix
, postfix
);
1968 snprintf(ext_filename
, PATH_MAX
, "%s%s", path
, desc_filename
);
1970 if (vmdk_create_extent(ext_filename
, size
,
1971 flat
, compress
, zeroed_grain
, opts
, errp
)) {
1977 /* Format description line */
1978 snprintf(desc_line
, BUF_SIZE
,
1979 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
1980 g_string_append(ext_desc_lines
, desc_line
);
1982 /* generate descriptor file */
1983 desc
= g_strdup_printf(desc_template
,
1988 ext_desc_lines
->str
,
1989 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
1991 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
1994 desc_len
= strlen(desc
);
1995 /* the descriptor offset = 0x200 */
1996 if (!split
&& !flat
) {
1997 desc_offset
= 0x200;
1999 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2001 error_propagate(errp
, local_err
);
2005 assert(new_bs
== NULL
);
2006 ret
= bdrv_open(&new_bs
, filename
, NULL
, NULL
,
2007 BDRV_O_RDWR
| BDRV_O_PROTOCOL
, &local_err
);
2009 error_propagate(errp
, local_err
);
2012 ret
= bdrv_pwrite(new_bs
, desc_offset
, desc
, desc_len
);
2014 error_setg_errno(errp
, -ret
, "Could not write description");
2017 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2018 * for description file */
2019 if (desc_offset
== 0) {
2020 ret
= bdrv_truncate(new_bs
, desc_len
);
2022 error_setg_errno(errp
, -ret
, "Could not truncate file");
2029 g_free(adapter_type
);
2030 g_free(backing_file
);
2037 g_free(ext_filename
);
2038 g_free(desc_filename
);
2039 g_free(parent_desc_line
);
2040 g_string_free(ext_desc_lines
, true);
2044 static void vmdk_close(BlockDriverState
*bs
)
2046 BDRVVmdkState
*s
= bs
->opaque
;
2048 vmdk_free_extents(bs
);
2049 g_free(s
->create_type
);
2051 migrate_del_blocker(s
->migration_blocker
);
2052 error_free(s
->migration_blocker
);
2055 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
2057 BDRVVmdkState
*s
= bs
->opaque
;
2061 for (i
= 0; i
< s
->num_extents
; i
++) {
2062 err
= bdrv_co_flush(s
->extents
[i
].file
->bs
);
2070 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2075 BDRVVmdkState
*s
= bs
->opaque
;
2077 ret
= bdrv_get_allocated_file_size(bs
->file
->bs
);
2081 for (i
= 0; i
< s
->num_extents
; i
++) {
2082 if (s
->extents
[i
].file
== bs
->file
) {
2085 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
->bs
);
2094 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2097 BDRVVmdkState
*s
= bs
->opaque
;
2099 /* If has a flat extent and its underlying storage doesn't have zero init,
2101 for (i
= 0; i
< s
->num_extents
; i
++) {
2102 if (s
->extents
[i
].flat
) {
2103 if (!bdrv_has_zero_init(s
->extents
[i
].file
->bs
)) {
2111 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2113 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2115 *info
= (ImageInfo
){
2116 .filename
= g_strdup(extent
->file
->bs
->filename
),
2117 .format
= g_strdup(extent
->type
),
2118 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2119 .compressed
= extent
->compressed
,
2120 .has_compressed
= extent
->compressed
,
2121 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2122 .has_cluster_size
= !extent
->flat
,
2128 static int vmdk_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
2131 BDRVVmdkState
*s
= bs
->opaque
;
2132 VmdkExtent
*extent
= NULL
;
2133 int64_t sector_num
= 0;
2134 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2136 uint64_t cluster_offset
;
2143 if (sector_num
>= total_sectors
) {
2146 extent
= find_extent(s
, sector_num
, extent
);
2149 "ERROR: could not find extent for sector %" PRId64
"\n",
2153 ret
= get_cluster_offset(bs
, extent
, NULL
,
2154 sector_num
<< BDRV_SECTOR_BITS
,
2155 false, &cluster_offset
, 0, 0);
2156 if (ret
== VMDK_ERROR
) {
2158 "ERROR: could not get cluster_offset for sector %"
2159 PRId64
"\n", sector_num
);
2162 if (ret
== VMDK_OK
&&
2163 cluster_offset
>= bdrv_getlength(extent
->file
->bs
))
2166 "ERROR: cluster offset for sector %"
2167 PRId64
" points after EOF\n", sector_num
);
2170 sector_num
+= extent
->cluster_sectors
;
2173 result
->corruptions
++;
2177 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2180 BDRVVmdkState
*s
= bs
->opaque
;
2181 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2182 ImageInfoList
**next
;
2184 *spec_info
= (ImageInfoSpecific
){
2185 .type
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2187 .vmdk
= g_new0(ImageInfoSpecificVmdk
, 1),
2191 *spec_info
->u
.vmdk
= (ImageInfoSpecificVmdk
) {
2192 .create_type
= g_strdup(s
->create_type
),
2194 .parent_cid
= s
->parent_cid
,
2197 next
= &spec_info
->u
.vmdk
->extents
;
2198 for (i
= 0; i
< s
->num_extents
; i
++) {
2199 *next
= g_new0(ImageInfoList
, 1);
2200 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2201 (*next
)->next
= NULL
;
2202 next
= &(*next
)->next
;
2208 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
2210 return a
->flat
== b
->flat
&&
2211 a
->compressed
== b
->compressed
&&
2212 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
2215 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2218 BDRVVmdkState
*s
= bs
->opaque
;
2219 assert(s
->num_extents
);
2221 /* See if we have multiple extents but they have different cases */
2222 for (i
= 1; i
< s
->num_extents
; i
++) {
2223 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
2227 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2228 if (!s
->extents
[0].flat
) {
2229 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2234 static void vmdk_detach_aio_context(BlockDriverState
*bs
)
2236 BDRVVmdkState
*s
= bs
->opaque
;
2239 for (i
= 0; i
< s
->num_extents
; i
++) {
2240 bdrv_detach_aio_context(s
->extents
[i
].file
->bs
);
2244 static void vmdk_attach_aio_context(BlockDriverState
*bs
,
2245 AioContext
*new_context
)
2247 BDRVVmdkState
*s
= bs
->opaque
;
2250 for (i
= 0; i
< s
->num_extents
; i
++) {
2251 bdrv_attach_aio_context(s
->extents
[i
].file
->bs
, new_context
);
2255 static QemuOptsList vmdk_create_opts
= {
2256 .name
= "vmdk-create-opts",
2257 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2260 .name
= BLOCK_OPT_SIZE
,
2261 .type
= QEMU_OPT_SIZE
,
2262 .help
= "Virtual disk size"
2265 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2266 .type
= QEMU_OPT_STRING
,
2267 .help
= "Virtual adapter type, can be one of "
2268 "ide (default), lsilogic, buslogic or legacyESX"
2271 .name
= BLOCK_OPT_BACKING_FILE
,
2272 .type
= QEMU_OPT_STRING
,
2273 .help
= "File name of a base image"
2276 .name
= BLOCK_OPT_COMPAT6
,
2277 .type
= QEMU_OPT_BOOL
,
2278 .help
= "VMDK version 6 image",
2279 .def_value_str
= "off"
2282 .name
= BLOCK_OPT_SUBFMT
,
2283 .type
= QEMU_OPT_STRING
,
2285 "VMDK flat extent format, can be one of "
2286 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2289 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2290 .type
= QEMU_OPT_BOOL
,
2291 .help
= "Enable efficient zero writes "
2292 "using the zeroed-grain GTE feature"
2294 { /* end of list */ }
2298 static BlockDriver bdrv_vmdk
= {
2299 .format_name
= "vmdk",
2300 .instance_size
= sizeof(BDRVVmdkState
),
2301 .bdrv_probe
= vmdk_probe
,
2302 .bdrv_open
= vmdk_open
,
2303 .bdrv_check
= vmdk_check
,
2304 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2305 .bdrv_read
= vmdk_co_read
,
2306 .bdrv_write
= vmdk_co_write
,
2307 .bdrv_write_compressed
= vmdk_write_compressed
,
2308 .bdrv_co_write_zeroes
= vmdk_co_write_zeroes
,
2309 .bdrv_close
= vmdk_close
,
2310 .bdrv_create
= vmdk_create
,
2311 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2312 .bdrv_co_get_block_status
= vmdk_co_get_block_status
,
2313 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2314 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2315 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2316 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2317 .bdrv_get_info
= vmdk_get_info
,
2318 .bdrv_detach_aio_context
= vmdk_detach_aio_context
,
2319 .bdrv_attach_aio_context
= vmdk_attach_aio_context
,
2321 .supports_backing
= true,
2322 .create_opts
= &vmdk_create_opts
,
2325 static void bdrv_vmdk_init(void)
2327 bdrv_register(&bdrv_vmdk
);
2330 block_init(bdrv_vmdk_init
);