2 * Block driver for the VMDK format
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu/osdep.h"
27 #include "qapi/error.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qemu/error-report.h"
32 #include "qemu/module.h"
33 #include "qemu/option.h"
34 #include "qemu/bswap.h"
35 #include "migration/blocker.h"
36 #include "qemu/cutils.h"
39 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
40 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
41 #define VMDK4_COMPRESSION_DEFLATE 1
42 #define VMDK4_FLAG_NL_DETECT (1 << 0)
43 #define VMDK4_FLAG_RGD (1 << 1)
44 /* Zeroed-grain enable bit */
45 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
46 #define VMDK4_FLAG_COMPRESS (1 << 16)
47 #define VMDK4_FLAG_MARKER (1 << 17)
48 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
50 #define VMDK_EXTENT_MAX_SECTORS (1ULL << 32)
52 #define VMDK_GTE_ZEROED 0x1
54 /* VMDK internal error codes */
56 #define VMDK_ERROR (-1)
57 /* Cluster not allocated */
58 #define VMDK_UNALLOC (-2)
59 #define VMDK_ZEROED (-3)
61 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
66 uint32_t disk_sectors
;
68 uint32_t l1dir_offset
;
70 uint32_t file_sectors
;
73 uint32_t sectors_per_track
;
74 } QEMU_PACKED VMDK3Header
;
83 /* Number of GrainTableEntries per GrainTable */
84 uint32_t num_gtes_per_gt
;
87 uint64_t grain_offset
;
90 uint16_t compressAlgorithm
;
91 } QEMU_PACKED VMDK4Header
;
93 #define L2_CACHE_SIZE 16
95 typedef struct VmdkExtent
{
104 int64_t flat_start_offset
;
105 int64_t l1_table_offset
;
106 int64_t l1_backup_table_offset
;
108 uint32_t *l1_backup_table
;
109 unsigned int l1_size
;
110 uint32_t l1_entry_sectors
;
112 unsigned int l2_size
;
114 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
115 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
117 int64_t cluster_sectors
;
118 int64_t next_cluster_sector
;
122 typedef struct BDRVVmdkState
{
124 uint64_t desc_offset
;
130 /* Extent array with num_extents entries, ascend ordered by address */
132 Error
*migration_blocker
;
136 typedef struct VmdkMetaData
{
137 unsigned int l1_index
;
138 unsigned int l2_index
;
139 unsigned int l2_offset
;
141 uint32_t *l2_cache_entry
;
144 typedef struct VmdkGrainMarker
{
148 } QEMU_PACKED VmdkGrainMarker
;
151 MARKER_END_OF_STREAM
= 0,
152 MARKER_GRAIN_TABLE
= 1,
153 MARKER_GRAIN_DIRECTORY
= 2,
157 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
164 magic
= be32_to_cpu(*(uint32_t *)buf
);
165 if (magic
== VMDK3_MAGIC
||
166 magic
== VMDK4_MAGIC
) {
169 const char *p
= (const char *)buf
;
170 const char *end
= p
+ buf_size
;
173 /* skip comment line */
174 while (p
< end
&& *p
!= '\n') {
181 while (p
< end
&& *p
== ' ') {
184 /* skip '\r' if windows line endings used. */
185 if (p
< end
&& *p
== '\r') {
188 /* only accept blank lines before 'version=' line */
189 if (p
== end
|| *p
!= '\n') {
195 if (end
- p
>= strlen("version=X\n")) {
196 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
197 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
201 if (end
- p
>= strlen("version=X\r\n")) {
202 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
203 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
213 #define SECTOR_SIZE 512
214 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
215 #define BUF_SIZE 4096
216 #define HEADER_SIZE 512 /* first sector of 512 bytes */
218 static void vmdk_free_extents(BlockDriverState
*bs
)
221 BDRVVmdkState
*s
= bs
->opaque
;
224 for (i
= 0; i
< s
->num_extents
; i
++) {
228 g_free(e
->l1_backup_table
);
230 if (e
->file
!= bs
->file
) {
231 bdrv_unref_child(bs
, e
->file
);
237 static void vmdk_free_last_extent(BlockDriverState
*bs
)
239 BDRVVmdkState
*s
= bs
->opaque
;
241 if (s
->num_extents
== 0) {
245 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
248 /* Return -ve errno, or 0 on success and write CID into *pcid. */
249 static int vmdk_read_cid(BlockDriverState
*bs
, int parent
, uint32_t *pcid
)
253 const char *p_name
, *cid_str
;
255 BDRVVmdkState
*s
= bs
->opaque
;
258 desc
= g_malloc0(DESC_SIZE
);
259 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
265 cid_str
= "parentCID";
266 cid_str_size
= sizeof("parentCID");
269 cid_str_size
= sizeof("CID");
272 desc
[DESC_SIZE
- 1] = '\0';
273 p_name
= strstr(desc
, cid_str
);
274 if (p_name
== NULL
) {
278 p_name
+= cid_str_size
;
279 if (sscanf(p_name
, "%" SCNx32
, &cid
) != 1) {
291 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
293 char *desc
, *tmp_desc
;
294 char *p_name
, *tmp_str
;
295 BDRVVmdkState
*s
= bs
->opaque
;
298 desc
= g_malloc0(DESC_SIZE
);
299 tmp_desc
= g_malloc0(DESC_SIZE
);
300 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
305 desc
[DESC_SIZE
- 1] = '\0';
306 tmp_str
= strstr(desc
, "parentCID");
307 if (tmp_str
== NULL
) {
312 pstrcpy(tmp_desc
, DESC_SIZE
, tmp_str
);
313 p_name
= strstr(desc
, "CID");
314 if (p_name
!= NULL
) {
315 p_name
+= sizeof("CID");
316 snprintf(p_name
, DESC_SIZE
- (p_name
- desc
), "%" PRIx32
"\n", cid
);
317 pstrcat(desc
, DESC_SIZE
, tmp_desc
);
320 ret
= bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
328 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
330 BDRVVmdkState
*s
= bs
->opaque
;
333 if (!s
->cid_checked
&& bs
->backing
) {
334 BlockDriverState
*p_bs
= bs
->backing
->bs
;
336 if (strcmp(p_bs
->drv
->format_name
, "vmdk")) {
337 /* Backing file is not in vmdk format, so it does not have
338 * a CID, which makes the overlay's parent CID invalid */
342 if (vmdk_read_cid(p_bs
, 0, &cur_pcid
) != 0) {
343 /* read failure: report as not valid */
346 if (s
->parent_cid
!= cur_pcid
) {
351 s
->cid_checked
= true;
356 /* We have nothing to do for VMDK reopen, stubs just return success */
357 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
358 BlockReopenQueue
*queue
, Error
**errp
)
360 assert(state
!= NULL
);
361 assert(state
->bs
!= NULL
);
365 static int vmdk_parent_open(BlockDriverState
*bs
)
369 BDRVVmdkState
*s
= bs
->opaque
;
372 desc
= g_malloc0(DESC_SIZE
+ 1);
373 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
379 p_name
= strstr(desc
, "parentFileNameHint");
380 if (p_name
!= NULL
) {
383 p_name
+= sizeof("parentFileNameHint") + 1;
384 end_name
= strchr(p_name
, '\"');
385 if (end_name
== NULL
) {
389 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
394 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
402 /* Create and append extent to the extent array. Return the added VmdkExtent
403 * address. return NULL if allocation failed. */
404 static int vmdk_add_extent(BlockDriverState
*bs
,
405 BdrvChild
*file
, bool flat
, int64_t sectors
,
406 int64_t l1_offset
, int64_t l1_backup_offset
,
408 int l2_size
, uint64_t cluster_sectors
,
409 VmdkExtent
**new_extent
,
413 BDRVVmdkState
*s
= bs
->opaque
;
416 if (cluster_sectors
> 0x200000) {
417 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
418 error_setg(errp
, "Invalid granularity, image may be corrupt");
421 if (l1_size
> 512 * 1024 * 1024) {
422 /* Although with big capacity and small l1_entry_sectors, we can get a
423 * big l1_size, we don't want unbounded value to allocate the table.
424 * Limit it to 512M, which is 16PB for default cluster and L2 table
426 error_setg(errp
, "L1 size too big");
430 nb_sectors
= bdrv_nb_sectors(file
->bs
);
431 if (nb_sectors
< 0) {
435 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
436 extent
= &s
->extents
[s
->num_extents
];
439 memset(extent
, 0, sizeof(VmdkExtent
));
442 extent
->sectors
= sectors
;
443 extent
->l1_table_offset
= l1_offset
;
444 extent
->l1_backup_table_offset
= l1_backup_offset
;
445 extent
->l1_size
= l1_size
;
446 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
447 extent
->l2_size
= l2_size
;
448 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
449 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
451 if (s
->num_extents
> 1) {
452 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
454 extent
->end_sector
= extent
->sectors
;
456 bs
->total_sectors
= extent
->end_sector
;
458 *new_extent
= extent
;
463 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
470 /* read the L1 table */
471 l1_size
= extent
->l1_size
* sizeof(uint32_t);
472 extent
->l1_table
= g_try_malloc(l1_size
);
473 if (l1_size
&& extent
->l1_table
== NULL
) {
477 ret
= bdrv_pread(extent
->file
,
478 extent
->l1_table_offset
,
482 error_setg_errno(errp
, -ret
,
483 "Could not read l1 table from extent '%s'",
484 extent
->file
->bs
->filename
);
487 for (i
= 0; i
< extent
->l1_size
; i
++) {
488 le32_to_cpus(&extent
->l1_table
[i
]);
491 if (extent
->l1_backup_table_offset
) {
492 extent
->l1_backup_table
= g_try_malloc(l1_size
);
493 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
497 ret
= bdrv_pread(extent
->file
,
498 extent
->l1_backup_table_offset
,
499 extent
->l1_backup_table
,
502 error_setg_errno(errp
, -ret
,
503 "Could not read l1 backup table from extent '%s'",
504 extent
->file
->bs
->filename
);
507 for (i
= 0; i
< extent
->l1_size
; i
++) {
508 le32_to_cpus(&extent
->l1_backup_table
[i
]);
513 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
516 g_free(extent
->l1_backup_table
);
518 g_free(extent
->l1_table
);
522 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
524 int flags
, Error
**errp
)
531 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
533 error_setg_errno(errp
, -ret
,
534 "Could not read header from file '%s'",
538 ret
= vmdk_add_extent(bs
, file
, false,
539 le32_to_cpu(header
.disk_sectors
),
540 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
542 le32_to_cpu(header
.l1dir_size
),
544 le32_to_cpu(header
.granularity
),
550 ret
= vmdk_init_tables(bs
, extent
, errp
);
552 /* free extent allocated by vmdk_add_extent */
553 vmdk_free_last_extent(bs
);
558 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
559 QDict
*options
, Error
**errp
);
561 static char *vmdk_read_desc(BdrvChild
*file
, uint64_t desc_offset
, Error
**errp
)
567 size
= bdrv_getlength(file
->bs
);
569 error_setg_errno(errp
, -size
, "Could not access file");
574 /* Both descriptor file and sparse image must be much larger than 4
575 * bytes, also callers of vmdk_read_desc want to compare the first 4
576 * bytes with VMDK4_MAGIC, let's error out if less is read. */
577 error_setg(errp
, "File is too small, not a valid image");
581 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
582 buf
= g_malloc(size
+ 1);
584 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
586 error_setg_errno(errp
, -ret
, "Could not read from file");
595 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
597 int flags
, QDict
*options
, Error
**errp
)
601 uint32_t l1_size
, l1_entry_sectors
;
604 BDRVVmdkState
*s
= bs
->opaque
;
605 int64_t l1_backup_offset
= 0;
608 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
610 error_setg_errno(errp
, -ret
,
611 "Could not read header from file '%s'",
615 if (header
.capacity
== 0) {
616 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
618 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
622 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
628 if (!s
->create_type
) {
629 s
->create_type
= g_strdup("monolithicSparse");
632 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
634 * The footer takes precedence over the header, so read it in. The
635 * footer starts at offset -1024 from the end: One sector for the
636 * footer, and another one for the end-of-stream marker.
643 uint8_t pad
[512 - 16];
644 } QEMU_PACKED footer_marker
;
648 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
654 uint8_t pad
[512 - 16];
655 } QEMU_PACKED eos_marker
;
656 } QEMU_PACKED footer
;
658 ret
= bdrv_pread(file
,
659 bs
->file
->bs
->total_sectors
* 512 - 1536,
660 &footer
, sizeof(footer
));
662 error_setg_errno(errp
, -ret
, "Failed to read footer");
666 /* Some sanity checks for the footer */
667 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
668 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
669 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
670 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
671 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
672 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
674 error_setg(errp
, "Invalid footer");
678 header
= footer
.header
;
682 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
683 if (le32_to_cpu(header
.version
) > 3) {
684 error_setg(errp
, "Unsupported VMDK version %" PRIu32
,
685 le32_to_cpu(header
.version
));
687 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
) &&
689 /* VMware KB 2064959 explains that version 3 added support for
690 * persistent changed block tracking (CBT), and backup software can
691 * read it as version=1 if it doesn't care about the changed area
692 * information. So we are safe to enable read only. */
693 error_setg(errp
, "VMDK version 3 must be read only");
697 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
698 error_setg(errp
, "L2 table size too big");
702 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
703 * le64_to_cpu(header
.granularity
);
704 if (l1_entry_sectors
== 0) {
705 error_setg(errp
, "L1 entry size is invalid");
708 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
710 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
711 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
713 if (bdrv_nb_sectors(file
->bs
) < le64_to_cpu(header
.grain_offset
)) {
714 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
715 (int64_t)(le64_to_cpu(header
.grain_offset
)
716 * BDRV_SECTOR_SIZE
));
720 ret
= vmdk_add_extent(bs
, file
, false,
721 le64_to_cpu(header
.capacity
),
722 le64_to_cpu(header
.gd_offset
) << 9,
725 le32_to_cpu(header
.num_gtes_per_gt
),
726 le64_to_cpu(header
.granularity
),
733 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
734 if (extent
->compressed
) {
735 g_free(s
->create_type
);
736 s
->create_type
= g_strdup("streamOptimized");
738 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
739 extent
->version
= le32_to_cpu(header
.version
);
740 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
741 ret
= vmdk_init_tables(bs
, extent
, errp
);
743 /* free extent allocated by vmdk_add_extent */
744 vmdk_free_last_extent(bs
);
749 /* find an option value out of descriptor file */
750 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
751 char *buf
, int buf_size
)
753 char *opt_pos
, *opt_end
;
754 const char *end
= desc
+ strlen(desc
);
756 opt_pos
= strstr(desc
, opt_name
);
760 /* Skip "=\"" following opt_name */
761 opt_pos
+= strlen(opt_name
) + 2;
762 if (opt_pos
>= end
) {
766 while (opt_end
< end
&& *opt_end
!= '"') {
769 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
772 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
776 /* Open an extent file and append to bs array */
777 static int vmdk_open_sparse(BlockDriverState
*bs
, BdrvChild
*file
, int flags
,
778 char *buf
, QDict
*options
, Error
**errp
)
782 magic
= ldl_be_p(buf
);
785 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
788 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
791 error_setg(errp
, "Image not in VMDK format");
797 static const char *next_line(const char *s
)
808 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
809 const char *desc_file_path
, QDict
*options
,
821 BdrvChild
*extent_file
;
822 BDRVVmdkState
*s
= bs
->opaque
;
824 char extent_opt_prefix
[32];
825 Error
*local_err
= NULL
;
827 for (p
= desc
; *p
; p
= next_line(p
)) {
828 /* parse extent line in one of below formats:
830 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
831 * RW [size in sectors] SPARSE "file-name.vmdk"
832 * RW [size in sectors] VMFS "file-name.vmdk"
833 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
836 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
837 access
, §ors
, type
, fname
, &flat_offset
);
838 if (matches
< 4 || strcmp(access
, "RW")) {
840 } else if (!strcmp(type
, "FLAT")) {
841 if (matches
!= 5 || flat_offset
< 0) {
844 } else if (!strcmp(type
, "VMFS")) {
850 } else if (matches
!= 4) {
855 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
856 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
857 (strcmp(access
, "RW"))) {
861 if (!path_is_absolute(fname
) && !path_has_protocol(fname
) &&
864 error_setg(errp
, "Cannot use relative extent paths with VMDK "
865 "descriptor file '%s'", bs
->file
->bs
->filename
);
869 extent_path
= g_malloc0(PATH_MAX
);
870 path_combine(extent_path
, PATH_MAX
, desc_file_path
, fname
);
872 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
875 extent_file
= bdrv_open_child(extent_path
, options
, extent_opt_prefix
,
876 bs
, &child_file
, false, &local_err
);
879 error_propagate(errp
, local_err
);
883 /* save to extents array */
884 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
887 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
888 0, 0, 0, 0, 0, &extent
, errp
);
890 bdrv_unref_child(bs
, extent_file
);
893 extent
->flat_start_offset
= flat_offset
<< 9;
894 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
895 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
896 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
900 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
905 bdrv_unref_child(bs
, extent_file
);
908 extent
= &s
->extents
[s
->num_extents
- 1];
910 error_setg(errp
, "Unsupported extent type '%s'", type
);
911 bdrv_unref_child(bs
, extent_file
);
914 extent
->type
= g_strdup(type
);
921 if (np
[-1] == '\n') {
924 error_setg(errp
, "Invalid extent line: %.*s", (int)(np
- p
), p
);
928 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
929 QDict
*options
, Error
**errp
)
933 BDRVVmdkState
*s
= bs
->opaque
;
935 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
936 error_setg(errp
, "invalid VMDK image descriptor");
940 if (strcmp(ct
, "monolithicFlat") &&
941 strcmp(ct
, "vmfs") &&
942 strcmp(ct
, "vmfsSparse") &&
943 strcmp(ct
, "twoGbMaxExtentSparse") &&
944 strcmp(ct
, "twoGbMaxExtentFlat")) {
945 error_setg(errp
, "Unsupported image type '%s'", ct
);
949 s
->create_type
= g_strdup(ct
);
951 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->bs
->exact_filename
, options
,
957 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
962 BDRVVmdkState
*s
= bs
->opaque
;
964 Error
*local_err
= NULL
;
966 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
972 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
977 magic
= ldl_be_p(buf
);
981 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
,
983 s
->desc_offset
= 0x200;
986 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
993 /* try to open parent images, if exist */
994 ret
= vmdk_parent_open(bs
);
998 ret
= vmdk_read_cid(bs
, 0, &s
->cid
);
1002 ret
= vmdk_read_cid(bs
, 1, &s
->parent_cid
);
1006 qemu_co_mutex_init(&s
->lock
);
1008 /* Disable migration when VMDK images are used */
1009 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
1010 "does not support live migration",
1011 bdrv_get_device_or_node_name(bs
));
1012 ret
= migrate_add_blocker(s
->migration_blocker
, &local_err
);
1014 error_propagate(errp
, local_err
);
1015 error_free(s
->migration_blocker
);
1024 g_free(s
->create_type
);
1025 s
->create_type
= NULL
;
1026 vmdk_free_extents(bs
);
1031 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1033 BDRVVmdkState
*s
= bs
->opaque
;
1036 for (i
= 0; i
< s
->num_extents
; i
++) {
1037 if (!s
->extents
[i
].flat
) {
1038 bs
->bl
.pwrite_zeroes_alignment
=
1039 MAX(bs
->bl
.pwrite_zeroes_alignment
,
1040 s
->extents
[i
].cluster_sectors
<< BDRV_SECTOR_BITS
);
1048 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1049 * to the cluster at @cluster_sector_num.
1051 * If @skip_start_sector < @skip_end_sector, the relative range
1052 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1053 * it for call to write user data in the request.
1055 static int get_whole_cluster(BlockDriverState
*bs
,
1057 uint64_t cluster_offset
,
1059 uint64_t skip_start_bytes
,
1060 uint64_t skip_end_bytes
)
1063 int64_t cluster_bytes
;
1064 uint8_t *whole_grain
;
1066 /* For COW, align request sector_num to cluster start */
1067 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1068 offset
= QEMU_ALIGN_DOWN(offset
, cluster_bytes
);
1069 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1072 memset(whole_grain
, 0, skip_start_bytes
);
1073 memset(whole_grain
+ skip_end_bytes
, 0, cluster_bytes
- skip_end_bytes
);
1076 assert(skip_end_bytes
<= cluster_bytes
);
1077 /* we will be here if it's first write on non-exist grain(cluster).
1078 * try to read from parent image, if exist */
1079 if (bs
->backing
&& !vmdk_is_cid_valid(bs
)) {
1084 /* Read backing data before skip range */
1085 if (skip_start_bytes
> 0) {
1087 /* qcow2 emits this on bs->file instead of bs->backing */
1088 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1089 ret
= bdrv_pread(bs
->backing
, offset
, whole_grain
,
1096 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1097 ret
= bdrv_pwrite(extent
->file
, cluster_offset
, whole_grain
,
1104 /* Read backing data after skip range */
1105 if (skip_end_bytes
< cluster_bytes
) {
1107 /* qcow2 emits this on bs->file instead of bs->backing */
1108 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1109 ret
= bdrv_pread(bs
->backing
, offset
+ skip_end_bytes
,
1110 whole_grain
+ skip_end_bytes
,
1111 cluster_bytes
- skip_end_bytes
);
1117 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1118 ret
= bdrv_pwrite(extent
->file
, cluster_offset
+ skip_end_bytes
,
1119 whole_grain
+ skip_end_bytes
,
1120 cluster_bytes
- skip_end_bytes
);
1129 qemu_vfree(whole_grain
);
1133 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1136 offset
= cpu_to_le32(offset
);
1137 /* update L2 table */
1138 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_UPDATE
);
1139 if (bdrv_pwrite_sync(extent
->file
,
1140 ((int64_t)m_data
->l2_offset
* 512)
1141 + (m_data
->l2_index
* sizeof(offset
)),
1142 &offset
, sizeof(offset
)) < 0) {
1145 /* update backup L2 table */
1146 if (extent
->l1_backup_table_offset
!= 0) {
1147 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1148 if (bdrv_pwrite_sync(extent
->file
,
1149 ((int64_t)m_data
->l2_offset
* 512)
1150 + (m_data
->l2_index
* sizeof(offset
)),
1151 &offset
, sizeof(offset
)) < 0) {
1155 if (m_data
->l2_cache_entry
) {
1156 *m_data
->l2_cache_entry
= offset
;
1163 * get_cluster_offset
1165 * Look up cluster offset in extent file by sector number, and store in
1168 * For flat extents, the start offset as parsed from the description file is
1171 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1172 * offset for a new cluster and update L2 cache. If there is a backing file,
1173 * COW is done before returning; otherwise, zeroes are written to the allocated
1174 * cluster. Both COW and zero writing skips the sector range
1175 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1176 * has new data to write there.
1178 * Returns: VMDK_OK if cluster exists and mapped in the image.
1179 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1180 * VMDK_ERROR if failed.
1182 static int get_cluster_offset(BlockDriverState
*bs
,
1184 VmdkMetaData
*m_data
,
1187 uint64_t *cluster_offset
,
1188 uint64_t skip_start_bytes
,
1189 uint64_t skip_end_bytes
)
1191 unsigned int l1_index
, l2_offset
, l2_index
;
1192 int min_index
, i
, j
;
1193 uint32_t min_count
, *l2_table
;
1194 bool zeroed
= false;
1196 int64_t cluster_sector
;
1202 *cluster_offset
= extent
->flat_start_offset
;
1206 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1207 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1208 if (l1_index
>= extent
->l1_size
) {
1211 l2_offset
= extent
->l1_table
[l1_index
];
1213 return VMDK_UNALLOC
;
1215 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1216 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1217 /* increment the hit count */
1218 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1219 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1220 extent
->l2_cache_counts
[j
] >>= 1;
1223 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1227 /* not found: load a new entry in the least used one */
1229 min_count
= 0xffffffff;
1230 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1231 if (extent
->l2_cache_counts
[i
] < min_count
) {
1232 min_count
= extent
->l2_cache_counts
[i
];
1236 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1237 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_LOAD
);
1238 if (bdrv_pread(extent
->file
,
1239 (int64_t)l2_offset
* 512,
1241 extent
->l2_size
* sizeof(uint32_t)
1242 ) != extent
->l2_size
* sizeof(uint32_t)) {
1246 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1247 extent
->l2_cache_counts
[min_index
] = 1;
1249 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1250 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1252 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1256 if (!cluster_sector
|| zeroed
) {
1258 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1261 if (extent
->next_cluster_sector
>= VMDK_EXTENT_MAX_SECTORS
) {
1265 cluster_sector
= extent
->next_cluster_sector
;
1266 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1268 /* First of all we write grain itself, to avoid race condition
1269 * that may to corrupt the image.
1270 * This problem may occur because of insufficient space on host disk
1271 * or inappropriate VM shutdown.
1273 ret
= get_whole_cluster(bs
, extent
, cluster_sector
* BDRV_SECTOR_SIZE
,
1274 offset
, skip_start_bytes
, skip_end_bytes
);
1280 m_data
->l1_index
= l1_index
;
1281 m_data
->l2_index
= l2_index
;
1282 m_data
->l2_offset
= l2_offset
;
1283 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1286 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1290 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1291 int64_t sector_num
, VmdkExtent
*start_hint
)
1293 VmdkExtent
*extent
= start_hint
;
1296 extent
= &s
->extents
[0];
1298 while (extent
< &s
->extents
[s
->num_extents
]) {
1299 if (sector_num
< extent
->end_sector
) {
1307 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent
*extent
,
1310 uint64_t extent_begin_offset
, extent_relative_offset
;
1311 uint64_t cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
1313 extent_begin_offset
=
1314 (extent
->end_sector
- extent
->sectors
) * BDRV_SECTOR_SIZE
;
1315 extent_relative_offset
= offset
- extent_begin_offset
;
1316 return extent_relative_offset
% cluster_size
;
1319 static int coroutine_fn
vmdk_co_block_status(BlockDriverState
*bs
,
1321 int64_t offset
, int64_t bytes
,
1322 int64_t *pnum
, int64_t *map
,
1323 BlockDriverState
**file
)
1325 BDRVVmdkState
*s
= bs
->opaque
;
1326 int64_t index_in_cluster
, n
, ret
;
1327 uint64_t cluster_offset
;
1330 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, NULL
);
1334 qemu_co_mutex_lock(&s
->lock
);
1335 ret
= get_cluster_offset(bs
, extent
, NULL
, offset
, false, &cluster_offset
,
1337 qemu_co_mutex_unlock(&s
->lock
);
1339 index_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1348 ret
= BDRV_BLOCK_ZERO
;
1351 ret
= BDRV_BLOCK_DATA
;
1352 if (!extent
->compressed
) {
1353 ret
|= BDRV_BLOCK_OFFSET_VALID
;
1354 *map
= cluster_offset
+ index_in_cluster
;
1356 *file
= extent
->file
->bs
;
1360 n
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
- index_in_cluster
;
1361 *pnum
= MIN(n
, bytes
);
1365 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1366 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1367 uint64_t qiov_offset
, uint64_t n_bytes
,
1371 VmdkGrainMarker
*data
= NULL
;
1373 QEMUIOVector local_qiov
;
1375 int64_t write_offset
;
1376 int64_t write_end_sector
;
1378 if (extent
->compressed
) {
1379 void *compressed_data
;
1381 if (!extent
->has_marker
) {
1385 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1386 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1388 compressed_data
= g_malloc(n_bytes
);
1389 qemu_iovec_to_buf(qiov
, qiov_offset
, compressed_data
, n_bytes
);
1390 ret
= compress(data
->data
, &buf_len
, compressed_data
, n_bytes
);
1391 g_free(compressed_data
);
1393 if (ret
!= Z_OK
|| buf_len
== 0) {
1398 data
->lba
= cpu_to_le64(offset
>> BDRV_SECTOR_BITS
);
1399 data
->size
= cpu_to_le32(buf_len
);
1401 n_bytes
= buf_len
+ sizeof(VmdkGrainMarker
);
1402 iov
= (struct iovec
) {
1406 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1408 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_COMPRESSED
);
1410 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1411 qemu_iovec_concat(&local_qiov
, qiov
, qiov_offset
, n_bytes
);
1413 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_AIO
);
1416 write_offset
= cluster_offset
+ offset_in_cluster
;
1417 ret
= bdrv_co_pwritev(extent
->file
, write_offset
, n_bytes
,
1420 write_end_sector
= DIV_ROUND_UP(write_offset
+ n_bytes
, BDRV_SECTOR_SIZE
);
1422 if (extent
->compressed
) {
1423 extent
->next_cluster_sector
= write_end_sector
;
1425 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1435 if (!extent
->compressed
) {
1436 qemu_iovec_destroy(&local_qiov
);
1441 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1442 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1446 int cluster_bytes
, buf_bytes
;
1447 uint8_t *cluster_buf
, *compressed_data
;
1448 uint8_t *uncomp_buf
;
1450 VmdkGrainMarker
*marker
;
1454 if (!extent
->compressed
) {
1455 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_AIO
);
1456 ret
= bdrv_co_preadv(extent
->file
,
1457 cluster_offset
+ offset_in_cluster
, bytes
,
1464 cluster_bytes
= extent
->cluster_sectors
* 512;
1465 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1466 buf_bytes
= cluster_bytes
* 2;
1467 cluster_buf
= g_malloc(buf_bytes
);
1468 uncomp_buf
= g_malloc(cluster_bytes
);
1469 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_COMPRESSED
);
1470 ret
= bdrv_pread(extent
->file
,
1472 cluster_buf
, buf_bytes
);
1476 compressed_data
= cluster_buf
;
1477 buf_len
= cluster_bytes
;
1478 data_len
= cluster_bytes
;
1479 if (extent
->has_marker
) {
1480 marker
= (VmdkGrainMarker
*)cluster_buf
;
1481 compressed_data
= marker
->data
;
1482 data_len
= le32_to_cpu(marker
->size
);
1484 if (!data_len
|| data_len
> buf_bytes
) {
1488 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1494 if (offset_in_cluster
< 0 ||
1495 offset_in_cluster
+ bytes
> buf_len
) {
1499 qemu_iovec_from_buf(qiov
, 0, uncomp_buf
+ offset_in_cluster
, bytes
);
1504 g_free(cluster_buf
);
1508 static int coroutine_fn
1509 vmdk_co_preadv(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1510 QEMUIOVector
*qiov
, int flags
)
1512 BDRVVmdkState
*s
= bs
->opaque
;
1514 uint64_t n_bytes
, offset_in_cluster
;
1515 VmdkExtent
*extent
= NULL
;
1516 QEMUIOVector local_qiov
;
1517 uint64_t cluster_offset
;
1518 uint64_t bytes_done
= 0;
1520 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1521 qemu_co_mutex_lock(&s
->lock
);
1524 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
1529 ret
= get_cluster_offset(bs
, extent
, NULL
,
1530 offset
, false, &cluster_offset
, 0, 0);
1531 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1533 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
1534 - offset_in_cluster
);
1536 if (ret
!= VMDK_OK
) {
1537 /* if not allocated, try to read from parent image, if exist */
1538 if (bs
->backing
&& ret
!= VMDK_ZEROED
) {
1539 if (!vmdk_is_cid_valid(bs
)) {
1544 qemu_iovec_reset(&local_qiov
);
1545 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1547 /* qcow2 emits this on bs->file instead of bs->backing */
1548 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1549 ret
= bdrv_co_preadv(bs
->backing
, offset
, n_bytes
,
1555 qemu_iovec_memset(qiov
, bytes_done
, 0, n_bytes
);
1558 qemu_iovec_reset(&local_qiov
);
1559 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1561 ret
= vmdk_read_extent(extent
, cluster_offset
, offset_in_cluster
,
1562 &local_qiov
, n_bytes
);
1569 bytes_done
+= n_bytes
;
1574 qemu_co_mutex_unlock(&s
->lock
);
1575 qemu_iovec_destroy(&local_qiov
);
1582 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1583 * if possible, otherwise return -ENOTSUP.
1584 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1585 * with each cluster. By dry run we can find if the zero write
1586 * is possible without modifying image data.
1588 * Returns: error code with 0 for success.
1590 static int vmdk_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1591 uint64_t bytes
, QEMUIOVector
*qiov
,
1592 bool zeroed
, bool zero_dry_run
)
1594 BDRVVmdkState
*s
= bs
->opaque
;
1595 VmdkExtent
*extent
= NULL
;
1597 int64_t offset_in_cluster
, n_bytes
;
1598 uint64_t cluster_offset
;
1599 uint64_t bytes_done
= 0;
1600 VmdkMetaData m_data
;
1602 if (DIV_ROUND_UP(offset
, BDRV_SECTOR_SIZE
) > bs
->total_sectors
) {
1603 error_report("Wrong offset: offset=0x%" PRIx64
1604 " total_sectors=0x%" PRIx64
,
1605 offset
, bs
->total_sectors
);
1610 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
1614 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1615 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
1616 - offset_in_cluster
);
1618 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
1619 !(extent
->compressed
|| zeroed
),
1620 &cluster_offset
, offset_in_cluster
,
1621 offset_in_cluster
+ n_bytes
);
1622 if (extent
->compressed
) {
1623 if (ret
== VMDK_OK
) {
1624 /* Refuse write to allocated cluster for streamOptimized */
1625 error_report("Could not write to allocated cluster"
1626 " for streamOptimized");
1630 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
1631 true, &cluster_offset
, 0, 0);
1634 if (ret
== VMDK_ERROR
) {
1638 /* Do zeroed write, buf is ignored */
1639 if (extent
->has_zero_grain
&&
1640 offset_in_cluster
== 0 &&
1641 n_bytes
>= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
) {
1642 n_bytes
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
1643 if (!zero_dry_run
) {
1644 /* update L2 tables */
1645 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1654 ret
= vmdk_write_extent(extent
, cluster_offset
, offset_in_cluster
,
1655 qiov
, bytes_done
, n_bytes
, offset
);
1660 /* update L2 tables */
1661 if (vmdk_L2update(extent
, &m_data
,
1662 cluster_offset
>> BDRV_SECTOR_BITS
)
1670 bytes_done
+= n_bytes
;
1672 /* update CID on the first write every time the virtual disk is
1674 if (!s
->cid_updated
) {
1675 ret
= vmdk_write_cid(bs
, g_random_int());
1679 s
->cid_updated
= true;
1685 static int coroutine_fn
1686 vmdk_co_pwritev(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1687 QEMUIOVector
*qiov
, int flags
)
1690 BDRVVmdkState
*s
= bs
->opaque
;
1691 qemu_co_mutex_lock(&s
->lock
);
1692 ret
= vmdk_pwritev(bs
, offset
, bytes
, qiov
, false, false);
1693 qemu_co_mutex_unlock(&s
->lock
);
1697 static int coroutine_fn
1698 vmdk_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
1699 uint64_t bytes
, QEMUIOVector
*qiov
)
1701 return vmdk_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
1704 static int coroutine_fn
vmdk_co_pwrite_zeroes(BlockDriverState
*bs
,
1707 BdrvRequestFlags flags
)
1710 BDRVVmdkState
*s
= bs
->opaque
;
1712 qemu_co_mutex_lock(&s
->lock
);
1713 /* write zeroes could fail if sectors not aligned to cluster, test it with
1714 * dry_run == true before really updating image */
1715 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, true);
1717 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, false);
1719 qemu_co_mutex_unlock(&s
->lock
);
1723 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1724 bool flat
, bool compress
, bool zeroed_grain
,
1725 QemuOpts
*opts
, Error
**errp
)
1728 BlockBackend
*blk
= NULL
;
1730 Error
*local_err
= NULL
;
1731 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1732 uint32_t *gd_buf
= NULL
;
1735 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1737 error_propagate(errp
, local_err
);
1741 blk
= blk_new_open(filename
, NULL
, NULL
,
1742 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
1745 error_propagate(errp
, local_err
);
1750 blk_set_allow_write_beyond_eof(blk
, true);
1753 ret
= blk_truncate(blk
, filesize
, PREALLOC_MODE_OFF
, errp
);
1756 magic
= cpu_to_be32(VMDK4_MAGIC
);
1757 memset(&header
, 0, sizeof(header
));
1760 } else if (zeroed_grain
) {
1765 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1766 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1767 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1768 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1769 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1770 header
.granularity
= 128;
1771 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1773 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1774 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1776 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1777 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1779 header
.desc_offset
= 1;
1780 header
.desc_size
= 20;
1781 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1782 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1783 header
.grain_offset
=
1784 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1785 header
.granularity
);
1786 /* swap endianness for all header fields */
1787 header
.version
= cpu_to_le32(header
.version
);
1788 header
.flags
= cpu_to_le32(header
.flags
);
1789 header
.capacity
= cpu_to_le64(header
.capacity
);
1790 header
.granularity
= cpu_to_le64(header
.granularity
);
1791 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1792 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1793 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1794 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1795 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1796 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1797 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1799 header
.check_bytes
[0] = 0xa;
1800 header
.check_bytes
[1] = 0x20;
1801 header
.check_bytes
[2] = 0xd;
1802 header
.check_bytes
[3] = 0xa;
1804 /* write all the data */
1805 ret
= blk_pwrite(blk
, 0, &magic
, sizeof(magic
), 0);
1807 error_setg(errp
, QERR_IO_ERROR
);
1810 ret
= blk_pwrite(blk
, sizeof(magic
), &header
, sizeof(header
), 0);
1812 error_setg(errp
, QERR_IO_ERROR
);
1816 ret
= blk_truncate(blk
, le64_to_cpu(header
.grain_offset
) << 9,
1817 PREALLOC_MODE_OFF
, errp
);
1822 /* write grain directory */
1823 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1824 gd_buf
= g_malloc0(gd_buf_size
);
1825 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1826 i
< gt_count
; i
++, tmp
+= gt_size
) {
1827 gd_buf
[i
] = cpu_to_le32(tmp
);
1829 ret
= blk_pwrite(blk
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1830 gd_buf
, gd_buf_size
, 0);
1832 error_setg(errp
, QERR_IO_ERROR
);
1836 /* write backup grain directory */
1837 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1838 i
< gt_count
; i
++, tmp
+= gt_size
) {
1839 gd_buf
[i
] = cpu_to_le32(tmp
);
1841 ret
= blk_pwrite(blk
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1842 gd_buf
, gd_buf_size
, 0);
1844 error_setg(errp
, QERR_IO_ERROR
);
1857 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1858 char *postfix
, size_t buf_len
, Error
**errp
)
1862 if (filename
== NULL
|| !strlen(filename
)) {
1863 error_setg(errp
, "No filename provided");
1866 p
= strrchr(filename
, '/');
1868 p
= strrchr(filename
, '\\');
1871 p
= strrchr(filename
, ':');
1875 if (p
- filename
>= buf_len
) {
1878 pstrcpy(path
, p
- filename
+ 1, filename
);
1883 q
= strrchr(p
, '.');
1885 pstrcpy(prefix
, buf_len
, p
);
1888 if (q
- p
>= buf_len
) {
1891 pstrcpy(prefix
, q
- p
+ 1, p
);
1892 pstrcpy(postfix
, buf_len
, q
);
1897 static int coroutine_fn
vmdk_co_create_opts(const char *filename
, QemuOpts
*opts
,
1901 BlockBackend
*new_blk
= NULL
;
1902 Error
*local_err
= NULL
;
1904 int64_t total_size
= 0, filesize
;
1905 char *adapter_type
= NULL
;
1906 char *backing_file
= NULL
;
1907 char *hw_version
= NULL
;
1910 bool flat
, split
, compress
;
1911 GString
*ext_desc_lines
;
1912 char *path
= g_malloc0(PATH_MAX
);
1913 char *prefix
= g_malloc0(PATH_MAX
);
1914 char *postfix
= g_malloc0(PATH_MAX
);
1915 char *desc_line
= g_malloc0(BUF_SIZE
);
1916 char *ext_filename
= g_malloc0(PATH_MAX
);
1917 char *desc_filename
= g_malloc0(PATH_MAX
);
1918 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1919 const char *desc_extent_line
;
1920 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
1921 uint32_t parent_cid
= 0xffffffff;
1922 uint32_t number_heads
= 16;
1923 bool zeroed_grain
= false;
1924 uint32_t desc_offset
= 0, desc_len
;
1925 const char desc_template
[] =
1926 "# Disk DescriptorFile\n"
1929 "parentCID=%" PRIx32
"\n"
1930 "createType=\"%s\"\n"
1933 "# Extent description\n"
1936 "# The Disk Data Base\n"
1939 "ddb.virtualHWVersion = \"%s\"\n"
1940 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1941 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1942 "ddb.geometry.sectors = \"63\"\n"
1943 "ddb.adapterType = \"%s\"\n";
1945 ext_desc_lines
= g_string_new(NULL
);
1947 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1951 /* Read out options */
1952 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1954 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1955 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1956 hw_version
= qemu_opt_get_del(opts
, BLOCK_OPT_HWVERSION
);
1957 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1958 if (strcmp(hw_version
, "undefined")) {
1960 "compat6 cannot be enabled with hwversion set");
1965 hw_version
= g_strdup("6");
1967 if (strcmp(hw_version
, "undefined") == 0) {
1969 hw_version
= g_strdup("4");
1971 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1972 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1973 zeroed_grain
= true;
1976 if (!adapter_type
) {
1977 adapter_type
= g_strdup("ide");
1978 } else if (strcmp(adapter_type
, "ide") &&
1979 strcmp(adapter_type
, "buslogic") &&
1980 strcmp(adapter_type
, "lsilogic") &&
1981 strcmp(adapter_type
, "legacyESX")) {
1982 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1986 if (strcmp(adapter_type
, "ide") != 0) {
1987 /* that's the number of heads with which vmware operates when
1988 creating, exporting, etc. vmdk files with a non-ide adapter type */
1992 /* Default format to monolithicSparse */
1993 fmt
= g_strdup("monolithicSparse");
1994 } else if (strcmp(fmt
, "monolithicFlat") &&
1995 strcmp(fmt
, "monolithicSparse") &&
1996 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1997 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1998 strcmp(fmt
, "streamOptimized")) {
1999 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
2003 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
2004 strcmp(fmt
, "twoGbMaxExtentSparse"));
2005 flat
= !(strcmp(fmt
, "monolithicFlat") &&
2006 strcmp(fmt
, "twoGbMaxExtentFlat"));
2007 compress
= !strcmp(fmt
, "streamOptimized");
2009 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
2011 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
2013 if (flat
&& backing_file
) {
2014 error_setg(errp
, "Flat image can't have backing file");
2018 if (flat
&& zeroed_grain
) {
2019 error_setg(errp
, "Flat image can't enable zeroed grain");
2025 char *full_backing
= g_new0(char, PATH_MAX
);
2026 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
2027 full_backing
, PATH_MAX
,
2030 g_free(full_backing
);
2031 error_propagate(errp
, local_err
);
2036 blk
= blk_new_open(full_backing
, NULL
, NULL
,
2037 BDRV_O_NO_BACKING
, errp
);
2038 g_free(full_backing
);
2043 if (strcmp(blk_bs(blk
)->drv
->format_name
, "vmdk")) {
2048 ret
= vmdk_read_cid(blk_bs(blk
), 0, &parent_cid
);
2053 snprintf(parent_desc_line
, BUF_SIZE
,
2054 "parentFileNameHint=\"%s\"", backing_file
);
2057 /* Create extents */
2058 filesize
= total_size
;
2059 while (filesize
> 0) {
2060 int64_t size
= filesize
;
2062 if (split
&& size
> split_size
) {
2066 snprintf(desc_filename
, PATH_MAX
, "%s-%c%03d%s",
2067 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
2069 snprintf(desc_filename
, PATH_MAX
, "%s-flat%s", prefix
, postfix
);
2071 snprintf(desc_filename
, PATH_MAX
, "%s%s", prefix
, postfix
);
2073 snprintf(ext_filename
, PATH_MAX
, "%s%s", path
, desc_filename
);
2075 if (vmdk_create_extent(ext_filename
, size
,
2076 flat
, compress
, zeroed_grain
, opts
, errp
)) {
2082 /* Format description line */
2083 snprintf(desc_line
, BUF_SIZE
,
2084 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
2085 g_string_append(ext_desc_lines
, desc_line
);
2087 /* generate descriptor file */
2088 desc
= g_strdup_printf(desc_template
,
2093 ext_desc_lines
->str
,
2096 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
2099 desc_len
= strlen(desc
);
2100 /* the descriptor offset = 0x200 */
2101 if (!split
&& !flat
) {
2102 desc_offset
= 0x200;
2104 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2106 error_propagate(errp
, local_err
);
2111 new_blk
= blk_new_open(filename
, NULL
, NULL
,
2112 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2114 if (new_blk
== NULL
) {
2115 error_propagate(errp
, local_err
);
2120 blk_set_allow_write_beyond_eof(new_blk
, true);
2122 ret
= blk_pwrite(new_blk
, desc_offset
, desc
, desc_len
, 0);
2124 error_setg_errno(errp
, -ret
, "Could not write description");
2127 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2128 * for description file */
2129 if (desc_offset
== 0) {
2130 ret
= blk_truncate(new_blk
, desc_len
, PREALLOC_MODE_OFF
, errp
);
2136 g_free(adapter_type
);
2137 g_free(backing_file
);
2145 g_free(ext_filename
);
2146 g_free(desc_filename
);
2147 g_free(parent_desc_line
);
2148 g_string_free(ext_desc_lines
, true);
2152 static void vmdk_close(BlockDriverState
*bs
)
2154 BDRVVmdkState
*s
= bs
->opaque
;
2156 vmdk_free_extents(bs
);
2157 g_free(s
->create_type
);
2159 migrate_del_blocker(s
->migration_blocker
);
2160 error_free(s
->migration_blocker
);
2163 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
2165 BDRVVmdkState
*s
= bs
->opaque
;
2169 for (i
= 0; i
< s
->num_extents
; i
++) {
2170 err
= bdrv_co_flush(s
->extents
[i
].file
->bs
);
2178 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2183 BDRVVmdkState
*s
= bs
->opaque
;
2185 ret
= bdrv_get_allocated_file_size(bs
->file
->bs
);
2189 for (i
= 0; i
< s
->num_extents
; i
++) {
2190 if (s
->extents
[i
].file
== bs
->file
) {
2193 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
->bs
);
2202 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2205 BDRVVmdkState
*s
= bs
->opaque
;
2207 /* If has a flat extent and its underlying storage doesn't have zero init,
2209 for (i
= 0; i
< s
->num_extents
; i
++) {
2210 if (s
->extents
[i
].flat
) {
2211 if (!bdrv_has_zero_init(s
->extents
[i
].file
->bs
)) {
2219 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2221 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2223 *info
= (ImageInfo
){
2224 .filename
= g_strdup(extent
->file
->bs
->filename
),
2225 .format
= g_strdup(extent
->type
),
2226 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2227 .compressed
= extent
->compressed
,
2228 .has_compressed
= extent
->compressed
,
2229 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2230 .has_cluster_size
= !extent
->flat
,
2236 static int coroutine_fn
vmdk_co_check(BlockDriverState
*bs
,
2237 BdrvCheckResult
*result
,
2240 BDRVVmdkState
*s
= bs
->opaque
;
2241 VmdkExtent
*extent
= NULL
;
2242 int64_t sector_num
= 0;
2243 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2245 uint64_t cluster_offset
;
2252 if (sector_num
>= total_sectors
) {
2255 extent
= find_extent(s
, sector_num
, extent
);
2258 "ERROR: could not find extent for sector %" PRId64
"\n",
2263 ret
= get_cluster_offset(bs
, extent
, NULL
,
2264 sector_num
<< BDRV_SECTOR_BITS
,
2265 false, &cluster_offset
, 0, 0);
2266 if (ret
== VMDK_ERROR
) {
2268 "ERROR: could not get cluster_offset for sector %"
2269 PRId64
"\n", sector_num
);
2272 if (ret
== VMDK_OK
) {
2273 int64_t extent_len
= bdrv_getlength(extent
->file
->bs
);
2274 if (extent_len
< 0) {
2276 "ERROR: could not get extent file length for sector %"
2277 PRId64
"\n", sector_num
);
2281 if (cluster_offset
>= extent_len
) {
2283 "ERROR: cluster offset for sector %"
2284 PRId64
" points after EOF\n", sector_num
);
2289 sector_num
+= extent
->cluster_sectors
;
2292 result
->corruptions
++;
2296 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2299 BDRVVmdkState
*s
= bs
->opaque
;
2300 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2301 ImageInfoList
**next
;
2303 *spec_info
= (ImageInfoSpecific
){
2304 .type
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2306 .vmdk
.data
= g_new0(ImageInfoSpecificVmdk
, 1),
2310 *spec_info
->u
.vmdk
.data
= (ImageInfoSpecificVmdk
) {
2311 .create_type
= g_strdup(s
->create_type
),
2313 .parent_cid
= s
->parent_cid
,
2316 next
= &spec_info
->u
.vmdk
.data
->extents
;
2317 for (i
= 0; i
< s
->num_extents
; i
++) {
2318 *next
= g_new0(ImageInfoList
, 1);
2319 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2320 (*next
)->next
= NULL
;
2321 next
= &(*next
)->next
;
2327 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
2329 return a
->flat
== b
->flat
&&
2330 a
->compressed
== b
->compressed
&&
2331 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
2334 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2337 BDRVVmdkState
*s
= bs
->opaque
;
2338 assert(s
->num_extents
);
2340 /* See if we have multiple extents but they have different cases */
2341 for (i
= 1; i
< s
->num_extents
; i
++) {
2342 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
2346 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2347 if (!s
->extents
[0].flat
) {
2348 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2353 static QemuOptsList vmdk_create_opts
= {
2354 .name
= "vmdk-create-opts",
2355 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2358 .name
= BLOCK_OPT_SIZE
,
2359 .type
= QEMU_OPT_SIZE
,
2360 .help
= "Virtual disk size"
2363 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2364 .type
= QEMU_OPT_STRING
,
2365 .help
= "Virtual adapter type, can be one of "
2366 "ide (default), lsilogic, buslogic or legacyESX"
2369 .name
= BLOCK_OPT_BACKING_FILE
,
2370 .type
= QEMU_OPT_STRING
,
2371 .help
= "File name of a base image"
2374 .name
= BLOCK_OPT_COMPAT6
,
2375 .type
= QEMU_OPT_BOOL
,
2376 .help
= "VMDK version 6 image",
2377 .def_value_str
= "off"
2380 .name
= BLOCK_OPT_HWVERSION
,
2381 .type
= QEMU_OPT_STRING
,
2382 .help
= "VMDK hardware version",
2383 .def_value_str
= "undefined"
2386 .name
= BLOCK_OPT_SUBFMT
,
2387 .type
= QEMU_OPT_STRING
,
2389 "VMDK flat extent format, can be one of "
2390 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2393 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2394 .type
= QEMU_OPT_BOOL
,
2395 .help
= "Enable efficient zero writes "
2396 "using the zeroed-grain GTE feature"
2398 { /* end of list */ }
2402 static BlockDriver bdrv_vmdk
= {
2403 .format_name
= "vmdk",
2404 .instance_size
= sizeof(BDRVVmdkState
),
2405 .bdrv_probe
= vmdk_probe
,
2406 .bdrv_open
= vmdk_open
,
2407 .bdrv_co_check
= vmdk_co_check
,
2408 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2409 .bdrv_child_perm
= bdrv_format_default_perms
,
2410 .bdrv_co_preadv
= vmdk_co_preadv
,
2411 .bdrv_co_pwritev
= vmdk_co_pwritev
,
2412 .bdrv_co_pwritev_compressed
= vmdk_co_pwritev_compressed
,
2413 .bdrv_co_pwrite_zeroes
= vmdk_co_pwrite_zeroes
,
2414 .bdrv_close
= vmdk_close
,
2415 .bdrv_co_create_opts
= vmdk_co_create_opts
,
2416 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2417 .bdrv_co_block_status
= vmdk_co_block_status
,
2418 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2419 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2420 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2421 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2422 .bdrv_get_info
= vmdk_get_info
,
2424 .supports_backing
= true,
2425 .create_opts
= &vmdk_create_opts
,
2428 static void bdrv_vmdk_init(void)
2430 bdrv_register(&bdrv_vmdk
);
2433 block_init(bdrv_vmdk_init
);