2 * Block driver for the VMDK format
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu/osdep.h"
27 #include "qapi/error.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qemu/error-report.h"
32 #include "qemu/module.h"
33 #include "qemu/option.h"
34 #include "qemu/bswap.h"
35 #include "migration/blocker.h"
36 #include "qemu/cutils.h"
39 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
40 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
41 #define VMDK4_COMPRESSION_DEFLATE 1
42 #define VMDK4_FLAG_NL_DETECT (1 << 0)
43 #define VMDK4_FLAG_RGD (1 << 1)
44 /* Zeroed-grain enable bit */
45 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
46 #define VMDK4_FLAG_COMPRESS (1 << 16)
47 #define VMDK4_FLAG_MARKER (1 << 17)
48 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
50 #define VMDK_EXTENT_MAX_SECTORS (1ULL << 32)
52 #define VMDK_GTE_ZEROED 0x1
54 /* VMDK internal error codes */
56 #define VMDK_ERROR (-1)
57 /* Cluster not allocated */
58 #define VMDK_UNALLOC (-2)
59 #define VMDK_ZEROED (-3)
61 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
66 uint32_t disk_sectors
;
68 uint32_t l1dir_offset
;
70 uint32_t file_sectors
;
73 uint32_t sectors_per_track
;
74 } QEMU_PACKED VMDK3Header
;
83 /* Number of GrainTableEntries per GrainTable */
84 uint32_t num_gtes_per_gt
;
87 uint64_t grain_offset
;
90 uint16_t compressAlgorithm
;
91 } QEMU_PACKED VMDK4Header
;
93 #define L2_CACHE_SIZE 16
95 typedef struct VmdkExtent
{
104 int64_t flat_start_offset
;
105 int64_t l1_table_offset
;
106 int64_t l1_backup_table_offset
;
108 uint32_t *l1_backup_table
;
109 unsigned int l1_size
;
110 uint32_t l1_entry_sectors
;
112 unsigned int l2_size
;
114 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
115 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
117 int64_t cluster_sectors
;
118 int64_t next_cluster_sector
;
122 typedef struct BDRVVmdkState
{
124 uint64_t desc_offset
;
130 /* Extent array with num_extents entries, ascend ordered by address */
132 Error
*migration_blocker
;
136 typedef struct VmdkMetaData
{
137 unsigned int l1_index
;
138 unsigned int l2_index
;
139 unsigned int l2_offset
;
141 uint32_t *l2_cache_entry
;
144 typedef struct VmdkGrainMarker
{
148 } QEMU_PACKED VmdkGrainMarker
;
151 MARKER_END_OF_STREAM
= 0,
152 MARKER_GRAIN_TABLE
= 1,
153 MARKER_GRAIN_DIRECTORY
= 2,
157 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
164 magic
= be32_to_cpu(*(uint32_t *)buf
);
165 if (magic
== VMDK3_MAGIC
||
166 magic
== VMDK4_MAGIC
) {
169 const char *p
= (const char *)buf
;
170 const char *end
= p
+ buf_size
;
173 /* skip comment line */
174 while (p
< end
&& *p
!= '\n') {
181 while (p
< end
&& *p
== ' ') {
184 /* skip '\r' if windows line endings used. */
185 if (p
< end
&& *p
== '\r') {
188 /* only accept blank lines before 'version=' line */
189 if (p
== end
|| *p
!= '\n') {
195 if (end
- p
>= strlen("version=X\n")) {
196 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
197 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
201 if (end
- p
>= strlen("version=X\r\n")) {
202 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
203 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
213 #define SECTOR_SIZE 512
214 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
215 #define BUF_SIZE 4096
216 #define HEADER_SIZE 512 /* first sector of 512 bytes */
218 static void vmdk_free_extents(BlockDriverState
*bs
)
221 BDRVVmdkState
*s
= bs
->opaque
;
224 for (i
= 0; i
< s
->num_extents
; i
++) {
228 g_free(e
->l1_backup_table
);
230 if (e
->file
!= bs
->file
) {
231 bdrv_unref_child(bs
, e
->file
);
237 static void vmdk_free_last_extent(BlockDriverState
*bs
)
239 BDRVVmdkState
*s
= bs
->opaque
;
241 if (s
->num_extents
== 0) {
245 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
248 /* Return -ve errno, or 0 on success and write CID into *pcid. */
249 static int vmdk_read_cid(BlockDriverState
*bs
, int parent
, uint32_t *pcid
)
253 const char *p_name
, *cid_str
;
255 BDRVVmdkState
*s
= bs
->opaque
;
258 desc
= g_malloc0(DESC_SIZE
);
259 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
265 cid_str
= "parentCID";
266 cid_str_size
= sizeof("parentCID");
269 cid_str_size
= sizeof("CID");
272 desc
[DESC_SIZE
- 1] = '\0';
273 p_name
= strstr(desc
, cid_str
);
274 if (p_name
== NULL
) {
278 p_name
+= cid_str_size
;
279 if (sscanf(p_name
, "%" SCNx32
, &cid
) != 1) {
291 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
293 char *desc
, *tmp_desc
;
294 char *p_name
, *tmp_str
;
295 BDRVVmdkState
*s
= bs
->opaque
;
298 desc
= g_malloc0(DESC_SIZE
);
299 tmp_desc
= g_malloc0(DESC_SIZE
);
300 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
305 desc
[DESC_SIZE
- 1] = '\0';
306 tmp_str
= strstr(desc
, "parentCID");
307 if (tmp_str
== NULL
) {
312 pstrcpy(tmp_desc
, DESC_SIZE
, tmp_str
);
313 p_name
= strstr(desc
, "CID");
314 if (p_name
!= NULL
) {
315 p_name
+= sizeof("CID");
316 snprintf(p_name
, DESC_SIZE
- (p_name
- desc
), "%" PRIx32
"\n", cid
);
317 pstrcat(desc
, DESC_SIZE
, tmp_desc
);
320 ret
= bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
328 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
330 BDRVVmdkState
*s
= bs
->opaque
;
333 if (!s
->cid_checked
&& bs
->backing
) {
334 BlockDriverState
*p_bs
= bs
->backing
->bs
;
336 if (vmdk_read_cid(p_bs
, 0, &cur_pcid
) != 0) {
337 /* read failure: report as not valid */
340 if (s
->parent_cid
!= cur_pcid
) {
345 s
->cid_checked
= true;
350 /* We have nothing to do for VMDK reopen, stubs just return success */
351 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
352 BlockReopenQueue
*queue
, Error
**errp
)
354 assert(state
!= NULL
);
355 assert(state
->bs
!= NULL
);
359 static int vmdk_parent_open(BlockDriverState
*bs
)
363 BDRVVmdkState
*s
= bs
->opaque
;
366 desc
= g_malloc0(DESC_SIZE
+ 1);
367 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
373 p_name
= strstr(desc
, "parentFileNameHint");
374 if (p_name
!= NULL
) {
377 p_name
+= sizeof("parentFileNameHint") + 1;
378 end_name
= strchr(p_name
, '\"');
379 if (end_name
== NULL
) {
383 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
388 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
396 /* Create and append extent to the extent array. Return the added VmdkExtent
397 * address. return NULL if allocation failed. */
398 static int vmdk_add_extent(BlockDriverState
*bs
,
399 BdrvChild
*file
, bool flat
, int64_t sectors
,
400 int64_t l1_offset
, int64_t l1_backup_offset
,
402 int l2_size
, uint64_t cluster_sectors
,
403 VmdkExtent
**new_extent
,
407 BDRVVmdkState
*s
= bs
->opaque
;
410 if (cluster_sectors
> 0x200000) {
411 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
412 error_setg(errp
, "Invalid granularity, image may be corrupt");
415 if (l1_size
> 512 * 1024 * 1024) {
416 /* Although with big capacity and small l1_entry_sectors, we can get a
417 * big l1_size, we don't want unbounded value to allocate the table.
418 * Limit it to 512M, which is 16PB for default cluster and L2 table
420 error_setg(errp
, "L1 size too big");
424 nb_sectors
= bdrv_nb_sectors(file
->bs
);
425 if (nb_sectors
< 0) {
429 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
430 extent
= &s
->extents
[s
->num_extents
];
433 memset(extent
, 0, sizeof(VmdkExtent
));
436 extent
->sectors
= sectors
;
437 extent
->l1_table_offset
= l1_offset
;
438 extent
->l1_backup_table_offset
= l1_backup_offset
;
439 extent
->l1_size
= l1_size
;
440 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
441 extent
->l2_size
= l2_size
;
442 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
443 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
445 if (s
->num_extents
> 1) {
446 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
448 extent
->end_sector
= extent
->sectors
;
450 bs
->total_sectors
= extent
->end_sector
;
452 *new_extent
= extent
;
457 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
464 /* read the L1 table */
465 l1_size
= extent
->l1_size
* sizeof(uint32_t);
466 extent
->l1_table
= g_try_malloc(l1_size
);
467 if (l1_size
&& extent
->l1_table
== NULL
) {
471 ret
= bdrv_pread(extent
->file
,
472 extent
->l1_table_offset
,
476 error_setg_errno(errp
, -ret
,
477 "Could not read l1 table from extent '%s'",
478 extent
->file
->bs
->filename
);
481 for (i
= 0; i
< extent
->l1_size
; i
++) {
482 le32_to_cpus(&extent
->l1_table
[i
]);
485 if (extent
->l1_backup_table_offset
) {
486 extent
->l1_backup_table
= g_try_malloc(l1_size
);
487 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
491 ret
= bdrv_pread(extent
->file
,
492 extent
->l1_backup_table_offset
,
493 extent
->l1_backup_table
,
496 error_setg_errno(errp
, -ret
,
497 "Could not read l1 backup table from extent '%s'",
498 extent
->file
->bs
->filename
);
501 for (i
= 0; i
< extent
->l1_size
; i
++) {
502 le32_to_cpus(&extent
->l1_backup_table
[i
]);
507 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
510 g_free(extent
->l1_backup_table
);
512 g_free(extent
->l1_table
);
516 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
518 int flags
, Error
**errp
)
525 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
527 error_setg_errno(errp
, -ret
,
528 "Could not read header from file '%s'",
532 ret
= vmdk_add_extent(bs
, file
, false,
533 le32_to_cpu(header
.disk_sectors
),
534 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
536 le32_to_cpu(header
.l1dir_size
),
538 le32_to_cpu(header
.granularity
),
544 ret
= vmdk_init_tables(bs
, extent
, errp
);
546 /* free extent allocated by vmdk_add_extent */
547 vmdk_free_last_extent(bs
);
552 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
553 QDict
*options
, Error
**errp
);
555 static char *vmdk_read_desc(BdrvChild
*file
, uint64_t desc_offset
, Error
**errp
)
561 size
= bdrv_getlength(file
->bs
);
563 error_setg_errno(errp
, -size
, "Could not access file");
568 /* Both descriptor file and sparse image must be much larger than 4
569 * bytes, also callers of vmdk_read_desc want to compare the first 4
570 * bytes with VMDK4_MAGIC, let's error out if less is read. */
571 error_setg(errp
, "File is too small, not a valid image");
575 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
576 buf
= g_malloc(size
+ 1);
578 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
580 error_setg_errno(errp
, -ret
, "Could not read from file");
589 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
591 int flags
, QDict
*options
, Error
**errp
)
595 uint32_t l1_size
, l1_entry_sectors
;
598 BDRVVmdkState
*s
= bs
->opaque
;
599 int64_t l1_backup_offset
= 0;
602 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
604 error_setg_errno(errp
, -ret
,
605 "Could not read header from file '%s'",
609 if (header
.capacity
== 0) {
610 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
612 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
616 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
622 if (!s
->create_type
) {
623 s
->create_type
= g_strdup("monolithicSparse");
626 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
628 * The footer takes precedence over the header, so read it in. The
629 * footer starts at offset -1024 from the end: One sector for the
630 * footer, and another one for the end-of-stream marker.
637 uint8_t pad
[512 - 16];
638 } QEMU_PACKED footer_marker
;
642 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
648 uint8_t pad
[512 - 16];
649 } QEMU_PACKED eos_marker
;
650 } QEMU_PACKED footer
;
652 ret
= bdrv_pread(file
,
653 bs
->file
->bs
->total_sectors
* 512 - 1536,
654 &footer
, sizeof(footer
));
656 error_setg_errno(errp
, -ret
, "Failed to read footer");
660 /* Some sanity checks for the footer */
661 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
662 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
663 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
664 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
665 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
666 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
668 error_setg(errp
, "Invalid footer");
672 header
= footer
.header
;
676 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
677 if (le32_to_cpu(header
.version
) > 3) {
678 error_setg(errp
, "Unsupported VMDK version %" PRIu32
,
679 le32_to_cpu(header
.version
));
681 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
) &&
683 /* VMware KB 2064959 explains that version 3 added support for
684 * persistent changed block tracking (CBT), and backup software can
685 * read it as version=1 if it doesn't care about the changed area
686 * information. So we are safe to enable read only. */
687 error_setg(errp
, "VMDK version 3 must be read only");
691 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
692 error_setg(errp
, "L2 table size too big");
696 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
697 * le64_to_cpu(header
.granularity
);
698 if (l1_entry_sectors
== 0) {
699 error_setg(errp
, "L1 entry size is invalid");
702 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
704 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
705 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
707 if (bdrv_nb_sectors(file
->bs
) < le64_to_cpu(header
.grain_offset
)) {
708 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
709 (int64_t)(le64_to_cpu(header
.grain_offset
)
710 * BDRV_SECTOR_SIZE
));
714 ret
= vmdk_add_extent(bs
, file
, false,
715 le64_to_cpu(header
.capacity
),
716 le64_to_cpu(header
.gd_offset
) << 9,
719 le32_to_cpu(header
.num_gtes_per_gt
),
720 le64_to_cpu(header
.granularity
),
727 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
728 if (extent
->compressed
) {
729 g_free(s
->create_type
);
730 s
->create_type
= g_strdup("streamOptimized");
732 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
733 extent
->version
= le32_to_cpu(header
.version
);
734 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
735 ret
= vmdk_init_tables(bs
, extent
, errp
);
737 /* free extent allocated by vmdk_add_extent */
738 vmdk_free_last_extent(bs
);
743 /* find an option value out of descriptor file */
744 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
745 char *buf
, int buf_size
)
747 char *opt_pos
, *opt_end
;
748 const char *end
= desc
+ strlen(desc
);
750 opt_pos
= strstr(desc
, opt_name
);
754 /* Skip "=\"" following opt_name */
755 opt_pos
+= strlen(opt_name
) + 2;
756 if (opt_pos
>= end
) {
760 while (opt_end
< end
&& *opt_end
!= '"') {
763 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
766 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
770 /* Open an extent file and append to bs array */
771 static int vmdk_open_sparse(BlockDriverState
*bs
, BdrvChild
*file
, int flags
,
772 char *buf
, QDict
*options
, Error
**errp
)
776 magic
= ldl_be_p(buf
);
779 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
782 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
785 error_setg(errp
, "Image not in VMDK format");
791 static const char *next_line(const char *s
)
802 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
803 const char *desc_file_path
, QDict
*options
,
815 BdrvChild
*extent_file
;
816 BDRVVmdkState
*s
= bs
->opaque
;
818 char extent_opt_prefix
[32];
819 Error
*local_err
= NULL
;
821 for (p
= desc
; *p
; p
= next_line(p
)) {
822 /* parse extent line in one of below formats:
824 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
825 * RW [size in sectors] SPARSE "file-name.vmdk"
826 * RW [size in sectors] VMFS "file-name.vmdk"
827 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
830 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
831 access
, §ors
, type
, fname
, &flat_offset
);
832 if (matches
< 4 || strcmp(access
, "RW")) {
834 } else if (!strcmp(type
, "FLAT")) {
835 if (matches
!= 5 || flat_offset
< 0) {
838 } else if (!strcmp(type
, "VMFS")) {
844 } else if (matches
!= 4) {
849 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
850 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
851 (strcmp(access
, "RW"))) {
855 if (!path_is_absolute(fname
) && !path_has_protocol(fname
) &&
858 error_setg(errp
, "Cannot use relative extent paths with VMDK "
859 "descriptor file '%s'", bs
->file
->bs
->filename
);
863 extent_path
= g_malloc0(PATH_MAX
);
864 path_combine(extent_path
, PATH_MAX
, desc_file_path
, fname
);
866 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
869 extent_file
= bdrv_open_child(extent_path
, options
, extent_opt_prefix
,
870 bs
, &child_file
, false, &local_err
);
873 error_propagate(errp
, local_err
);
877 /* save to extents array */
878 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
881 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
882 0, 0, 0, 0, 0, &extent
, errp
);
884 bdrv_unref_child(bs
, extent_file
);
887 extent
->flat_start_offset
= flat_offset
<< 9;
888 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
889 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
890 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
894 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
899 bdrv_unref_child(bs
, extent_file
);
902 extent
= &s
->extents
[s
->num_extents
- 1];
904 error_setg(errp
, "Unsupported extent type '%s'", type
);
905 bdrv_unref_child(bs
, extent_file
);
908 extent
->type
= g_strdup(type
);
915 if (np
[-1] == '\n') {
918 error_setg(errp
, "Invalid extent line: %.*s", (int)(np
- p
), p
);
922 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
923 QDict
*options
, Error
**errp
)
927 BDRVVmdkState
*s
= bs
->opaque
;
929 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
930 error_setg(errp
, "invalid VMDK image descriptor");
934 if (strcmp(ct
, "monolithicFlat") &&
935 strcmp(ct
, "vmfs") &&
936 strcmp(ct
, "vmfsSparse") &&
937 strcmp(ct
, "twoGbMaxExtentSparse") &&
938 strcmp(ct
, "twoGbMaxExtentFlat")) {
939 error_setg(errp
, "Unsupported image type '%s'", ct
);
943 s
->create_type
= g_strdup(ct
);
945 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->bs
->exact_filename
, options
,
951 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
956 BDRVVmdkState
*s
= bs
->opaque
;
958 Error
*local_err
= NULL
;
960 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
966 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
971 magic
= ldl_be_p(buf
);
975 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
,
977 s
->desc_offset
= 0x200;
980 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
987 /* try to open parent images, if exist */
988 ret
= vmdk_parent_open(bs
);
992 ret
= vmdk_read_cid(bs
, 0, &s
->cid
);
996 ret
= vmdk_read_cid(bs
, 1, &s
->parent_cid
);
1000 qemu_co_mutex_init(&s
->lock
);
1002 /* Disable migration when VMDK images are used */
1003 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
1004 "does not support live migration",
1005 bdrv_get_device_or_node_name(bs
));
1006 ret
= migrate_add_blocker(s
->migration_blocker
, &local_err
);
1008 error_propagate(errp
, local_err
);
1009 error_free(s
->migration_blocker
);
1018 g_free(s
->create_type
);
1019 s
->create_type
= NULL
;
1020 vmdk_free_extents(bs
);
1025 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1027 BDRVVmdkState
*s
= bs
->opaque
;
1030 for (i
= 0; i
< s
->num_extents
; i
++) {
1031 if (!s
->extents
[i
].flat
) {
1032 bs
->bl
.pwrite_zeroes_alignment
=
1033 MAX(bs
->bl
.pwrite_zeroes_alignment
,
1034 s
->extents
[i
].cluster_sectors
<< BDRV_SECTOR_BITS
);
1042 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1043 * to the cluster at @cluster_sector_num.
1045 * If @skip_start_sector < @skip_end_sector, the relative range
1046 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1047 * it for call to write user data in the request.
1049 static int get_whole_cluster(BlockDriverState
*bs
,
1051 uint64_t cluster_offset
,
1053 uint64_t skip_start_bytes
,
1054 uint64_t skip_end_bytes
)
1057 int64_t cluster_bytes
;
1058 uint8_t *whole_grain
;
1060 /* For COW, align request sector_num to cluster start */
1061 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1062 offset
= QEMU_ALIGN_DOWN(offset
, cluster_bytes
);
1063 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1066 memset(whole_grain
, 0, skip_start_bytes
);
1067 memset(whole_grain
+ skip_end_bytes
, 0, cluster_bytes
- skip_end_bytes
);
1070 assert(skip_end_bytes
<= cluster_bytes
);
1071 /* we will be here if it's first write on non-exist grain(cluster).
1072 * try to read from parent image, if exist */
1073 if (bs
->backing
&& !vmdk_is_cid_valid(bs
)) {
1078 /* Read backing data before skip range */
1079 if (skip_start_bytes
> 0) {
1081 /* qcow2 emits this on bs->file instead of bs->backing */
1082 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1083 ret
= bdrv_pread(bs
->backing
, offset
, whole_grain
,
1090 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1091 ret
= bdrv_pwrite(extent
->file
, cluster_offset
, whole_grain
,
1098 /* Read backing data after skip range */
1099 if (skip_end_bytes
< cluster_bytes
) {
1101 /* qcow2 emits this on bs->file instead of bs->backing */
1102 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1103 ret
= bdrv_pread(bs
->backing
, offset
+ skip_end_bytes
,
1104 whole_grain
+ skip_end_bytes
,
1105 cluster_bytes
- skip_end_bytes
);
1111 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1112 ret
= bdrv_pwrite(extent
->file
, cluster_offset
+ skip_end_bytes
,
1113 whole_grain
+ skip_end_bytes
,
1114 cluster_bytes
- skip_end_bytes
);
1123 qemu_vfree(whole_grain
);
1127 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1130 offset
= cpu_to_le32(offset
);
1131 /* update L2 table */
1132 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_UPDATE
);
1133 if (bdrv_pwrite_sync(extent
->file
,
1134 ((int64_t)m_data
->l2_offset
* 512)
1135 + (m_data
->l2_index
* sizeof(offset
)),
1136 &offset
, sizeof(offset
)) < 0) {
1139 /* update backup L2 table */
1140 if (extent
->l1_backup_table_offset
!= 0) {
1141 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1142 if (bdrv_pwrite_sync(extent
->file
,
1143 ((int64_t)m_data
->l2_offset
* 512)
1144 + (m_data
->l2_index
* sizeof(offset
)),
1145 &offset
, sizeof(offset
)) < 0) {
1149 if (m_data
->l2_cache_entry
) {
1150 *m_data
->l2_cache_entry
= offset
;
1157 * get_cluster_offset
1159 * Look up cluster offset in extent file by sector number, and store in
1162 * For flat extents, the start offset as parsed from the description file is
1165 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1166 * offset for a new cluster and update L2 cache. If there is a backing file,
1167 * COW is done before returning; otherwise, zeroes are written to the allocated
1168 * cluster. Both COW and zero writing skips the sector range
1169 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1170 * has new data to write there.
1172 * Returns: VMDK_OK if cluster exists and mapped in the image.
1173 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1174 * VMDK_ERROR if failed.
1176 static int get_cluster_offset(BlockDriverState
*bs
,
1178 VmdkMetaData
*m_data
,
1181 uint64_t *cluster_offset
,
1182 uint64_t skip_start_bytes
,
1183 uint64_t skip_end_bytes
)
1185 unsigned int l1_index
, l2_offset
, l2_index
;
1186 int min_index
, i
, j
;
1187 uint32_t min_count
, *l2_table
;
1188 bool zeroed
= false;
1190 int64_t cluster_sector
;
1196 *cluster_offset
= extent
->flat_start_offset
;
1200 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1201 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1202 if (l1_index
>= extent
->l1_size
) {
1205 l2_offset
= extent
->l1_table
[l1_index
];
1207 return VMDK_UNALLOC
;
1209 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1210 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1211 /* increment the hit count */
1212 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1213 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1214 extent
->l2_cache_counts
[j
] >>= 1;
1217 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1221 /* not found: load a new entry in the least used one */
1223 min_count
= 0xffffffff;
1224 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1225 if (extent
->l2_cache_counts
[i
] < min_count
) {
1226 min_count
= extent
->l2_cache_counts
[i
];
1230 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1231 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_LOAD
);
1232 if (bdrv_pread(extent
->file
,
1233 (int64_t)l2_offset
* 512,
1235 extent
->l2_size
* sizeof(uint32_t)
1236 ) != extent
->l2_size
* sizeof(uint32_t)) {
1240 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1241 extent
->l2_cache_counts
[min_index
] = 1;
1243 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1244 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1246 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1250 if (!cluster_sector
|| zeroed
) {
1252 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1255 if (extent
->next_cluster_sector
>= VMDK_EXTENT_MAX_SECTORS
) {
1259 cluster_sector
= extent
->next_cluster_sector
;
1260 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1262 /* First of all we write grain itself, to avoid race condition
1263 * that may to corrupt the image.
1264 * This problem may occur because of insufficient space on host disk
1265 * or inappropriate VM shutdown.
1267 ret
= get_whole_cluster(bs
, extent
, cluster_sector
* BDRV_SECTOR_SIZE
,
1268 offset
, skip_start_bytes
, skip_end_bytes
);
1274 m_data
->l1_index
= l1_index
;
1275 m_data
->l2_index
= l2_index
;
1276 m_data
->l2_offset
= l2_offset
;
1277 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1280 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1284 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1285 int64_t sector_num
, VmdkExtent
*start_hint
)
1287 VmdkExtent
*extent
= start_hint
;
1290 extent
= &s
->extents
[0];
1292 while (extent
< &s
->extents
[s
->num_extents
]) {
1293 if (sector_num
< extent
->end_sector
) {
1301 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent
*extent
,
1304 uint64_t extent_begin_offset
, extent_relative_offset
;
1305 uint64_t cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
1307 extent_begin_offset
=
1308 (extent
->end_sector
- extent
->sectors
) * BDRV_SECTOR_SIZE
;
1309 extent_relative_offset
= offset
- extent_begin_offset
;
1310 return extent_relative_offset
% cluster_size
;
1313 static int coroutine_fn
vmdk_co_block_status(BlockDriverState
*bs
,
1315 int64_t offset
, int64_t bytes
,
1316 int64_t *pnum
, int64_t *map
,
1317 BlockDriverState
**file
)
1319 BDRVVmdkState
*s
= bs
->opaque
;
1320 int64_t index_in_cluster
, n
, ret
;
1321 uint64_t cluster_offset
;
1324 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, NULL
);
1328 qemu_co_mutex_lock(&s
->lock
);
1329 ret
= get_cluster_offset(bs
, extent
, NULL
, offset
, false, &cluster_offset
,
1331 qemu_co_mutex_unlock(&s
->lock
);
1333 index_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1342 ret
= BDRV_BLOCK_ZERO
;
1345 ret
= BDRV_BLOCK_DATA
;
1346 if (!extent
->compressed
) {
1347 ret
|= BDRV_BLOCK_OFFSET_VALID
;
1348 *map
= cluster_offset
+ index_in_cluster
;
1350 *file
= extent
->file
->bs
;
1354 n
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
- index_in_cluster
;
1355 *pnum
= MIN(n
, bytes
);
1359 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1360 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1361 uint64_t qiov_offset
, uint64_t n_bytes
,
1365 VmdkGrainMarker
*data
= NULL
;
1367 QEMUIOVector local_qiov
;
1369 int64_t write_offset
;
1370 int64_t write_end_sector
;
1372 if (extent
->compressed
) {
1373 void *compressed_data
;
1375 if (!extent
->has_marker
) {
1379 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1380 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1382 compressed_data
= g_malloc(n_bytes
);
1383 qemu_iovec_to_buf(qiov
, qiov_offset
, compressed_data
, n_bytes
);
1384 ret
= compress(data
->data
, &buf_len
, compressed_data
, n_bytes
);
1385 g_free(compressed_data
);
1387 if (ret
!= Z_OK
|| buf_len
== 0) {
1392 data
->lba
= cpu_to_le64(offset
>> BDRV_SECTOR_BITS
);
1393 data
->size
= cpu_to_le32(buf_len
);
1395 n_bytes
= buf_len
+ sizeof(VmdkGrainMarker
);
1396 iov
= (struct iovec
) {
1400 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1402 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_COMPRESSED
);
1404 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1405 qemu_iovec_concat(&local_qiov
, qiov
, qiov_offset
, n_bytes
);
1407 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_AIO
);
1410 write_offset
= cluster_offset
+ offset_in_cluster
;
1411 ret
= bdrv_co_pwritev(extent
->file
, write_offset
, n_bytes
,
1414 write_end_sector
= DIV_ROUND_UP(write_offset
+ n_bytes
, BDRV_SECTOR_SIZE
);
1416 if (extent
->compressed
) {
1417 extent
->next_cluster_sector
= write_end_sector
;
1419 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1429 if (!extent
->compressed
) {
1430 qemu_iovec_destroy(&local_qiov
);
1435 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1436 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1440 int cluster_bytes
, buf_bytes
;
1441 uint8_t *cluster_buf
, *compressed_data
;
1442 uint8_t *uncomp_buf
;
1444 VmdkGrainMarker
*marker
;
1448 if (!extent
->compressed
) {
1449 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_AIO
);
1450 ret
= bdrv_co_preadv(extent
->file
,
1451 cluster_offset
+ offset_in_cluster
, bytes
,
1458 cluster_bytes
= extent
->cluster_sectors
* 512;
1459 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1460 buf_bytes
= cluster_bytes
* 2;
1461 cluster_buf
= g_malloc(buf_bytes
);
1462 uncomp_buf
= g_malloc(cluster_bytes
);
1463 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_COMPRESSED
);
1464 ret
= bdrv_pread(extent
->file
,
1466 cluster_buf
, buf_bytes
);
1470 compressed_data
= cluster_buf
;
1471 buf_len
= cluster_bytes
;
1472 data_len
= cluster_bytes
;
1473 if (extent
->has_marker
) {
1474 marker
= (VmdkGrainMarker
*)cluster_buf
;
1475 compressed_data
= marker
->data
;
1476 data_len
= le32_to_cpu(marker
->size
);
1478 if (!data_len
|| data_len
> buf_bytes
) {
1482 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1488 if (offset_in_cluster
< 0 ||
1489 offset_in_cluster
+ bytes
> buf_len
) {
1493 qemu_iovec_from_buf(qiov
, 0, uncomp_buf
+ offset_in_cluster
, bytes
);
1498 g_free(cluster_buf
);
1502 static int coroutine_fn
1503 vmdk_co_preadv(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1504 QEMUIOVector
*qiov
, int flags
)
1506 BDRVVmdkState
*s
= bs
->opaque
;
1508 uint64_t n_bytes
, offset_in_cluster
;
1509 VmdkExtent
*extent
= NULL
;
1510 QEMUIOVector local_qiov
;
1511 uint64_t cluster_offset
;
1512 uint64_t bytes_done
= 0;
1514 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1515 qemu_co_mutex_lock(&s
->lock
);
1518 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
1523 ret
= get_cluster_offset(bs
, extent
, NULL
,
1524 offset
, false, &cluster_offset
, 0, 0);
1525 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1527 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
1528 - offset_in_cluster
);
1530 if (ret
!= VMDK_OK
) {
1531 /* if not allocated, try to read from parent image, if exist */
1532 if (bs
->backing
&& ret
!= VMDK_ZEROED
) {
1533 if (!vmdk_is_cid_valid(bs
)) {
1538 qemu_iovec_reset(&local_qiov
);
1539 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1541 /* qcow2 emits this on bs->file instead of bs->backing */
1542 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1543 ret
= bdrv_co_preadv(bs
->backing
, offset
, n_bytes
,
1549 qemu_iovec_memset(qiov
, bytes_done
, 0, n_bytes
);
1552 qemu_iovec_reset(&local_qiov
);
1553 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1555 ret
= vmdk_read_extent(extent
, cluster_offset
, offset_in_cluster
,
1556 &local_qiov
, n_bytes
);
1563 bytes_done
+= n_bytes
;
1568 qemu_co_mutex_unlock(&s
->lock
);
1569 qemu_iovec_destroy(&local_qiov
);
1576 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1577 * if possible, otherwise return -ENOTSUP.
1578 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1579 * with each cluster. By dry run we can find if the zero write
1580 * is possible without modifying image data.
1582 * Returns: error code with 0 for success.
1584 static int vmdk_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1585 uint64_t bytes
, QEMUIOVector
*qiov
,
1586 bool zeroed
, bool zero_dry_run
)
1588 BDRVVmdkState
*s
= bs
->opaque
;
1589 VmdkExtent
*extent
= NULL
;
1591 int64_t offset_in_cluster
, n_bytes
;
1592 uint64_t cluster_offset
;
1593 uint64_t bytes_done
= 0;
1594 VmdkMetaData m_data
;
1596 if (DIV_ROUND_UP(offset
, BDRV_SECTOR_SIZE
) > bs
->total_sectors
) {
1597 error_report("Wrong offset: offset=0x%" PRIx64
1598 " total_sectors=0x%" PRIx64
,
1599 offset
, bs
->total_sectors
);
1604 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
1608 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1609 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
1610 - offset_in_cluster
);
1612 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
1613 !(extent
->compressed
|| zeroed
),
1614 &cluster_offset
, offset_in_cluster
,
1615 offset_in_cluster
+ n_bytes
);
1616 if (extent
->compressed
) {
1617 if (ret
== VMDK_OK
) {
1618 /* Refuse write to allocated cluster for streamOptimized */
1619 error_report("Could not write to allocated cluster"
1620 " for streamOptimized");
1624 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
1625 true, &cluster_offset
, 0, 0);
1628 if (ret
== VMDK_ERROR
) {
1632 /* Do zeroed write, buf is ignored */
1633 if (extent
->has_zero_grain
&&
1634 offset_in_cluster
== 0 &&
1635 n_bytes
>= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
) {
1636 n_bytes
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
1637 if (!zero_dry_run
) {
1638 /* update L2 tables */
1639 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1648 ret
= vmdk_write_extent(extent
, cluster_offset
, offset_in_cluster
,
1649 qiov
, bytes_done
, n_bytes
, offset
);
1654 /* update L2 tables */
1655 if (vmdk_L2update(extent
, &m_data
,
1656 cluster_offset
>> BDRV_SECTOR_BITS
)
1664 bytes_done
+= n_bytes
;
1666 /* update CID on the first write every time the virtual disk is
1668 if (!s
->cid_updated
) {
1669 ret
= vmdk_write_cid(bs
, g_random_int());
1673 s
->cid_updated
= true;
1679 static int coroutine_fn
1680 vmdk_co_pwritev(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1681 QEMUIOVector
*qiov
, int flags
)
1684 BDRVVmdkState
*s
= bs
->opaque
;
1685 qemu_co_mutex_lock(&s
->lock
);
1686 ret
= vmdk_pwritev(bs
, offset
, bytes
, qiov
, false, false);
1687 qemu_co_mutex_unlock(&s
->lock
);
1691 static int coroutine_fn
1692 vmdk_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
1693 uint64_t bytes
, QEMUIOVector
*qiov
)
1695 return vmdk_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
1698 static int coroutine_fn
vmdk_co_pwrite_zeroes(BlockDriverState
*bs
,
1701 BdrvRequestFlags flags
)
1704 BDRVVmdkState
*s
= bs
->opaque
;
1706 qemu_co_mutex_lock(&s
->lock
);
1707 /* write zeroes could fail if sectors not aligned to cluster, test it with
1708 * dry_run == true before really updating image */
1709 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, true);
1711 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, false);
1713 qemu_co_mutex_unlock(&s
->lock
);
1717 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1718 bool flat
, bool compress
, bool zeroed_grain
,
1719 QemuOpts
*opts
, Error
**errp
)
1722 BlockBackend
*blk
= NULL
;
1724 Error
*local_err
= NULL
;
1725 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1726 uint32_t *gd_buf
= NULL
;
1729 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1731 error_propagate(errp
, local_err
);
1735 blk
= blk_new_open(filename
, NULL
, NULL
,
1736 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
1739 error_propagate(errp
, local_err
);
1744 blk_set_allow_write_beyond_eof(blk
, true);
1747 ret
= blk_truncate(blk
, filesize
, PREALLOC_MODE_OFF
, errp
);
1750 magic
= cpu_to_be32(VMDK4_MAGIC
);
1751 memset(&header
, 0, sizeof(header
));
1754 } else if (zeroed_grain
) {
1759 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1760 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1761 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1762 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1763 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1764 header
.granularity
= 128;
1765 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1767 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1768 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1770 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1771 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1773 header
.desc_offset
= 1;
1774 header
.desc_size
= 20;
1775 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1776 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1777 header
.grain_offset
=
1778 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1779 header
.granularity
);
1780 /* swap endianness for all header fields */
1781 header
.version
= cpu_to_le32(header
.version
);
1782 header
.flags
= cpu_to_le32(header
.flags
);
1783 header
.capacity
= cpu_to_le64(header
.capacity
);
1784 header
.granularity
= cpu_to_le64(header
.granularity
);
1785 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1786 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1787 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1788 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1789 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1790 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1791 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1793 header
.check_bytes
[0] = 0xa;
1794 header
.check_bytes
[1] = 0x20;
1795 header
.check_bytes
[2] = 0xd;
1796 header
.check_bytes
[3] = 0xa;
1798 /* write all the data */
1799 ret
= blk_pwrite(blk
, 0, &magic
, sizeof(magic
), 0);
1801 error_setg(errp
, QERR_IO_ERROR
);
1804 ret
= blk_pwrite(blk
, sizeof(magic
), &header
, sizeof(header
), 0);
1806 error_setg(errp
, QERR_IO_ERROR
);
1810 ret
= blk_truncate(blk
, le64_to_cpu(header
.grain_offset
) << 9,
1811 PREALLOC_MODE_OFF
, errp
);
1816 /* write grain directory */
1817 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1818 gd_buf
= g_malloc0(gd_buf_size
);
1819 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1820 i
< gt_count
; i
++, tmp
+= gt_size
) {
1821 gd_buf
[i
] = cpu_to_le32(tmp
);
1823 ret
= blk_pwrite(blk
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1824 gd_buf
, gd_buf_size
, 0);
1826 error_setg(errp
, QERR_IO_ERROR
);
1830 /* write backup grain directory */
1831 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1832 i
< gt_count
; i
++, tmp
+= gt_size
) {
1833 gd_buf
[i
] = cpu_to_le32(tmp
);
1835 ret
= blk_pwrite(blk
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1836 gd_buf
, gd_buf_size
, 0);
1838 error_setg(errp
, QERR_IO_ERROR
);
1851 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1852 char *postfix
, size_t buf_len
, Error
**errp
)
1856 if (filename
== NULL
|| !strlen(filename
)) {
1857 error_setg(errp
, "No filename provided");
1860 p
= strrchr(filename
, '/');
1862 p
= strrchr(filename
, '\\');
1865 p
= strrchr(filename
, ':');
1869 if (p
- filename
>= buf_len
) {
1872 pstrcpy(path
, p
- filename
+ 1, filename
);
1877 q
= strrchr(p
, '.');
1879 pstrcpy(prefix
, buf_len
, p
);
1882 if (q
- p
>= buf_len
) {
1885 pstrcpy(prefix
, q
- p
+ 1, p
);
1886 pstrcpy(postfix
, buf_len
, q
);
1891 static int coroutine_fn
vmdk_co_create_opts(const char *filename
, QemuOpts
*opts
,
1895 BlockBackend
*new_blk
= NULL
;
1896 Error
*local_err
= NULL
;
1898 int64_t total_size
= 0, filesize
;
1899 char *adapter_type
= NULL
;
1900 char *backing_file
= NULL
;
1901 char *hw_version
= NULL
;
1904 bool flat
, split
, compress
;
1905 GString
*ext_desc_lines
;
1906 char *path
= g_malloc0(PATH_MAX
);
1907 char *prefix
= g_malloc0(PATH_MAX
);
1908 char *postfix
= g_malloc0(PATH_MAX
);
1909 char *desc_line
= g_malloc0(BUF_SIZE
);
1910 char *ext_filename
= g_malloc0(PATH_MAX
);
1911 char *desc_filename
= g_malloc0(PATH_MAX
);
1912 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1913 const char *desc_extent_line
;
1914 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
1915 uint32_t parent_cid
= 0xffffffff;
1916 uint32_t number_heads
= 16;
1917 bool zeroed_grain
= false;
1918 uint32_t desc_offset
= 0, desc_len
;
1919 const char desc_template
[] =
1920 "# Disk DescriptorFile\n"
1923 "parentCID=%" PRIx32
"\n"
1924 "createType=\"%s\"\n"
1927 "# Extent description\n"
1930 "# The Disk Data Base\n"
1933 "ddb.virtualHWVersion = \"%s\"\n"
1934 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1935 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1936 "ddb.geometry.sectors = \"63\"\n"
1937 "ddb.adapterType = \"%s\"\n";
1939 ext_desc_lines
= g_string_new(NULL
);
1941 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1945 /* Read out options */
1946 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1948 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1949 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1950 hw_version
= qemu_opt_get_del(opts
, BLOCK_OPT_HWVERSION
);
1951 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1952 if (strcmp(hw_version
, "undefined")) {
1954 "compat6 cannot be enabled with hwversion set");
1959 hw_version
= g_strdup("6");
1961 if (strcmp(hw_version
, "undefined") == 0) {
1963 hw_version
= g_strdup("4");
1965 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1966 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1967 zeroed_grain
= true;
1970 if (!adapter_type
) {
1971 adapter_type
= g_strdup("ide");
1972 } else if (strcmp(adapter_type
, "ide") &&
1973 strcmp(adapter_type
, "buslogic") &&
1974 strcmp(adapter_type
, "lsilogic") &&
1975 strcmp(adapter_type
, "legacyESX")) {
1976 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1980 if (strcmp(adapter_type
, "ide") != 0) {
1981 /* that's the number of heads with which vmware operates when
1982 creating, exporting, etc. vmdk files with a non-ide adapter type */
1986 /* Default format to monolithicSparse */
1987 fmt
= g_strdup("monolithicSparse");
1988 } else if (strcmp(fmt
, "monolithicFlat") &&
1989 strcmp(fmt
, "monolithicSparse") &&
1990 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1991 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1992 strcmp(fmt
, "streamOptimized")) {
1993 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1997 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1998 strcmp(fmt
, "twoGbMaxExtentSparse"));
1999 flat
= !(strcmp(fmt
, "monolithicFlat") &&
2000 strcmp(fmt
, "twoGbMaxExtentFlat"));
2001 compress
= !strcmp(fmt
, "streamOptimized");
2003 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
2005 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
2007 if (flat
&& backing_file
) {
2008 error_setg(errp
, "Flat image can't have backing file");
2012 if (flat
&& zeroed_grain
) {
2013 error_setg(errp
, "Flat image can't enable zeroed grain");
2019 char *full_backing
= g_new0(char, PATH_MAX
);
2020 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
2021 full_backing
, PATH_MAX
,
2024 g_free(full_backing
);
2025 error_propagate(errp
, local_err
);
2030 blk
= blk_new_open(full_backing
, NULL
, NULL
,
2031 BDRV_O_NO_BACKING
, errp
);
2032 g_free(full_backing
);
2037 if (strcmp(blk_bs(blk
)->drv
->format_name
, "vmdk")) {
2042 ret
= vmdk_read_cid(blk_bs(blk
), 0, &parent_cid
);
2047 snprintf(parent_desc_line
, BUF_SIZE
,
2048 "parentFileNameHint=\"%s\"", backing_file
);
2051 /* Create extents */
2052 filesize
= total_size
;
2053 while (filesize
> 0) {
2054 int64_t size
= filesize
;
2056 if (split
&& size
> split_size
) {
2060 snprintf(desc_filename
, PATH_MAX
, "%s-%c%03d%s",
2061 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
2063 snprintf(desc_filename
, PATH_MAX
, "%s-flat%s", prefix
, postfix
);
2065 snprintf(desc_filename
, PATH_MAX
, "%s%s", prefix
, postfix
);
2067 snprintf(ext_filename
, PATH_MAX
, "%s%s", path
, desc_filename
);
2069 if (vmdk_create_extent(ext_filename
, size
,
2070 flat
, compress
, zeroed_grain
, opts
, errp
)) {
2076 /* Format description line */
2077 snprintf(desc_line
, BUF_SIZE
,
2078 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
2079 g_string_append(ext_desc_lines
, desc_line
);
2081 /* generate descriptor file */
2082 desc
= g_strdup_printf(desc_template
,
2087 ext_desc_lines
->str
,
2090 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
2093 desc_len
= strlen(desc
);
2094 /* the descriptor offset = 0x200 */
2095 if (!split
&& !flat
) {
2096 desc_offset
= 0x200;
2098 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2100 error_propagate(errp
, local_err
);
2105 new_blk
= blk_new_open(filename
, NULL
, NULL
,
2106 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2108 if (new_blk
== NULL
) {
2109 error_propagate(errp
, local_err
);
2114 blk_set_allow_write_beyond_eof(new_blk
, true);
2116 ret
= blk_pwrite(new_blk
, desc_offset
, desc
, desc_len
, 0);
2118 error_setg_errno(errp
, -ret
, "Could not write description");
2121 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2122 * for description file */
2123 if (desc_offset
== 0) {
2124 ret
= blk_truncate(new_blk
, desc_len
, PREALLOC_MODE_OFF
, errp
);
2130 g_free(adapter_type
);
2131 g_free(backing_file
);
2139 g_free(ext_filename
);
2140 g_free(desc_filename
);
2141 g_free(parent_desc_line
);
2142 g_string_free(ext_desc_lines
, true);
2146 static void vmdk_close(BlockDriverState
*bs
)
2148 BDRVVmdkState
*s
= bs
->opaque
;
2150 vmdk_free_extents(bs
);
2151 g_free(s
->create_type
);
2153 migrate_del_blocker(s
->migration_blocker
);
2154 error_free(s
->migration_blocker
);
2157 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
2159 BDRVVmdkState
*s
= bs
->opaque
;
2163 for (i
= 0; i
< s
->num_extents
; i
++) {
2164 err
= bdrv_co_flush(s
->extents
[i
].file
->bs
);
2172 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2177 BDRVVmdkState
*s
= bs
->opaque
;
2179 ret
= bdrv_get_allocated_file_size(bs
->file
->bs
);
2183 for (i
= 0; i
< s
->num_extents
; i
++) {
2184 if (s
->extents
[i
].file
== bs
->file
) {
2187 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
->bs
);
2196 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2199 BDRVVmdkState
*s
= bs
->opaque
;
2201 /* If has a flat extent and its underlying storage doesn't have zero init,
2203 for (i
= 0; i
< s
->num_extents
; i
++) {
2204 if (s
->extents
[i
].flat
) {
2205 if (!bdrv_has_zero_init(s
->extents
[i
].file
->bs
)) {
2213 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2215 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2217 *info
= (ImageInfo
){
2218 .filename
= g_strdup(extent
->file
->bs
->filename
),
2219 .format
= g_strdup(extent
->type
),
2220 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2221 .compressed
= extent
->compressed
,
2222 .has_compressed
= extent
->compressed
,
2223 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2224 .has_cluster_size
= !extent
->flat
,
2230 static int coroutine_fn
vmdk_co_check(BlockDriverState
*bs
,
2231 BdrvCheckResult
*result
,
2234 BDRVVmdkState
*s
= bs
->opaque
;
2235 VmdkExtent
*extent
= NULL
;
2236 int64_t sector_num
= 0;
2237 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2239 uint64_t cluster_offset
;
2246 if (sector_num
>= total_sectors
) {
2249 extent
= find_extent(s
, sector_num
, extent
);
2252 "ERROR: could not find extent for sector %" PRId64
"\n",
2257 ret
= get_cluster_offset(bs
, extent
, NULL
,
2258 sector_num
<< BDRV_SECTOR_BITS
,
2259 false, &cluster_offset
, 0, 0);
2260 if (ret
== VMDK_ERROR
) {
2262 "ERROR: could not get cluster_offset for sector %"
2263 PRId64
"\n", sector_num
);
2266 if (ret
== VMDK_OK
) {
2267 int64_t extent_len
= bdrv_getlength(extent
->file
->bs
);
2268 if (extent_len
< 0) {
2270 "ERROR: could not get extent file length for sector %"
2271 PRId64
"\n", sector_num
);
2275 if (cluster_offset
>= extent_len
) {
2277 "ERROR: cluster offset for sector %"
2278 PRId64
" points after EOF\n", sector_num
);
2283 sector_num
+= extent
->cluster_sectors
;
2286 result
->corruptions
++;
2290 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2293 BDRVVmdkState
*s
= bs
->opaque
;
2294 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2295 ImageInfoList
**next
;
2297 *spec_info
= (ImageInfoSpecific
){
2298 .type
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2300 .vmdk
.data
= g_new0(ImageInfoSpecificVmdk
, 1),
2304 *spec_info
->u
.vmdk
.data
= (ImageInfoSpecificVmdk
) {
2305 .create_type
= g_strdup(s
->create_type
),
2307 .parent_cid
= s
->parent_cid
,
2310 next
= &spec_info
->u
.vmdk
.data
->extents
;
2311 for (i
= 0; i
< s
->num_extents
; i
++) {
2312 *next
= g_new0(ImageInfoList
, 1);
2313 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2314 (*next
)->next
= NULL
;
2315 next
= &(*next
)->next
;
2321 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
2323 return a
->flat
== b
->flat
&&
2324 a
->compressed
== b
->compressed
&&
2325 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
2328 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2331 BDRVVmdkState
*s
= bs
->opaque
;
2332 assert(s
->num_extents
);
2334 /* See if we have multiple extents but they have different cases */
2335 for (i
= 1; i
< s
->num_extents
; i
++) {
2336 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
2340 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2341 if (!s
->extents
[0].flat
) {
2342 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2347 static QemuOptsList vmdk_create_opts
= {
2348 .name
= "vmdk-create-opts",
2349 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2352 .name
= BLOCK_OPT_SIZE
,
2353 .type
= QEMU_OPT_SIZE
,
2354 .help
= "Virtual disk size"
2357 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2358 .type
= QEMU_OPT_STRING
,
2359 .help
= "Virtual adapter type, can be one of "
2360 "ide (default), lsilogic, buslogic or legacyESX"
2363 .name
= BLOCK_OPT_BACKING_FILE
,
2364 .type
= QEMU_OPT_STRING
,
2365 .help
= "File name of a base image"
2368 .name
= BLOCK_OPT_COMPAT6
,
2369 .type
= QEMU_OPT_BOOL
,
2370 .help
= "VMDK version 6 image",
2371 .def_value_str
= "off"
2374 .name
= BLOCK_OPT_HWVERSION
,
2375 .type
= QEMU_OPT_STRING
,
2376 .help
= "VMDK hardware version",
2377 .def_value_str
= "undefined"
2380 .name
= BLOCK_OPT_SUBFMT
,
2381 .type
= QEMU_OPT_STRING
,
2383 "VMDK flat extent format, can be one of "
2384 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2387 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2388 .type
= QEMU_OPT_BOOL
,
2389 .help
= "Enable efficient zero writes "
2390 "using the zeroed-grain GTE feature"
2392 { /* end of list */ }
2396 static BlockDriver bdrv_vmdk
= {
2397 .format_name
= "vmdk",
2398 .instance_size
= sizeof(BDRVVmdkState
),
2399 .bdrv_probe
= vmdk_probe
,
2400 .bdrv_open
= vmdk_open
,
2401 .bdrv_co_check
= vmdk_co_check
,
2402 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2403 .bdrv_child_perm
= bdrv_format_default_perms
,
2404 .bdrv_co_preadv
= vmdk_co_preadv
,
2405 .bdrv_co_pwritev
= vmdk_co_pwritev
,
2406 .bdrv_co_pwritev_compressed
= vmdk_co_pwritev_compressed
,
2407 .bdrv_co_pwrite_zeroes
= vmdk_co_pwrite_zeroes
,
2408 .bdrv_close
= vmdk_close
,
2409 .bdrv_co_create_opts
= vmdk_co_create_opts
,
2410 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2411 .bdrv_co_block_status
= vmdk_co_block_status
,
2412 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2413 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2414 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2415 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2416 .bdrv_get_info
= vmdk_get_info
,
2418 .supports_backing
= true,
2419 .create_opts
= &vmdk_create_opts
,
2422 static void bdrv_vmdk_init(void)
2424 bdrv_register(&bdrv_vmdk
);
2427 block_init(bdrv_vmdk_init
);