2 * Block driver for the VMDK format
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu-common.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "migration/migration.h"
33 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
34 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
35 #define VMDK4_COMPRESSION_DEFLATE 1
36 #define VMDK4_FLAG_NL_DETECT (1 << 0)
37 #define VMDK4_FLAG_RGD (1 << 1)
38 /* Zeroed-grain enable bit */
39 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
40 #define VMDK4_FLAG_COMPRESS (1 << 16)
41 #define VMDK4_FLAG_MARKER (1 << 17)
42 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
44 #define VMDK_GTE_ZEROED 0x1
46 /* VMDK internal error codes */
48 #define VMDK_ERROR (-1)
49 /* Cluster not allocated */
50 #define VMDK_UNALLOC (-2)
51 #define VMDK_ZEROED (-3)
53 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
58 uint32_t disk_sectors
;
60 uint32_t l1dir_offset
;
62 uint32_t file_sectors
;
65 uint32_t sectors_per_track
;
66 } QEMU_PACKED VMDK3Header
;
75 /* Number of GrainTableEntries per GrainTable */
76 uint32_t num_gtes_per_gt
;
79 uint64_t grain_offset
;
82 uint16_t compressAlgorithm
;
83 } QEMU_PACKED VMDK4Header
;
85 #define L2_CACHE_SIZE 16
87 typedef struct VmdkExtent
{
88 BlockDriverState
*file
;
96 int64_t flat_start_offset
;
97 int64_t l1_table_offset
;
98 int64_t l1_backup_table_offset
;
100 uint32_t *l1_backup_table
;
101 unsigned int l1_size
;
102 uint32_t l1_entry_sectors
;
104 unsigned int l2_size
;
106 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
107 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
109 int64_t cluster_sectors
;
110 int64_t next_cluster_sector
;
114 typedef struct BDRVVmdkState
{
116 uint64_t desc_offset
;
122 /* Extent array with num_extents entries, ascend ordered by address */
124 Error
*migration_blocker
;
128 typedef struct VmdkMetaData
{
129 unsigned int l1_index
;
130 unsigned int l2_index
;
131 unsigned int l2_offset
;
133 uint32_t *l2_cache_entry
;
136 typedef struct VmdkGrainMarker
{
140 } QEMU_PACKED VmdkGrainMarker
;
143 MARKER_END_OF_STREAM
= 0,
144 MARKER_GRAIN_TABLE
= 1,
145 MARKER_GRAIN_DIRECTORY
= 2,
149 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
156 magic
= be32_to_cpu(*(uint32_t *)buf
);
157 if (magic
== VMDK3_MAGIC
||
158 magic
== VMDK4_MAGIC
) {
161 const char *p
= (const char *)buf
;
162 const char *end
= p
+ buf_size
;
165 /* skip comment line */
166 while (p
< end
&& *p
!= '\n') {
173 while (p
< end
&& *p
== ' ') {
176 /* skip '\r' if windows line endings used. */
177 if (p
< end
&& *p
== '\r') {
180 /* only accept blank lines before 'version=' line */
181 if (p
== end
|| *p
!= '\n') {
187 if (end
- p
>= strlen("version=X\n")) {
188 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
189 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
193 if (end
- p
>= strlen("version=X\r\n")) {
194 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
195 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
205 #define SECTOR_SIZE 512
206 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
207 #define BUF_SIZE 4096
208 #define HEADER_SIZE 512 /* first sector of 512 bytes */
210 static void vmdk_free_extents(BlockDriverState
*bs
)
213 BDRVVmdkState
*s
= bs
->opaque
;
216 for (i
= 0; i
< s
->num_extents
; i
++) {
220 g_free(e
->l1_backup_table
);
222 if (e
->file
!= bs
->file
) {
229 static void vmdk_free_last_extent(BlockDriverState
*bs
)
231 BDRVVmdkState
*s
= bs
->opaque
;
233 if (s
->num_extents
== 0) {
237 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
240 static uint32_t vmdk_read_cid(BlockDriverState
*bs
, int parent
)
242 char desc
[DESC_SIZE
];
243 uint32_t cid
= 0xffffffff;
244 const char *p_name
, *cid_str
;
246 BDRVVmdkState
*s
= bs
->opaque
;
249 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
255 cid_str
= "parentCID";
256 cid_str_size
= sizeof("parentCID");
259 cid_str_size
= sizeof("CID");
262 desc
[DESC_SIZE
- 1] = '\0';
263 p_name
= strstr(desc
, cid_str
);
264 if (p_name
!= NULL
) {
265 p_name
+= cid_str_size
;
266 sscanf(p_name
, "%" SCNx32
, &cid
);
272 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
274 char desc
[DESC_SIZE
], tmp_desc
[DESC_SIZE
];
275 char *p_name
, *tmp_str
;
276 BDRVVmdkState
*s
= bs
->opaque
;
279 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
284 desc
[DESC_SIZE
- 1] = '\0';
285 tmp_str
= strstr(desc
, "parentCID");
286 if (tmp_str
== NULL
) {
290 pstrcpy(tmp_desc
, sizeof(tmp_desc
), tmp_str
);
291 p_name
= strstr(desc
, "CID");
292 if (p_name
!= NULL
) {
293 p_name
+= sizeof("CID");
294 snprintf(p_name
, sizeof(desc
) - (p_name
- desc
), "%" PRIx32
"\n", cid
);
295 pstrcat(desc
, sizeof(desc
), tmp_desc
);
298 ret
= bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
306 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
308 BDRVVmdkState
*s
= bs
->opaque
;
309 BlockDriverState
*p_bs
= bs
->backing_hd
;
312 if (!s
->cid_checked
&& p_bs
) {
313 cur_pcid
= vmdk_read_cid(p_bs
, 0);
314 if (s
->parent_cid
!= cur_pcid
) {
319 s
->cid_checked
= true;
324 /* We have nothing to do for VMDK reopen, stubs just return success */
325 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
326 BlockReopenQueue
*queue
, Error
**errp
)
328 assert(state
!= NULL
);
329 assert(state
->bs
!= NULL
);
333 static int vmdk_parent_open(BlockDriverState
*bs
)
336 char desc
[DESC_SIZE
+ 1];
337 BDRVVmdkState
*s
= bs
->opaque
;
340 desc
[DESC_SIZE
] = '\0';
341 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
346 p_name
= strstr(desc
, "parentFileNameHint");
347 if (p_name
!= NULL
) {
350 p_name
+= sizeof("parentFileNameHint") + 1;
351 end_name
= strchr(p_name
, '\"');
352 if (end_name
== NULL
) {
355 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
359 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
365 /* Create and append extent to the extent array. Return the added VmdkExtent
366 * address. return NULL if allocation failed. */
367 static int vmdk_add_extent(BlockDriverState
*bs
,
368 BlockDriverState
*file
, bool flat
, int64_t sectors
,
369 int64_t l1_offset
, int64_t l1_backup_offset
,
371 int l2_size
, uint64_t cluster_sectors
,
372 VmdkExtent
**new_extent
,
376 BDRVVmdkState
*s
= bs
->opaque
;
379 if (cluster_sectors
> 0x200000) {
380 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
381 error_setg(errp
, "Invalid granularity, image may be corrupt");
384 if (l1_size
> 512 * 1024 * 1024) {
385 /* Although with big capacity and small l1_entry_sectors, we can get a
386 * big l1_size, we don't want unbounded value to allocate the table.
387 * Limit it to 512M, which is 16PB for default cluster and L2 table
389 error_setg(errp
, "L1 size too big");
393 nb_sectors
= bdrv_nb_sectors(file
);
394 if (nb_sectors
< 0) {
398 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
399 extent
= &s
->extents
[s
->num_extents
];
402 memset(extent
, 0, sizeof(VmdkExtent
));
405 extent
->sectors
= sectors
;
406 extent
->l1_table_offset
= l1_offset
;
407 extent
->l1_backup_table_offset
= l1_backup_offset
;
408 extent
->l1_size
= l1_size
;
409 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
410 extent
->l2_size
= l2_size
;
411 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
412 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
414 if (s
->num_extents
> 1) {
415 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
417 extent
->end_sector
= extent
->sectors
;
419 bs
->total_sectors
= extent
->end_sector
;
421 *new_extent
= extent
;
426 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
433 /* read the L1 table */
434 l1_size
= extent
->l1_size
* sizeof(uint32_t);
435 extent
->l1_table
= g_try_malloc(l1_size
);
436 if (l1_size
&& extent
->l1_table
== NULL
) {
440 ret
= bdrv_pread(extent
->file
,
441 extent
->l1_table_offset
,
445 error_setg_errno(errp
, -ret
,
446 "Could not read l1 table from extent '%s'",
447 extent
->file
->filename
);
450 for (i
= 0; i
< extent
->l1_size
; i
++) {
451 le32_to_cpus(&extent
->l1_table
[i
]);
454 if (extent
->l1_backup_table_offset
) {
455 extent
->l1_backup_table
= g_try_malloc(l1_size
);
456 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
460 ret
= bdrv_pread(extent
->file
,
461 extent
->l1_backup_table_offset
,
462 extent
->l1_backup_table
,
465 error_setg_errno(errp
, -ret
,
466 "Could not read l1 backup table from extent '%s'",
467 extent
->file
->filename
);
470 for (i
= 0; i
< extent
->l1_size
; i
++) {
471 le32_to_cpus(&extent
->l1_backup_table
[i
]);
476 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
479 g_free(extent
->l1_backup_table
);
481 g_free(extent
->l1_table
);
485 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
486 BlockDriverState
*file
,
487 int flags
, Error
**errp
)
494 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
496 error_setg_errno(errp
, -ret
,
497 "Could not read header from file '%s'",
501 ret
= vmdk_add_extent(bs
, file
, false,
502 le32_to_cpu(header
.disk_sectors
),
503 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
505 le32_to_cpu(header
.l1dir_size
),
507 le32_to_cpu(header
.granularity
),
513 ret
= vmdk_init_tables(bs
, extent
, errp
);
515 /* free extent allocated by vmdk_add_extent */
516 vmdk_free_last_extent(bs
);
521 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
522 QDict
*options
, Error
**errp
);
524 static char *vmdk_read_desc(BlockDriverState
*file
, uint64_t desc_offset
,
531 size
= bdrv_getlength(file
);
533 error_setg_errno(errp
, -size
, "Could not access file");
538 /* Both descriptor file and sparse image must be much larger than 4
539 * bytes, also callers of vmdk_read_desc want to compare the first 4
540 * bytes with VMDK4_MAGIC, let's error out if less is read. */
541 error_setg(errp
, "File is too small, not a valid image");
545 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
546 buf
= g_malloc(size
+ 1);
548 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
550 error_setg_errno(errp
, -ret
, "Could not read from file");
559 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
560 BlockDriverState
*file
,
561 int flags
, QDict
*options
, Error
**errp
)
565 uint32_t l1_size
, l1_entry_sectors
;
568 BDRVVmdkState
*s
= bs
->opaque
;
569 int64_t l1_backup_offset
= 0;
571 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
573 error_setg_errno(errp
, -ret
,
574 "Could not read header from file '%s'",
578 if (header
.capacity
== 0) {
579 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
581 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
585 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
591 if (!s
->create_type
) {
592 s
->create_type
= g_strdup("monolithicSparse");
595 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
597 * The footer takes precedence over the header, so read it in. The
598 * footer starts at offset -1024 from the end: One sector for the
599 * footer, and another one for the end-of-stream marker.
606 uint8_t pad
[512 - 16];
607 } QEMU_PACKED footer_marker
;
611 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
617 uint8_t pad
[512 - 16];
618 } QEMU_PACKED eos_marker
;
619 } QEMU_PACKED footer
;
621 ret
= bdrv_pread(file
,
622 bs
->file
->total_sectors
* 512 - 1536,
623 &footer
, sizeof(footer
));
625 error_setg_errno(errp
, -ret
, "Failed to read footer");
629 /* Some sanity checks for the footer */
630 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
631 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
632 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
633 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
634 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
635 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
637 error_setg(errp
, "Invalid footer");
641 header
= footer
.header
;
644 if (le32_to_cpu(header
.version
) > 3) {
646 snprintf(buf
, sizeof(buf
), "VMDK version %" PRId32
,
647 le32_to_cpu(header
.version
));
648 error_set(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
,
649 bdrv_get_device_or_node_name(bs
), "vmdk", buf
);
651 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
)) {
652 /* VMware KB 2064959 explains that version 3 added support for
653 * persistent changed block tracking (CBT), and backup software can
654 * read it as version=1 if it doesn't care about the changed area
655 * information. So we are safe to enable read only. */
656 error_setg(errp
, "VMDK version 3 must be read only");
660 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
661 error_setg(errp
, "L2 table size too big");
665 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
666 * le64_to_cpu(header
.granularity
);
667 if (l1_entry_sectors
== 0) {
668 error_setg(errp
, "L1 entry size is invalid");
671 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
673 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
674 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
676 if (bdrv_nb_sectors(file
) < le64_to_cpu(header
.grain_offset
)) {
677 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
678 (int64_t)(le64_to_cpu(header
.grain_offset
)
679 * BDRV_SECTOR_SIZE
));
683 ret
= vmdk_add_extent(bs
, file
, false,
684 le64_to_cpu(header
.capacity
),
685 le64_to_cpu(header
.gd_offset
) << 9,
688 le32_to_cpu(header
.num_gtes_per_gt
),
689 le64_to_cpu(header
.granularity
),
696 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
697 if (extent
->compressed
) {
698 g_free(s
->create_type
);
699 s
->create_type
= g_strdup("streamOptimized");
701 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
702 extent
->version
= le32_to_cpu(header
.version
);
703 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
704 ret
= vmdk_init_tables(bs
, extent
, errp
);
706 /* free extent allocated by vmdk_add_extent */
707 vmdk_free_last_extent(bs
);
712 /* find an option value out of descriptor file */
713 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
714 char *buf
, int buf_size
)
716 char *opt_pos
, *opt_end
;
717 const char *end
= desc
+ strlen(desc
);
719 opt_pos
= strstr(desc
, opt_name
);
723 /* Skip "=\"" following opt_name */
724 opt_pos
+= strlen(opt_name
) + 2;
725 if (opt_pos
>= end
) {
729 while (opt_end
< end
&& *opt_end
!= '"') {
732 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
735 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
739 /* Open an extent file and append to bs array */
740 static int vmdk_open_sparse(BlockDriverState
*bs
,
741 BlockDriverState
*file
, int flags
,
742 char *buf
, QDict
*options
, Error
**errp
)
746 magic
= ldl_be_p(buf
);
749 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
752 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
755 error_setg(errp
, "Image not in VMDK format");
761 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
762 const char *desc_file_path
, QDict
*options
,
770 const char *p
= desc
;
774 BlockDriverState
*extent_file
;
775 BDRVVmdkState
*s
= bs
->opaque
;
777 char extent_opt_prefix
[32];
780 /* parse extent line in one of below formats:
782 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
783 * RW [size in sectors] SPARSE "file-name.vmdk"
784 * RW [size in sectors] VMFS "file-name.vmdk"
785 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
788 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
789 access
, §ors
, type
, fname
, &flat_offset
);
790 if (matches
< 4 || strcmp(access
, "RW")) {
792 } else if (!strcmp(type
, "FLAT")) {
793 if (matches
!= 5 || flat_offset
< 0) {
794 error_setg(errp
, "Invalid extent lines: \n%s", p
);
797 } else if (!strcmp(type
, "VMFS")) {
801 error_setg(errp
, "Invalid extent lines:\n%s", p
);
804 } else if (matches
!= 4) {
805 error_setg(errp
, "Invalid extent lines:\n%s", p
);
810 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
811 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
812 (strcmp(access
, "RW"))) {
816 if (!path_is_absolute(fname
) && !path_has_protocol(fname
) &&
819 error_setg(errp
, "Cannot use relative extent paths with VMDK "
820 "descriptor file '%s'", bs
->file
->filename
);
824 extent_path
= g_malloc0(PATH_MAX
);
825 path_combine(extent_path
, PATH_MAX
, desc_file_path
, fname
);
828 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
831 ret
= bdrv_open_image(&extent_file
, extent_path
, options
,
832 extent_opt_prefix
, bs
, &child_file
, false, errp
);
838 /* save to extents array */
839 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
842 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
843 0, 0, 0, 0, 0, &extent
, errp
);
845 bdrv_unref(extent_file
);
848 extent
->flat_start_offset
= flat_offset
<< 9;
849 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
850 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
851 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
855 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
860 bdrv_unref(extent_file
);
863 extent
= &s
->extents
[s
->num_extents
- 1];
865 error_setg(errp
, "Unsupported extent type '%s'", type
);
866 bdrv_unref(extent_file
);
869 extent
->type
= g_strdup(type
);
871 /* move to next line */
883 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
884 QDict
*options
, Error
**errp
)
888 BDRVVmdkState
*s
= bs
->opaque
;
890 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
891 error_setg(errp
, "invalid VMDK image descriptor");
895 if (strcmp(ct
, "monolithicFlat") &&
896 strcmp(ct
, "vmfs") &&
897 strcmp(ct
, "vmfsSparse") &&
898 strcmp(ct
, "twoGbMaxExtentSparse") &&
899 strcmp(ct
, "twoGbMaxExtentFlat")) {
900 error_setg(errp
, "Unsupported image type '%s'", ct
);
904 s
->create_type
= g_strdup(ct
);
906 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->exact_filename
, options
, errp
);
911 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
916 BDRVVmdkState
*s
= bs
->opaque
;
919 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
924 magic
= ldl_be_p(buf
);
928 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
, errp
);
929 s
->desc_offset
= 0x200;
932 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
939 /* try to open parent images, if exist */
940 ret
= vmdk_parent_open(bs
);
944 s
->cid
= vmdk_read_cid(bs
, 0);
945 s
->parent_cid
= vmdk_read_cid(bs
, 1);
946 qemu_co_mutex_init(&s
->lock
);
948 /* Disable migration when VMDK images are used */
949 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
950 "does not support live migration",
951 bdrv_get_device_or_node_name(bs
));
952 migrate_add_blocker(s
->migration_blocker
);
958 g_free(s
->create_type
);
959 s
->create_type
= NULL
;
960 vmdk_free_extents(bs
);
965 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
967 BDRVVmdkState
*s
= bs
->opaque
;
970 for (i
= 0; i
< s
->num_extents
; i
++) {
971 if (!s
->extents
[i
].flat
) {
972 bs
->bl
.write_zeroes_alignment
=
973 MAX(bs
->bl
.write_zeroes_alignment
,
974 s
->extents
[i
].cluster_sectors
);
982 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
983 * to the cluster at @cluster_sector_num.
985 * If @skip_start_sector < @skip_end_sector, the relative range
986 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
987 * it for call to write user data in the request.
989 static int get_whole_cluster(BlockDriverState
*bs
,
991 uint64_t cluster_sector_num
,
993 uint64_t skip_start_sector
,
994 uint64_t skip_end_sector
)
997 int64_t cluster_bytes
;
998 uint8_t *whole_grain
;
1000 /* For COW, align request sector_num to cluster start */
1001 sector_num
= QEMU_ALIGN_DOWN(sector_num
, extent
->cluster_sectors
);
1002 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1003 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1005 if (!bs
->backing_hd
) {
1006 memset(whole_grain
, 0, skip_start_sector
<< BDRV_SECTOR_BITS
);
1007 memset(whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
), 0,
1008 cluster_bytes
- (skip_end_sector
<< BDRV_SECTOR_BITS
));
1011 assert(skip_end_sector
<= extent
->cluster_sectors
);
1012 /* we will be here if it's first write on non-exist grain(cluster).
1013 * try to read from parent image, if exist */
1014 if (bs
->backing_hd
&& !vmdk_is_cid_valid(bs
)) {
1019 /* Read backing data before skip range */
1020 if (skip_start_sector
> 0) {
1021 if (bs
->backing_hd
) {
1022 ret
= bdrv_read(bs
->backing_hd
, sector_num
,
1023 whole_grain
, skip_start_sector
);
1029 ret
= bdrv_write(extent
->file
, cluster_sector_num
, whole_grain
,
1036 /* Read backing data after skip range */
1037 if (skip_end_sector
< extent
->cluster_sectors
) {
1038 if (bs
->backing_hd
) {
1039 ret
= bdrv_read(bs
->backing_hd
, sector_num
+ skip_end_sector
,
1040 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1041 extent
->cluster_sectors
- skip_end_sector
);
1047 ret
= bdrv_write(extent
->file
, cluster_sector_num
+ skip_end_sector
,
1048 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1049 extent
->cluster_sectors
- skip_end_sector
);
1057 qemu_vfree(whole_grain
);
1061 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1064 offset
= cpu_to_le32(offset
);
1065 /* update L2 table */
1066 if (bdrv_pwrite_sync(
1068 ((int64_t)m_data
->l2_offset
* 512)
1069 + (m_data
->l2_index
* sizeof(offset
)),
1070 &offset
, sizeof(offset
)) < 0) {
1073 /* update backup L2 table */
1074 if (extent
->l1_backup_table_offset
!= 0) {
1075 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1076 if (bdrv_pwrite_sync(
1078 ((int64_t)m_data
->l2_offset
* 512)
1079 + (m_data
->l2_index
* sizeof(offset
)),
1080 &offset
, sizeof(offset
)) < 0) {
1084 if (m_data
->l2_cache_entry
) {
1085 *m_data
->l2_cache_entry
= offset
;
1092 * get_cluster_offset
1094 * Look up cluster offset in extent file by sector number, and store in
1097 * For flat extents, the start offset as parsed from the description file is
1100 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1101 * offset for a new cluster and update L2 cache. If there is a backing file,
1102 * COW is done before returning; otherwise, zeroes are written to the allocated
1103 * cluster. Both COW and zero writing skips the sector range
1104 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1105 * has new data to write there.
1107 * Returns: VMDK_OK if cluster exists and mapped in the image.
1108 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1109 * VMDK_ERROR if failed.
1111 static int get_cluster_offset(BlockDriverState
*bs
,
1113 VmdkMetaData
*m_data
,
1116 uint64_t *cluster_offset
,
1117 uint64_t skip_start_sector
,
1118 uint64_t skip_end_sector
)
1120 unsigned int l1_index
, l2_offset
, l2_index
;
1121 int min_index
, i
, j
;
1122 uint32_t min_count
, *l2_table
;
1123 bool zeroed
= false;
1125 int64_t cluster_sector
;
1131 *cluster_offset
= extent
->flat_start_offset
;
1135 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1136 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1137 if (l1_index
>= extent
->l1_size
) {
1140 l2_offset
= extent
->l1_table
[l1_index
];
1142 return VMDK_UNALLOC
;
1144 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1145 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1146 /* increment the hit count */
1147 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1148 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1149 extent
->l2_cache_counts
[j
] >>= 1;
1152 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1156 /* not found: load a new entry in the least used one */
1158 min_count
= 0xffffffff;
1159 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1160 if (extent
->l2_cache_counts
[i
] < min_count
) {
1161 min_count
= extent
->l2_cache_counts
[i
];
1165 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1168 (int64_t)l2_offset
* 512,
1170 extent
->l2_size
* sizeof(uint32_t)
1171 ) != extent
->l2_size
* sizeof(uint32_t)) {
1175 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1176 extent
->l2_cache_counts
[min_index
] = 1;
1178 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1179 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1183 m_data
->l1_index
= l1_index
;
1184 m_data
->l2_index
= l2_index
;
1185 m_data
->l2_offset
= l2_offset
;
1186 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1188 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1192 if (!cluster_sector
|| zeroed
) {
1194 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1197 cluster_sector
= extent
->next_cluster_sector
;
1198 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1200 /* First of all we write grain itself, to avoid race condition
1201 * that may to corrupt the image.
1202 * This problem may occur because of insufficient space on host disk
1203 * or inappropriate VM shutdown.
1205 ret
= get_whole_cluster(bs
, extent
,
1207 offset
>> BDRV_SECTOR_BITS
,
1208 skip_start_sector
, skip_end_sector
);
1213 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1217 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1218 int64_t sector_num
, VmdkExtent
*start_hint
)
1220 VmdkExtent
*extent
= start_hint
;
1223 extent
= &s
->extents
[0];
1225 while (extent
< &s
->extents
[s
->num_extents
]) {
1226 if (sector_num
< extent
->end_sector
) {
1234 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent
*extent
,
1237 uint64_t index_in_cluster
, extent_begin_sector
, extent_relative_sector_num
;
1239 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1240 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1241 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1242 return index_in_cluster
;
1245 static int64_t coroutine_fn
vmdk_co_get_block_status(BlockDriverState
*bs
,
1246 int64_t sector_num
, int nb_sectors
, int *pnum
)
1248 BDRVVmdkState
*s
= bs
->opaque
;
1249 int64_t index_in_cluster
, n
, ret
;
1253 extent
= find_extent(s
, sector_num
, NULL
);
1257 qemu_co_mutex_lock(&s
->lock
);
1258 ret
= get_cluster_offset(bs
, extent
, NULL
,
1259 sector_num
* 512, false, &offset
,
1261 qemu_co_mutex_unlock(&s
->lock
);
1271 ret
= BDRV_BLOCK_ZERO
;
1274 ret
= BDRV_BLOCK_DATA
;
1275 if (extent
->file
== bs
->file
&& !extent
->compressed
) {
1276 ret
|= BDRV_BLOCK_OFFSET_VALID
| offset
;
1282 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1283 n
= extent
->cluster_sectors
- index_in_cluster
;
1284 if (n
> nb_sectors
) {
1291 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1292 int64_t offset_in_cluster
, const uint8_t *buf
,
1293 int nb_sectors
, int64_t sector_num
)
1296 VmdkGrainMarker
*data
= NULL
;
1298 const uint8_t *write_buf
= buf
;
1299 int write_len
= nb_sectors
* 512;
1300 int64_t write_offset
;
1301 int64_t write_end_sector
;
1303 if (extent
->compressed
) {
1304 if (!extent
->has_marker
) {
1308 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1309 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1310 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
1315 data
->lba
= sector_num
;
1316 data
->size
= buf_len
;
1317 write_buf
= (uint8_t *)data
;
1318 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
1320 write_offset
= cluster_offset
+ offset_in_cluster
,
1321 ret
= bdrv_pwrite(extent
->file
, write_offset
, write_buf
, write_len
);
1323 write_end_sector
= DIV_ROUND_UP(write_offset
+ write_len
, BDRV_SECTOR_SIZE
);
1325 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1328 if (ret
!= write_len
) {
1329 ret
= ret
< 0 ? ret
: -EIO
;
1338 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1339 int64_t offset_in_cluster
, uint8_t *buf
,
1343 int cluster_bytes
, buf_bytes
;
1344 uint8_t *cluster_buf
, *compressed_data
;
1345 uint8_t *uncomp_buf
;
1347 VmdkGrainMarker
*marker
;
1351 if (!extent
->compressed
) {
1352 ret
= bdrv_pread(extent
->file
,
1353 cluster_offset
+ offset_in_cluster
,
1354 buf
, nb_sectors
* 512);
1355 if (ret
== nb_sectors
* 512) {
1361 cluster_bytes
= extent
->cluster_sectors
* 512;
1362 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1363 buf_bytes
= cluster_bytes
* 2;
1364 cluster_buf
= g_malloc(buf_bytes
);
1365 uncomp_buf
= g_malloc(cluster_bytes
);
1366 ret
= bdrv_pread(extent
->file
,
1368 cluster_buf
, buf_bytes
);
1372 compressed_data
= cluster_buf
;
1373 buf_len
= cluster_bytes
;
1374 data_len
= cluster_bytes
;
1375 if (extent
->has_marker
) {
1376 marker
= (VmdkGrainMarker
*)cluster_buf
;
1377 compressed_data
= marker
->data
;
1378 data_len
= le32_to_cpu(marker
->size
);
1380 if (!data_len
|| data_len
> buf_bytes
) {
1384 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1390 if (offset_in_cluster
< 0 ||
1391 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
1395 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
1400 g_free(cluster_buf
);
1404 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
1405 uint8_t *buf
, int nb_sectors
)
1407 BDRVVmdkState
*s
= bs
->opaque
;
1409 uint64_t n
, index_in_cluster
;
1410 VmdkExtent
*extent
= NULL
;
1411 uint64_t cluster_offset
;
1413 while (nb_sectors
> 0) {
1414 extent
= find_extent(s
, sector_num
, extent
);
1418 ret
= get_cluster_offset(bs
, extent
, NULL
,
1419 sector_num
<< 9, false, &cluster_offset
,
1421 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1422 n
= extent
->cluster_sectors
- index_in_cluster
;
1423 if (n
> nb_sectors
) {
1426 if (ret
!= VMDK_OK
) {
1427 /* if not allocated, try to read from parent image, if exist */
1428 if (bs
->backing_hd
&& ret
!= VMDK_ZEROED
) {
1429 if (!vmdk_is_cid_valid(bs
)) {
1432 ret
= bdrv_read(bs
->backing_hd
, sector_num
, buf
, n
);
1437 memset(buf
, 0, 512 * n
);
1440 ret
= vmdk_read_extent(extent
,
1441 cluster_offset
, index_in_cluster
* 512,
1454 static coroutine_fn
int vmdk_co_read(BlockDriverState
*bs
, int64_t sector_num
,
1455 uint8_t *buf
, int nb_sectors
)
1458 BDRVVmdkState
*s
= bs
->opaque
;
1459 qemu_co_mutex_lock(&s
->lock
);
1460 ret
= vmdk_read(bs
, sector_num
, buf
, nb_sectors
);
1461 qemu_co_mutex_unlock(&s
->lock
);
1467 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1468 * if possible, otherwise return -ENOTSUP.
1469 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1470 * with each cluster. By dry run we can find if the zero write
1471 * is possible without modifying image data.
1473 * Returns: error code with 0 for success.
1475 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1476 const uint8_t *buf
, int nb_sectors
,
1477 bool zeroed
, bool zero_dry_run
)
1479 BDRVVmdkState
*s
= bs
->opaque
;
1480 VmdkExtent
*extent
= NULL
;
1482 int64_t index_in_cluster
, n
;
1483 uint64_t cluster_offset
;
1484 VmdkMetaData m_data
;
1486 if (sector_num
> bs
->total_sectors
) {
1487 error_report("Wrong offset: sector_num=0x%" PRIx64
1488 " total_sectors=0x%" PRIx64
"\n",
1489 sector_num
, bs
->total_sectors
);
1493 while (nb_sectors
> 0) {
1494 extent
= find_extent(s
, sector_num
, extent
);
1498 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1499 n
= extent
->cluster_sectors
- index_in_cluster
;
1500 if (n
> nb_sectors
) {
1503 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1504 !(extent
->compressed
|| zeroed
),
1506 index_in_cluster
, index_in_cluster
+ n
);
1507 if (extent
->compressed
) {
1508 if (ret
== VMDK_OK
) {
1509 /* Refuse write to allocated cluster for streamOptimized */
1510 error_report("Could not write to allocated cluster"
1511 " for streamOptimized");
1515 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1516 true, &cluster_offset
, 0, 0);
1519 if (ret
== VMDK_ERROR
) {
1523 /* Do zeroed write, buf is ignored */
1524 if (extent
->has_zero_grain
&&
1525 index_in_cluster
== 0 &&
1526 n
>= extent
->cluster_sectors
) {
1527 n
= extent
->cluster_sectors
;
1528 if (!zero_dry_run
) {
1529 /* update L2 tables */
1530 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1539 ret
= vmdk_write_extent(extent
,
1540 cluster_offset
, index_in_cluster
* 512,
1541 buf
, n
, sector_num
);
1546 /* update L2 tables */
1547 if (vmdk_L2update(extent
, &m_data
,
1548 cluster_offset
>> BDRV_SECTOR_BITS
)
1558 /* update CID on the first write every time the virtual disk is
1560 if (!s
->cid_updated
) {
1561 ret
= vmdk_write_cid(bs
, g_random_int());
1565 s
->cid_updated
= true;
1571 static coroutine_fn
int vmdk_co_write(BlockDriverState
*bs
, int64_t sector_num
,
1572 const uint8_t *buf
, int nb_sectors
)
1575 BDRVVmdkState
*s
= bs
->opaque
;
1576 qemu_co_mutex_lock(&s
->lock
);
1577 ret
= vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1578 qemu_co_mutex_unlock(&s
->lock
);
1582 static int vmdk_write_compressed(BlockDriverState
*bs
,
1587 BDRVVmdkState
*s
= bs
->opaque
;
1588 if (s
->num_extents
== 1 && s
->extents
[0].compressed
) {
1589 return vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1595 static int coroutine_fn
vmdk_co_write_zeroes(BlockDriverState
*bs
,
1598 BdrvRequestFlags flags
)
1601 BDRVVmdkState
*s
= bs
->opaque
;
1602 qemu_co_mutex_lock(&s
->lock
);
1603 /* write zeroes could fail if sectors not aligned to cluster, test it with
1604 * dry_run == true before really updating image */
1605 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, true);
1607 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, false);
1609 qemu_co_mutex_unlock(&s
->lock
);
1613 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1614 bool flat
, bool compress
, bool zeroed_grain
,
1615 QemuOpts
*opts
, Error
**errp
)
1618 BlockDriverState
*bs
= NULL
;
1620 Error
*local_err
= NULL
;
1621 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1622 uint32_t *gd_buf
= NULL
;
1625 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1627 error_propagate(errp
, local_err
);
1632 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, BDRV_O_RDWR
| BDRV_O_PROTOCOL
,
1635 error_propagate(errp
, local_err
);
1640 ret
= bdrv_truncate(bs
, filesize
);
1642 error_setg_errno(errp
, -ret
, "Could not truncate file");
1646 magic
= cpu_to_be32(VMDK4_MAGIC
);
1647 memset(&header
, 0, sizeof(header
));
1648 header
.version
= zeroed_grain
? 2 : 1;
1649 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1650 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1651 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1652 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1653 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1654 header
.granularity
= 128;
1655 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1657 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1658 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1660 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1661 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1663 header
.desc_offset
= 1;
1664 header
.desc_size
= 20;
1665 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1666 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1667 header
.grain_offset
=
1668 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1669 header
.granularity
);
1670 /* swap endianness for all header fields */
1671 header
.version
= cpu_to_le32(header
.version
);
1672 header
.flags
= cpu_to_le32(header
.flags
);
1673 header
.capacity
= cpu_to_le64(header
.capacity
);
1674 header
.granularity
= cpu_to_le64(header
.granularity
);
1675 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1676 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1677 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1678 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1679 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1680 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1681 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1683 header
.check_bytes
[0] = 0xa;
1684 header
.check_bytes
[1] = 0x20;
1685 header
.check_bytes
[2] = 0xd;
1686 header
.check_bytes
[3] = 0xa;
1688 /* write all the data */
1689 ret
= bdrv_pwrite(bs
, 0, &magic
, sizeof(magic
));
1691 error_set(errp
, QERR_IO_ERROR
);
1694 ret
= bdrv_pwrite(bs
, sizeof(magic
), &header
, sizeof(header
));
1696 error_set(errp
, QERR_IO_ERROR
);
1700 ret
= bdrv_truncate(bs
, le64_to_cpu(header
.grain_offset
) << 9);
1702 error_setg_errno(errp
, -ret
, "Could not truncate file");
1706 /* write grain directory */
1707 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1708 gd_buf
= g_malloc0(gd_buf_size
);
1709 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1710 i
< gt_count
; i
++, tmp
+= gt_size
) {
1711 gd_buf
[i
] = cpu_to_le32(tmp
);
1713 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1714 gd_buf
, gd_buf_size
);
1716 error_set(errp
, QERR_IO_ERROR
);
1720 /* write backup grain directory */
1721 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1722 i
< gt_count
; i
++, tmp
+= gt_size
) {
1723 gd_buf
[i
] = cpu_to_le32(tmp
);
1725 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1726 gd_buf
, gd_buf_size
);
1728 error_set(errp
, QERR_IO_ERROR
);
1741 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1742 char *postfix
, size_t buf_len
, Error
**errp
)
1746 if (filename
== NULL
|| !strlen(filename
)) {
1747 error_setg(errp
, "No filename provided");
1750 p
= strrchr(filename
, '/');
1752 p
= strrchr(filename
, '\\');
1755 p
= strrchr(filename
, ':');
1759 if (p
- filename
>= buf_len
) {
1762 pstrcpy(path
, p
- filename
+ 1, filename
);
1767 q
= strrchr(p
, '.');
1769 pstrcpy(prefix
, buf_len
, p
);
1772 if (q
- p
>= buf_len
) {
1775 pstrcpy(prefix
, q
- p
+ 1, p
);
1776 pstrcpy(postfix
, buf_len
, q
);
1781 static int vmdk_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1784 BlockDriverState
*new_bs
= NULL
;
1785 Error
*local_err
= NULL
;
1787 int64_t total_size
= 0, filesize
;
1788 char *adapter_type
= NULL
;
1789 char *backing_file
= NULL
;
1793 bool flat
, split
, compress
;
1794 GString
*ext_desc_lines
;
1795 char *path
= g_malloc0(PATH_MAX
);
1796 char *prefix
= g_malloc0(PATH_MAX
);
1797 char *postfix
= g_malloc0(PATH_MAX
);
1798 char *desc_line
= g_malloc0(BUF_SIZE
);
1799 char *ext_filename
= g_malloc0(PATH_MAX
);
1800 char *desc_filename
= g_malloc0(PATH_MAX
);
1801 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1802 const char *desc_extent_line
;
1803 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
1804 uint32_t parent_cid
= 0xffffffff;
1805 uint32_t number_heads
= 16;
1806 bool zeroed_grain
= false;
1807 uint32_t desc_offset
= 0, desc_len
;
1808 const char desc_template
[] =
1809 "# Disk DescriptorFile\n"
1812 "parentCID=%" PRIx32
"\n"
1813 "createType=\"%s\"\n"
1816 "# Extent description\n"
1819 "# The Disk Data Base\n"
1822 "ddb.virtualHWVersion = \"%d\"\n"
1823 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1824 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1825 "ddb.geometry.sectors = \"63\"\n"
1826 "ddb.adapterType = \"%s\"\n";
1828 ext_desc_lines
= g_string_new(NULL
);
1830 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1834 /* Read out options */
1835 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1837 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1838 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1839 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1840 flags
|= BLOCK_FLAG_COMPAT6
;
1842 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1843 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1844 zeroed_grain
= true;
1847 if (!adapter_type
) {
1848 adapter_type
= g_strdup("ide");
1849 } else if (strcmp(adapter_type
, "ide") &&
1850 strcmp(adapter_type
, "buslogic") &&
1851 strcmp(adapter_type
, "lsilogic") &&
1852 strcmp(adapter_type
, "legacyESX")) {
1853 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1857 if (strcmp(adapter_type
, "ide") != 0) {
1858 /* that's the number of heads with which vmware operates when
1859 creating, exporting, etc. vmdk files with a non-ide adapter type */
1863 /* Default format to monolithicSparse */
1864 fmt
= g_strdup("monolithicSparse");
1865 } else if (strcmp(fmt
, "monolithicFlat") &&
1866 strcmp(fmt
, "monolithicSparse") &&
1867 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1868 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1869 strcmp(fmt
, "streamOptimized")) {
1870 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1874 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1875 strcmp(fmt
, "twoGbMaxExtentSparse"));
1876 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1877 strcmp(fmt
, "twoGbMaxExtentFlat"));
1878 compress
= !strcmp(fmt
, "streamOptimized");
1880 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
1882 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
1884 if (flat
&& backing_file
) {
1885 error_setg(errp
, "Flat image can't have backing file");
1889 if (flat
&& zeroed_grain
) {
1890 error_setg(errp
, "Flat image can't enable zeroed grain");
1895 BlockDriverState
*bs
= NULL
;
1896 char *full_backing
= g_new0(char, PATH_MAX
);
1897 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
1898 full_backing
, PATH_MAX
,
1901 g_free(full_backing
);
1902 error_propagate(errp
, local_err
);
1906 ret
= bdrv_open(&bs
, full_backing
, NULL
, NULL
, BDRV_O_NO_BACKING
, NULL
,
1908 g_free(full_backing
);
1912 if (strcmp(bs
->drv
->format_name
, "vmdk")) {
1917 parent_cid
= vmdk_read_cid(bs
, 0);
1919 snprintf(parent_desc_line
, BUF_SIZE
,
1920 "parentFileNameHint=\"%s\"", backing_file
);
1923 /* Create extents */
1924 filesize
= total_size
;
1925 while (filesize
> 0) {
1926 int64_t size
= filesize
;
1928 if (split
&& size
> split_size
) {
1932 snprintf(desc_filename
, PATH_MAX
, "%s-%c%03d%s",
1933 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1935 snprintf(desc_filename
, PATH_MAX
, "%s-flat%s", prefix
, postfix
);
1937 snprintf(desc_filename
, PATH_MAX
, "%s%s", prefix
, postfix
);
1939 snprintf(ext_filename
, PATH_MAX
, "%s%s", path
, desc_filename
);
1941 if (vmdk_create_extent(ext_filename
, size
,
1942 flat
, compress
, zeroed_grain
, opts
, errp
)) {
1948 /* Format description line */
1949 snprintf(desc_line
, BUF_SIZE
,
1950 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
1951 g_string_append(ext_desc_lines
, desc_line
);
1953 /* generate descriptor file */
1954 desc
= g_strdup_printf(desc_template
,
1959 ext_desc_lines
->str
,
1960 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
1962 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
1965 desc_len
= strlen(desc
);
1966 /* the descriptor offset = 0x200 */
1967 if (!split
&& !flat
) {
1968 desc_offset
= 0x200;
1970 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1972 error_propagate(errp
, local_err
);
1976 assert(new_bs
== NULL
);
1977 ret
= bdrv_open(&new_bs
, filename
, NULL
, NULL
,
1978 BDRV_O_RDWR
| BDRV_O_PROTOCOL
, NULL
, &local_err
);
1980 error_propagate(errp
, local_err
);
1983 ret
= bdrv_pwrite(new_bs
, desc_offset
, desc
, desc_len
);
1985 error_setg_errno(errp
, -ret
, "Could not write description");
1988 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1989 * for description file */
1990 if (desc_offset
== 0) {
1991 ret
= bdrv_truncate(new_bs
, desc_len
);
1993 error_setg_errno(errp
, -ret
, "Could not truncate file");
2000 g_free(adapter_type
);
2001 g_free(backing_file
);
2008 g_free(ext_filename
);
2009 g_free(desc_filename
);
2010 g_free(parent_desc_line
);
2011 g_string_free(ext_desc_lines
, true);
2015 static void vmdk_close(BlockDriverState
*bs
)
2017 BDRVVmdkState
*s
= bs
->opaque
;
2019 vmdk_free_extents(bs
);
2020 g_free(s
->create_type
);
2022 migrate_del_blocker(s
->migration_blocker
);
2023 error_free(s
->migration_blocker
);
2026 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
2028 BDRVVmdkState
*s
= bs
->opaque
;
2032 for (i
= 0; i
< s
->num_extents
; i
++) {
2033 err
= bdrv_co_flush(s
->extents
[i
].file
);
2041 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2046 BDRVVmdkState
*s
= bs
->opaque
;
2048 ret
= bdrv_get_allocated_file_size(bs
->file
);
2052 for (i
= 0; i
< s
->num_extents
; i
++) {
2053 if (s
->extents
[i
].file
== bs
->file
) {
2056 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
);
2065 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2068 BDRVVmdkState
*s
= bs
->opaque
;
2070 /* If has a flat extent and its underlying storage doesn't have zero init,
2072 for (i
= 0; i
< s
->num_extents
; i
++) {
2073 if (s
->extents
[i
].flat
) {
2074 if (!bdrv_has_zero_init(s
->extents
[i
].file
)) {
2082 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2084 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2086 *info
= (ImageInfo
){
2087 .filename
= g_strdup(extent
->file
->filename
),
2088 .format
= g_strdup(extent
->type
),
2089 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2090 .compressed
= extent
->compressed
,
2091 .has_compressed
= extent
->compressed
,
2092 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2093 .has_cluster_size
= !extent
->flat
,
2099 static int vmdk_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
2102 BDRVVmdkState
*s
= bs
->opaque
;
2103 VmdkExtent
*extent
= NULL
;
2104 int64_t sector_num
= 0;
2105 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2107 uint64_t cluster_offset
;
2114 if (sector_num
>= total_sectors
) {
2117 extent
= find_extent(s
, sector_num
, extent
);
2120 "ERROR: could not find extent for sector %" PRId64
"\n",
2124 ret
= get_cluster_offset(bs
, extent
, NULL
,
2125 sector_num
<< BDRV_SECTOR_BITS
,
2126 false, &cluster_offset
, 0, 0);
2127 if (ret
== VMDK_ERROR
) {
2129 "ERROR: could not get cluster_offset for sector %"
2130 PRId64
"\n", sector_num
);
2133 if (ret
== VMDK_OK
&& cluster_offset
>= bdrv_getlength(extent
->file
)) {
2135 "ERROR: cluster offset for sector %"
2136 PRId64
" points after EOF\n", sector_num
);
2139 sector_num
+= extent
->cluster_sectors
;
2142 result
->corruptions
++;
2146 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2149 BDRVVmdkState
*s
= bs
->opaque
;
2150 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2151 ImageInfoList
**next
;
2153 *spec_info
= (ImageInfoSpecific
){
2154 .kind
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2156 .vmdk
= g_new0(ImageInfoSpecificVmdk
, 1),
2160 *spec_info
->vmdk
= (ImageInfoSpecificVmdk
) {
2161 .create_type
= g_strdup(s
->create_type
),
2163 .parent_cid
= s
->parent_cid
,
2166 next
= &spec_info
->vmdk
->extents
;
2167 for (i
= 0; i
< s
->num_extents
; i
++) {
2168 *next
= g_new0(ImageInfoList
, 1);
2169 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2170 (*next
)->next
= NULL
;
2171 next
= &(*next
)->next
;
2177 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
2179 return a
->flat
== b
->flat
&&
2180 a
->compressed
== b
->compressed
&&
2181 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
2184 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2187 BDRVVmdkState
*s
= bs
->opaque
;
2188 assert(s
->num_extents
);
2190 /* See if we have multiple extents but they have different cases */
2191 for (i
= 1; i
< s
->num_extents
; i
++) {
2192 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
2196 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2197 if (!s
->extents
[0].flat
) {
2198 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2203 static void vmdk_detach_aio_context(BlockDriverState
*bs
)
2205 BDRVVmdkState
*s
= bs
->opaque
;
2208 for (i
= 0; i
< s
->num_extents
; i
++) {
2209 bdrv_detach_aio_context(s
->extents
[i
].file
);
2213 static void vmdk_attach_aio_context(BlockDriverState
*bs
,
2214 AioContext
*new_context
)
2216 BDRVVmdkState
*s
= bs
->opaque
;
2219 for (i
= 0; i
< s
->num_extents
; i
++) {
2220 bdrv_attach_aio_context(s
->extents
[i
].file
, new_context
);
2224 static QemuOptsList vmdk_create_opts
= {
2225 .name
= "vmdk-create-opts",
2226 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2229 .name
= BLOCK_OPT_SIZE
,
2230 .type
= QEMU_OPT_SIZE
,
2231 .help
= "Virtual disk size"
2234 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2235 .type
= QEMU_OPT_STRING
,
2236 .help
= "Virtual adapter type, can be one of "
2237 "ide (default), lsilogic, buslogic or legacyESX"
2240 .name
= BLOCK_OPT_BACKING_FILE
,
2241 .type
= QEMU_OPT_STRING
,
2242 .help
= "File name of a base image"
2245 .name
= BLOCK_OPT_COMPAT6
,
2246 .type
= QEMU_OPT_BOOL
,
2247 .help
= "VMDK version 6 image",
2248 .def_value_str
= "off"
2251 .name
= BLOCK_OPT_SUBFMT
,
2252 .type
= QEMU_OPT_STRING
,
2254 "VMDK flat extent format, can be one of "
2255 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2258 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2259 .type
= QEMU_OPT_BOOL
,
2260 .help
= "Enable efficient zero writes "
2261 "using the zeroed-grain GTE feature"
2263 { /* end of list */ }
2267 static BlockDriver bdrv_vmdk
= {
2268 .format_name
= "vmdk",
2269 .instance_size
= sizeof(BDRVVmdkState
),
2270 .bdrv_probe
= vmdk_probe
,
2271 .bdrv_open
= vmdk_open
,
2272 .bdrv_check
= vmdk_check
,
2273 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2274 .bdrv_read
= vmdk_co_read
,
2275 .bdrv_write
= vmdk_co_write
,
2276 .bdrv_write_compressed
= vmdk_write_compressed
,
2277 .bdrv_co_write_zeroes
= vmdk_co_write_zeroes
,
2278 .bdrv_close
= vmdk_close
,
2279 .bdrv_create
= vmdk_create
,
2280 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2281 .bdrv_co_get_block_status
= vmdk_co_get_block_status
,
2282 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2283 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2284 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2285 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2286 .bdrv_get_info
= vmdk_get_info
,
2287 .bdrv_detach_aio_context
= vmdk_detach_aio_context
,
2288 .bdrv_attach_aio_context
= vmdk_attach_aio_context
,
2290 .supports_backing
= true,
2291 .create_opts
= &vmdk_create_opts
,
2294 static void bdrv_vmdk_init(void)
2296 bdrv_register(&bdrv_vmdk
);
2299 block_init(bdrv_vmdk_init
);