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_GTE_ZEROED 0x1
52 /* VMDK internal error codes */
54 #define VMDK_ERROR (-1)
55 /* Cluster not allocated */
56 #define VMDK_UNALLOC (-2)
57 #define VMDK_ZEROED (-3)
59 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
64 uint32_t disk_sectors
;
66 uint32_t l1dir_offset
;
68 uint32_t file_sectors
;
71 uint32_t sectors_per_track
;
72 } QEMU_PACKED VMDK3Header
;
81 /* Number of GrainTableEntries per GrainTable */
82 uint32_t num_gtes_per_gt
;
85 uint64_t grain_offset
;
88 uint16_t compressAlgorithm
;
89 } QEMU_PACKED VMDK4Header
;
91 #define L2_CACHE_SIZE 16
93 typedef struct VmdkExtent
{
102 int64_t flat_start_offset
;
103 int64_t l1_table_offset
;
104 int64_t l1_backup_table_offset
;
106 uint32_t *l1_backup_table
;
107 unsigned int l1_size
;
108 uint32_t l1_entry_sectors
;
110 unsigned int l2_size
;
112 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
113 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
115 int64_t cluster_sectors
;
116 int64_t next_cluster_sector
;
120 typedef struct BDRVVmdkState
{
122 uint64_t desc_offset
;
128 /* Extent array with num_extents entries, ascend ordered by address */
130 Error
*migration_blocker
;
134 typedef struct VmdkMetaData
{
135 unsigned int l1_index
;
136 unsigned int l2_index
;
137 unsigned int l2_offset
;
139 uint32_t *l2_cache_entry
;
142 typedef struct VmdkGrainMarker
{
146 } QEMU_PACKED VmdkGrainMarker
;
149 MARKER_END_OF_STREAM
= 0,
150 MARKER_GRAIN_TABLE
= 1,
151 MARKER_GRAIN_DIRECTORY
= 2,
155 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
162 magic
= be32_to_cpu(*(uint32_t *)buf
);
163 if (magic
== VMDK3_MAGIC
||
164 magic
== VMDK4_MAGIC
) {
167 const char *p
= (const char *)buf
;
168 const char *end
= p
+ buf_size
;
171 /* skip comment line */
172 while (p
< end
&& *p
!= '\n') {
179 while (p
< end
&& *p
== ' ') {
182 /* skip '\r' if windows line endings used. */
183 if (p
< end
&& *p
== '\r') {
186 /* only accept blank lines before 'version=' line */
187 if (p
== end
|| *p
!= '\n') {
193 if (end
- p
>= strlen("version=X\n")) {
194 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
195 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
199 if (end
- p
>= strlen("version=X\r\n")) {
200 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
201 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
211 #define SECTOR_SIZE 512
212 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
213 #define BUF_SIZE 4096
214 #define HEADER_SIZE 512 /* first sector of 512 bytes */
216 static void vmdk_free_extents(BlockDriverState
*bs
)
219 BDRVVmdkState
*s
= bs
->opaque
;
222 for (i
= 0; i
< s
->num_extents
; i
++) {
226 g_free(e
->l1_backup_table
);
228 if (e
->file
!= bs
->file
) {
229 bdrv_unref_child(bs
, e
->file
);
235 static void vmdk_free_last_extent(BlockDriverState
*bs
)
237 BDRVVmdkState
*s
= bs
->opaque
;
239 if (s
->num_extents
== 0) {
243 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
246 /* Return -ve errno, or 0 on success and write CID into *pcid. */
247 static int vmdk_read_cid(BlockDriverState
*bs
, int parent
, uint32_t *pcid
)
251 const char *p_name
, *cid_str
;
253 BDRVVmdkState
*s
= bs
->opaque
;
256 desc
= g_malloc0(DESC_SIZE
);
257 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
263 cid_str
= "parentCID";
264 cid_str_size
= sizeof("parentCID");
267 cid_str_size
= sizeof("CID");
270 desc
[DESC_SIZE
- 1] = '\0';
271 p_name
= strstr(desc
, cid_str
);
272 if (p_name
== NULL
) {
276 p_name
+= cid_str_size
;
277 if (sscanf(p_name
, "%" SCNx32
, &cid
) != 1) {
289 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
291 char *desc
, *tmp_desc
;
292 char *p_name
, *tmp_str
;
293 BDRVVmdkState
*s
= bs
->opaque
;
296 desc
= g_malloc0(DESC_SIZE
);
297 tmp_desc
= g_malloc0(DESC_SIZE
);
298 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
303 desc
[DESC_SIZE
- 1] = '\0';
304 tmp_str
= strstr(desc
, "parentCID");
305 if (tmp_str
== NULL
) {
310 pstrcpy(tmp_desc
, DESC_SIZE
, tmp_str
);
311 p_name
= strstr(desc
, "CID");
312 if (p_name
!= NULL
) {
313 p_name
+= sizeof("CID");
314 snprintf(p_name
, DESC_SIZE
- (p_name
- desc
), "%" PRIx32
"\n", cid
);
315 pstrcat(desc
, DESC_SIZE
, tmp_desc
);
318 ret
= bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
326 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
328 BDRVVmdkState
*s
= bs
->opaque
;
331 if (!s
->cid_checked
&& bs
->backing
) {
332 BlockDriverState
*p_bs
= bs
->backing
->bs
;
334 if (vmdk_read_cid(p_bs
, 0, &cur_pcid
) != 0) {
335 /* read failure: report as not valid */
338 if (s
->parent_cid
!= cur_pcid
) {
343 s
->cid_checked
= true;
348 /* We have nothing to do for VMDK reopen, stubs just return success */
349 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
350 BlockReopenQueue
*queue
, Error
**errp
)
352 assert(state
!= NULL
);
353 assert(state
->bs
!= NULL
);
357 static int vmdk_parent_open(BlockDriverState
*bs
)
361 BDRVVmdkState
*s
= bs
->opaque
;
364 desc
= g_malloc0(DESC_SIZE
+ 1);
365 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
371 p_name
= strstr(desc
, "parentFileNameHint");
372 if (p_name
!= NULL
) {
375 p_name
+= sizeof("parentFileNameHint") + 1;
376 end_name
= strchr(p_name
, '\"');
377 if (end_name
== NULL
) {
381 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
386 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
394 /* Create and append extent to the extent array. Return the added VmdkExtent
395 * address. return NULL if allocation failed. */
396 static int vmdk_add_extent(BlockDriverState
*bs
,
397 BdrvChild
*file
, bool flat
, int64_t sectors
,
398 int64_t l1_offset
, int64_t l1_backup_offset
,
400 int l2_size
, uint64_t cluster_sectors
,
401 VmdkExtent
**new_extent
,
405 BDRVVmdkState
*s
= bs
->opaque
;
408 if (cluster_sectors
> 0x200000) {
409 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
410 error_setg(errp
, "Invalid granularity, image may be corrupt");
413 if (l1_size
> 512 * 1024 * 1024) {
414 /* Although with big capacity and small l1_entry_sectors, we can get a
415 * big l1_size, we don't want unbounded value to allocate the table.
416 * Limit it to 512M, which is 16PB for default cluster and L2 table
418 error_setg(errp
, "L1 size too big");
422 nb_sectors
= bdrv_nb_sectors(file
->bs
);
423 if (nb_sectors
< 0) {
427 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
428 extent
= &s
->extents
[s
->num_extents
];
431 memset(extent
, 0, sizeof(VmdkExtent
));
434 extent
->sectors
= sectors
;
435 extent
->l1_table_offset
= l1_offset
;
436 extent
->l1_backup_table_offset
= l1_backup_offset
;
437 extent
->l1_size
= l1_size
;
438 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
439 extent
->l2_size
= l2_size
;
440 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
441 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
443 if (s
->num_extents
> 1) {
444 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
446 extent
->end_sector
= extent
->sectors
;
448 bs
->total_sectors
= extent
->end_sector
;
450 *new_extent
= extent
;
455 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
462 /* read the L1 table */
463 l1_size
= extent
->l1_size
* sizeof(uint32_t);
464 extent
->l1_table
= g_try_malloc(l1_size
);
465 if (l1_size
&& extent
->l1_table
== NULL
) {
469 ret
= bdrv_pread(extent
->file
,
470 extent
->l1_table_offset
,
474 error_setg_errno(errp
, -ret
,
475 "Could not read l1 table from extent '%s'",
476 extent
->file
->bs
->filename
);
479 for (i
= 0; i
< extent
->l1_size
; i
++) {
480 le32_to_cpus(&extent
->l1_table
[i
]);
483 if (extent
->l1_backup_table_offset
) {
484 extent
->l1_backup_table
= g_try_malloc(l1_size
);
485 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
489 ret
= bdrv_pread(extent
->file
,
490 extent
->l1_backup_table_offset
,
491 extent
->l1_backup_table
,
494 error_setg_errno(errp
, -ret
,
495 "Could not read l1 backup table from extent '%s'",
496 extent
->file
->bs
->filename
);
499 for (i
= 0; i
< extent
->l1_size
; i
++) {
500 le32_to_cpus(&extent
->l1_backup_table
[i
]);
505 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
508 g_free(extent
->l1_backup_table
);
510 g_free(extent
->l1_table
);
514 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
516 int flags
, Error
**errp
)
523 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
525 error_setg_errno(errp
, -ret
,
526 "Could not read header from file '%s'",
530 ret
= vmdk_add_extent(bs
, file
, false,
531 le32_to_cpu(header
.disk_sectors
),
532 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
534 le32_to_cpu(header
.l1dir_size
),
536 le32_to_cpu(header
.granularity
),
542 ret
= vmdk_init_tables(bs
, extent
, errp
);
544 /* free extent allocated by vmdk_add_extent */
545 vmdk_free_last_extent(bs
);
550 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
551 QDict
*options
, Error
**errp
);
553 static char *vmdk_read_desc(BdrvChild
*file
, uint64_t desc_offset
, Error
**errp
)
559 size
= bdrv_getlength(file
->bs
);
561 error_setg_errno(errp
, -size
, "Could not access file");
566 /* Both descriptor file and sparse image must be much larger than 4
567 * bytes, also callers of vmdk_read_desc want to compare the first 4
568 * bytes with VMDK4_MAGIC, let's error out if less is read. */
569 error_setg(errp
, "File is too small, not a valid image");
573 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
574 buf
= g_malloc(size
+ 1);
576 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
578 error_setg_errno(errp
, -ret
, "Could not read from file");
587 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
589 int flags
, QDict
*options
, Error
**errp
)
593 uint32_t l1_size
, l1_entry_sectors
;
596 BDRVVmdkState
*s
= bs
->opaque
;
597 int64_t l1_backup_offset
= 0;
600 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
602 error_setg_errno(errp
, -ret
,
603 "Could not read header from file '%s'",
607 if (header
.capacity
== 0) {
608 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
610 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
614 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
620 if (!s
->create_type
) {
621 s
->create_type
= g_strdup("monolithicSparse");
624 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
626 * The footer takes precedence over the header, so read it in. The
627 * footer starts at offset -1024 from the end: One sector for the
628 * footer, and another one for the end-of-stream marker.
635 uint8_t pad
[512 - 16];
636 } QEMU_PACKED footer_marker
;
640 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
646 uint8_t pad
[512 - 16];
647 } QEMU_PACKED eos_marker
;
648 } QEMU_PACKED footer
;
650 ret
= bdrv_pread(file
,
651 bs
->file
->bs
->total_sectors
* 512 - 1536,
652 &footer
, sizeof(footer
));
654 error_setg_errno(errp
, -ret
, "Failed to read footer");
658 /* Some sanity checks for the footer */
659 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
660 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
661 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
662 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
663 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
664 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
666 error_setg(errp
, "Invalid footer");
670 header
= footer
.header
;
674 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
675 if (le32_to_cpu(header
.version
) > 3) {
676 error_setg(errp
, "Unsupported VMDK version %" PRIu32
,
677 le32_to_cpu(header
.version
));
679 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
) &&
681 /* VMware KB 2064959 explains that version 3 added support for
682 * persistent changed block tracking (CBT), and backup software can
683 * read it as version=1 if it doesn't care about the changed area
684 * information. So we are safe to enable read only. */
685 error_setg(errp
, "VMDK version 3 must be read only");
689 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
690 error_setg(errp
, "L2 table size too big");
694 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
695 * le64_to_cpu(header
.granularity
);
696 if (l1_entry_sectors
== 0) {
697 error_setg(errp
, "L1 entry size is invalid");
700 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
702 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
703 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
705 if (bdrv_nb_sectors(file
->bs
) < le64_to_cpu(header
.grain_offset
)) {
706 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
707 (int64_t)(le64_to_cpu(header
.grain_offset
)
708 * BDRV_SECTOR_SIZE
));
712 ret
= vmdk_add_extent(bs
, file
, false,
713 le64_to_cpu(header
.capacity
),
714 le64_to_cpu(header
.gd_offset
) << 9,
717 le32_to_cpu(header
.num_gtes_per_gt
),
718 le64_to_cpu(header
.granularity
),
725 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
726 if (extent
->compressed
) {
727 g_free(s
->create_type
);
728 s
->create_type
= g_strdup("streamOptimized");
730 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
731 extent
->version
= le32_to_cpu(header
.version
);
732 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
733 ret
= vmdk_init_tables(bs
, extent
, errp
);
735 /* free extent allocated by vmdk_add_extent */
736 vmdk_free_last_extent(bs
);
741 /* find an option value out of descriptor file */
742 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
743 char *buf
, int buf_size
)
745 char *opt_pos
, *opt_end
;
746 const char *end
= desc
+ strlen(desc
);
748 opt_pos
= strstr(desc
, opt_name
);
752 /* Skip "=\"" following opt_name */
753 opt_pos
+= strlen(opt_name
) + 2;
754 if (opt_pos
>= end
) {
758 while (opt_end
< end
&& *opt_end
!= '"') {
761 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
764 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
768 /* Open an extent file and append to bs array */
769 static int vmdk_open_sparse(BlockDriverState
*bs
, BdrvChild
*file
, int flags
,
770 char *buf
, QDict
*options
, Error
**errp
)
774 magic
= ldl_be_p(buf
);
777 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
780 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
783 error_setg(errp
, "Image not in VMDK format");
789 static const char *next_line(const char *s
)
800 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
801 const char *desc_file_path
, QDict
*options
,
813 BdrvChild
*extent_file
;
814 BDRVVmdkState
*s
= bs
->opaque
;
816 char extent_opt_prefix
[32];
817 Error
*local_err
= NULL
;
819 for (p
= desc
; *p
; p
= next_line(p
)) {
820 /* parse extent line in one of below formats:
822 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
823 * RW [size in sectors] SPARSE "file-name.vmdk"
824 * RW [size in sectors] VMFS "file-name.vmdk"
825 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
828 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
829 access
, §ors
, type
, fname
, &flat_offset
);
830 if (matches
< 4 || strcmp(access
, "RW")) {
832 } else if (!strcmp(type
, "FLAT")) {
833 if (matches
!= 5 || flat_offset
< 0) {
836 } else if (!strcmp(type
, "VMFS")) {
842 } else if (matches
!= 4) {
847 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
848 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
849 (strcmp(access
, "RW"))) {
853 if (!path_is_absolute(fname
) && !path_has_protocol(fname
) &&
856 error_setg(errp
, "Cannot use relative extent paths with VMDK "
857 "descriptor file '%s'", bs
->file
->bs
->filename
);
861 extent_path
= g_malloc0(PATH_MAX
);
862 path_combine(extent_path
, PATH_MAX
, desc_file_path
, fname
);
864 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
867 extent_file
= bdrv_open_child(extent_path
, options
, extent_opt_prefix
,
868 bs
, &child_file
, false, &local_err
);
871 error_propagate(errp
, local_err
);
875 /* save to extents array */
876 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
879 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
880 0, 0, 0, 0, 0, &extent
, errp
);
882 bdrv_unref_child(bs
, extent_file
);
885 extent
->flat_start_offset
= flat_offset
<< 9;
886 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
887 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
888 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
892 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
897 bdrv_unref_child(bs
, extent_file
);
900 extent
= &s
->extents
[s
->num_extents
- 1];
902 error_setg(errp
, "Unsupported extent type '%s'", type
);
903 bdrv_unref_child(bs
, extent_file
);
906 extent
->type
= g_strdup(type
);
913 if (np
[-1] == '\n') {
916 error_setg(errp
, "Invalid extent line: %.*s", (int)(np
- p
), p
);
920 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
921 QDict
*options
, Error
**errp
)
925 BDRVVmdkState
*s
= bs
->opaque
;
927 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
928 error_setg(errp
, "invalid VMDK image descriptor");
932 if (strcmp(ct
, "monolithicFlat") &&
933 strcmp(ct
, "vmfs") &&
934 strcmp(ct
, "vmfsSparse") &&
935 strcmp(ct
, "twoGbMaxExtentSparse") &&
936 strcmp(ct
, "twoGbMaxExtentFlat")) {
937 error_setg(errp
, "Unsupported image type '%s'", ct
);
941 s
->create_type
= g_strdup(ct
);
943 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->bs
->exact_filename
, options
,
949 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
954 BDRVVmdkState
*s
= bs
->opaque
;
956 Error
*local_err
= NULL
;
958 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
964 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
969 magic
= ldl_be_p(buf
);
973 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
,
975 s
->desc_offset
= 0x200;
978 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
985 /* try to open parent images, if exist */
986 ret
= vmdk_parent_open(bs
);
990 ret
= vmdk_read_cid(bs
, 0, &s
->cid
);
994 ret
= vmdk_read_cid(bs
, 1, &s
->parent_cid
);
998 qemu_co_mutex_init(&s
->lock
);
1000 /* Disable migration when VMDK images are used */
1001 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
1002 "does not support live migration",
1003 bdrv_get_device_or_node_name(bs
));
1004 ret
= migrate_add_blocker(s
->migration_blocker
, &local_err
);
1006 error_propagate(errp
, local_err
);
1007 error_free(s
->migration_blocker
);
1016 g_free(s
->create_type
);
1017 s
->create_type
= NULL
;
1018 vmdk_free_extents(bs
);
1023 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1025 BDRVVmdkState
*s
= bs
->opaque
;
1028 for (i
= 0; i
< s
->num_extents
; i
++) {
1029 if (!s
->extents
[i
].flat
) {
1030 bs
->bl
.pwrite_zeroes_alignment
=
1031 MAX(bs
->bl
.pwrite_zeroes_alignment
,
1032 s
->extents
[i
].cluster_sectors
<< BDRV_SECTOR_BITS
);
1040 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1041 * to the cluster at @cluster_sector_num.
1043 * If @skip_start_sector < @skip_end_sector, the relative range
1044 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1045 * it for call to write user data in the request.
1047 static int get_whole_cluster(BlockDriverState
*bs
,
1049 uint64_t cluster_offset
,
1051 uint64_t skip_start_bytes
,
1052 uint64_t skip_end_bytes
)
1055 int64_t cluster_bytes
;
1056 uint8_t *whole_grain
;
1058 /* For COW, align request sector_num to cluster start */
1059 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1060 offset
= QEMU_ALIGN_DOWN(offset
, cluster_bytes
);
1061 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1064 memset(whole_grain
, 0, skip_start_bytes
);
1065 memset(whole_grain
+ skip_end_bytes
, 0, cluster_bytes
- skip_end_bytes
);
1068 assert(skip_end_bytes
<= cluster_bytes
);
1069 /* we will be here if it's first write on non-exist grain(cluster).
1070 * try to read from parent image, if exist */
1071 if (bs
->backing
&& !vmdk_is_cid_valid(bs
)) {
1076 /* Read backing data before skip range */
1077 if (skip_start_bytes
> 0) {
1079 /* qcow2 emits this on bs->file instead of bs->backing */
1080 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1081 ret
= bdrv_pread(bs
->backing
, offset
, whole_grain
,
1088 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1089 ret
= bdrv_pwrite(extent
->file
, cluster_offset
, whole_grain
,
1096 /* Read backing data after skip range */
1097 if (skip_end_bytes
< cluster_bytes
) {
1099 /* qcow2 emits this on bs->file instead of bs->backing */
1100 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1101 ret
= bdrv_pread(bs
->backing
, offset
+ skip_end_bytes
,
1102 whole_grain
+ skip_end_bytes
,
1103 cluster_bytes
- skip_end_bytes
);
1109 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1110 ret
= bdrv_pwrite(extent
->file
, cluster_offset
+ skip_end_bytes
,
1111 whole_grain
+ skip_end_bytes
,
1112 cluster_bytes
- skip_end_bytes
);
1121 qemu_vfree(whole_grain
);
1125 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1128 offset
= cpu_to_le32(offset
);
1129 /* update L2 table */
1130 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_UPDATE
);
1131 if (bdrv_pwrite_sync(extent
->file
,
1132 ((int64_t)m_data
->l2_offset
* 512)
1133 + (m_data
->l2_index
* sizeof(offset
)),
1134 &offset
, sizeof(offset
)) < 0) {
1137 /* update backup L2 table */
1138 if (extent
->l1_backup_table_offset
!= 0) {
1139 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1140 if (bdrv_pwrite_sync(extent
->file
,
1141 ((int64_t)m_data
->l2_offset
* 512)
1142 + (m_data
->l2_index
* sizeof(offset
)),
1143 &offset
, sizeof(offset
)) < 0) {
1147 if (m_data
->l2_cache_entry
) {
1148 *m_data
->l2_cache_entry
= offset
;
1155 * get_cluster_offset
1157 * Look up cluster offset in extent file by sector number, and store in
1160 * For flat extents, the start offset as parsed from the description file is
1163 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1164 * offset for a new cluster and update L2 cache. If there is a backing file,
1165 * COW is done before returning; otherwise, zeroes are written to the allocated
1166 * cluster. Both COW and zero writing skips the sector range
1167 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1168 * has new data to write there.
1170 * Returns: VMDK_OK if cluster exists and mapped in the image.
1171 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1172 * VMDK_ERROR if failed.
1174 static int get_cluster_offset(BlockDriverState
*bs
,
1176 VmdkMetaData
*m_data
,
1179 uint64_t *cluster_offset
,
1180 uint64_t skip_start_bytes
,
1181 uint64_t skip_end_bytes
)
1183 unsigned int l1_index
, l2_offset
, l2_index
;
1184 int min_index
, i
, j
;
1185 uint32_t min_count
, *l2_table
;
1186 bool zeroed
= false;
1188 int64_t cluster_sector
;
1194 *cluster_offset
= extent
->flat_start_offset
;
1198 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1199 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1200 if (l1_index
>= extent
->l1_size
) {
1203 l2_offset
= extent
->l1_table
[l1_index
];
1205 return VMDK_UNALLOC
;
1207 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1208 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1209 /* increment the hit count */
1210 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1211 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1212 extent
->l2_cache_counts
[j
] >>= 1;
1215 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1219 /* not found: load a new entry in the least used one */
1221 min_count
= 0xffffffff;
1222 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1223 if (extent
->l2_cache_counts
[i
] < min_count
) {
1224 min_count
= extent
->l2_cache_counts
[i
];
1228 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1229 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_LOAD
);
1230 if (bdrv_pread(extent
->file
,
1231 (int64_t)l2_offset
* 512,
1233 extent
->l2_size
* sizeof(uint32_t)
1234 ) != extent
->l2_size
* sizeof(uint32_t)) {
1238 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1239 extent
->l2_cache_counts
[min_index
] = 1;
1241 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1242 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1244 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1248 if (!cluster_sector
|| zeroed
) {
1250 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1253 cluster_sector
= extent
->next_cluster_sector
;
1254 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1256 /* First of all we write grain itself, to avoid race condition
1257 * that may to corrupt the image.
1258 * This problem may occur because of insufficient space on host disk
1259 * or inappropriate VM shutdown.
1261 ret
= get_whole_cluster(bs
, extent
, cluster_sector
* BDRV_SECTOR_SIZE
,
1262 offset
, skip_start_bytes
, skip_end_bytes
);
1268 m_data
->l1_index
= l1_index
;
1269 m_data
->l2_index
= l2_index
;
1270 m_data
->l2_offset
= l2_offset
;
1271 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1274 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1278 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1279 int64_t sector_num
, VmdkExtent
*start_hint
)
1281 VmdkExtent
*extent
= start_hint
;
1284 extent
= &s
->extents
[0];
1286 while (extent
< &s
->extents
[s
->num_extents
]) {
1287 if (sector_num
< extent
->end_sector
) {
1295 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent
*extent
,
1298 uint64_t extent_begin_offset
, extent_relative_offset
;
1299 uint64_t cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
1301 extent_begin_offset
=
1302 (extent
->end_sector
- extent
->sectors
) * BDRV_SECTOR_SIZE
;
1303 extent_relative_offset
= offset
- extent_begin_offset
;
1304 return extent_relative_offset
% cluster_size
;
1307 static int coroutine_fn
vmdk_co_block_status(BlockDriverState
*bs
,
1309 int64_t offset
, int64_t bytes
,
1310 int64_t *pnum
, int64_t *map
,
1311 BlockDriverState
**file
)
1313 BDRVVmdkState
*s
= bs
->opaque
;
1314 int64_t index_in_cluster
, n
, ret
;
1315 uint64_t cluster_offset
;
1318 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, NULL
);
1322 qemu_co_mutex_lock(&s
->lock
);
1323 ret
= get_cluster_offset(bs
, extent
, NULL
, offset
, false, &cluster_offset
,
1325 qemu_co_mutex_unlock(&s
->lock
);
1327 index_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1336 ret
= BDRV_BLOCK_ZERO
;
1339 ret
= BDRV_BLOCK_DATA
;
1340 if (!extent
->compressed
) {
1341 ret
|= BDRV_BLOCK_OFFSET_VALID
;
1342 *map
= cluster_offset
+ index_in_cluster
;
1344 *file
= extent
->file
->bs
;
1348 n
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
- index_in_cluster
;
1349 *pnum
= MIN(n
, bytes
);
1353 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1354 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1355 uint64_t qiov_offset
, uint64_t n_bytes
,
1359 VmdkGrainMarker
*data
= NULL
;
1361 QEMUIOVector local_qiov
;
1363 int64_t write_offset
;
1364 int64_t write_end_sector
;
1366 if (extent
->compressed
) {
1367 void *compressed_data
;
1369 if (!extent
->has_marker
) {
1373 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1374 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1376 compressed_data
= g_malloc(n_bytes
);
1377 qemu_iovec_to_buf(qiov
, qiov_offset
, compressed_data
, n_bytes
);
1378 ret
= compress(data
->data
, &buf_len
, compressed_data
, n_bytes
);
1379 g_free(compressed_data
);
1381 if (ret
!= Z_OK
|| buf_len
== 0) {
1386 data
->lba
= cpu_to_le64(offset
>> BDRV_SECTOR_BITS
);
1387 data
->size
= cpu_to_le32(buf_len
);
1389 n_bytes
= buf_len
+ sizeof(VmdkGrainMarker
);
1390 iov
= (struct iovec
) {
1394 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1396 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_COMPRESSED
);
1398 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1399 qemu_iovec_concat(&local_qiov
, qiov
, qiov_offset
, n_bytes
);
1401 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_AIO
);
1404 write_offset
= cluster_offset
+ offset_in_cluster
;
1405 ret
= bdrv_co_pwritev(extent
->file
, write_offset
, n_bytes
,
1408 write_end_sector
= DIV_ROUND_UP(write_offset
+ n_bytes
, BDRV_SECTOR_SIZE
);
1410 if (extent
->compressed
) {
1411 extent
->next_cluster_sector
= write_end_sector
;
1413 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1423 if (!extent
->compressed
) {
1424 qemu_iovec_destroy(&local_qiov
);
1429 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1430 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1434 int cluster_bytes
, buf_bytes
;
1435 uint8_t *cluster_buf
, *compressed_data
;
1436 uint8_t *uncomp_buf
;
1438 VmdkGrainMarker
*marker
;
1442 if (!extent
->compressed
) {
1443 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_AIO
);
1444 ret
= bdrv_co_preadv(extent
->file
,
1445 cluster_offset
+ offset_in_cluster
, bytes
,
1452 cluster_bytes
= extent
->cluster_sectors
* 512;
1453 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1454 buf_bytes
= cluster_bytes
* 2;
1455 cluster_buf
= g_malloc(buf_bytes
);
1456 uncomp_buf
= g_malloc(cluster_bytes
);
1457 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_COMPRESSED
);
1458 ret
= bdrv_pread(extent
->file
,
1460 cluster_buf
, buf_bytes
);
1464 compressed_data
= cluster_buf
;
1465 buf_len
= cluster_bytes
;
1466 data_len
= cluster_bytes
;
1467 if (extent
->has_marker
) {
1468 marker
= (VmdkGrainMarker
*)cluster_buf
;
1469 compressed_data
= marker
->data
;
1470 data_len
= le32_to_cpu(marker
->size
);
1472 if (!data_len
|| data_len
> buf_bytes
) {
1476 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1482 if (offset_in_cluster
< 0 ||
1483 offset_in_cluster
+ bytes
> buf_len
) {
1487 qemu_iovec_from_buf(qiov
, 0, uncomp_buf
+ offset_in_cluster
, bytes
);
1492 g_free(cluster_buf
);
1496 static int coroutine_fn
1497 vmdk_co_preadv(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1498 QEMUIOVector
*qiov
, int flags
)
1500 BDRVVmdkState
*s
= bs
->opaque
;
1502 uint64_t n_bytes
, offset_in_cluster
;
1503 VmdkExtent
*extent
= NULL
;
1504 QEMUIOVector local_qiov
;
1505 uint64_t cluster_offset
;
1506 uint64_t bytes_done
= 0;
1508 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1509 qemu_co_mutex_lock(&s
->lock
);
1512 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
1517 ret
= get_cluster_offset(bs
, extent
, NULL
,
1518 offset
, false, &cluster_offset
, 0, 0);
1519 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1521 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
1522 - offset_in_cluster
);
1524 if (ret
!= VMDK_OK
) {
1525 /* if not allocated, try to read from parent image, if exist */
1526 if (bs
->backing
&& ret
!= VMDK_ZEROED
) {
1527 if (!vmdk_is_cid_valid(bs
)) {
1532 qemu_iovec_reset(&local_qiov
);
1533 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1535 /* qcow2 emits this on bs->file instead of bs->backing */
1536 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1537 ret
= bdrv_co_preadv(bs
->backing
, offset
, n_bytes
,
1543 qemu_iovec_memset(qiov
, bytes_done
, 0, n_bytes
);
1546 qemu_iovec_reset(&local_qiov
);
1547 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1549 ret
= vmdk_read_extent(extent
, cluster_offset
, offset_in_cluster
,
1550 &local_qiov
, n_bytes
);
1557 bytes_done
+= n_bytes
;
1562 qemu_co_mutex_unlock(&s
->lock
);
1563 qemu_iovec_destroy(&local_qiov
);
1570 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1571 * if possible, otherwise return -ENOTSUP.
1572 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1573 * with each cluster. By dry run we can find if the zero write
1574 * is possible without modifying image data.
1576 * Returns: error code with 0 for success.
1578 static int vmdk_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1579 uint64_t bytes
, QEMUIOVector
*qiov
,
1580 bool zeroed
, bool zero_dry_run
)
1582 BDRVVmdkState
*s
= bs
->opaque
;
1583 VmdkExtent
*extent
= NULL
;
1585 int64_t offset_in_cluster
, n_bytes
;
1586 uint64_t cluster_offset
;
1587 uint64_t bytes_done
= 0;
1588 VmdkMetaData m_data
;
1590 if (DIV_ROUND_UP(offset
, BDRV_SECTOR_SIZE
) > bs
->total_sectors
) {
1591 error_report("Wrong offset: offset=0x%" PRIx64
1592 " total_sectors=0x%" PRIx64
,
1593 offset
, bs
->total_sectors
);
1598 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
1602 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1603 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
1604 - offset_in_cluster
);
1606 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
1607 !(extent
->compressed
|| zeroed
),
1608 &cluster_offset
, offset_in_cluster
,
1609 offset_in_cluster
+ n_bytes
);
1610 if (extent
->compressed
) {
1611 if (ret
== VMDK_OK
) {
1612 /* Refuse write to allocated cluster for streamOptimized */
1613 error_report("Could not write to allocated cluster"
1614 " for streamOptimized");
1618 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
1619 true, &cluster_offset
, 0, 0);
1622 if (ret
== VMDK_ERROR
) {
1626 /* Do zeroed write, buf is ignored */
1627 if (extent
->has_zero_grain
&&
1628 offset_in_cluster
== 0 &&
1629 n_bytes
>= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
) {
1630 n_bytes
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
1631 if (!zero_dry_run
) {
1632 /* update L2 tables */
1633 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1642 ret
= vmdk_write_extent(extent
, cluster_offset
, offset_in_cluster
,
1643 qiov
, bytes_done
, n_bytes
, offset
);
1648 /* update L2 tables */
1649 if (vmdk_L2update(extent
, &m_data
,
1650 cluster_offset
>> BDRV_SECTOR_BITS
)
1658 bytes_done
+= n_bytes
;
1660 /* update CID on the first write every time the virtual disk is
1662 if (!s
->cid_updated
) {
1663 ret
= vmdk_write_cid(bs
, g_random_int());
1667 s
->cid_updated
= true;
1673 static int coroutine_fn
1674 vmdk_co_pwritev(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1675 QEMUIOVector
*qiov
, int flags
)
1678 BDRVVmdkState
*s
= bs
->opaque
;
1679 qemu_co_mutex_lock(&s
->lock
);
1680 ret
= vmdk_pwritev(bs
, offset
, bytes
, qiov
, false, false);
1681 qemu_co_mutex_unlock(&s
->lock
);
1685 static int coroutine_fn
1686 vmdk_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
1687 uint64_t bytes
, QEMUIOVector
*qiov
)
1689 return vmdk_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
1692 static int coroutine_fn
vmdk_co_pwrite_zeroes(BlockDriverState
*bs
,
1695 BdrvRequestFlags flags
)
1698 BDRVVmdkState
*s
= bs
->opaque
;
1700 qemu_co_mutex_lock(&s
->lock
);
1701 /* write zeroes could fail if sectors not aligned to cluster, test it with
1702 * dry_run == true before really updating image */
1703 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, true);
1705 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, false);
1707 qemu_co_mutex_unlock(&s
->lock
);
1711 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1712 bool flat
, bool compress
, bool zeroed_grain
,
1713 QemuOpts
*opts
, Error
**errp
)
1716 BlockBackend
*blk
= NULL
;
1718 Error
*local_err
= NULL
;
1719 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1720 uint32_t *gd_buf
= NULL
;
1723 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1725 error_propagate(errp
, local_err
);
1729 blk
= blk_new_open(filename
, NULL
, NULL
,
1730 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
1733 error_propagate(errp
, local_err
);
1738 blk_set_allow_write_beyond_eof(blk
, true);
1741 ret
= blk_truncate(blk
, filesize
, PREALLOC_MODE_OFF
, errp
);
1744 magic
= cpu_to_be32(VMDK4_MAGIC
);
1745 memset(&header
, 0, sizeof(header
));
1748 } else if (zeroed_grain
) {
1753 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1754 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1755 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1756 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1757 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1758 header
.granularity
= 128;
1759 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1761 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1762 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1764 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1765 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1767 header
.desc_offset
= 1;
1768 header
.desc_size
= 20;
1769 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1770 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1771 header
.grain_offset
=
1772 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1773 header
.granularity
);
1774 /* swap endianness for all header fields */
1775 header
.version
= cpu_to_le32(header
.version
);
1776 header
.flags
= cpu_to_le32(header
.flags
);
1777 header
.capacity
= cpu_to_le64(header
.capacity
);
1778 header
.granularity
= cpu_to_le64(header
.granularity
);
1779 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1780 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1781 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1782 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1783 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1784 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1785 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1787 header
.check_bytes
[0] = 0xa;
1788 header
.check_bytes
[1] = 0x20;
1789 header
.check_bytes
[2] = 0xd;
1790 header
.check_bytes
[3] = 0xa;
1792 /* write all the data */
1793 ret
= blk_pwrite(blk
, 0, &magic
, sizeof(magic
), 0);
1795 error_setg(errp
, QERR_IO_ERROR
);
1798 ret
= blk_pwrite(blk
, sizeof(magic
), &header
, sizeof(header
), 0);
1800 error_setg(errp
, QERR_IO_ERROR
);
1804 ret
= blk_truncate(blk
, le64_to_cpu(header
.grain_offset
) << 9,
1805 PREALLOC_MODE_OFF
, errp
);
1810 /* write grain directory */
1811 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1812 gd_buf
= g_malloc0(gd_buf_size
);
1813 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1814 i
< gt_count
; i
++, tmp
+= gt_size
) {
1815 gd_buf
[i
] = cpu_to_le32(tmp
);
1817 ret
= blk_pwrite(blk
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1818 gd_buf
, gd_buf_size
, 0);
1820 error_setg(errp
, QERR_IO_ERROR
);
1824 /* write backup grain directory */
1825 for (i
= 0, tmp
= le64_to_cpu(header
.gd_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
.gd_offset
) * BDRV_SECTOR_SIZE
,
1830 gd_buf
, gd_buf_size
, 0);
1832 error_setg(errp
, QERR_IO_ERROR
);
1845 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1846 char *postfix
, size_t buf_len
, Error
**errp
)
1850 if (filename
== NULL
|| !strlen(filename
)) {
1851 error_setg(errp
, "No filename provided");
1854 p
= strrchr(filename
, '/');
1856 p
= strrchr(filename
, '\\');
1859 p
= strrchr(filename
, ':');
1863 if (p
- filename
>= buf_len
) {
1866 pstrcpy(path
, p
- filename
+ 1, filename
);
1871 q
= strrchr(p
, '.');
1873 pstrcpy(prefix
, buf_len
, p
);
1876 if (q
- p
>= buf_len
) {
1879 pstrcpy(prefix
, q
- p
+ 1, p
);
1880 pstrcpy(postfix
, buf_len
, q
);
1885 static int vmdk_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1888 BlockBackend
*new_blk
= NULL
;
1889 Error
*local_err
= NULL
;
1891 int64_t total_size
= 0, filesize
;
1892 char *adapter_type
= NULL
;
1893 char *backing_file
= NULL
;
1894 char *hw_version
= NULL
;
1897 bool flat
, split
, compress
;
1898 GString
*ext_desc_lines
;
1899 char *path
= g_malloc0(PATH_MAX
);
1900 char *prefix
= g_malloc0(PATH_MAX
);
1901 char *postfix
= g_malloc0(PATH_MAX
);
1902 char *desc_line
= g_malloc0(BUF_SIZE
);
1903 char *ext_filename
= g_malloc0(PATH_MAX
);
1904 char *desc_filename
= g_malloc0(PATH_MAX
);
1905 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1906 const char *desc_extent_line
;
1907 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
1908 uint32_t parent_cid
= 0xffffffff;
1909 uint32_t number_heads
= 16;
1910 bool zeroed_grain
= false;
1911 uint32_t desc_offset
= 0, desc_len
;
1912 const char desc_template
[] =
1913 "# Disk DescriptorFile\n"
1916 "parentCID=%" PRIx32
"\n"
1917 "createType=\"%s\"\n"
1920 "# Extent description\n"
1923 "# The Disk Data Base\n"
1926 "ddb.virtualHWVersion = \"%s\"\n"
1927 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1928 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1929 "ddb.geometry.sectors = \"63\"\n"
1930 "ddb.adapterType = \"%s\"\n";
1932 ext_desc_lines
= g_string_new(NULL
);
1934 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1938 /* Read out options */
1939 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1941 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1942 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1943 hw_version
= qemu_opt_get_del(opts
, BLOCK_OPT_HWVERSION
);
1944 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1945 if (strcmp(hw_version
, "undefined")) {
1947 "compat6 cannot be enabled with hwversion set");
1952 hw_version
= g_strdup("6");
1954 if (strcmp(hw_version
, "undefined") == 0) {
1956 hw_version
= g_strdup("4");
1958 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1959 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1960 zeroed_grain
= true;
1963 if (!adapter_type
) {
1964 adapter_type
= g_strdup("ide");
1965 } else if (strcmp(adapter_type
, "ide") &&
1966 strcmp(adapter_type
, "buslogic") &&
1967 strcmp(adapter_type
, "lsilogic") &&
1968 strcmp(adapter_type
, "legacyESX")) {
1969 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1973 if (strcmp(adapter_type
, "ide") != 0) {
1974 /* that's the number of heads with which vmware operates when
1975 creating, exporting, etc. vmdk files with a non-ide adapter type */
1979 /* Default format to monolithicSparse */
1980 fmt
= g_strdup("monolithicSparse");
1981 } else if (strcmp(fmt
, "monolithicFlat") &&
1982 strcmp(fmt
, "monolithicSparse") &&
1983 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1984 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1985 strcmp(fmt
, "streamOptimized")) {
1986 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1990 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1991 strcmp(fmt
, "twoGbMaxExtentSparse"));
1992 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1993 strcmp(fmt
, "twoGbMaxExtentFlat"));
1994 compress
= !strcmp(fmt
, "streamOptimized");
1996 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
1998 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
2000 if (flat
&& backing_file
) {
2001 error_setg(errp
, "Flat image can't have backing file");
2005 if (flat
&& zeroed_grain
) {
2006 error_setg(errp
, "Flat image can't enable zeroed grain");
2012 char *full_backing
= g_new0(char, PATH_MAX
);
2013 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
2014 full_backing
, PATH_MAX
,
2017 g_free(full_backing
);
2018 error_propagate(errp
, local_err
);
2023 blk
= blk_new_open(full_backing
, NULL
, NULL
,
2024 BDRV_O_NO_BACKING
, errp
);
2025 g_free(full_backing
);
2030 if (strcmp(blk_bs(blk
)->drv
->format_name
, "vmdk")) {
2035 ret
= vmdk_read_cid(blk_bs(blk
), 0, &parent_cid
);
2040 snprintf(parent_desc_line
, BUF_SIZE
,
2041 "parentFileNameHint=\"%s\"", backing_file
);
2044 /* Create extents */
2045 filesize
= total_size
;
2046 while (filesize
> 0) {
2047 int64_t size
= filesize
;
2049 if (split
&& size
> split_size
) {
2053 snprintf(desc_filename
, PATH_MAX
, "%s-%c%03d%s",
2054 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
2056 snprintf(desc_filename
, PATH_MAX
, "%s-flat%s", prefix
, postfix
);
2058 snprintf(desc_filename
, PATH_MAX
, "%s%s", prefix
, postfix
);
2060 snprintf(ext_filename
, PATH_MAX
, "%s%s", path
, desc_filename
);
2062 if (vmdk_create_extent(ext_filename
, size
,
2063 flat
, compress
, zeroed_grain
, opts
, errp
)) {
2069 /* Format description line */
2070 snprintf(desc_line
, BUF_SIZE
,
2071 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
2072 g_string_append(ext_desc_lines
, desc_line
);
2074 /* generate descriptor file */
2075 desc
= g_strdup_printf(desc_template
,
2080 ext_desc_lines
->str
,
2083 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
2086 desc_len
= strlen(desc
);
2087 /* the descriptor offset = 0x200 */
2088 if (!split
&& !flat
) {
2089 desc_offset
= 0x200;
2091 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2093 error_propagate(errp
, local_err
);
2098 new_blk
= blk_new_open(filename
, NULL
, NULL
,
2099 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2101 if (new_blk
== NULL
) {
2102 error_propagate(errp
, local_err
);
2107 blk_set_allow_write_beyond_eof(new_blk
, true);
2109 ret
= blk_pwrite(new_blk
, desc_offset
, desc
, desc_len
, 0);
2111 error_setg_errno(errp
, -ret
, "Could not write description");
2114 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2115 * for description file */
2116 if (desc_offset
== 0) {
2117 ret
= blk_truncate(new_blk
, desc_len
, PREALLOC_MODE_OFF
, errp
);
2123 g_free(adapter_type
);
2124 g_free(backing_file
);
2132 g_free(ext_filename
);
2133 g_free(desc_filename
);
2134 g_free(parent_desc_line
);
2135 g_string_free(ext_desc_lines
, true);
2139 static void vmdk_close(BlockDriverState
*bs
)
2141 BDRVVmdkState
*s
= bs
->opaque
;
2143 vmdk_free_extents(bs
);
2144 g_free(s
->create_type
);
2146 migrate_del_blocker(s
->migration_blocker
);
2147 error_free(s
->migration_blocker
);
2150 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
2152 BDRVVmdkState
*s
= bs
->opaque
;
2156 for (i
= 0; i
< s
->num_extents
; i
++) {
2157 err
= bdrv_co_flush(s
->extents
[i
].file
->bs
);
2165 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2170 BDRVVmdkState
*s
= bs
->opaque
;
2172 ret
= bdrv_get_allocated_file_size(bs
->file
->bs
);
2176 for (i
= 0; i
< s
->num_extents
; i
++) {
2177 if (s
->extents
[i
].file
== bs
->file
) {
2180 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
->bs
);
2189 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2192 BDRVVmdkState
*s
= bs
->opaque
;
2194 /* If has a flat extent and its underlying storage doesn't have zero init,
2196 for (i
= 0; i
< s
->num_extents
; i
++) {
2197 if (s
->extents
[i
].flat
) {
2198 if (!bdrv_has_zero_init(s
->extents
[i
].file
->bs
)) {
2206 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2208 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2210 *info
= (ImageInfo
){
2211 .filename
= g_strdup(extent
->file
->bs
->filename
),
2212 .format
= g_strdup(extent
->type
),
2213 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2214 .compressed
= extent
->compressed
,
2215 .has_compressed
= extent
->compressed
,
2216 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2217 .has_cluster_size
= !extent
->flat
,
2223 static int vmdk_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
2226 BDRVVmdkState
*s
= bs
->opaque
;
2227 VmdkExtent
*extent
= NULL
;
2228 int64_t sector_num
= 0;
2229 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2231 uint64_t cluster_offset
;
2238 if (sector_num
>= total_sectors
) {
2241 extent
= find_extent(s
, sector_num
, extent
);
2244 "ERROR: could not find extent for sector %" PRId64
"\n",
2249 ret
= get_cluster_offset(bs
, extent
, NULL
,
2250 sector_num
<< BDRV_SECTOR_BITS
,
2251 false, &cluster_offset
, 0, 0);
2252 if (ret
== VMDK_ERROR
) {
2254 "ERROR: could not get cluster_offset for sector %"
2255 PRId64
"\n", sector_num
);
2258 if (ret
== VMDK_OK
) {
2259 int64_t extent_len
= bdrv_getlength(extent
->file
->bs
);
2260 if (extent_len
< 0) {
2262 "ERROR: could not get extent file length for sector %"
2263 PRId64
"\n", sector_num
);
2267 if (cluster_offset
>= extent_len
) {
2269 "ERROR: cluster offset for sector %"
2270 PRId64
" points after EOF\n", sector_num
);
2275 sector_num
+= extent
->cluster_sectors
;
2278 result
->corruptions
++;
2282 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2285 BDRVVmdkState
*s
= bs
->opaque
;
2286 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2287 ImageInfoList
**next
;
2289 *spec_info
= (ImageInfoSpecific
){
2290 .type
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2292 .vmdk
.data
= g_new0(ImageInfoSpecificVmdk
, 1),
2296 *spec_info
->u
.vmdk
.data
= (ImageInfoSpecificVmdk
) {
2297 .create_type
= g_strdup(s
->create_type
),
2299 .parent_cid
= s
->parent_cid
,
2302 next
= &spec_info
->u
.vmdk
.data
->extents
;
2303 for (i
= 0; i
< s
->num_extents
; i
++) {
2304 *next
= g_new0(ImageInfoList
, 1);
2305 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2306 (*next
)->next
= NULL
;
2307 next
= &(*next
)->next
;
2313 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
2315 return a
->flat
== b
->flat
&&
2316 a
->compressed
== b
->compressed
&&
2317 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
2320 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2323 BDRVVmdkState
*s
= bs
->opaque
;
2324 assert(s
->num_extents
);
2326 /* See if we have multiple extents but they have different cases */
2327 for (i
= 1; i
< s
->num_extents
; i
++) {
2328 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
2332 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2333 if (!s
->extents
[0].flat
) {
2334 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2339 static QemuOptsList vmdk_create_opts
= {
2340 .name
= "vmdk-create-opts",
2341 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2344 .name
= BLOCK_OPT_SIZE
,
2345 .type
= QEMU_OPT_SIZE
,
2346 .help
= "Virtual disk size"
2349 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2350 .type
= QEMU_OPT_STRING
,
2351 .help
= "Virtual adapter type, can be one of "
2352 "ide (default), lsilogic, buslogic or legacyESX"
2355 .name
= BLOCK_OPT_BACKING_FILE
,
2356 .type
= QEMU_OPT_STRING
,
2357 .help
= "File name of a base image"
2360 .name
= BLOCK_OPT_COMPAT6
,
2361 .type
= QEMU_OPT_BOOL
,
2362 .help
= "VMDK version 6 image",
2363 .def_value_str
= "off"
2366 .name
= BLOCK_OPT_HWVERSION
,
2367 .type
= QEMU_OPT_STRING
,
2368 .help
= "VMDK hardware version",
2369 .def_value_str
= "undefined"
2372 .name
= BLOCK_OPT_SUBFMT
,
2373 .type
= QEMU_OPT_STRING
,
2375 "VMDK flat extent format, can be one of "
2376 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2379 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2380 .type
= QEMU_OPT_BOOL
,
2381 .help
= "Enable efficient zero writes "
2382 "using the zeroed-grain GTE feature"
2384 { /* end of list */ }
2388 static BlockDriver bdrv_vmdk
= {
2389 .format_name
= "vmdk",
2390 .instance_size
= sizeof(BDRVVmdkState
),
2391 .bdrv_probe
= vmdk_probe
,
2392 .bdrv_open
= vmdk_open
,
2393 .bdrv_check
= vmdk_check
,
2394 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2395 .bdrv_child_perm
= bdrv_format_default_perms
,
2396 .bdrv_co_preadv
= vmdk_co_preadv
,
2397 .bdrv_co_pwritev
= vmdk_co_pwritev
,
2398 .bdrv_co_pwritev_compressed
= vmdk_co_pwritev_compressed
,
2399 .bdrv_co_pwrite_zeroes
= vmdk_co_pwrite_zeroes
,
2400 .bdrv_close
= vmdk_close
,
2401 .bdrv_create
= vmdk_create
,
2402 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2403 .bdrv_co_block_status
= vmdk_co_block_status
,
2404 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2405 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2406 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2407 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2408 .bdrv_get_info
= vmdk_get_info
,
2410 .supports_backing
= true,
2411 .create_opts
= &vmdk_create_opts
,
2414 static void bdrv_vmdk_init(void)
2416 bdrv_register(&bdrv_vmdk
);
2419 block_init(bdrv_vmdk_init
);