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/qdict.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qemu/error-report.h"
33 #include "qemu/module.h"
34 #include "qemu/option.h"
35 #include "qemu/bswap.h"
36 #include "qemu/memalign.h"
37 #include "migration/blocker.h"
38 #include "qemu/cutils.h"
41 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
42 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
43 #define VMDK4_COMPRESSION_DEFLATE 1
44 #define VMDK4_FLAG_NL_DETECT (1 << 0)
45 #define VMDK4_FLAG_RGD (1 << 1)
46 /* Zeroed-grain enable bit */
47 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
48 #define VMDK4_FLAG_COMPRESS (1 << 16)
49 #define VMDK4_FLAG_MARKER (1 << 17)
50 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
52 #define VMDK_EXTENT_MAX_SECTORS (1ULL << 32)
54 #define VMDK_GTE_ZEROED 0x1
56 /* VMDK internal error codes */
58 #define VMDK_ERROR (-1)
59 /* Cluster not allocated */
60 #define VMDK_UNALLOC (-2)
61 #define VMDK_ZEROED (-3)
63 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
64 #define BLOCK_OPT_TOOLSVERSION "toolsversion"
69 uint32_t disk_sectors
;
71 uint32_t l1dir_offset
;
73 uint32_t file_sectors
;
76 uint32_t sectors_per_track
;
77 } QEMU_PACKED VMDK3Header
;
86 /* Number of GrainTableEntries per GrainTable */
87 uint32_t num_gtes_per_gt
;
90 uint64_t grain_offset
;
93 uint16_t compressAlgorithm
;
94 } QEMU_PACKED VMDK4Header
;
96 typedef struct VMDKSESparseConstHeader
{
101 uint64_t grain_table_size
;
107 uint64_t volatile_header_offset
;
108 uint64_t volatile_header_size
;
109 uint64_t journal_header_offset
;
110 uint64_t journal_header_size
;
111 uint64_t journal_offset
;
112 uint64_t journal_size
;
113 uint64_t grain_dir_offset
;
114 uint64_t grain_dir_size
;
115 uint64_t grain_tables_offset
;
116 uint64_t grain_tables_size
;
117 uint64_t free_bitmap_offset
;
118 uint64_t free_bitmap_size
;
119 uint64_t backmap_offset
;
120 uint64_t backmap_size
;
121 uint64_t grains_offset
;
122 uint64_t grains_size
;
124 } QEMU_PACKED VMDKSESparseConstHeader
;
126 typedef struct VMDKSESparseVolatileHeader
{
128 uint64_t free_gt_number
;
129 uint64_t next_txn_seq_number
;
130 uint64_t replay_journal
;
132 } QEMU_PACKED VMDKSESparseVolatileHeader
;
134 #define L2_CACHE_SIZE 16
136 typedef struct VmdkExtent
{
143 uint64_t sesparse_l2_tables_offset
;
144 uint64_t sesparse_clusters_offset
;
149 int64_t flat_start_offset
;
150 int64_t l1_table_offset
;
151 int64_t l1_backup_table_offset
;
153 uint32_t *l1_backup_table
;
154 unsigned int l1_size
;
155 uint32_t l1_entry_sectors
;
157 unsigned int l2_size
;
159 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
160 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
162 int64_t cluster_sectors
;
163 int64_t next_cluster_sector
;
167 typedef struct BDRVVmdkState
{
169 uint64_t desc_offset
;
175 /* Extent array with num_extents entries, ascend ordered by address */
177 Error
*migration_blocker
;
181 typedef struct BDRVVmdkReopenState
{
182 bool *extents_using_bs_file
;
183 } BDRVVmdkReopenState
;
185 typedef struct VmdkMetaData
{
186 unsigned int l1_index
;
187 unsigned int l2_index
;
188 unsigned int l2_offset
;
190 uint32_t *l2_cache_entry
;
193 typedef struct VmdkGrainMarker
{
197 } QEMU_PACKED VmdkGrainMarker
;
200 MARKER_END_OF_STREAM
= 0,
201 MARKER_GRAIN_TABLE
= 1,
202 MARKER_GRAIN_DIRECTORY
= 2,
206 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
213 magic
= be32_to_cpu(*(uint32_t *)buf
);
214 if (magic
== VMDK3_MAGIC
||
215 magic
== VMDK4_MAGIC
) {
218 const char *p
= (const char *)buf
;
219 const char *end
= p
+ buf_size
;
222 /* skip comment line */
223 while (p
< end
&& *p
!= '\n') {
230 while (p
< end
&& *p
== ' ') {
233 /* skip '\r' if windows line endings used. */
234 if (p
< end
&& *p
== '\r') {
237 /* only accept blank lines before 'version=' line */
238 if (p
== end
|| *p
!= '\n') {
244 if (end
- p
>= strlen("version=X\n")) {
245 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
246 strncmp("version=2\n", p
, strlen("version=2\n")) == 0 ||
247 strncmp("version=3\n", p
, strlen("version=3\n")) == 0) {
251 if (end
- p
>= strlen("version=X\r\n")) {
252 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
253 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0 ||
254 strncmp("version=3\r\n", p
, strlen("version=3\r\n")) == 0) {
264 #define SECTOR_SIZE 512
265 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
266 #define BUF_SIZE 4096
267 #define HEADER_SIZE 512 /* first sector of 512 bytes */
269 static void vmdk_free_extents(BlockDriverState
*bs
)
272 BDRVVmdkState
*s
= bs
->opaque
;
275 for (i
= 0; i
< s
->num_extents
; i
++) {
279 g_free(e
->l1_backup_table
);
281 if (e
->file
!= bs
->file
) {
282 bdrv_unref_child(bs
, e
->file
);
288 static void vmdk_free_last_extent(BlockDriverState
*bs
)
290 BDRVVmdkState
*s
= bs
->opaque
;
292 if (s
->num_extents
== 0) {
296 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
299 /* Return -ve errno, or 0 on success and write CID into *pcid. */
300 static int vmdk_read_cid(BlockDriverState
*bs
, int parent
, uint32_t *pcid
)
304 const char *p_name
, *cid_str
;
306 BDRVVmdkState
*s
= bs
->opaque
;
309 desc
= g_malloc0(DESC_SIZE
);
310 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
316 cid_str
= "parentCID";
317 cid_str_size
= sizeof("parentCID");
320 cid_str_size
= sizeof("CID");
323 desc
[DESC_SIZE
- 1] = '\0';
324 p_name
= strstr(desc
, cid_str
);
325 if (p_name
== NULL
) {
329 p_name
+= cid_str_size
;
330 if (sscanf(p_name
, "%" SCNx32
, &cid
) != 1) {
342 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
344 char *desc
, *tmp_desc
;
345 char *p_name
, *tmp_str
;
346 BDRVVmdkState
*s
= bs
->opaque
;
349 desc
= g_malloc0(DESC_SIZE
);
350 tmp_desc
= g_malloc0(DESC_SIZE
);
351 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
356 desc
[DESC_SIZE
- 1] = '\0';
357 tmp_str
= strstr(desc
, "parentCID");
358 if (tmp_str
== NULL
) {
363 pstrcpy(tmp_desc
, DESC_SIZE
, tmp_str
);
364 p_name
= strstr(desc
, "CID");
365 if (p_name
!= NULL
) {
366 p_name
+= sizeof("CID");
367 snprintf(p_name
, DESC_SIZE
- (p_name
- desc
), "%" PRIx32
"\n", cid
);
368 pstrcat(desc
, DESC_SIZE
, tmp_desc
);
371 ret
= bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
379 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
381 BDRVVmdkState
*s
= bs
->opaque
;
384 if (!s
->cid_checked
&& bs
->backing
) {
385 BlockDriverState
*p_bs
= bs
->backing
->bs
;
387 if (strcmp(p_bs
->drv
->format_name
, "vmdk")) {
388 /* Backing file is not in vmdk format, so it does not have
389 * a CID, which makes the overlay's parent CID invalid */
393 if (vmdk_read_cid(p_bs
, 0, &cur_pcid
) != 0) {
394 /* read failure: report as not valid */
397 if (s
->parent_cid
!= cur_pcid
) {
402 s
->cid_checked
= true;
407 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
408 BlockReopenQueue
*queue
, Error
**errp
)
411 BDRVVmdkReopenState
*rs
;
414 assert(state
!= NULL
);
415 assert(state
->bs
!= NULL
);
416 assert(state
->opaque
== NULL
);
418 s
= state
->bs
->opaque
;
420 rs
= g_new0(BDRVVmdkReopenState
, 1);
424 * Check whether there are any extents stored in bs->file; if bs->file
425 * changes, we will need to update their .file pointers to follow suit
427 rs
->extents_using_bs_file
= g_new(bool, s
->num_extents
);
428 for (i
= 0; i
< s
->num_extents
; i
++) {
429 rs
->extents_using_bs_file
[i
] = s
->extents
[i
].file
== state
->bs
->file
;
435 static void vmdk_reopen_clean(BDRVReopenState
*state
)
437 BDRVVmdkReopenState
*rs
= state
->opaque
;
439 g_free(rs
->extents_using_bs_file
);
441 state
->opaque
= NULL
;
444 static void vmdk_reopen_commit(BDRVReopenState
*state
)
446 BDRVVmdkState
*s
= state
->bs
->opaque
;
447 BDRVVmdkReopenState
*rs
= state
->opaque
;
450 for (i
= 0; i
< s
->num_extents
; i
++) {
451 if (rs
->extents_using_bs_file
[i
]) {
452 s
->extents
[i
].file
= state
->bs
->file
;
456 vmdk_reopen_clean(state
);
459 static void vmdk_reopen_abort(BDRVReopenState
*state
)
461 vmdk_reopen_clean(state
);
464 static int vmdk_parent_open(BlockDriverState
*bs
)
468 BDRVVmdkState
*s
= bs
->opaque
;
471 desc
= g_malloc0(DESC_SIZE
+ 1);
472 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
478 p_name
= strstr(desc
, "parentFileNameHint");
479 if (p_name
!= NULL
) {
482 p_name
+= sizeof("parentFileNameHint") + 1;
483 end_name
= strchr(p_name
, '\"');
484 if (end_name
== NULL
) {
488 if ((end_name
- p_name
) > sizeof(bs
->auto_backing_file
) - 1) {
493 pstrcpy(bs
->auto_backing_file
, end_name
- p_name
+ 1, p_name
);
494 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
),
495 bs
->auto_backing_file
);
496 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
),
505 /* Create and append extent to the extent array. Return the added VmdkExtent
506 * address. return NULL if allocation failed. */
507 static int vmdk_add_extent(BlockDriverState
*bs
,
508 BdrvChild
*file
, bool flat
, int64_t sectors
,
509 int64_t l1_offset
, int64_t l1_backup_offset
,
511 int l2_size
, uint64_t cluster_sectors
,
512 VmdkExtent
**new_extent
,
516 BDRVVmdkState
*s
= bs
->opaque
;
519 if (cluster_sectors
> 0x200000) {
520 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
521 error_setg(errp
, "Invalid granularity, image may be corrupt");
524 if (l1_size
> 32 * 1024 * 1024) {
526 * Although with big capacity and small l1_entry_sectors, we can get a
527 * big l1_size, we don't want unbounded value to allocate the table.
528 * Limit it to 32M, which is enough to store:
529 * 8TB - for both VMDK3 & VMDK4 with
530 * minimal cluster size: 512B
531 * minimal L2 table size: 512 entries
532 * 8 TB is still more than the maximal value supported for
533 * VMDK3 & VMDK4 which is 2TB.
534 * 64TB - for "ESXi seSparse Extent"
535 * minimal cluster size: 512B (default is 4KB)
536 * L2 table size: 4096 entries (const).
537 * 64TB is more than the maximal value supported for
538 * seSparse VMDKs (which is slightly less than 64TB)
540 error_setg(errp
, "L1 size too big");
544 nb_sectors
= bdrv_nb_sectors(file
->bs
);
545 if (nb_sectors
< 0) {
549 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
550 extent
= &s
->extents
[s
->num_extents
];
553 memset(extent
, 0, sizeof(VmdkExtent
));
556 extent
->sectors
= sectors
;
557 extent
->l1_table_offset
= l1_offset
;
558 extent
->l1_backup_table_offset
= l1_backup_offset
;
559 extent
->l1_size
= l1_size
;
560 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
561 extent
->l2_size
= l2_size
;
562 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
563 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
564 extent
->entry_size
= sizeof(uint32_t);
566 if (s
->num_extents
> 1) {
567 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
569 extent
->end_sector
= extent
->sectors
;
571 bs
->total_sectors
= extent
->end_sector
;
573 *new_extent
= extent
;
578 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
585 /* read the L1 table */
586 l1_size
= extent
->l1_size
* extent
->entry_size
;
587 extent
->l1_table
= g_try_malloc(l1_size
);
588 if (l1_size
&& extent
->l1_table
== NULL
) {
592 ret
= bdrv_pread(extent
->file
,
593 extent
->l1_table_offset
,
597 bdrv_refresh_filename(extent
->file
->bs
);
598 error_setg_errno(errp
, -ret
,
599 "Could not read l1 table from extent '%s'",
600 extent
->file
->bs
->filename
);
603 for (i
= 0; i
< extent
->l1_size
; i
++) {
604 if (extent
->entry_size
== sizeof(uint64_t)) {
605 le64_to_cpus((uint64_t *)extent
->l1_table
+ i
);
607 assert(extent
->entry_size
== sizeof(uint32_t));
608 le32_to_cpus((uint32_t *)extent
->l1_table
+ i
);
612 if (extent
->l1_backup_table_offset
) {
613 assert(!extent
->sesparse
);
614 extent
->l1_backup_table
= g_try_malloc(l1_size
);
615 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
619 ret
= bdrv_pread(extent
->file
,
620 extent
->l1_backup_table_offset
,
621 extent
->l1_backup_table
,
624 bdrv_refresh_filename(extent
->file
->bs
);
625 error_setg_errno(errp
, -ret
,
626 "Could not read l1 backup table from extent '%s'",
627 extent
->file
->bs
->filename
);
630 for (i
= 0; i
< extent
->l1_size
; i
++) {
631 le32_to_cpus(&extent
->l1_backup_table
[i
]);
636 g_malloc(extent
->entry_size
* extent
->l2_size
* L2_CACHE_SIZE
);
639 g_free(extent
->l1_backup_table
);
641 g_free(extent
->l1_table
);
645 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
647 int flags
, Error
**errp
)
652 VmdkExtent
*extent
= NULL
;
654 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
656 bdrv_refresh_filename(file
->bs
);
657 error_setg_errno(errp
, -ret
,
658 "Could not read header from file '%s'",
662 ret
= vmdk_add_extent(bs
, file
, false,
663 le32_to_cpu(header
.disk_sectors
),
664 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
666 le32_to_cpu(header
.l1dir_size
),
668 le32_to_cpu(header
.granularity
),
674 ret
= vmdk_init_tables(bs
, extent
, errp
);
676 /* free extent allocated by vmdk_add_extent */
677 vmdk_free_last_extent(bs
);
682 #define SESPARSE_CONST_HEADER_MAGIC UINT64_C(0x00000000cafebabe)
683 #define SESPARSE_VOLATILE_HEADER_MAGIC UINT64_C(0x00000000cafecafe)
685 /* Strict checks - format not officially documented */
686 static int check_se_sparse_const_header(VMDKSESparseConstHeader
*header
,
689 header
->magic
= le64_to_cpu(header
->magic
);
690 header
->version
= le64_to_cpu(header
->version
);
691 header
->grain_size
= le64_to_cpu(header
->grain_size
);
692 header
->grain_table_size
= le64_to_cpu(header
->grain_table_size
);
693 header
->flags
= le64_to_cpu(header
->flags
);
694 header
->reserved1
= le64_to_cpu(header
->reserved1
);
695 header
->reserved2
= le64_to_cpu(header
->reserved2
);
696 header
->reserved3
= le64_to_cpu(header
->reserved3
);
697 header
->reserved4
= le64_to_cpu(header
->reserved4
);
699 header
->volatile_header_offset
=
700 le64_to_cpu(header
->volatile_header_offset
);
701 header
->volatile_header_size
= le64_to_cpu(header
->volatile_header_size
);
703 header
->journal_header_offset
= le64_to_cpu(header
->journal_header_offset
);
704 header
->journal_header_size
= le64_to_cpu(header
->journal_header_size
);
706 header
->journal_offset
= le64_to_cpu(header
->journal_offset
);
707 header
->journal_size
= le64_to_cpu(header
->journal_size
);
709 header
->grain_dir_offset
= le64_to_cpu(header
->grain_dir_offset
);
710 header
->grain_dir_size
= le64_to_cpu(header
->grain_dir_size
);
712 header
->grain_tables_offset
= le64_to_cpu(header
->grain_tables_offset
);
713 header
->grain_tables_size
= le64_to_cpu(header
->grain_tables_size
);
715 header
->free_bitmap_offset
= le64_to_cpu(header
->free_bitmap_offset
);
716 header
->free_bitmap_size
= le64_to_cpu(header
->free_bitmap_size
);
718 header
->backmap_offset
= le64_to_cpu(header
->backmap_offset
);
719 header
->backmap_size
= le64_to_cpu(header
->backmap_size
);
721 header
->grains_offset
= le64_to_cpu(header
->grains_offset
);
722 header
->grains_size
= le64_to_cpu(header
->grains_size
);
724 if (header
->magic
!= SESPARSE_CONST_HEADER_MAGIC
) {
725 error_setg(errp
, "Bad const header magic: 0x%016" PRIx64
,
730 if (header
->version
!= 0x0000000200000001) {
731 error_setg(errp
, "Unsupported version: 0x%016" PRIx64
,
736 if (header
->grain_size
!= 8) {
737 error_setg(errp
, "Unsupported grain size: %" PRIu64
,
742 if (header
->grain_table_size
!= 64) {
743 error_setg(errp
, "Unsupported grain table size: %" PRIu64
,
744 header
->grain_table_size
);
748 if (header
->flags
!= 0) {
749 error_setg(errp
, "Unsupported flags: 0x%016" PRIx64
,
754 if (header
->reserved1
!= 0 || header
->reserved2
!= 0 ||
755 header
->reserved3
!= 0 || header
->reserved4
!= 0) {
756 error_setg(errp
, "Unsupported reserved bits:"
757 " 0x%016" PRIx64
" 0x%016" PRIx64
758 " 0x%016" PRIx64
" 0x%016" PRIx64
,
759 header
->reserved1
, header
->reserved2
,
760 header
->reserved3
, header
->reserved4
);
764 /* check that padding is 0 */
765 if (!buffer_is_zero(header
->pad
, sizeof(header
->pad
))) {
766 error_setg(errp
, "Unsupported non-zero const header padding");
773 static int check_se_sparse_volatile_header(VMDKSESparseVolatileHeader
*header
,
776 header
->magic
= le64_to_cpu(header
->magic
);
777 header
->free_gt_number
= le64_to_cpu(header
->free_gt_number
);
778 header
->next_txn_seq_number
= le64_to_cpu(header
->next_txn_seq_number
);
779 header
->replay_journal
= le64_to_cpu(header
->replay_journal
);
781 if (header
->magic
!= SESPARSE_VOLATILE_HEADER_MAGIC
) {
782 error_setg(errp
, "Bad volatile header magic: 0x%016" PRIx64
,
787 if (header
->replay_journal
) {
788 error_setg(errp
, "Image is dirty, Replaying journal not supported");
792 /* check that padding is 0 */
793 if (!buffer_is_zero(header
->pad
, sizeof(header
->pad
))) {
794 error_setg(errp
, "Unsupported non-zero volatile header padding");
801 static int vmdk_open_se_sparse(BlockDriverState
*bs
,
803 int flags
, Error
**errp
)
806 VMDKSESparseConstHeader const_header
;
807 VMDKSESparseVolatileHeader volatile_header
;
808 VmdkExtent
*extent
= NULL
;
810 ret
= bdrv_apply_auto_read_only(bs
,
811 "No write support for seSparse images available", errp
);
816 assert(sizeof(const_header
) == SECTOR_SIZE
);
818 ret
= bdrv_pread(file
, 0, &const_header
, sizeof(const_header
));
820 bdrv_refresh_filename(file
->bs
);
821 error_setg_errno(errp
, -ret
,
822 "Could not read const header from file '%s'",
827 /* check const header */
828 ret
= check_se_sparse_const_header(&const_header
, errp
);
833 assert(sizeof(volatile_header
) == SECTOR_SIZE
);
835 ret
= bdrv_pread(file
,
836 const_header
.volatile_header_offset
* SECTOR_SIZE
,
837 &volatile_header
, sizeof(volatile_header
));
839 bdrv_refresh_filename(file
->bs
);
840 error_setg_errno(errp
, -ret
,
841 "Could not read volatile header from file '%s'",
846 /* check volatile header */
847 ret
= check_se_sparse_volatile_header(&volatile_header
, errp
);
852 ret
= vmdk_add_extent(bs
, file
, false,
853 const_header
.capacity
,
854 const_header
.grain_dir_offset
* SECTOR_SIZE
,
856 const_header
.grain_dir_size
*
857 SECTOR_SIZE
/ sizeof(uint64_t),
858 const_header
.grain_table_size
*
859 SECTOR_SIZE
/ sizeof(uint64_t),
860 const_header
.grain_size
,
867 extent
->sesparse
= true;
868 extent
->sesparse_l2_tables_offset
= const_header
.grain_tables_offset
;
869 extent
->sesparse_clusters_offset
= const_header
.grains_offset
;
870 extent
->entry_size
= sizeof(uint64_t);
872 ret
= vmdk_init_tables(bs
, extent
, errp
);
874 /* free extent allocated by vmdk_add_extent */
875 vmdk_free_last_extent(bs
);
881 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
882 QDict
*options
, Error
**errp
);
884 static char *vmdk_read_desc(BdrvChild
*file
, uint64_t desc_offset
, Error
**errp
)
890 size
= bdrv_getlength(file
->bs
);
892 error_setg_errno(errp
, -size
, "Could not access file");
897 /* Both descriptor file and sparse image must be much larger than 4
898 * bytes, also callers of vmdk_read_desc want to compare the first 4
899 * bytes with VMDK4_MAGIC, let's error out if less is read. */
900 error_setg(errp
, "File is too small, not a valid image");
904 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
905 buf
= g_malloc(size
+ 1);
907 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
909 error_setg_errno(errp
, -ret
, "Could not read from file");
918 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
920 int flags
, QDict
*options
, Error
**errp
)
924 uint32_t l1_size
, l1_entry_sectors
;
926 VmdkExtent
*extent
= NULL
;
927 BDRVVmdkState
*s
= bs
->opaque
;
928 int64_t l1_backup_offset
= 0;
931 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
933 bdrv_refresh_filename(file
->bs
);
934 error_setg_errno(errp
, -ret
,
935 "Could not read header from file '%s'",
939 if (header
.capacity
== 0) {
940 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
942 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
946 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
952 if (!s
->create_type
) {
953 s
->create_type
= g_strdup("monolithicSparse");
956 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
958 * The footer takes precedence over the header, so read it in. The
959 * footer starts at offset -1024 from the end: One sector for the
960 * footer, and another one for the end-of-stream marker.
967 uint8_t pad
[512 - 16];
968 } QEMU_PACKED footer_marker
;
972 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
978 uint8_t pad
[512 - 16];
979 } QEMU_PACKED eos_marker
;
980 } QEMU_PACKED footer
;
982 ret
= bdrv_pread(file
,
983 bs
->file
->bs
->total_sectors
* 512 - 1536,
984 &footer
, sizeof(footer
));
986 error_setg_errno(errp
, -ret
, "Failed to read footer");
990 /* Some sanity checks for the footer */
991 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
992 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
993 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
994 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
995 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
996 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
998 error_setg(errp
, "Invalid footer");
1002 header
= footer
.header
;
1006 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
1007 if (le32_to_cpu(header
.version
) > 3) {
1008 error_setg(errp
, "Unsupported VMDK version %" PRIu32
,
1009 le32_to_cpu(header
.version
));
1011 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
) &&
1013 /* VMware KB 2064959 explains that version 3 added support for
1014 * persistent changed block tracking (CBT), and backup software can
1015 * read it as version=1 if it doesn't care about the changed area
1016 * information. So we are safe to enable read only. */
1017 error_setg(errp
, "VMDK version 3 must be read only");
1021 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
1022 error_setg(errp
, "L2 table size too big");
1026 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
1027 * le64_to_cpu(header
.granularity
);
1028 if (l1_entry_sectors
== 0) {
1029 error_setg(errp
, "L1 entry size is invalid");
1032 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
1034 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
1035 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
1037 if (bdrv_nb_sectors(file
->bs
) < le64_to_cpu(header
.grain_offset
)) {
1038 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
1039 (int64_t)(le64_to_cpu(header
.grain_offset
)
1040 * BDRV_SECTOR_SIZE
));
1044 ret
= vmdk_add_extent(bs
, file
, false,
1045 le64_to_cpu(header
.capacity
),
1046 le64_to_cpu(header
.gd_offset
) << 9,
1049 le32_to_cpu(header
.num_gtes_per_gt
),
1050 le64_to_cpu(header
.granularity
),
1056 extent
->compressed
=
1057 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
1058 if (extent
->compressed
) {
1059 g_free(s
->create_type
);
1060 s
->create_type
= g_strdup("streamOptimized");
1062 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
1063 extent
->version
= le32_to_cpu(header
.version
);
1064 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
1065 ret
= vmdk_init_tables(bs
, extent
, errp
);
1067 /* free extent allocated by vmdk_add_extent */
1068 vmdk_free_last_extent(bs
);
1073 /* find an option value out of descriptor file */
1074 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
1075 char *buf
, int buf_size
)
1077 char *opt_pos
, *opt_end
;
1078 const char *end
= desc
+ strlen(desc
);
1080 opt_pos
= strstr(desc
, opt_name
);
1084 /* Skip "=\"" following opt_name */
1085 opt_pos
+= strlen(opt_name
) + 2;
1086 if (opt_pos
>= end
) {
1090 while (opt_end
< end
&& *opt_end
!= '"') {
1093 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
1096 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
1100 /* Open an extent file and append to bs array */
1101 static int vmdk_open_sparse(BlockDriverState
*bs
, BdrvChild
*file
, int flags
,
1102 char *buf
, QDict
*options
, Error
**errp
)
1106 magic
= ldl_be_p(buf
);
1109 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
1111 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
1113 error_setg(errp
, "Image not in VMDK format");
1118 static const char *next_line(const char *s
)
1129 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
1130 QDict
*options
, Error
**errp
)
1138 int64_t sectors
= 0;
1139 int64_t flat_offset
;
1140 char *desc_file_dir
= NULL
;
1142 BdrvChild
*extent_file
;
1143 BdrvChildRole extent_role
;
1144 BDRVVmdkState
*s
= bs
->opaque
;
1145 VmdkExtent
*extent
= NULL
;
1146 char extent_opt_prefix
[32];
1147 Error
*local_err
= NULL
;
1149 for (p
= desc
; *p
; p
= next_line(p
)) {
1150 /* parse extent line in one of below formats:
1152 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
1153 * RW [size in sectors] SPARSE "file-name.vmdk"
1154 * RW [size in sectors] VMFS "file-name.vmdk"
1155 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
1156 * RW [size in sectors] SESPARSE "file-name.vmdk"
1159 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
1160 access
, §ors
, type
, fname
, &flat_offset
);
1161 if (matches
< 4 || strcmp(access
, "RW")) {
1163 } else if (!strcmp(type
, "FLAT")) {
1164 if (matches
!= 5 || flat_offset
< 0) {
1167 } else if (!strcmp(type
, "VMFS")) {
1173 } else if (matches
!= 4) {
1178 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
1179 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE") &&
1180 strcmp(type
, "SESPARSE")) ||
1181 (strcmp(access
, "RW"))) {
1185 if (path_is_absolute(fname
)) {
1186 extent_path
= g_strdup(fname
);
1188 if (!desc_file_dir
) {
1189 desc_file_dir
= bdrv_dirname(bs
->file
->bs
, errp
);
1190 if (!desc_file_dir
) {
1191 bdrv_refresh_filename(bs
->file
->bs
);
1192 error_prepend(errp
, "Cannot use relative paths with VMDK "
1193 "descriptor file '%s': ",
1194 bs
->file
->bs
->filename
);
1200 extent_path
= g_strconcat(desc_file_dir
, fname
, NULL
);
1203 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
1206 extent_role
= BDRV_CHILD_DATA
;
1207 if (strcmp(type
, "FLAT") != 0 && strcmp(type
, "VMFS") != 0) {
1208 /* non-flat extents have metadata */
1209 extent_role
|= BDRV_CHILD_METADATA
;
1212 extent_file
= bdrv_open_child(extent_path
, options
, extent_opt_prefix
,
1213 bs
, &child_of_bds
, extent_role
, false,
1215 g_free(extent_path
);
1217 error_propagate(errp
, local_err
);
1222 /* save to extents array */
1223 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
1226 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
1227 0, 0, 0, 0, 0, &extent
, errp
);
1229 bdrv_unref_child(bs
, extent_file
);
1232 extent
->flat_start_offset
= flat_offset
<< 9;
1233 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
1234 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
1235 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
1239 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
1244 bdrv_unref_child(bs
, extent_file
);
1247 extent
= &s
->extents
[s
->num_extents
- 1];
1248 } else if (!strcmp(type
, "SESPARSE")) {
1249 ret
= vmdk_open_se_sparse(bs
, extent_file
, bs
->open_flags
, errp
);
1251 bdrv_unref_child(bs
, extent_file
);
1254 extent
= &s
->extents
[s
->num_extents
- 1];
1256 error_setg(errp
, "Unsupported extent type '%s'", type
);
1257 bdrv_unref_child(bs
, extent_file
);
1261 extent
->type
= g_strdup(type
);
1270 if (np
[-1] == '\n') {
1273 error_setg(errp
, "Invalid extent line: %.*s", (int)(np
- p
), p
);
1277 g_free(desc_file_dir
);
1281 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
1282 QDict
*options
, Error
**errp
)
1286 BDRVVmdkState
*s
= bs
->opaque
;
1288 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
1289 error_setg(errp
, "invalid VMDK image descriptor");
1293 if (strcmp(ct
, "monolithicFlat") &&
1294 strcmp(ct
, "vmfs") &&
1295 strcmp(ct
, "vmfsSparse") &&
1296 strcmp(ct
, "seSparse") &&
1297 strcmp(ct
, "twoGbMaxExtentSparse") &&
1298 strcmp(ct
, "twoGbMaxExtentFlat")) {
1299 error_setg(errp
, "Unsupported image type '%s'", ct
);
1303 s
->create_type
= g_strdup(ct
);
1305 ret
= vmdk_parse_extents(buf
, bs
, options
, errp
);
1310 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1315 BDRVVmdkState
*s
= bs
->opaque
;
1318 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_of_bds
,
1319 BDRV_CHILD_IMAGE
, false, errp
);
1324 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
1329 magic
= ldl_be_p(buf
);
1333 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
,
1335 s
->desc_offset
= 0x200;
1338 /* No data in the descriptor file */
1339 bs
->file
->role
&= ~BDRV_CHILD_DATA
;
1341 /* Must succeed because we have given up permissions if anything */
1342 bdrv_child_refresh_perms(bs
, bs
->file
, &error_abort
);
1344 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
1351 /* try to open parent images, if exist */
1352 ret
= vmdk_parent_open(bs
);
1356 ret
= vmdk_read_cid(bs
, 0, &s
->cid
);
1360 ret
= vmdk_read_cid(bs
, 1, &s
->parent_cid
);
1364 qemu_co_mutex_init(&s
->lock
);
1366 /* Disable migration when VMDK images are used */
1367 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
1368 "does not support live migration",
1369 bdrv_get_device_or_node_name(bs
));
1370 ret
= migrate_add_blocker(s
->migration_blocker
, errp
);
1372 error_free(s
->migration_blocker
);
1381 g_free(s
->create_type
);
1382 s
->create_type
= NULL
;
1383 vmdk_free_extents(bs
);
1388 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1390 BDRVVmdkState
*s
= bs
->opaque
;
1393 for (i
= 0; i
< s
->num_extents
; i
++) {
1394 if (!s
->extents
[i
].flat
) {
1395 bs
->bl
.pwrite_zeroes_alignment
=
1396 MAX(bs
->bl
.pwrite_zeroes_alignment
,
1397 s
->extents
[i
].cluster_sectors
<< BDRV_SECTOR_BITS
);
1405 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1406 * to the cluster at @cluster_sector_num. If @zeroed is true, we're overwriting
1407 * a zeroed cluster in the current layer and must not copy data from the
1410 * If @skip_start_sector < @skip_end_sector, the relative range
1411 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1412 * it for call to write user data in the request.
1414 static int get_whole_cluster(BlockDriverState
*bs
,
1416 uint64_t cluster_offset
,
1418 uint64_t skip_start_bytes
,
1419 uint64_t skip_end_bytes
,
1423 int64_t cluster_bytes
;
1424 uint8_t *whole_grain
;
1425 bool copy_from_backing
;
1427 /* For COW, align request sector_num to cluster start */
1428 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1429 offset
= QEMU_ALIGN_DOWN(offset
, cluster_bytes
);
1430 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1431 copy_from_backing
= bs
->backing
&& !zeroed
;
1433 if (!copy_from_backing
) {
1434 memset(whole_grain
, 0, skip_start_bytes
);
1435 memset(whole_grain
+ skip_end_bytes
, 0, cluster_bytes
- skip_end_bytes
);
1438 assert(skip_end_bytes
<= cluster_bytes
);
1439 /* we will be here if it's first write on non-exist grain(cluster).
1440 * try to read from parent image, if exist */
1441 if (bs
->backing
&& !vmdk_is_cid_valid(bs
)) {
1446 /* Read backing data before skip range */
1447 if (skip_start_bytes
> 0) {
1448 if (copy_from_backing
) {
1449 /* qcow2 emits this on bs->file instead of bs->backing */
1450 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1451 ret
= bdrv_pread(bs
->backing
, offset
, whole_grain
,
1458 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1459 ret
= bdrv_pwrite(extent
->file
, cluster_offset
, whole_grain
,
1466 /* Read backing data after skip range */
1467 if (skip_end_bytes
< cluster_bytes
) {
1468 if (copy_from_backing
) {
1469 /* qcow2 emits this on bs->file instead of bs->backing */
1470 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1471 ret
= bdrv_pread(bs
->backing
, offset
+ skip_end_bytes
,
1472 whole_grain
+ skip_end_bytes
,
1473 cluster_bytes
- skip_end_bytes
);
1479 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1480 ret
= bdrv_pwrite(extent
->file
, cluster_offset
+ skip_end_bytes
,
1481 whole_grain
+ skip_end_bytes
,
1482 cluster_bytes
- skip_end_bytes
);
1491 qemu_vfree(whole_grain
);
1495 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1498 offset
= cpu_to_le32(offset
);
1499 /* update L2 table */
1500 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_UPDATE
);
1501 if (bdrv_pwrite(extent
->file
,
1502 ((int64_t)m_data
->l2_offset
* 512)
1503 + (m_data
->l2_index
* sizeof(offset
)),
1504 &offset
, sizeof(offset
)) < 0) {
1507 /* update backup L2 table */
1508 if (extent
->l1_backup_table_offset
!= 0) {
1509 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1510 if (bdrv_pwrite(extent
->file
,
1511 ((int64_t)m_data
->l2_offset
* 512)
1512 + (m_data
->l2_index
* sizeof(offset
)),
1513 &offset
, sizeof(offset
)) < 0) {
1517 if (bdrv_flush(extent
->file
->bs
) < 0) {
1520 if (m_data
->l2_cache_entry
) {
1521 *m_data
->l2_cache_entry
= offset
;
1528 * get_cluster_offset
1530 * Look up cluster offset in extent file by sector number, and store in
1533 * For flat extents, the start offset as parsed from the description file is
1536 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1537 * offset for a new cluster and update L2 cache. If there is a backing file,
1538 * COW is done before returning; otherwise, zeroes are written to the allocated
1539 * cluster. Both COW and zero writing skips the sector range
1540 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1541 * has new data to write there.
1543 * Returns: VMDK_OK if cluster exists and mapped in the image.
1544 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1545 * VMDK_ERROR if failed.
1547 static int get_cluster_offset(BlockDriverState
*bs
,
1549 VmdkMetaData
*m_data
,
1552 uint64_t *cluster_offset
,
1553 uint64_t skip_start_bytes
,
1554 uint64_t skip_end_bytes
)
1556 unsigned int l1_index
, l2_offset
, l2_index
;
1557 int min_index
, i
, j
;
1560 bool zeroed
= false;
1562 int64_t cluster_sector
;
1563 unsigned int l2_size_bytes
= extent
->l2_size
* extent
->entry_size
;
1566 m_data
->new_allocation
= false;
1569 *cluster_offset
= extent
->flat_start_offset
;
1573 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1574 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1575 if (l1_index
>= extent
->l1_size
) {
1578 if (extent
->sesparse
) {
1579 uint64_t l2_offset_u64
;
1581 assert(extent
->entry_size
== sizeof(uint64_t));
1583 l2_offset_u64
= ((uint64_t *)extent
->l1_table
)[l1_index
];
1584 if (l2_offset_u64
== 0) {
1586 } else if ((l2_offset_u64
& 0xffffffff00000000) != 0x1000000000000000) {
1588 * Top most nibble is 0x1 if grain table is allocated.
1589 * strict check - top most 4 bytes must be 0x10000000 since max
1590 * supported size is 64TB for disk - so no more than 64TB / 16MB
1591 * grain directories which is smaller than uint32,
1592 * where 16MB is the only supported default grain table coverage.
1596 l2_offset_u64
= l2_offset_u64
& 0x00000000ffffffff;
1597 l2_offset_u64
= extent
->sesparse_l2_tables_offset
+
1598 l2_offset_u64
* l2_size_bytes
/ SECTOR_SIZE
;
1599 if (l2_offset_u64
> 0x00000000ffffffff) {
1602 l2_offset
= (unsigned int)(l2_offset_u64
);
1605 assert(extent
->entry_size
== sizeof(uint32_t));
1606 l2_offset
= ((uint32_t *)extent
->l1_table
)[l1_index
];
1609 return VMDK_UNALLOC
;
1611 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1612 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1613 /* increment the hit count */
1614 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1615 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1616 extent
->l2_cache_counts
[j
] >>= 1;
1619 l2_table
= (char *)extent
->l2_cache
+ (i
* l2_size_bytes
);
1623 /* not found: load a new entry in the least used one */
1625 min_count
= 0xffffffff;
1626 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1627 if (extent
->l2_cache_counts
[i
] < min_count
) {
1628 min_count
= extent
->l2_cache_counts
[i
];
1632 l2_table
= (char *)extent
->l2_cache
+ (min_index
* l2_size_bytes
);
1633 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_LOAD
);
1634 if (bdrv_pread(extent
->file
,
1635 (int64_t)l2_offset
* 512,
1638 ) != l2_size_bytes
) {
1642 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1643 extent
->l2_cache_counts
[min_index
] = 1;
1645 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1647 m_data
->l1_index
= l1_index
;
1648 m_data
->l2_index
= l2_index
;
1649 m_data
->l2_offset
= l2_offset
;
1650 m_data
->l2_cache_entry
= ((uint32_t *)l2_table
) + l2_index
;
1653 if (extent
->sesparse
) {
1654 cluster_sector
= le64_to_cpu(((uint64_t *)l2_table
)[l2_index
]);
1655 switch (cluster_sector
& 0xf000000000000000) {
1656 case 0x0000000000000000:
1657 /* unallocated grain */
1658 if (cluster_sector
!= 0) {
1662 case 0x1000000000000000:
1663 /* scsi-unmapped grain - fallthrough */
1664 case 0x2000000000000000:
1668 case 0x3000000000000000:
1669 /* allocated grain */
1670 cluster_sector
= (((cluster_sector
& 0x0fff000000000000) >> 48) |
1671 ((cluster_sector
& 0x0000ffffffffffff) << 12));
1672 cluster_sector
= extent
->sesparse_clusters_offset
+
1673 cluster_sector
* extent
->cluster_sectors
;
1679 cluster_sector
= le32_to_cpu(((uint32_t *)l2_table
)[l2_index
]);
1681 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1686 if (!cluster_sector
|| zeroed
) {
1688 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1690 assert(!extent
->sesparse
);
1692 if (extent
->next_cluster_sector
>= VMDK_EXTENT_MAX_SECTORS
) {
1696 cluster_sector
= extent
->next_cluster_sector
;
1697 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1699 /* First of all we write grain itself, to avoid race condition
1700 * that may to corrupt the image.
1701 * This problem may occur because of insufficient space on host disk
1702 * or inappropriate VM shutdown.
1704 ret
= get_whole_cluster(bs
, extent
, cluster_sector
* BDRV_SECTOR_SIZE
,
1705 offset
, skip_start_bytes
, skip_end_bytes
,
1711 m_data
->new_allocation
= true;
1714 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1718 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1719 int64_t sector_num
, VmdkExtent
*start_hint
)
1721 VmdkExtent
*extent
= start_hint
;
1724 extent
= &s
->extents
[0];
1726 while (extent
< &s
->extents
[s
->num_extents
]) {
1727 if (sector_num
< extent
->end_sector
) {
1735 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent
*extent
,
1738 uint64_t extent_begin_offset
, extent_relative_offset
;
1739 uint64_t cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
1741 extent_begin_offset
=
1742 (extent
->end_sector
- extent
->sectors
) * BDRV_SECTOR_SIZE
;
1743 extent_relative_offset
= offset
- extent_begin_offset
;
1744 return extent_relative_offset
% cluster_size
;
1747 static int coroutine_fn
vmdk_co_block_status(BlockDriverState
*bs
,
1749 int64_t offset
, int64_t bytes
,
1750 int64_t *pnum
, int64_t *map
,
1751 BlockDriverState
**file
)
1753 BDRVVmdkState
*s
= bs
->opaque
;
1754 int64_t index_in_cluster
, n
, ret
;
1755 uint64_t cluster_offset
;
1758 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, NULL
);
1762 qemu_co_mutex_lock(&s
->lock
);
1763 ret
= get_cluster_offset(bs
, extent
, NULL
, offset
, false, &cluster_offset
,
1765 qemu_co_mutex_unlock(&s
->lock
);
1767 index_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1776 ret
= BDRV_BLOCK_ZERO
;
1779 ret
= BDRV_BLOCK_DATA
;
1780 if (!extent
->compressed
) {
1781 ret
|= BDRV_BLOCK_OFFSET_VALID
;
1782 *map
= cluster_offset
+ index_in_cluster
;
1784 ret
|= BDRV_BLOCK_RECURSE
;
1787 *file
= extent
->file
->bs
;
1791 n
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
- index_in_cluster
;
1792 *pnum
= MIN(n
, bytes
);
1796 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1797 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1798 uint64_t qiov_offset
, uint64_t n_bytes
,
1802 VmdkGrainMarker
*data
= NULL
;
1804 QEMUIOVector local_qiov
;
1805 int64_t write_offset
;
1806 int64_t write_end_sector
;
1808 if (extent
->compressed
) {
1809 void *compressed_data
;
1811 /* Only whole clusters */
1812 if (offset_in_cluster
||
1813 n_bytes
> (extent
->cluster_sectors
* SECTOR_SIZE
) ||
1814 (n_bytes
< (extent
->cluster_sectors
* SECTOR_SIZE
) &&
1815 offset
+ n_bytes
!= extent
->end_sector
* SECTOR_SIZE
))
1821 if (!extent
->has_marker
) {
1825 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1826 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1828 compressed_data
= g_malloc(n_bytes
);
1829 qemu_iovec_to_buf(qiov
, qiov_offset
, compressed_data
, n_bytes
);
1830 ret
= compress(data
->data
, &buf_len
, compressed_data
, n_bytes
);
1831 g_free(compressed_data
);
1833 if (ret
!= Z_OK
|| buf_len
== 0) {
1838 data
->lba
= cpu_to_le64(offset
>> BDRV_SECTOR_BITS
);
1839 data
->size
= cpu_to_le32(buf_len
);
1841 n_bytes
= buf_len
+ sizeof(VmdkGrainMarker
);
1842 qemu_iovec_init_buf(&local_qiov
, data
, n_bytes
);
1844 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_COMPRESSED
);
1846 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1847 qemu_iovec_concat(&local_qiov
, qiov
, qiov_offset
, n_bytes
);
1849 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_AIO
);
1852 write_offset
= cluster_offset
+ offset_in_cluster
;
1853 ret
= bdrv_co_pwritev(extent
->file
, write_offset
, n_bytes
,
1856 write_end_sector
= DIV_ROUND_UP(write_offset
+ n_bytes
, BDRV_SECTOR_SIZE
);
1858 if (extent
->compressed
) {
1859 extent
->next_cluster_sector
= write_end_sector
;
1861 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1871 if (!extent
->compressed
) {
1872 qemu_iovec_destroy(&local_qiov
);
1877 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1878 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1882 int cluster_bytes
, buf_bytes
;
1883 uint8_t *cluster_buf
, *compressed_data
;
1884 uint8_t *uncomp_buf
;
1886 VmdkGrainMarker
*marker
;
1890 if (!extent
->compressed
) {
1891 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_AIO
);
1892 ret
= bdrv_co_preadv(extent
->file
,
1893 cluster_offset
+ offset_in_cluster
, bytes
,
1900 cluster_bytes
= extent
->cluster_sectors
* 512;
1901 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1902 buf_bytes
= cluster_bytes
* 2;
1903 cluster_buf
= g_malloc(buf_bytes
);
1904 uncomp_buf
= g_malloc(cluster_bytes
);
1905 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_COMPRESSED
);
1906 ret
= bdrv_pread(extent
->file
,
1908 cluster_buf
, buf_bytes
);
1912 compressed_data
= cluster_buf
;
1913 buf_len
= cluster_bytes
;
1914 data_len
= cluster_bytes
;
1915 if (extent
->has_marker
) {
1916 marker
= (VmdkGrainMarker
*)cluster_buf
;
1917 compressed_data
= marker
->data
;
1918 data_len
= le32_to_cpu(marker
->size
);
1920 if (!data_len
|| data_len
> buf_bytes
) {
1924 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1930 if (offset_in_cluster
< 0 ||
1931 offset_in_cluster
+ bytes
> buf_len
) {
1935 qemu_iovec_from_buf(qiov
, 0, uncomp_buf
+ offset_in_cluster
, bytes
);
1940 g_free(cluster_buf
);
1944 static int coroutine_fn
1945 vmdk_co_preadv(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1946 QEMUIOVector
*qiov
, BdrvRequestFlags flags
)
1948 BDRVVmdkState
*s
= bs
->opaque
;
1950 uint64_t n_bytes
, offset_in_cluster
;
1951 VmdkExtent
*extent
= NULL
;
1952 QEMUIOVector local_qiov
;
1953 uint64_t cluster_offset
;
1954 uint64_t bytes_done
= 0;
1956 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1957 qemu_co_mutex_lock(&s
->lock
);
1960 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
1965 ret
= get_cluster_offset(bs
, extent
, NULL
,
1966 offset
, false, &cluster_offset
, 0, 0);
1967 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1969 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
1970 - offset_in_cluster
);
1972 if (ret
!= VMDK_OK
) {
1973 /* if not allocated, try to read from parent image, if exist */
1974 if (bs
->backing
&& ret
!= VMDK_ZEROED
) {
1975 if (!vmdk_is_cid_valid(bs
)) {
1980 qemu_iovec_reset(&local_qiov
);
1981 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1983 /* qcow2 emits this on bs->file instead of bs->backing */
1984 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1985 ret
= bdrv_co_preadv(bs
->backing
, offset
, n_bytes
,
1991 qemu_iovec_memset(qiov
, bytes_done
, 0, n_bytes
);
1994 qemu_iovec_reset(&local_qiov
);
1995 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1997 ret
= vmdk_read_extent(extent
, cluster_offset
, offset_in_cluster
,
1998 &local_qiov
, n_bytes
);
2005 bytes_done
+= n_bytes
;
2010 qemu_co_mutex_unlock(&s
->lock
);
2011 qemu_iovec_destroy(&local_qiov
);
2018 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
2019 * if possible, otherwise return -ENOTSUP.
2020 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
2021 * with each cluster. By dry run we can find if the zero write
2022 * is possible without modifying image data.
2024 * Returns: error code with 0 for success.
2026 static int vmdk_pwritev(BlockDriverState
*bs
, uint64_t offset
,
2027 uint64_t bytes
, QEMUIOVector
*qiov
,
2028 bool zeroed
, bool zero_dry_run
)
2030 BDRVVmdkState
*s
= bs
->opaque
;
2031 VmdkExtent
*extent
= NULL
;
2033 int64_t offset_in_cluster
, n_bytes
;
2034 uint64_t cluster_offset
;
2035 uint64_t bytes_done
= 0;
2036 VmdkMetaData m_data
;
2038 if (DIV_ROUND_UP(offset
, BDRV_SECTOR_SIZE
) > bs
->total_sectors
) {
2039 error_report("Wrong offset: offset=0x%" PRIx64
2040 " total_sectors=0x%" PRIx64
,
2041 offset
, bs
->total_sectors
);
2046 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
2050 if (extent
->sesparse
) {
2053 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
2054 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
2055 - offset_in_cluster
);
2057 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
2058 !(extent
->compressed
|| zeroed
),
2059 &cluster_offset
, offset_in_cluster
,
2060 offset_in_cluster
+ n_bytes
);
2061 if (extent
->compressed
) {
2062 if (ret
== VMDK_OK
) {
2063 /* Refuse write to allocated cluster for streamOptimized */
2064 error_report("Could not write to allocated cluster"
2065 " for streamOptimized");
2067 } else if (!zeroed
) {
2069 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
2070 true, &cluster_offset
, 0, 0);
2073 if (ret
== VMDK_ERROR
) {
2077 /* Do zeroed write, buf is ignored */
2078 if (extent
->has_zero_grain
&&
2079 offset_in_cluster
== 0 &&
2080 n_bytes
>= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
) {
2081 n_bytes
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
2082 if (!zero_dry_run
&& ret
!= VMDK_ZEROED
) {
2083 /* update L2 tables */
2084 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
2093 ret
= vmdk_write_extent(extent
, cluster_offset
, offset_in_cluster
,
2094 qiov
, bytes_done
, n_bytes
, offset
);
2098 if (m_data
.new_allocation
) {
2099 /* update L2 tables */
2100 if (vmdk_L2update(extent
, &m_data
,
2101 cluster_offset
>> BDRV_SECTOR_BITS
)
2109 bytes_done
+= n_bytes
;
2111 /* update CID on the first write every time the virtual disk is
2113 if (!s
->cid_updated
) {
2114 ret
= vmdk_write_cid(bs
, g_random_int());
2118 s
->cid_updated
= true;
2124 static int coroutine_fn
2125 vmdk_co_pwritev(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2126 QEMUIOVector
*qiov
, BdrvRequestFlags flags
)
2129 BDRVVmdkState
*s
= bs
->opaque
;
2130 qemu_co_mutex_lock(&s
->lock
);
2131 ret
= vmdk_pwritev(bs
, offset
, bytes
, qiov
, false, false);
2132 qemu_co_mutex_unlock(&s
->lock
);
2136 static int coroutine_fn
2137 vmdk_co_pwritev_compressed(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2141 /* The caller will write bytes 0 to signal EOF.
2142 * When receive it, we align EOF to a sector boundary. */
2143 BDRVVmdkState
*s
= bs
->opaque
;
2147 for (i
= 0; i
< s
->num_extents
; i
++) {
2148 length
= bdrv_getlength(s
->extents
[i
].file
->bs
);
2152 length
= QEMU_ALIGN_UP(length
, BDRV_SECTOR_SIZE
);
2153 ret
= bdrv_truncate(s
->extents
[i
].file
, length
, false,
2154 PREALLOC_MODE_OFF
, 0, NULL
);
2161 return vmdk_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
2164 static int coroutine_fn
vmdk_co_pwrite_zeroes(BlockDriverState
*bs
,
2167 BdrvRequestFlags flags
)
2170 BDRVVmdkState
*s
= bs
->opaque
;
2172 qemu_co_mutex_lock(&s
->lock
);
2173 /* write zeroes could fail if sectors not aligned to cluster, test it with
2174 * dry_run == true before really updating image */
2175 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, true);
2177 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, false);
2179 qemu_co_mutex_unlock(&s
->lock
);
2183 static int vmdk_init_extent(BlockBackend
*blk
,
2184 int64_t filesize
, bool flat
,
2185 bool compress
, bool zeroed_grain
,
2190 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
2191 uint32_t *gd_buf
= NULL
;
2195 ret
= blk_truncate(blk
, filesize
, false, PREALLOC_MODE_OFF
, 0, errp
);
2198 magic
= cpu_to_be32(VMDK4_MAGIC
);
2199 memset(&header
, 0, sizeof(header
));
2202 } else if (zeroed_grain
) {
2207 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
2208 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
2209 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
2210 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
2211 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
2212 header
.granularity
= 128;
2213 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
2215 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
2216 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
2218 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
2219 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
2221 header
.desc_offset
= 1;
2222 header
.desc_size
= 20;
2223 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
2224 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
2225 header
.grain_offset
=
2226 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
2227 header
.granularity
);
2228 /* swap endianness for all header fields */
2229 header
.version
= cpu_to_le32(header
.version
);
2230 header
.flags
= cpu_to_le32(header
.flags
);
2231 header
.capacity
= cpu_to_le64(header
.capacity
);
2232 header
.granularity
= cpu_to_le64(header
.granularity
);
2233 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
2234 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
2235 header
.desc_size
= cpu_to_le64(header
.desc_size
);
2236 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
2237 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
2238 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
2239 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
2241 header
.check_bytes
[0] = 0xa;
2242 header
.check_bytes
[1] = 0x20;
2243 header
.check_bytes
[2] = 0xd;
2244 header
.check_bytes
[3] = 0xa;
2246 /* write all the data */
2247 ret
= blk_pwrite(blk
, 0, &magic
, sizeof(magic
), 0);
2249 error_setg(errp
, QERR_IO_ERROR
);
2252 ret
= blk_pwrite(blk
, sizeof(magic
), &header
, sizeof(header
), 0);
2254 error_setg(errp
, QERR_IO_ERROR
);
2258 ret
= blk_truncate(blk
, le64_to_cpu(header
.grain_offset
) << 9, false,
2259 PREALLOC_MODE_OFF
, 0, errp
);
2264 /* write grain directory */
2265 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
2266 gd_buf
= g_malloc0(gd_buf_size
);
2267 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
2268 i
< gt_count
; i
++, tmp
+= gt_size
) {
2269 gd_buf
[i
] = cpu_to_le32(tmp
);
2271 ret
= blk_pwrite(blk
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
2272 gd_buf
, gd_buf_size
, 0);
2274 error_setg(errp
, QERR_IO_ERROR
);
2278 /* write backup grain directory */
2279 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
2280 i
< gt_count
; i
++, tmp
+= gt_size
) {
2281 gd_buf
[i
] = cpu_to_le32(tmp
);
2283 ret
= blk_pwrite(blk
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
2284 gd_buf
, gd_buf_size
, 0);
2286 error_setg(errp
, QERR_IO_ERROR
);
2295 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
2296 bool flat
, bool compress
, bool zeroed_grain
,
2298 QemuOpts
*opts
, Error
**errp
)
2301 BlockBackend
*blk
= NULL
;
2303 ret
= bdrv_create_file(filename
, opts
, errp
);
2308 blk
= blk_new_open(filename
, NULL
, NULL
,
2309 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2316 blk_set_allow_write_beyond_eof(blk
, true);
2318 ret
= vmdk_init_extent(blk
, filesize
, flat
, compress
, zeroed_grain
, errp
);
2331 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
2332 char *postfix
, size_t buf_len
, Error
**errp
)
2336 if (filename
== NULL
|| !strlen(filename
)) {
2337 error_setg(errp
, "No filename provided");
2340 p
= strrchr(filename
, '/');
2342 p
= strrchr(filename
, '\\');
2345 p
= strrchr(filename
, ':');
2349 if (p
- filename
>= buf_len
) {
2352 pstrcpy(path
, p
- filename
+ 1, filename
);
2357 q
= strrchr(p
, '.');
2359 pstrcpy(prefix
, buf_len
, p
);
2362 if (q
- p
>= buf_len
) {
2365 pstrcpy(prefix
, q
- p
+ 1, p
);
2366 pstrcpy(postfix
, buf_len
, q
);
2372 * idx == 0: get or create the descriptor file (also the image file if in a
2374 * idx >= 1: get the n-th extent if in a split subformat
2376 typedef BlockBackend
*(*vmdk_create_extent_fn
)(int64_t size
,
2385 static void vmdk_desc_add_extent(GString
*desc
,
2386 const char *extent_line_fmt
,
2387 int64_t size
, const char *filename
)
2389 char *basename
= g_path_get_basename(filename
);
2391 g_string_append_printf(desc
, extent_line_fmt
,
2392 DIV_ROUND_UP(size
, BDRV_SECTOR_SIZE
), basename
);
2396 static int coroutine_fn
vmdk_co_do_create(int64_t size
,
2397 BlockdevVmdkSubformat subformat
,
2398 BlockdevVmdkAdapterType adapter_type
,
2399 const char *backing_file
,
2400 const char *hw_version
,
2401 const char *toolsversion
,
2404 vmdk_create_extent_fn extent_fn
,
2409 BlockBackend
*blk
= NULL
;
2410 BlockBackend
*extent_blk
;
2411 Error
*local_err
= NULL
;
2414 bool flat
, split
, compress
;
2415 GString
*ext_desc_lines
;
2416 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
2417 int64_t extent_size
;
2418 int64_t created_size
= 0;
2419 const char *extent_line_fmt
;
2420 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
2421 uint32_t parent_cid
= 0xffffffff;
2422 uint32_t number_heads
= 16;
2423 uint32_t desc_offset
= 0, desc_len
;
2424 const char desc_template
[] =
2425 "# Disk DescriptorFile\n"
2428 "parentCID=%" PRIx32
"\n"
2429 "createType=\"%s\"\n"
2432 "# Extent description\n"
2435 "# The Disk Data Base\n"
2438 "ddb.virtualHWVersion = \"%s\"\n"
2439 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
2440 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
2441 "ddb.geometry.sectors = \"63\"\n"
2442 "ddb.adapterType = \"%s\"\n"
2443 "ddb.toolsVersion = \"%s\"\n";
2445 ext_desc_lines
= g_string_new(NULL
);
2447 /* Read out options */
2451 "compat6 cannot be enabled with hwversion set");
2460 if (!toolsversion
) {
2461 toolsversion
= "2147483647";
2464 if (adapter_type
!= BLOCKDEV_VMDK_ADAPTER_TYPE_IDE
) {
2465 /* that's the number of heads with which vmware operates when
2466 creating, exporting, etc. vmdk files with a non-ide adapter type */
2469 split
= (subformat
== BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT
) ||
2470 (subformat
== BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTSPARSE
);
2471 flat
= (subformat
== BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICFLAT
) ||
2472 (subformat
== BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT
);
2473 compress
= subformat
== BLOCKDEV_VMDK_SUBFORMAT_STREAMOPTIMIZED
;
2476 extent_line_fmt
= "RW %" PRId64
" FLAT \"%s\" 0\n";
2478 extent_line_fmt
= "RW %" PRId64
" SPARSE \"%s\"\n";
2480 if (flat
&& backing_file
) {
2481 error_setg(errp
, "Flat image can't have backing file");
2485 if (flat
&& zeroed_grain
) {
2486 error_setg(errp
, "Flat image can't enable zeroed grain");
2491 /* Create extents */
2493 extent_size
= split_size
;
2497 if (!split
&& !flat
) {
2498 created_size
= extent_size
;
2502 /* Get the descriptor file BDS */
2503 blk
= extent_fn(created_size
, 0, flat
, split
, compress
, zeroed_grain
,
2509 if (!split
&& !flat
) {
2510 vmdk_desc_add_extent(ext_desc_lines
, extent_line_fmt
, created_size
,
2511 blk_bs(blk
)->filename
);
2515 BlockBackend
*backing
;
2516 char *full_backing
=
2517 bdrv_get_full_backing_filename_from_filename(blk_bs(blk
)->filename
,
2521 error_propagate(errp
, local_err
);
2525 assert(full_backing
);
2527 backing
= blk_new_open(full_backing
, NULL
, NULL
,
2528 BDRV_O_NO_BACKING
, errp
);
2529 g_free(full_backing
);
2530 if (backing
== NULL
) {
2534 if (strcmp(blk_bs(backing
)->drv
->format_name
, "vmdk")) {
2535 error_setg(errp
, "Invalid backing file format: %s. Must be vmdk",
2536 blk_bs(backing
)->drv
->format_name
);
2541 ret
= vmdk_read_cid(blk_bs(backing
), 0, &parent_cid
);
2544 error_setg(errp
, "Failed to read parent CID");
2547 snprintf(parent_desc_line
, BUF_SIZE
,
2548 "parentFileNameHint=\"%s\"", backing_file
);
2551 while (created_size
< size
) {
2552 int64_t cur_size
= MIN(size
- created_size
, extent_size
);
2553 extent_blk
= extent_fn(cur_size
, extent_idx
, flat
, split
, compress
,
2554 zeroed_grain
, opaque
, errp
);
2559 vmdk_desc_add_extent(ext_desc_lines
, extent_line_fmt
, cur_size
,
2560 blk_bs(extent_blk
)->filename
);
2561 created_size
+= cur_size
;
2563 blk_unref(extent_blk
);
2566 /* Check whether we got excess extents */
2567 extent_blk
= extent_fn(-1, extent_idx
, flat
, split
, compress
, zeroed_grain
,
2570 blk_unref(extent_blk
);
2571 error_setg(errp
, "List of extents contains unused extents");
2576 /* generate descriptor file */
2577 desc
= g_strdup_printf(desc_template
,
2580 BlockdevVmdkSubformat_str(subformat
),
2582 ext_desc_lines
->str
,
2585 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
2587 BlockdevVmdkAdapterType_str(adapter_type
),
2589 desc_len
= strlen(desc
);
2590 /* the descriptor offset = 0x200 */
2591 if (!split
&& !flat
) {
2592 desc_offset
= 0x200;
2595 ret
= blk_pwrite(blk
, desc_offset
, desc
, desc_len
, 0);
2597 error_setg_errno(errp
, -ret
, "Could not write description");
2600 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2601 * for description file */
2602 if (desc_offset
== 0) {
2603 ret
= blk_truncate(blk
, desc_len
, false, PREALLOC_MODE_OFF
, 0, errp
);
2614 g_free(parent_desc_line
);
2615 g_string_free(ext_desc_lines
, true);
2624 } VMDKCreateOptsData
;
2626 static BlockBackend
*vmdk_co_create_opts_cb(int64_t size
, int idx
,
2627 bool flat
, bool split
, bool compress
,
2628 bool zeroed_grain
, void *opaque
,
2631 BlockBackend
*blk
= NULL
;
2632 BlockDriverState
*bs
= NULL
;
2633 VMDKCreateOptsData
*data
= opaque
;
2634 char *ext_filename
= NULL
;
2635 char *rel_filename
= NULL
;
2637 /* We're done, don't create excess extents. */
2639 assert(errp
== NULL
);
2644 rel_filename
= g_strdup_printf("%s%s", data
->prefix
, data
->postfix
);
2646 rel_filename
= g_strdup_printf("%s-%c%03d%s",
2648 flat
? 'f' : 's', idx
, data
->postfix
);
2651 rel_filename
= g_strdup_printf("%s-flat%s", data
->prefix
, data
->postfix
);
2654 ext_filename
= g_strdup_printf("%s%s", data
->path
, rel_filename
);
2655 g_free(rel_filename
);
2657 if (vmdk_create_extent(ext_filename
, size
,
2658 flat
, compress
, zeroed_grain
, &blk
, data
->opts
,
2664 g_free(ext_filename
);
2668 static int coroutine_fn
vmdk_co_create_opts(BlockDriver
*drv
,
2669 const char *filename
,
2673 Error
*local_err
= NULL
;
2675 int64_t total_size
= 0;
2676 char *adapter_type
= NULL
;
2677 BlockdevVmdkAdapterType adapter_type_enum
;
2678 char *backing_file
= NULL
;
2679 char *hw_version
= NULL
;
2680 char *toolsversion
= NULL
;
2682 BlockdevVmdkSubformat subformat
;
2684 char *path
= g_malloc0(PATH_MAX
);
2685 char *prefix
= g_malloc0(PATH_MAX
);
2686 char *postfix
= g_malloc0(PATH_MAX
);
2687 char *desc_line
= g_malloc0(BUF_SIZE
);
2688 char *ext_filename
= g_malloc0(PATH_MAX
);
2689 char *desc_filename
= g_malloc0(PATH_MAX
);
2690 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
2693 VMDKCreateOptsData data
;
2694 char *backing_fmt
= NULL
;
2696 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
2697 if (backing_fmt
&& strcmp(backing_fmt
, "vmdk") != 0) {
2698 error_setg(errp
, "backing_file must be a vmdk image");
2703 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
2707 /* Read out options */
2708 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2710 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
2711 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
2712 hw_version
= qemu_opt_get_del(opts
, BLOCK_OPT_HWVERSION
);
2713 toolsversion
= qemu_opt_get_del(opts
, BLOCK_OPT_TOOLSVERSION
);
2714 compat6
= qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false);
2715 if (strcmp(hw_version
, "undefined") == 0) {
2719 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
2720 zeroed_grain
= qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false);
2723 adapter_type_enum
= qapi_enum_parse(&BlockdevVmdkAdapterType_lookup
,
2725 BLOCKDEV_VMDK_ADAPTER_TYPE_IDE
,
2728 error_propagate(errp
, local_err
);
2733 adapter_type_enum
= BLOCKDEV_VMDK_ADAPTER_TYPE_IDE
;
2737 /* Default format to monolithicSparse */
2738 subformat
= BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE
;
2740 subformat
= qapi_enum_parse(&BlockdevVmdkSubformat_lookup
,
2742 BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE
,
2745 error_propagate(errp
, local_err
);
2750 data
= (VMDKCreateOptsData
){
2756 ret
= vmdk_co_do_create(total_size
, subformat
, adapter_type_enum
,
2757 backing_file
, hw_version
, toolsversion
, compat6
,
2758 zeroed_grain
, vmdk_co_create_opts_cb
, &data
, errp
);
2761 g_free(backing_fmt
);
2762 g_free(adapter_type
);
2763 g_free(backing_file
);
2765 g_free(toolsversion
);
2772 g_free(ext_filename
);
2773 g_free(desc_filename
);
2774 g_free(parent_desc_line
);
2778 static BlockBackend
*vmdk_co_create_cb(int64_t size
, int idx
,
2779 bool flat
, bool split
, bool compress
,
2780 bool zeroed_grain
, void *opaque
,
2784 BlockDriverState
*bs
;
2786 BlockdevCreateOptionsVmdk
*opts
= opaque
;
2789 bs
= bdrv_open_blockdev_ref(opts
->file
, errp
);
2792 BlockdevRefList
*list
= opts
->extents
;
2793 for (i
= 1; i
< idx
; i
++) {
2794 if (!list
|| !list
->next
) {
2795 error_setg(errp
, "Extent [%d] not specified", i
);
2801 error_setg(errp
, "Extent [%d] not specified", idx
- 1);
2804 bs
= bdrv_open_blockdev_ref(list
->value
, errp
);
2809 blk
= blk_new_with_bs(bs
,
2810 BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE
| BLK_PERM_RESIZE
,
2811 BLK_PERM_ALL
, errp
);
2815 blk_set_allow_write_beyond_eof(blk
, true);
2819 ret
= vmdk_init_extent(blk
, size
, flat
, compress
, zeroed_grain
, errp
);
2828 static int coroutine_fn
vmdk_co_create(BlockdevCreateOptions
*create_options
,
2832 BlockdevCreateOptionsVmdk
*opts
;
2834 opts
= &create_options
->u
.vmdk
;
2836 /* Validate options */
2837 if (!QEMU_IS_ALIGNED(opts
->size
, BDRV_SECTOR_SIZE
)) {
2838 error_setg(errp
, "Image size must be a multiple of 512 bytes");
2843 ret
= vmdk_co_do_create(opts
->size
,
2859 static void vmdk_close(BlockDriverState
*bs
)
2861 BDRVVmdkState
*s
= bs
->opaque
;
2863 vmdk_free_extents(bs
);
2864 g_free(s
->create_type
);
2866 migrate_del_blocker(s
->migration_blocker
);
2867 error_free(s
->migration_blocker
);
2870 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2875 BDRVVmdkState
*s
= bs
->opaque
;
2877 ret
= bdrv_get_allocated_file_size(bs
->file
->bs
);
2881 for (i
= 0; i
< s
->num_extents
; i
++) {
2882 if (s
->extents
[i
].file
== bs
->file
) {
2885 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
->bs
);
2894 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2897 BDRVVmdkState
*s
= bs
->opaque
;
2899 /* If has a flat extent and its underlying storage doesn't have zero init,
2901 for (i
= 0; i
< s
->num_extents
; i
++) {
2902 if (s
->extents
[i
].flat
) {
2903 if (!bdrv_has_zero_init(s
->extents
[i
].file
->bs
)) {
2911 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2913 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2915 bdrv_refresh_filename(extent
->file
->bs
);
2916 *info
= (ImageInfo
){
2917 .filename
= g_strdup(extent
->file
->bs
->filename
),
2918 .format
= g_strdup(extent
->type
),
2919 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2920 .compressed
= extent
->compressed
,
2921 .has_compressed
= extent
->compressed
,
2922 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2923 .has_cluster_size
= !extent
->flat
,
2929 static int coroutine_fn
vmdk_co_check(BlockDriverState
*bs
,
2930 BdrvCheckResult
*result
,
2933 BDRVVmdkState
*s
= bs
->opaque
;
2934 VmdkExtent
*extent
= NULL
;
2935 int64_t sector_num
= 0;
2936 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2938 uint64_t cluster_offset
;
2945 if (sector_num
>= total_sectors
) {
2948 extent
= find_extent(s
, sector_num
, extent
);
2951 "ERROR: could not find extent for sector %" PRId64
"\n",
2956 ret
= get_cluster_offset(bs
, extent
, NULL
,
2957 sector_num
<< BDRV_SECTOR_BITS
,
2958 false, &cluster_offset
, 0, 0);
2959 if (ret
== VMDK_ERROR
) {
2961 "ERROR: could not get cluster_offset for sector %"
2962 PRId64
"\n", sector_num
);
2965 if (ret
== VMDK_OK
) {
2966 int64_t extent_len
= bdrv_getlength(extent
->file
->bs
);
2967 if (extent_len
< 0) {
2969 "ERROR: could not get extent file length for sector %"
2970 PRId64
"\n", sector_num
);
2974 if (cluster_offset
>= extent_len
) {
2976 "ERROR: cluster offset for sector %"
2977 PRId64
" points after EOF\n", sector_num
);
2982 sector_num
+= extent
->cluster_sectors
;
2985 result
->corruptions
++;
2989 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
,
2993 BDRVVmdkState
*s
= bs
->opaque
;
2994 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2995 ImageInfoList
**tail
;
2997 *spec_info
= (ImageInfoSpecific
){
2998 .type
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
3000 .vmdk
.data
= g_new0(ImageInfoSpecificVmdk
, 1),
3004 *spec_info
->u
.vmdk
.data
= (ImageInfoSpecificVmdk
) {
3005 .create_type
= g_strdup(s
->create_type
),
3007 .parent_cid
= s
->parent_cid
,
3010 tail
= &spec_info
->u
.vmdk
.data
->extents
;
3011 for (i
= 0; i
< s
->num_extents
; i
++) {
3012 QAPI_LIST_APPEND(tail
, vmdk_get_extent_info(&s
->extents
[i
]));
3018 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
3020 return a
->flat
== b
->flat
&&
3021 a
->compressed
== b
->compressed
&&
3022 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
3025 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3028 BDRVVmdkState
*s
= bs
->opaque
;
3029 assert(s
->num_extents
);
3031 /* See if we have multiple extents but they have different cases */
3032 for (i
= 1; i
< s
->num_extents
; i
++) {
3033 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
3037 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
3038 if (!s
->extents
[0].flat
) {
3039 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
3044 static void vmdk_gather_child_options(BlockDriverState
*bs
, QDict
*target
,
3045 bool backing_overridden
)
3047 /* No children but file and backing can be explicitly specified (TODO) */
3048 qdict_put(target
, "file",
3049 qobject_ref(bs
->file
->bs
->full_open_options
));
3051 if (backing_overridden
) {
3053 qdict_put(target
, "backing",
3054 qobject_ref(bs
->backing
->bs
->full_open_options
));
3056 qdict_put_null(target
, "backing");
3061 static QemuOptsList vmdk_create_opts
= {
3062 .name
= "vmdk-create-opts",
3063 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
3066 .name
= BLOCK_OPT_SIZE
,
3067 .type
= QEMU_OPT_SIZE
,
3068 .help
= "Virtual disk size"
3071 .name
= BLOCK_OPT_ADAPTER_TYPE
,
3072 .type
= QEMU_OPT_STRING
,
3073 .help
= "Virtual adapter type, can be one of "
3074 "ide (default), lsilogic, buslogic or legacyESX"
3077 .name
= BLOCK_OPT_BACKING_FILE
,
3078 .type
= QEMU_OPT_STRING
,
3079 .help
= "File name of a base image"
3082 .name
= BLOCK_OPT_BACKING_FMT
,
3083 .type
= QEMU_OPT_STRING
,
3084 .help
= "Must be 'vmdk' if present",
3087 .name
= BLOCK_OPT_COMPAT6
,
3088 .type
= QEMU_OPT_BOOL
,
3089 .help
= "VMDK version 6 image",
3090 .def_value_str
= "off"
3093 .name
= BLOCK_OPT_HWVERSION
,
3094 .type
= QEMU_OPT_STRING
,
3095 .help
= "VMDK hardware version",
3096 .def_value_str
= "undefined"
3099 .name
= BLOCK_OPT_TOOLSVERSION
,
3100 .type
= QEMU_OPT_STRING
,
3101 .help
= "VMware guest tools version",
3104 .name
= BLOCK_OPT_SUBFMT
,
3105 .type
= QEMU_OPT_STRING
,
3107 "VMDK flat extent format, can be one of "
3108 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
3111 .name
= BLOCK_OPT_ZEROED_GRAIN
,
3112 .type
= QEMU_OPT_BOOL
,
3113 .help
= "Enable efficient zero writes "
3114 "using the zeroed-grain GTE feature"
3116 { /* end of list */ }
3120 static BlockDriver bdrv_vmdk
= {
3121 .format_name
= "vmdk",
3122 .instance_size
= sizeof(BDRVVmdkState
),
3123 .bdrv_probe
= vmdk_probe
,
3124 .bdrv_open
= vmdk_open
,
3125 .bdrv_co_check
= vmdk_co_check
,
3126 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
3127 .bdrv_reopen_commit
= vmdk_reopen_commit
,
3128 .bdrv_reopen_abort
= vmdk_reopen_abort
,
3129 .bdrv_child_perm
= bdrv_default_perms
,
3130 .bdrv_co_preadv
= vmdk_co_preadv
,
3131 .bdrv_co_pwritev
= vmdk_co_pwritev
,
3132 .bdrv_co_pwritev_compressed
= vmdk_co_pwritev_compressed
,
3133 .bdrv_co_pwrite_zeroes
= vmdk_co_pwrite_zeroes
,
3134 .bdrv_close
= vmdk_close
,
3135 .bdrv_co_create_opts
= vmdk_co_create_opts
,
3136 .bdrv_co_create
= vmdk_co_create
,
3137 .bdrv_co_block_status
= vmdk_co_block_status
,
3138 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
3139 .bdrv_has_zero_init
= vmdk_has_zero_init
,
3140 .bdrv_get_specific_info
= vmdk_get_specific_info
,
3141 .bdrv_refresh_limits
= vmdk_refresh_limits
,
3142 .bdrv_get_info
= vmdk_get_info
,
3143 .bdrv_gather_child_options
= vmdk_gather_child_options
,
3146 .supports_backing
= true,
3147 .create_opts
= &vmdk_create_opts
,
3150 static void bdrv_vmdk_init(void)
3152 bdrv_register(&bdrv_vmdk
);
3155 block_init(bdrv_vmdk_init
);