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_SIZE
, desc
, 0);
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_SIZE
, desc
, 0);
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_SIZE
, desc
, 0);
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_SIZE
, desc
, 0);
477 p_name
= strstr(desc
, "parentFileNameHint");
478 if (p_name
!= NULL
) {
481 p_name
+= sizeof("parentFileNameHint") + 1;
482 end_name
= strchr(p_name
, '\"');
483 if (end_name
== NULL
) {
487 if ((end_name
- p_name
) > sizeof(bs
->auto_backing_file
) - 1) {
492 pstrcpy(bs
->auto_backing_file
, end_name
- p_name
+ 1, p_name
);
493 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
),
494 bs
->auto_backing_file
);
495 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
),
504 /* Create and append extent to the extent array. Return the added VmdkExtent
505 * address. return NULL if allocation failed. */
506 static int vmdk_add_extent(BlockDriverState
*bs
,
507 BdrvChild
*file
, bool flat
, int64_t sectors
,
508 int64_t l1_offset
, int64_t l1_backup_offset
,
510 int l2_size
, uint64_t cluster_sectors
,
511 VmdkExtent
**new_extent
,
515 BDRVVmdkState
*s
= bs
->opaque
;
518 if (cluster_sectors
> 0x200000) {
519 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
520 error_setg(errp
, "Invalid granularity, image may be corrupt");
523 if (l1_size
> 32 * 1024 * 1024) {
525 * Although with big capacity and small l1_entry_sectors, we can get a
526 * big l1_size, we don't want unbounded value to allocate the table.
527 * Limit it to 32M, which is enough to store:
528 * 8TB - for both VMDK3 & VMDK4 with
529 * minimal cluster size: 512B
530 * minimal L2 table size: 512 entries
531 * 8 TB is still more than the maximal value supported for
532 * VMDK3 & VMDK4 which is 2TB.
533 * 64TB - for "ESXi seSparse Extent"
534 * minimal cluster size: 512B (default is 4KB)
535 * L2 table size: 4096 entries (const).
536 * 64TB is more than the maximal value supported for
537 * seSparse VMDKs (which is slightly less than 64TB)
539 error_setg(errp
, "L1 size too big");
543 nb_sectors
= bdrv_nb_sectors(file
->bs
);
544 if (nb_sectors
< 0) {
548 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
549 extent
= &s
->extents
[s
->num_extents
];
552 memset(extent
, 0, sizeof(VmdkExtent
));
555 extent
->sectors
= sectors
;
556 extent
->l1_table_offset
= l1_offset
;
557 extent
->l1_backup_table_offset
= l1_backup_offset
;
558 extent
->l1_size
= l1_size
;
559 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
560 extent
->l2_size
= l2_size
;
561 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
562 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
563 extent
->entry_size
= sizeof(uint32_t);
565 if (s
->num_extents
> 1) {
566 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
568 extent
->end_sector
= extent
->sectors
;
570 bs
->total_sectors
= extent
->end_sector
;
572 *new_extent
= extent
;
577 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
584 /* read the L1 table */
585 l1_size
= extent
->l1_size
* extent
->entry_size
;
586 extent
->l1_table
= g_try_malloc(l1_size
);
587 if (l1_size
&& extent
->l1_table
== NULL
) {
591 ret
= bdrv_pread(extent
->file
, extent
->l1_table_offset
, l1_size
,
592 extent
->l1_table
, 0);
594 bdrv_refresh_filename(extent
->file
->bs
);
595 error_setg_errno(errp
, -ret
,
596 "Could not read l1 table from extent '%s'",
597 extent
->file
->bs
->filename
);
600 for (i
= 0; i
< extent
->l1_size
; i
++) {
601 if (extent
->entry_size
== sizeof(uint64_t)) {
602 le64_to_cpus((uint64_t *)extent
->l1_table
+ i
);
604 assert(extent
->entry_size
== sizeof(uint32_t));
605 le32_to_cpus((uint32_t *)extent
->l1_table
+ i
);
609 if (extent
->l1_backup_table_offset
) {
610 assert(!extent
->sesparse
);
611 extent
->l1_backup_table
= g_try_malloc(l1_size
);
612 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
616 ret
= bdrv_pread(extent
->file
, extent
->l1_backup_table_offset
,
617 l1_size
, extent
->l1_backup_table
, 0);
619 bdrv_refresh_filename(extent
->file
->bs
);
620 error_setg_errno(errp
, -ret
,
621 "Could not read l1 backup table from extent '%s'",
622 extent
->file
->bs
->filename
);
625 for (i
= 0; i
< extent
->l1_size
; i
++) {
626 le32_to_cpus(&extent
->l1_backup_table
[i
]);
631 g_malloc(extent
->entry_size
* extent
->l2_size
* L2_CACHE_SIZE
);
634 g_free(extent
->l1_backup_table
);
636 g_free(extent
->l1_table
);
640 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
642 int flags
, Error
**errp
)
647 VmdkExtent
*extent
= NULL
;
649 ret
= bdrv_pread(file
, sizeof(magic
), sizeof(header
), &header
, 0);
651 bdrv_refresh_filename(file
->bs
);
652 error_setg_errno(errp
, -ret
,
653 "Could not read header from file '%s'",
657 ret
= vmdk_add_extent(bs
, file
, false,
658 le32_to_cpu(header
.disk_sectors
),
659 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
661 le32_to_cpu(header
.l1dir_size
),
663 le32_to_cpu(header
.granularity
),
669 ret
= vmdk_init_tables(bs
, extent
, errp
);
671 /* free extent allocated by vmdk_add_extent */
672 vmdk_free_last_extent(bs
);
677 #define SESPARSE_CONST_HEADER_MAGIC UINT64_C(0x00000000cafebabe)
678 #define SESPARSE_VOLATILE_HEADER_MAGIC UINT64_C(0x00000000cafecafe)
680 /* Strict checks - format not officially documented */
681 static int check_se_sparse_const_header(VMDKSESparseConstHeader
*header
,
684 header
->magic
= le64_to_cpu(header
->magic
);
685 header
->version
= le64_to_cpu(header
->version
);
686 header
->grain_size
= le64_to_cpu(header
->grain_size
);
687 header
->grain_table_size
= le64_to_cpu(header
->grain_table_size
);
688 header
->flags
= le64_to_cpu(header
->flags
);
689 header
->reserved1
= le64_to_cpu(header
->reserved1
);
690 header
->reserved2
= le64_to_cpu(header
->reserved2
);
691 header
->reserved3
= le64_to_cpu(header
->reserved3
);
692 header
->reserved4
= le64_to_cpu(header
->reserved4
);
694 header
->volatile_header_offset
=
695 le64_to_cpu(header
->volatile_header_offset
);
696 header
->volatile_header_size
= le64_to_cpu(header
->volatile_header_size
);
698 header
->journal_header_offset
= le64_to_cpu(header
->journal_header_offset
);
699 header
->journal_header_size
= le64_to_cpu(header
->journal_header_size
);
701 header
->journal_offset
= le64_to_cpu(header
->journal_offset
);
702 header
->journal_size
= le64_to_cpu(header
->journal_size
);
704 header
->grain_dir_offset
= le64_to_cpu(header
->grain_dir_offset
);
705 header
->grain_dir_size
= le64_to_cpu(header
->grain_dir_size
);
707 header
->grain_tables_offset
= le64_to_cpu(header
->grain_tables_offset
);
708 header
->grain_tables_size
= le64_to_cpu(header
->grain_tables_size
);
710 header
->free_bitmap_offset
= le64_to_cpu(header
->free_bitmap_offset
);
711 header
->free_bitmap_size
= le64_to_cpu(header
->free_bitmap_size
);
713 header
->backmap_offset
= le64_to_cpu(header
->backmap_offset
);
714 header
->backmap_size
= le64_to_cpu(header
->backmap_size
);
716 header
->grains_offset
= le64_to_cpu(header
->grains_offset
);
717 header
->grains_size
= le64_to_cpu(header
->grains_size
);
719 if (header
->magic
!= SESPARSE_CONST_HEADER_MAGIC
) {
720 error_setg(errp
, "Bad const header magic: 0x%016" PRIx64
,
725 if (header
->version
!= 0x0000000200000001) {
726 error_setg(errp
, "Unsupported version: 0x%016" PRIx64
,
731 if (header
->grain_size
!= 8) {
732 error_setg(errp
, "Unsupported grain size: %" PRIu64
,
737 if (header
->grain_table_size
!= 64) {
738 error_setg(errp
, "Unsupported grain table size: %" PRIu64
,
739 header
->grain_table_size
);
743 if (header
->flags
!= 0) {
744 error_setg(errp
, "Unsupported flags: 0x%016" PRIx64
,
749 if (header
->reserved1
!= 0 || header
->reserved2
!= 0 ||
750 header
->reserved3
!= 0 || header
->reserved4
!= 0) {
751 error_setg(errp
, "Unsupported reserved bits:"
752 " 0x%016" PRIx64
" 0x%016" PRIx64
753 " 0x%016" PRIx64
" 0x%016" PRIx64
,
754 header
->reserved1
, header
->reserved2
,
755 header
->reserved3
, header
->reserved4
);
759 /* check that padding is 0 */
760 if (!buffer_is_zero(header
->pad
, sizeof(header
->pad
))) {
761 error_setg(errp
, "Unsupported non-zero const header padding");
768 static int check_se_sparse_volatile_header(VMDKSESparseVolatileHeader
*header
,
771 header
->magic
= le64_to_cpu(header
->magic
);
772 header
->free_gt_number
= le64_to_cpu(header
->free_gt_number
);
773 header
->next_txn_seq_number
= le64_to_cpu(header
->next_txn_seq_number
);
774 header
->replay_journal
= le64_to_cpu(header
->replay_journal
);
776 if (header
->magic
!= SESPARSE_VOLATILE_HEADER_MAGIC
) {
777 error_setg(errp
, "Bad volatile header magic: 0x%016" PRIx64
,
782 if (header
->replay_journal
) {
783 error_setg(errp
, "Image is dirty, Replaying journal not supported");
787 /* check that padding is 0 */
788 if (!buffer_is_zero(header
->pad
, sizeof(header
->pad
))) {
789 error_setg(errp
, "Unsupported non-zero volatile header padding");
796 static int vmdk_open_se_sparse(BlockDriverState
*bs
,
798 int flags
, Error
**errp
)
801 VMDKSESparseConstHeader const_header
;
802 VMDKSESparseVolatileHeader volatile_header
;
803 VmdkExtent
*extent
= NULL
;
805 ret
= bdrv_apply_auto_read_only(bs
,
806 "No write support for seSparse images available", errp
);
811 assert(sizeof(const_header
) == SECTOR_SIZE
);
813 ret
= bdrv_pread(file
, 0, sizeof(const_header
), &const_header
, 0);
815 bdrv_refresh_filename(file
->bs
);
816 error_setg_errno(errp
, -ret
,
817 "Could not read const header from file '%s'",
822 /* check const header */
823 ret
= check_se_sparse_const_header(&const_header
, errp
);
828 assert(sizeof(volatile_header
) == SECTOR_SIZE
);
830 ret
= bdrv_pread(file
, const_header
.volatile_header_offset
* SECTOR_SIZE
,
831 sizeof(volatile_header
), &volatile_header
, 0);
833 bdrv_refresh_filename(file
->bs
);
834 error_setg_errno(errp
, -ret
,
835 "Could not read volatile header from file '%s'",
840 /* check volatile header */
841 ret
= check_se_sparse_volatile_header(&volatile_header
, errp
);
846 ret
= vmdk_add_extent(bs
, file
, false,
847 const_header
.capacity
,
848 const_header
.grain_dir_offset
* SECTOR_SIZE
,
850 const_header
.grain_dir_size
*
851 SECTOR_SIZE
/ sizeof(uint64_t),
852 const_header
.grain_table_size
*
853 SECTOR_SIZE
/ sizeof(uint64_t),
854 const_header
.grain_size
,
861 extent
->sesparse
= true;
862 extent
->sesparse_l2_tables_offset
= const_header
.grain_tables_offset
;
863 extent
->sesparse_clusters_offset
= const_header
.grains_offset
;
864 extent
->entry_size
= sizeof(uint64_t);
866 ret
= vmdk_init_tables(bs
, extent
, errp
);
868 /* free extent allocated by vmdk_add_extent */
869 vmdk_free_last_extent(bs
);
875 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
876 QDict
*options
, Error
**errp
);
878 static char *vmdk_read_desc(BdrvChild
*file
, uint64_t desc_offset
, Error
**errp
)
884 size
= bdrv_getlength(file
->bs
);
886 error_setg_errno(errp
, -size
, "Could not access file");
891 /* Both descriptor file and sparse image must be much larger than 4
892 * bytes, also callers of vmdk_read_desc want to compare the first 4
893 * bytes with VMDK4_MAGIC, let's error out if less is read. */
894 error_setg(errp
, "File is too small, not a valid image");
898 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
899 buf
= g_malloc(size
+ 1);
901 ret
= bdrv_pread(file
, desc_offset
, size
, buf
, 0);
903 error_setg_errno(errp
, -ret
, "Could not read from file");
912 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
914 int flags
, QDict
*options
, Error
**errp
)
918 uint32_t l1_size
, l1_entry_sectors
;
920 VmdkExtent
*extent
= NULL
;
921 BDRVVmdkState
*s
= bs
->opaque
;
922 int64_t l1_backup_offset
= 0;
925 ret
= bdrv_pread(file
, sizeof(magic
), sizeof(header
), &header
, 0);
927 bdrv_refresh_filename(file
->bs
);
928 error_setg_errno(errp
, -ret
,
929 "Could not read header from file '%s'",
933 if (header
.capacity
== 0) {
934 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
936 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
940 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
946 if (!s
->create_type
) {
947 s
->create_type
= g_strdup("monolithicSparse");
950 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
952 * The footer takes precedence over the header, so read it in. The
953 * footer starts at offset -1024 from the end: One sector for the
954 * footer, and another one for the end-of-stream marker.
961 uint8_t pad
[512 - 16];
962 } QEMU_PACKED footer_marker
;
966 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
972 uint8_t pad
[512 - 16];
973 } QEMU_PACKED eos_marker
;
974 } QEMU_PACKED footer
;
976 ret
= bdrv_pread(file
, bs
->file
->bs
->total_sectors
* 512 - 1536,
977 sizeof(footer
), &footer
, 0);
979 error_setg_errno(errp
, -ret
, "Failed to read footer");
983 /* Some sanity checks for the footer */
984 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
985 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
986 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
987 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
988 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
989 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
991 error_setg(errp
, "Invalid footer");
995 header
= footer
.header
;
999 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
1000 if (le32_to_cpu(header
.version
) > 3) {
1001 error_setg(errp
, "Unsupported VMDK version %" PRIu32
,
1002 le32_to_cpu(header
.version
));
1004 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
) &&
1006 /* VMware KB 2064959 explains that version 3 added support for
1007 * persistent changed block tracking (CBT), and backup software can
1008 * read it as version=1 if it doesn't care about the changed area
1009 * information. So we are safe to enable read only. */
1010 error_setg(errp
, "VMDK version 3 must be read only");
1014 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
1015 error_setg(errp
, "L2 table size too big");
1019 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
1020 * le64_to_cpu(header
.granularity
);
1021 if (l1_entry_sectors
== 0) {
1022 error_setg(errp
, "L1 entry size is invalid");
1025 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
1027 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
1028 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
1030 if (bdrv_nb_sectors(file
->bs
) < le64_to_cpu(header
.grain_offset
)) {
1031 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
1032 (int64_t)(le64_to_cpu(header
.grain_offset
)
1033 * BDRV_SECTOR_SIZE
));
1037 ret
= vmdk_add_extent(bs
, file
, false,
1038 le64_to_cpu(header
.capacity
),
1039 le64_to_cpu(header
.gd_offset
) << 9,
1042 le32_to_cpu(header
.num_gtes_per_gt
),
1043 le64_to_cpu(header
.granularity
),
1049 extent
->compressed
=
1050 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
1051 if (extent
->compressed
) {
1052 g_free(s
->create_type
);
1053 s
->create_type
= g_strdup("streamOptimized");
1055 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
1056 extent
->version
= le32_to_cpu(header
.version
);
1057 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
1058 ret
= vmdk_init_tables(bs
, extent
, errp
);
1060 /* free extent allocated by vmdk_add_extent */
1061 vmdk_free_last_extent(bs
);
1066 /* find an option value out of descriptor file */
1067 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
1068 char *buf
, int buf_size
)
1070 char *opt_pos
, *opt_end
;
1071 const char *end
= desc
+ strlen(desc
);
1073 opt_pos
= strstr(desc
, opt_name
);
1077 /* Skip "=\"" following opt_name */
1078 opt_pos
+= strlen(opt_name
) + 2;
1079 if (opt_pos
>= end
) {
1083 while (opt_end
< end
&& *opt_end
!= '"') {
1086 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
1089 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
1093 /* Open an extent file and append to bs array */
1094 static int vmdk_open_sparse(BlockDriverState
*bs
, BdrvChild
*file
, int flags
,
1095 char *buf
, QDict
*options
, Error
**errp
)
1099 magic
= ldl_be_p(buf
);
1102 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
1104 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
1106 error_setg(errp
, "Image not in VMDK format");
1111 static const char *next_line(const char *s
)
1122 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
1123 QDict
*options
, Error
**errp
)
1131 int64_t sectors
= 0;
1132 int64_t flat_offset
;
1133 char *desc_file_dir
= NULL
;
1135 BdrvChild
*extent_file
;
1136 BdrvChildRole extent_role
;
1137 BDRVVmdkState
*s
= bs
->opaque
;
1138 VmdkExtent
*extent
= NULL
;
1139 char extent_opt_prefix
[32];
1140 Error
*local_err
= NULL
;
1142 for (p
= desc
; *p
; p
= next_line(p
)) {
1143 /* parse extent line in one of below formats:
1145 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
1146 * RW [size in sectors] SPARSE "file-name.vmdk"
1147 * RW [size in sectors] VMFS "file-name.vmdk"
1148 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
1149 * RW [size in sectors] SESPARSE "file-name.vmdk"
1152 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
1153 access
, §ors
, type
, fname
, &flat_offset
);
1154 if (matches
< 4 || strcmp(access
, "RW")) {
1156 } else if (!strcmp(type
, "FLAT")) {
1157 if (matches
!= 5 || flat_offset
< 0) {
1160 } else if (!strcmp(type
, "VMFS")) {
1166 } else if (matches
!= 4) {
1171 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
1172 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE") &&
1173 strcmp(type
, "SESPARSE")) ||
1174 (strcmp(access
, "RW"))) {
1178 if (path_is_absolute(fname
)) {
1179 extent_path
= g_strdup(fname
);
1181 if (!desc_file_dir
) {
1182 desc_file_dir
= bdrv_dirname(bs
->file
->bs
, errp
);
1183 if (!desc_file_dir
) {
1184 bdrv_refresh_filename(bs
->file
->bs
);
1185 error_prepend(errp
, "Cannot use relative paths with VMDK "
1186 "descriptor file '%s': ",
1187 bs
->file
->bs
->filename
);
1193 extent_path
= g_strconcat(desc_file_dir
, fname
, NULL
);
1196 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
1199 extent_role
= BDRV_CHILD_DATA
;
1200 if (strcmp(type
, "FLAT") != 0 && strcmp(type
, "VMFS") != 0) {
1201 /* non-flat extents have metadata */
1202 extent_role
|= BDRV_CHILD_METADATA
;
1205 extent_file
= bdrv_open_child(extent_path
, options
, extent_opt_prefix
,
1206 bs
, &child_of_bds
, extent_role
, false,
1208 g_free(extent_path
);
1210 error_propagate(errp
, local_err
);
1215 /* save to extents array */
1216 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
1219 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
1220 0, 0, 0, 0, 0, &extent
, errp
);
1222 bdrv_unref_child(bs
, extent_file
);
1225 extent
->flat_start_offset
= flat_offset
<< 9;
1226 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
1227 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
1228 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
1232 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
1237 bdrv_unref_child(bs
, extent_file
);
1240 extent
= &s
->extents
[s
->num_extents
- 1];
1241 } else if (!strcmp(type
, "SESPARSE")) {
1242 ret
= vmdk_open_se_sparse(bs
, extent_file
, bs
->open_flags
, errp
);
1244 bdrv_unref_child(bs
, extent_file
);
1247 extent
= &s
->extents
[s
->num_extents
- 1];
1249 error_setg(errp
, "Unsupported extent type '%s'", type
);
1250 bdrv_unref_child(bs
, extent_file
);
1254 extent
->type
= g_strdup(type
);
1263 if (np
[-1] == '\n') {
1266 error_setg(errp
, "Invalid extent line: %.*s", (int)(np
- p
), p
);
1270 g_free(desc_file_dir
);
1274 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
1275 QDict
*options
, Error
**errp
)
1279 BDRVVmdkState
*s
= bs
->opaque
;
1281 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
1282 error_setg(errp
, "invalid VMDK image descriptor");
1286 if (strcmp(ct
, "monolithicFlat") &&
1287 strcmp(ct
, "vmfs") &&
1288 strcmp(ct
, "vmfsSparse") &&
1289 strcmp(ct
, "seSparse") &&
1290 strcmp(ct
, "twoGbMaxExtentSparse") &&
1291 strcmp(ct
, "twoGbMaxExtentFlat")) {
1292 error_setg(errp
, "Unsupported image type '%s'", ct
);
1296 s
->create_type
= g_strdup(ct
);
1298 ret
= vmdk_parse_extents(buf
, bs
, options
, errp
);
1303 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1308 BDRVVmdkState
*s
= bs
->opaque
;
1311 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_of_bds
,
1312 BDRV_CHILD_IMAGE
, false, errp
);
1317 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
1322 magic
= ldl_be_p(buf
);
1326 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
,
1328 s
->desc_offset
= 0x200;
1331 /* No data in the descriptor file */
1332 bs
->file
->role
&= ~BDRV_CHILD_DATA
;
1334 /* Must succeed because we have given up permissions if anything */
1335 bdrv_child_refresh_perms(bs
, bs
->file
, &error_abort
);
1337 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
1344 /* try to open parent images, if exist */
1345 ret
= vmdk_parent_open(bs
);
1349 ret
= vmdk_read_cid(bs
, 0, &s
->cid
);
1353 ret
= vmdk_read_cid(bs
, 1, &s
->parent_cid
);
1357 qemu_co_mutex_init(&s
->lock
);
1359 /* Disable migration when VMDK images are used */
1360 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
1361 "does not support live migration",
1362 bdrv_get_device_or_node_name(bs
));
1363 ret
= migrate_add_blocker(s
->migration_blocker
, errp
);
1365 error_free(s
->migration_blocker
);
1374 g_free(s
->create_type
);
1375 s
->create_type
= NULL
;
1376 vmdk_free_extents(bs
);
1381 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1383 BDRVVmdkState
*s
= bs
->opaque
;
1386 for (i
= 0; i
< s
->num_extents
; i
++) {
1387 if (!s
->extents
[i
].flat
) {
1388 bs
->bl
.pwrite_zeroes_alignment
=
1389 MAX(bs
->bl
.pwrite_zeroes_alignment
,
1390 s
->extents
[i
].cluster_sectors
<< BDRV_SECTOR_BITS
);
1398 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1399 * to the cluster at @cluster_sector_num. If @zeroed is true, we're overwriting
1400 * a zeroed cluster in the current layer and must not copy data from the
1403 * If @skip_start_sector < @skip_end_sector, the relative range
1404 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1405 * it for call to write user data in the request.
1407 static int get_whole_cluster(BlockDriverState
*bs
,
1409 uint64_t cluster_offset
,
1411 uint64_t skip_start_bytes
,
1412 uint64_t skip_end_bytes
,
1416 int64_t cluster_bytes
;
1417 uint8_t *whole_grain
;
1418 bool copy_from_backing
;
1420 /* For COW, align request sector_num to cluster start */
1421 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1422 offset
= QEMU_ALIGN_DOWN(offset
, cluster_bytes
);
1423 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1424 copy_from_backing
= bs
->backing
&& !zeroed
;
1426 if (!copy_from_backing
) {
1427 memset(whole_grain
, 0, skip_start_bytes
);
1428 memset(whole_grain
+ skip_end_bytes
, 0, cluster_bytes
- skip_end_bytes
);
1431 assert(skip_end_bytes
<= cluster_bytes
);
1432 /* we will be here if it's first write on non-exist grain(cluster).
1433 * try to read from parent image, if exist */
1434 if (bs
->backing
&& !vmdk_is_cid_valid(bs
)) {
1439 /* Read backing data before skip range */
1440 if (skip_start_bytes
> 0) {
1441 if (copy_from_backing
) {
1442 /* qcow2 emits this on bs->file instead of bs->backing */
1443 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1444 ret
= bdrv_pread(bs
->backing
, offset
, skip_start_bytes
,
1451 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1452 ret
= bdrv_pwrite(extent
->file
, cluster_offset
, skip_start_bytes
,
1459 /* Read backing data after skip range */
1460 if (skip_end_bytes
< cluster_bytes
) {
1461 if (copy_from_backing
) {
1462 /* qcow2 emits this on bs->file instead of bs->backing */
1463 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_READ
);
1464 ret
= bdrv_pread(bs
->backing
, offset
+ skip_end_bytes
,
1465 cluster_bytes
- skip_end_bytes
,
1466 whole_grain
+ skip_end_bytes
, 0);
1472 BLKDBG_EVENT(extent
->file
, BLKDBG_COW_WRITE
);
1473 ret
= bdrv_pwrite(extent
->file
, cluster_offset
+ skip_end_bytes
,
1474 cluster_bytes
- skip_end_bytes
,
1475 whole_grain
+ skip_end_bytes
, 0);
1484 qemu_vfree(whole_grain
);
1488 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1491 offset
= cpu_to_le32(offset
);
1492 /* update L2 table */
1493 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_UPDATE
);
1494 if (bdrv_pwrite(extent
->file
,
1495 ((int64_t)m_data
->l2_offset
* 512)
1496 + (m_data
->l2_index
* sizeof(offset
)),
1497 sizeof(offset
), &offset
, 0) < 0) {
1500 /* update backup L2 table */
1501 if (extent
->l1_backup_table_offset
!= 0) {
1502 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1503 if (bdrv_pwrite(extent
->file
,
1504 ((int64_t)m_data
->l2_offset
* 512)
1505 + (m_data
->l2_index
* sizeof(offset
)),
1506 sizeof(offset
), &offset
, 0) < 0) {
1510 if (bdrv_flush(extent
->file
->bs
) < 0) {
1513 if (m_data
->l2_cache_entry
) {
1514 *m_data
->l2_cache_entry
= offset
;
1521 * get_cluster_offset
1523 * Look up cluster offset in extent file by sector number, and store in
1526 * For flat extents, the start offset as parsed from the description file is
1529 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1530 * offset for a new cluster and update L2 cache. If there is a backing file,
1531 * COW is done before returning; otherwise, zeroes are written to the allocated
1532 * cluster. Both COW and zero writing skips the sector range
1533 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1534 * has new data to write there.
1536 * Returns: VMDK_OK if cluster exists and mapped in the image.
1537 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1538 * VMDK_ERROR if failed.
1540 static int get_cluster_offset(BlockDriverState
*bs
,
1542 VmdkMetaData
*m_data
,
1545 uint64_t *cluster_offset
,
1546 uint64_t skip_start_bytes
,
1547 uint64_t skip_end_bytes
)
1549 unsigned int l1_index
, l2_offset
, l2_index
;
1550 int min_index
, i
, j
;
1553 bool zeroed
= false;
1555 int64_t cluster_sector
;
1556 unsigned int l2_size_bytes
= extent
->l2_size
* extent
->entry_size
;
1559 m_data
->new_allocation
= false;
1562 *cluster_offset
= extent
->flat_start_offset
;
1566 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1567 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1568 if (l1_index
>= extent
->l1_size
) {
1571 if (extent
->sesparse
) {
1572 uint64_t l2_offset_u64
;
1574 assert(extent
->entry_size
== sizeof(uint64_t));
1576 l2_offset_u64
= ((uint64_t *)extent
->l1_table
)[l1_index
];
1577 if (l2_offset_u64
== 0) {
1579 } else if ((l2_offset_u64
& 0xffffffff00000000) != 0x1000000000000000) {
1581 * Top most nibble is 0x1 if grain table is allocated.
1582 * strict check - top most 4 bytes must be 0x10000000 since max
1583 * supported size is 64TB for disk - so no more than 64TB / 16MB
1584 * grain directories which is smaller than uint32,
1585 * where 16MB is the only supported default grain table coverage.
1589 l2_offset_u64
= l2_offset_u64
& 0x00000000ffffffff;
1590 l2_offset_u64
= extent
->sesparse_l2_tables_offset
+
1591 l2_offset_u64
* l2_size_bytes
/ SECTOR_SIZE
;
1592 if (l2_offset_u64
> 0x00000000ffffffff) {
1595 l2_offset
= (unsigned int)(l2_offset_u64
);
1598 assert(extent
->entry_size
== sizeof(uint32_t));
1599 l2_offset
= ((uint32_t *)extent
->l1_table
)[l1_index
];
1602 return VMDK_UNALLOC
;
1604 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1605 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1606 /* increment the hit count */
1607 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1608 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1609 extent
->l2_cache_counts
[j
] >>= 1;
1612 l2_table
= (char *)extent
->l2_cache
+ (i
* l2_size_bytes
);
1616 /* not found: load a new entry in the least used one */
1618 min_count
= 0xffffffff;
1619 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1620 if (extent
->l2_cache_counts
[i
] < min_count
) {
1621 min_count
= extent
->l2_cache_counts
[i
];
1625 l2_table
= (char *)extent
->l2_cache
+ (min_index
* l2_size_bytes
);
1626 BLKDBG_EVENT(extent
->file
, BLKDBG_L2_LOAD
);
1627 if (bdrv_pread(extent
->file
,
1628 (int64_t)l2_offset
* 512,
1636 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1637 extent
->l2_cache_counts
[min_index
] = 1;
1639 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1641 m_data
->l1_index
= l1_index
;
1642 m_data
->l2_index
= l2_index
;
1643 m_data
->l2_offset
= l2_offset
;
1644 m_data
->l2_cache_entry
= ((uint32_t *)l2_table
) + l2_index
;
1647 if (extent
->sesparse
) {
1648 cluster_sector
= le64_to_cpu(((uint64_t *)l2_table
)[l2_index
]);
1649 switch (cluster_sector
& 0xf000000000000000) {
1650 case 0x0000000000000000:
1651 /* unallocated grain */
1652 if (cluster_sector
!= 0) {
1656 case 0x1000000000000000:
1657 /* scsi-unmapped grain - fallthrough */
1658 case 0x2000000000000000:
1662 case 0x3000000000000000:
1663 /* allocated grain */
1664 cluster_sector
= (((cluster_sector
& 0x0fff000000000000) >> 48) |
1665 ((cluster_sector
& 0x0000ffffffffffff) << 12));
1666 cluster_sector
= extent
->sesparse_clusters_offset
+
1667 cluster_sector
* extent
->cluster_sectors
;
1673 cluster_sector
= le32_to_cpu(((uint32_t *)l2_table
)[l2_index
]);
1675 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1680 if (!cluster_sector
|| zeroed
) {
1682 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1684 assert(!extent
->sesparse
);
1686 if (extent
->next_cluster_sector
>= VMDK_EXTENT_MAX_SECTORS
) {
1690 cluster_sector
= extent
->next_cluster_sector
;
1691 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1693 /* First of all we write grain itself, to avoid race condition
1694 * that may to corrupt the image.
1695 * This problem may occur because of insufficient space on host disk
1696 * or inappropriate VM shutdown.
1698 ret
= get_whole_cluster(bs
, extent
, cluster_sector
* BDRV_SECTOR_SIZE
,
1699 offset
, skip_start_bytes
, skip_end_bytes
,
1705 m_data
->new_allocation
= true;
1708 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1712 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1713 int64_t sector_num
, VmdkExtent
*start_hint
)
1715 VmdkExtent
*extent
= start_hint
;
1718 extent
= &s
->extents
[0];
1720 while (extent
< &s
->extents
[s
->num_extents
]) {
1721 if (sector_num
< extent
->end_sector
) {
1729 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent
*extent
,
1732 uint64_t extent_begin_offset
, extent_relative_offset
;
1733 uint64_t cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
1735 extent_begin_offset
=
1736 (extent
->end_sector
- extent
->sectors
) * BDRV_SECTOR_SIZE
;
1737 extent_relative_offset
= offset
- extent_begin_offset
;
1738 return extent_relative_offset
% cluster_size
;
1741 static int coroutine_fn
vmdk_co_block_status(BlockDriverState
*bs
,
1743 int64_t offset
, int64_t bytes
,
1744 int64_t *pnum
, int64_t *map
,
1745 BlockDriverState
**file
)
1747 BDRVVmdkState
*s
= bs
->opaque
;
1748 int64_t index_in_cluster
, n
, ret
;
1749 uint64_t cluster_offset
;
1752 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, NULL
);
1756 qemu_co_mutex_lock(&s
->lock
);
1757 ret
= get_cluster_offset(bs
, extent
, NULL
, offset
, false, &cluster_offset
,
1759 qemu_co_mutex_unlock(&s
->lock
);
1761 index_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1770 ret
= BDRV_BLOCK_ZERO
;
1773 ret
= BDRV_BLOCK_DATA
;
1774 if (!extent
->compressed
) {
1775 ret
|= BDRV_BLOCK_OFFSET_VALID
;
1776 *map
= cluster_offset
+ index_in_cluster
;
1778 ret
|= BDRV_BLOCK_RECURSE
;
1781 *file
= extent
->file
->bs
;
1785 n
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
- index_in_cluster
;
1786 *pnum
= MIN(n
, bytes
);
1790 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1791 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1792 uint64_t qiov_offset
, uint64_t n_bytes
,
1796 VmdkGrainMarker
*data
= NULL
;
1798 QEMUIOVector local_qiov
;
1799 int64_t write_offset
;
1800 int64_t write_end_sector
;
1802 if (extent
->compressed
) {
1803 void *compressed_data
;
1805 /* Only whole clusters */
1806 if (offset_in_cluster
||
1807 n_bytes
> (extent
->cluster_sectors
* SECTOR_SIZE
) ||
1808 (n_bytes
< (extent
->cluster_sectors
* SECTOR_SIZE
) &&
1809 offset
+ n_bytes
!= extent
->end_sector
* SECTOR_SIZE
))
1815 if (!extent
->has_marker
) {
1819 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1820 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1822 compressed_data
= g_malloc(n_bytes
);
1823 qemu_iovec_to_buf(qiov
, qiov_offset
, compressed_data
, n_bytes
);
1824 ret
= compress(data
->data
, &buf_len
, compressed_data
, n_bytes
);
1825 g_free(compressed_data
);
1827 if (ret
!= Z_OK
|| buf_len
== 0) {
1832 data
->lba
= cpu_to_le64(offset
>> BDRV_SECTOR_BITS
);
1833 data
->size
= cpu_to_le32(buf_len
);
1835 n_bytes
= buf_len
+ sizeof(VmdkGrainMarker
);
1836 qemu_iovec_init_buf(&local_qiov
, data
, n_bytes
);
1838 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_COMPRESSED
);
1840 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1841 qemu_iovec_concat(&local_qiov
, qiov
, qiov_offset
, n_bytes
);
1843 BLKDBG_EVENT(extent
->file
, BLKDBG_WRITE_AIO
);
1846 write_offset
= cluster_offset
+ offset_in_cluster
;
1847 ret
= bdrv_co_pwritev(extent
->file
, write_offset
, n_bytes
,
1850 write_end_sector
= DIV_ROUND_UP(write_offset
+ n_bytes
, BDRV_SECTOR_SIZE
);
1852 if (extent
->compressed
) {
1853 extent
->next_cluster_sector
= write_end_sector
;
1855 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1865 if (!extent
->compressed
) {
1866 qemu_iovec_destroy(&local_qiov
);
1871 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1872 int64_t offset_in_cluster
, QEMUIOVector
*qiov
,
1876 int cluster_bytes
, buf_bytes
;
1877 uint8_t *cluster_buf
, *compressed_data
;
1878 uint8_t *uncomp_buf
;
1880 VmdkGrainMarker
*marker
;
1884 if (!extent
->compressed
) {
1885 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_AIO
);
1886 ret
= bdrv_co_preadv(extent
->file
,
1887 cluster_offset
+ offset_in_cluster
, bytes
,
1894 cluster_bytes
= extent
->cluster_sectors
* 512;
1895 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1896 buf_bytes
= cluster_bytes
* 2;
1897 cluster_buf
= g_malloc(buf_bytes
);
1898 uncomp_buf
= g_malloc(cluster_bytes
);
1899 BLKDBG_EVENT(extent
->file
, BLKDBG_READ_COMPRESSED
);
1900 ret
= bdrv_pread(extent
->file
, cluster_offset
, buf_bytes
, cluster_buf
, 0);
1904 compressed_data
= cluster_buf
;
1905 buf_len
= cluster_bytes
;
1906 data_len
= cluster_bytes
;
1907 if (extent
->has_marker
) {
1908 marker
= (VmdkGrainMarker
*)cluster_buf
;
1909 compressed_data
= marker
->data
;
1910 data_len
= le32_to_cpu(marker
->size
);
1912 if (!data_len
|| data_len
> buf_bytes
) {
1916 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1922 if (offset_in_cluster
< 0 ||
1923 offset_in_cluster
+ bytes
> buf_len
) {
1927 qemu_iovec_from_buf(qiov
, 0, uncomp_buf
+ offset_in_cluster
, bytes
);
1932 g_free(cluster_buf
);
1936 static int coroutine_fn
1937 vmdk_co_preadv(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1938 QEMUIOVector
*qiov
, BdrvRequestFlags flags
)
1940 BDRVVmdkState
*s
= bs
->opaque
;
1942 uint64_t n_bytes
, offset_in_cluster
;
1943 VmdkExtent
*extent
= NULL
;
1944 QEMUIOVector local_qiov
;
1945 uint64_t cluster_offset
;
1946 uint64_t bytes_done
= 0;
1948 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1949 qemu_co_mutex_lock(&s
->lock
);
1952 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
1957 ret
= get_cluster_offset(bs
, extent
, NULL
,
1958 offset
, false, &cluster_offset
, 0, 0);
1959 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
1961 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
1962 - offset_in_cluster
);
1964 if (ret
!= VMDK_OK
) {
1965 /* if not allocated, try to read from parent image, if exist */
1966 if (bs
->backing
&& ret
!= VMDK_ZEROED
) {
1967 if (!vmdk_is_cid_valid(bs
)) {
1972 qemu_iovec_reset(&local_qiov
);
1973 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1975 /* qcow2 emits this on bs->file instead of bs->backing */
1976 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1977 ret
= bdrv_co_preadv(bs
->backing
, offset
, n_bytes
,
1983 qemu_iovec_memset(qiov
, bytes_done
, 0, n_bytes
);
1986 qemu_iovec_reset(&local_qiov
);
1987 qemu_iovec_concat(&local_qiov
, qiov
, bytes_done
, n_bytes
);
1989 ret
= vmdk_read_extent(extent
, cluster_offset
, offset_in_cluster
,
1990 &local_qiov
, n_bytes
);
1997 bytes_done
+= n_bytes
;
2002 qemu_co_mutex_unlock(&s
->lock
);
2003 qemu_iovec_destroy(&local_qiov
);
2010 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
2011 * if possible, otherwise return -ENOTSUP.
2012 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
2013 * with each cluster. By dry run we can find if the zero write
2014 * is possible without modifying image data.
2016 * Returns: error code with 0 for success.
2018 static int vmdk_pwritev(BlockDriverState
*bs
, uint64_t offset
,
2019 uint64_t bytes
, QEMUIOVector
*qiov
,
2020 bool zeroed
, bool zero_dry_run
)
2022 BDRVVmdkState
*s
= bs
->opaque
;
2023 VmdkExtent
*extent
= NULL
;
2025 int64_t offset_in_cluster
, n_bytes
;
2026 uint64_t cluster_offset
;
2027 uint64_t bytes_done
= 0;
2028 VmdkMetaData m_data
;
2030 if (DIV_ROUND_UP(offset
, BDRV_SECTOR_SIZE
) > bs
->total_sectors
) {
2031 error_report("Wrong offset: offset=0x%" PRIx64
2032 " total_sectors=0x%" PRIx64
,
2033 offset
, bs
->total_sectors
);
2038 extent
= find_extent(s
, offset
>> BDRV_SECTOR_BITS
, extent
);
2042 if (extent
->sesparse
) {
2045 offset_in_cluster
= vmdk_find_offset_in_cluster(extent
, offset
);
2046 n_bytes
= MIN(bytes
, extent
->cluster_sectors
* BDRV_SECTOR_SIZE
2047 - offset_in_cluster
);
2049 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
2050 !(extent
->compressed
|| zeroed
),
2051 &cluster_offset
, offset_in_cluster
,
2052 offset_in_cluster
+ n_bytes
);
2053 if (extent
->compressed
) {
2054 if (ret
== VMDK_OK
) {
2055 /* Refuse write to allocated cluster for streamOptimized */
2056 error_report("Could not write to allocated cluster"
2057 " for streamOptimized");
2059 } else if (!zeroed
) {
2061 ret
= get_cluster_offset(bs
, extent
, &m_data
, offset
,
2062 true, &cluster_offset
, 0, 0);
2065 if (ret
== VMDK_ERROR
) {
2069 /* Do zeroed write, buf is ignored */
2070 if (extent
->has_zero_grain
&&
2071 offset_in_cluster
== 0 &&
2072 n_bytes
>= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
) {
2073 n_bytes
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
;
2074 if (!zero_dry_run
&& ret
!= VMDK_ZEROED
) {
2075 /* update L2 tables */
2076 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
2085 ret
= vmdk_write_extent(extent
, cluster_offset
, offset_in_cluster
,
2086 qiov
, bytes_done
, n_bytes
, offset
);
2090 if (m_data
.new_allocation
) {
2091 /* update L2 tables */
2092 if (vmdk_L2update(extent
, &m_data
,
2093 cluster_offset
>> BDRV_SECTOR_BITS
)
2101 bytes_done
+= n_bytes
;
2103 /* update CID on the first write every time the virtual disk is
2105 if (!s
->cid_updated
) {
2106 ret
= vmdk_write_cid(bs
, g_random_int());
2110 s
->cid_updated
= true;
2116 static int coroutine_fn
2117 vmdk_co_pwritev(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2118 QEMUIOVector
*qiov
, BdrvRequestFlags flags
)
2121 BDRVVmdkState
*s
= bs
->opaque
;
2122 qemu_co_mutex_lock(&s
->lock
);
2123 ret
= vmdk_pwritev(bs
, offset
, bytes
, qiov
, false, false);
2124 qemu_co_mutex_unlock(&s
->lock
);
2128 static int coroutine_fn
2129 vmdk_co_pwritev_compressed(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2133 /* The caller will write bytes 0 to signal EOF.
2134 * When receive it, we align EOF to a sector boundary. */
2135 BDRVVmdkState
*s
= bs
->opaque
;
2139 for (i
= 0; i
< s
->num_extents
; i
++) {
2140 length
= bdrv_getlength(s
->extents
[i
].file
->bs
);
2144 length
= QEMU_ALIGN_UP(length
, BDRV_SECTOR_SIZE
);
2145 ret
= bdrv_truncate(s
->extents
[i
].file
, length
, false,
2146 PREALLOC_MODE_OFF
, 0, NULL
);
2153 return vmdk_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
2156 static int coroutine_fn
vmdk_co_pwrite_zeroes(BlockDriverState
*bs
,
2159 BdrvRequestFlags flags
)
2162 BDRVVmdkState
*s
= bs
->opaque
;
2164 qemu_co_mutex_lock(&s
->lock
);
2165 /* write zeroes could fail if sectors not aligned to cluster, test it with
2166 * dry_run == true before really updating image */
2167 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, true);
2169 ret
= vmdk_pwritev(bs
, offset
, bytes
, NULL
, true, false);
2171 qemu_co_mutex_unlock(&s
->lock
);
2175 static int vmdk_init_extent(BlockBackend
*blk
,
2176 int64_t filesize
, bool flat
,
2177 bool compress
, bool zeroed_grain
,
2182 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
2183 uint32_t *gd_buf
= NULL
;
2187 ret
= blk_truncate(blk
, filesize
, false, PREALLOC_MODE_OFF
, 0, errp
);
2190 magic
= cpu_to_be32(VMDK4_MAGIC
);
2191 memset(&header
, 0, sizeof(header
));
2194 } else if (zeroed_grain
) {
2199 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
2200 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
2201 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
2202 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
2203 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
2204 header
.granularity
= 128;
2205 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
2207 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
2208 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
2210 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
2211 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
2213 header
.desc_offset
= 1;
2214 header
.desc_size
= 20;
2215 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
2216 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
2217 header
.grain_offset
=
2218 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
2219 header
.granularity
);
2220 /* swap endianness for all header fields */
2221 header
.version
= cpu_to_le32(header
.version
);
2222 header
.flags
= cpu_to_le32(header
.flags
);
2223 header
.capacity
= cpu_to_le64(header
.capacity
);
2224 header
.granularity
= cpu_to_le64(header
.granularity
);
2225 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
2226 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
2227 header
.desc_size
= cpu_to_le64(header
.desc_size
);
2228 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
2229 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
2230 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
2231 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
2233 header
.check_bytes
[0] = 0xa;
2234 header
.check_bytes
[1] = 0x20;
2235 header
.check_bytes
[2] = 0xd;
2236 header
.check_bytes
[3] = 0xa;
2238 /* write all the data */
2239 ret
= blk_pwrite(blk
, 0, sizeof(magic
), &magic
, 0);
2241 error_setg(errp
, QERR_IO_ERROR
);
2244 ret
= blk_pwrite(blk
, sizeof(magic
), sizeof(header
), &header
, 0);
2246 error_setg(errp
, QERR_IO_ERROR
);
2250 ret
= blk_truncate(blk
, le64_to_cpu(header
.grain_offset
) << 9, false,
2251 PREALLOC_MODE_OFF
, 0, errp
);
2256 /* write grain directory */
2257 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
2258 gd_buf
= g_malloc0(gd_buf_size
);
2259 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
2260 i
< gt_count
; i
++, tmp
+= gt_size
) {
2261 gd_buf
[i
] = cpu_to_le32(tmp
);
2263 ret
= blk_pwrite(blk
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
2264 gd_buf_size
, gd_buf
, 0);
2266 error_setg(errp
, QERR_IO_ERROR
);
2270 /* write backup grain directory */
2271 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
2272 i
< gt_count
; i
++, tmp
+= gt_size
) {
2273 gd_buf
[i
] = cpu_to_le32(tmp
);
2275 ret
= blk_pwrite(blk
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
2276 gd_buf_size
, gd_buf
, 0);
2278 error_setg(errp
, QERR_IO_ERROR
);
2287 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
2288 bool flat
, bool compress
, bool zeroed_grain
,
2290 QemuOpts
*opts
, Error
**errp
)
2293 BlockBackend
*blk
= NULL
;
2295 ret
= bdrv_create_file(filename
, opts
, errp
);
2300 blk
= blk_new_open(filename
, NULL
, NULL
,
2301 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2308 blk_set_allow_write_beyond_eof(blk
, true);
2310 ret
= vmdk_init_extent(blk
, filesize
, flat
, compress
, zeroed_grain
, errp
);
2323 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
2324 char *postfix
, size_t buf_len
, Error
**errp
)
2328 if (filename
== NULL
|| !strlen(filename
)) {
2329 error_setg(errp
, "No filename provided");
2332 p
= strrchr(filename
, '/');
2334 p
= strrchr(filename
, '\\');
2337 p
= strrchr(filename
, ':');
2341 if (p
- filename
>= buf_len
) {
2344 pstrcpy(path
, p
- filename
+ 1, filename
);
2349 q
= strrchr(p
, '.');
2351 pstrcpy(prefix
, buf_len
, p
);
2354 if (q
- p
>= buf_len
) {
2357 pstrcpy(prefix
, q
- p
+ 1, p
);
2358 pstrcpy(postfix
, buf_len
, q
);
2364 * idx == 0: get or create the descriptor file (also the image file if in a
2366 * idx >= 1: get the n-th extent if in a split subformat
2368 typedef BlockBackend
*(*vmdk_create_extent_fn
)(int64_t size
,
2377 static void vmdk_desc_add_extent(GString
*desc
,
2378 const char *extent_line_fmt
,
2379 int64_t size
, const char *filename
)
2381 char *basename
= g_path_get_basename(filename
);
2383 g_string_append_printf(desc
, extent_line_fmt
,
2384 DIV_ROUND_UP(size
, BDRV_SECTOR_SIZE
), basename
);
2388 static int coroutine_fn
vmdk_co_do_create(int64_t size
,
2389 BlockdevVmdkSubformat subformat
,
2390 BlockdevVmdkAdapterType adapter_type
,
2391 const char *backing_file
,
2392 const char *hw_version
,
2393 const char *toolsversion
,
2396 vmdk_create_extent_fn extent_fn
,
2401 BlockBackend
*blk
= NULL
;
2402 BlockBackend
*extent_blk
;
2403 Error
*local_err
= NULL
;
2406 bool flat
, split
, compress
;
2407 GString
*ext_desc_lines
;
2408 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
2409 int64_t extent_size
;
2410 int64_t created_size
= 0;
2411 const char *extent_line_fmt
;
2412 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
2413 uint32_t parent_cid
= 0xffffffff;
2414 uint32_t number_heads
= 16;
2415 uint32_t desc_offset
= 0, desc_len
;
2416 const char desc_template
[] =
2417 "# Disk DescriptorFile\n"
2420 "parentCID=%" PRIx32
"\n"
2421 "createType=\"%s\"\n"
2424 "# Extent description\n"
2427 "# The Disk Data Base\n"
2430 "ddb.virtualHWVersion = \"%s\"\n"
2431 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
2432 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
2433 "ddb.geometry.sectors = \"63\"\n"
2434 "ddb.adapterType = \"%s\"\n"
2435 "ddb.toolsVersion = \"%s\"\n";
2437 ext_desc_lines
= g_string_new(NULL
);
2439 /* Read out options */
2443 "compat6 cannot be enabled with hwversion set");
2452 if (!toolsversion
) {
2453 toolsversion
= "2147483647";
2456 if (adapter_type
!= BLOCKDEV_VMDK_ADAPTER_TYPE_IDE
) {
2457 /* that's the number of heads with which vmware operates when
2458 creating, exporting, etc. vmdk files with a non-ide adapter type */
2461 split
= (subformat
== BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT
) ||
2462 (subformat
== BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTSPARSE
);
2463 flat
= (subformat
== BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICFLAT
) ||
2464 (subformat
== BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT
);
2465 compress
= subformat
== BLOCKDEV_VMDK_SUBFORMAT_STREAMOPTIMIZED
;
2468 extent_line_fmt
= "RW %" PRId64
" FLAT \"%s\" 0\n";
2470 extent_line_fmt
= "RW %" PRId64
" SPARSE \"%s\"\n";
2472 if (flat
&& backing_file
) {
2473 error_setg(errp
, "Flat image can't have backing file");
2477 if (flat
&& zeroed_grain
) {
2478 error_setg(errp
, "Flat image can't enable zeroed grain");
2483 /* Create extents */
2485 extent_size
= split_size
;
2489 if (!split
&& !flat
) {
2490 created_size
= extent_size
;
2494 /* Get the descriptor file BDS */
2495 blk
= extent_fn(created_size
, 0, flat
, split
, compress
, zeroed_grain
,
2501 if (!split
&& !flat
) {
2502 vmdk_desc_add_extent(ext_desc_lines
, extent_line_fmt
, created_size
,
2503 blk_bs(blk
)->filename
);
2507 BlockBackend
*backing
;
2508 char *full_backing
=
2509 bdrv_get_full_backing_filename_from_filename(blk_bs(blk
)->filename
,
2513 error_propagate(errp
, local_err
);
2517 assert(full_backing
);
2519 backing
= blk_new_open(full_backing
, NULL
, NULL
,
2520 BDRV_O_NO_BACKING
, errp
);
2521 g_free(full_backing
);
2522 if (backing
== NULL
) {
2526 if (strcmp(blk_bs(backing
)->drv
->format_name
, "vmdk")) {
2527 error_setg(errp
, "Invalid backing file format: %s. Must be vmdk",
2528 blk_bs(backing
)->drv
->format_name
);
2533 ret
= vmdk_read_cid(blk_bs(backing
), 0, &parent_cid
);
2536 error_setg(errp
, "Failed to read parent CID");
2539 snprintf(parent_desc_line
, BUF_SIZE
,
2540 "parentFileNameHint=\"%s\"", backing_file
);
2543 while (created_size
< size
) {
2544 int64_t cur_size
= MIN(size
- created_size
, extent_size
);
2545 extent_blk
= extent_fn(cur_size
, extent_idx
, flat
, split
, compress
,
2546 zeroed_grain
, opaque
, errp
);
2551 vmdk_desc_add_extent(ext_desc_lines
, extent_line_fmt
, cur_size
,
2552 blk_bs(extent_blk
)->filename
);
2553 created_size
+= cur_size
;
2555 blk_unref(extent_blk
);
2558 /* Check whether we got excess extents */
2559 extent_blk
= extent_fn(-1, extent_idx
, flat
, split
, compress
, zeroed_grain
,
2562 blk_unref(extent_blk
);
2563 error_setg(errp
, "List of extents contains unused extents");
2568 /* generate descriptor file */
2569 desc
= g_strdup_printf(desc_template
,
2572 BlockdevVmdkSubformat_str(subformat
),
2574 ext_desc_lines
->str
,
2577 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
2579 BlockdevVmdkAdapterType_str(adapter_type
),
2581 desc_len
= strlen(desc
);
2582 /* the descriptor offset = 0x200 */
2583 if (!split
&& !flat
) {
2584 desc_offset
= 0x200;
2587 ret
= blk_pwrite(blk
, desc_offset
, desc_len
, desc
, 0);
2589 error_setg_errno(errp
, -ret
, "Could not write description");
2592 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2593 * for description file */
2594 if (desc_offset
== 0) {
2595 ret
= blk_truncate(blk
, desc_len
, false, PREALLOC_MODE_OFF
, 0, errp
);
2606 g_free(parent_desc_line
);
2607 g_string_free(ext_desc_lines
, true);
2616 } VMDKCreateOptsData
;
2618 static BlockBackend
*vmdk_co_create_opts_cb(int64_t size
, int idx
,
2619 bool flat
, bool split
, bool compress
,
2620 bool zeroed_grain
, void *opaque
,
2623 BlockBackend
*blk
= NULL
;
2624 BlockDriverState
*bs
= NULL
;
2625 VMDKCreateOptsData
*data
= opaque
;
2626 char *ext_filename
= NULL
;
2627 char *rel_filename
= NULL
;
2629 /* We're done, don't create excess extents. */
2631 assert(errp
== NULL
);
2636 rel_filename
= g_strdup_printf("%s%s", data
->prefix
, data
->postfix
);
2638 rel_filename
= g_strdup_printf("%s-%c%03d%s",
2640 flat
? 'f' : 's', idx
, data
->postfix
);
2643 rel_filename
= g_strdup_printf("%s-flat%s", data
->prefix
, data
->postfix
);
2646 ext_filename
= g_strdup_printf("%s%s", data
->path
, rel_filename
);
2647 g_free(rel_filename
);
2649 if (vmdk_create_extent(ext_filename
, size
,
2650 flat
, compress
, zeroed_grain
, &blk
, data
->opts
,
2656 g_free(ext_filename
);
2660 static int coroutine_fn
vmdk_co_create_opts(BlockDriver
*drv
,
2661 const char *filename
,
2665 Error
*local_err
= NULL
;
2667 int64_t total_size
= 0;
2668 char *adapter_type
= NULL
;
2669 BlockdevVmdkAdapterType adapter_type_enum
;
2670 char *backing_file
= NULL
;
2671 char *hw_version
= NULL
;
2672 char *toolsversion
= NULL
;
2674 BlockdevVmdkSubformat subformat
;
2676 char *path
= g_malloc0(PATH_MAX
);
2677 char *prefix
= g_malloc0(PATH_MAX
);
2678 char *postfix
= g_malloc0(PATH_MAX
);
2679 char *desc_line
= g_malloc0(BUF_SIZE
);
2680 char *ext_filename
= g_malloc0(PATH_MAX
);
2681 char *desc_filename
= g_malloc0(PATH_MAX
);
2682 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
2685 VMDKCreateOptsData data
;
2686 char *backing_fmt
= NULL
;
2688 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
2689 if (backing_fmt
&& strcmp(backing_fmt
, "vmdk") != 0) {
2690 error_setg(errp
, "backing_file must be a vmdk image");
2695 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
2699 /* Read out options */
2700 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2702 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
2703 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
2704 hw_version
= qemu_opt_get_del(opts
, BLOCK_OPT_HWVERSION
);
2705 toolsversion
= qemu_opt_get_del(opts
, BLOCK_OPT_TOOLSVERSION
);
2706 compat6
= qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false);
2707 if (strcmp(hw_version
, "undefined") == 0) {
2711 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
2712 zeroed_grain
= qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false);
2715 adapter_type_enum
= qapi_enum_parse(&BlockdevVmdkAdapterType_lookup
,
2717 BLOCKDEV_VMDK_ADAPTER_TYPE_IDE
,
2720 error_propagate(errp
, local_err
);
2725 adapter_type_enum
= BLOCKDEV_VMDK_ADAPTER_TYPE_IDE
;
2729 /* Default format to monolithicSparse */
2730 subformat
= BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE
;
2732 subformat
= qapi_enum_parse(&BlockdevVmdkSubformat_lookup
,
2734 BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE
,
2737 error_propagate(errp
, local_err
);
2742 data
= (VMDKCreateOptsData
){
2748 ret
= vmdk_co_do_create(total_size
, subformat
, adapter_type_enum
,
2749 backing_file
, hw_version
, toolsversion
, compat6
,
2750 zeroed_grain
, vmdk_co_create_opts_cb
, &data
, errp
);
2753 g_free(backing_fmt
);
2754 g_free(adapter_type
);
2755 g_free(backing_file
);
2757 g_free(toolsversion
);
2764 g_free(ext_filename
);
2765 g_free(desc_filename
);
2766 g_free(parent_desc_line
);
2770 static BlockBackend
*vmdk_co_create_cb(int64_t size
, int idx
,
2771 bool flat
, bool split
, bool compress
,
2772 bool zeroed_grain
, void *opaque
,
2776 BlockDriverState
*bs
;
2778 BlockdevCreateOptionsVmdk
*opts
= opaque
;
2781 bs
= bdrv_open_blockdev_ref(opts
->file
, errp
);
2784 BlockdevRefList
*list
= opts
->extents
;
2785 for (i
= 1; i
< idx
; i
++) {
2786 if (!list
|| !list
->next
) {
2787 error_setg(errp
, "Extent [%d] not specified", i
);
2793 error_setg(errp
, "Extent [%d] not specified", idx
- 1);
2796 bs
= bdrv_open_blockdev_ref(list
->value
, errp
);
2801 blk
= blk_new_with_bs(bs
,
2802 BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE
| BLK_PERM_RESIZE
,
2803 BLK_PERM_ALL
, errp
);
2807 blk_set_allow_write_beyond_eof(blk
, true);
2811 ret
= vmdk_init_extent(blk
, size
, flat
, compress
, zeroed_grain
, errp
);
2820 static int coroutine_fn
vmdk_co_create(BlockdevCreateOptions
*create_options
,
2824 BlockdevCreateOptionsVmdk
*opts
;
2826 opts
= &create_options
->u
.vmdk
;
2828 /* Validate options */
2829 if (!QEMU_IS_ALIGNED(opts
->size
, BDRV_SECTOR_SIZE
)) {
2830 error_setg(errp
, "Image size must be a multiple of 512 bytes");
2835 ret
= vmdk_co_do_create(opts
->size
,
2851 static void vmdk_close(BlockDriverState
*bs
)
2853 BDRVVmdkState
*s
= bs
->opaque
;
2855 vmdk_free_extents(bs
);
2856 g_free(s
->create_type
);
2858 migrate_del_blocker(s
->migration_blocker
);
2859 error_free(s
->migration_blocker
);
2862 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2867 BDRVVmdkState
*s
= bs
->opaque
;
2869 ret
= bdrv_get_allocated_file_size(bs
->file
->bs
);
2873 for (i
= 0; i
< s
->num_extents
; i
++) {
2874 if (s
->extents
[i
].file
== bs
->file
) {
2877 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
->bs
);
2886 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2889 BDRVVmdkState
*s
= bs
->opaque
;
2891 /* If has a flat extent and its underlying storage doesn't have zero init,
2893 for (i
= 0; i
< s
->num_extents
; i
++) {
2894 if (s
->extents
[i
].flat
) {
2895 if (!bdrv_has_zero_init(s
->extents
[i
].file
->bs
)) {
2903 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2905 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2907 bdrv_refresh_filename(extent
->file
->bs
);
2908 *info
= (ImageInfo
){
2909 .filename
= g_strdup(extent
->file
->bs
->filename
),
2910 .format
= g_strdup(extent
->type
),
2911 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2912 .compressed
= extent
->compressed
,
2913 .has_compressed
= extent
->compressed
,
2914 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2915 .has_cluster_size
= !extent
->flat
,
2921 static int coroutine_fn
vmdk_co_check(BlockDriverState
*bs
,
2922 BdrvCheckResult
*result
,
2925 BDRVVmdkState
*s
= bs
->opaque
;
2926 VmdkExtent
*extent
= NULL
;
2927 int64_t sector_num
= 0;
2928 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2930 uint64_t cluster_offset
;
2937 if (sector_num
>= total_sectors
) {
2940 extent
= find_extent(s
, sector_num
, extent
);
2943 "ERROR: could not find extent for sector %" PRId64
"\n",
2948 ret
= get_cluster_offset(bs
, extent
, NULL
,
2949 sector_num
<< BDRV_SECTOR_BITS
,
2950 false, &cluster_offset
, 0, 0);
2951 if (ret
== VMDK_ERROR
) {
2953 "ERROR: could not get cluster_offset for sector %"
2954 PRId64
"\n", sector_num
);
2957 if (ret
== VMDK_OK
) {
2958 int64_t extent_len
= bdrv_getlength(extent
->file
->bs
);
2959 if (extent_len
< 0) {
2961 "ERROR: could not get extent file length for sector %"
2962 PRId64
"\n", sector_num
);
2966 if (cluster_offset
>= extent_len
) {
2968 "ERROR: cluster offset for sector %"
2969 PRId64
" points after EOF\n", sector_num
);
2974 sector_num
+= extent
->cluster_sectors
;
2977 result
->corruptions
++;
2981 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
,
2985 BDRVVmdkState
*s
= bs
->opaque
;
2986 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2987 ImageInfoList
**tail
;
2989 *spec_info
= (ImageInfoSpecific
){
2990 .type
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2992 .vmdk
.data
= g_new0(ImageInfoSpecificVmdk
, 1),
2996 *spec_info
->u
.vmdk
.data
= (ImageInfoSpecificVmdk
) {
2997 .create_type
= g_strdup(s
->create_type
),
2999 .parent_cid
= s
->parent_cid
,
3002 tail
= &spec_info
->u
.vmdk
.data
->extents
;
3003 for (i
= 0; i
< s
->num_extents
; i
++) {
3004 QAPI_LIST_APPEND(tail
, vmdk_get_extent_info(&s
->extents
[i
]));
3010 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
3012 return a
->flat
== b
->flat
&&
3013 a
->compressed
== b
->compressed
&&
3014 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
3017 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3020 BDRVVmdkState
*s
= bs
->opaque
;
3021 assert(s
->num_extents
);
3023 /* See if we have multiple extents but they have different cases */
3024 for (i
= 1; i
< s
->num_extents
; i
++) {
3025 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
3029 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
3030 if (!s
->extents
[0].flat
) {
3031 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
3036 static void vmdk_gather_child_options(BlockDriverState
*bs
, QDict
*target
,
3037 bool backing_overridden
)
3039 /* No children but file and backing can be explicitly specified (TODO) */
3040 qdict_put(target
, "file",
3041 qobject_ref(bs
->file
->bs
->full_open_options
));
3043 if (backing_overridden
) {
3045 qdict_put(target
, "backing",
3046 qobject_ref(bs
->backing
->bs
->full_open_options
));
3048 qdict_put_null(target
, "backing");
3053 static QemuOptsList vmdk_create_opts
= {
3054 .name
= "vmdk-create-opts",
3055 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
3058 .name
= BLOCK_OPT_SIZE
,
3059 .type
= QEMU_OPT_SIZE
,
3060 .help
= "Virtual disk size"
3063 .name
= BLOCK_OPT_ADAPTER_TYPE
,
3064 .type
= QEMU_OPT_STRING
,
3065 .help
= "Virtual adapter type, can be one of "
3066 "ide (default), lsilogic, buslogic or legacyESX"
3069 .name
= BLOCK_OPT_BACKING_FILE
,
3070 .type
= QEMU_OPT_STRING
,
3071 .help
= "File name of a base image"
3074 .name
= BLOCK_OPT_BACKING_FMT
,
3075 .type
= QEMU_OPT_STRING
,
3076 .help
= "Must be 'vmdk' if present",
3079 .name
= BLOCK_OPT_COMPAT6
,
3080 .type
= QEMU_OPT_BOOL
,
3081 .help
= "VMDK version 6 image",
3082 .def_value_str
= "off"
3085 .name
= BLOCK_OPT_HWVERSION
,
3086 .type
= QEMU_OPT_STRING
,
3087 .help
= "VMDK hardware version",
3088 .def_value_str
= "undefined"
3091 .name
= BLOCK_OPT_TOOLSVERSION
,
3092 .type
= QEMU_OPT_STRING
,
3093 .help
= "VMware guest tools version",
3096 .name
= BLOCK_OPT_SUBFMT
,
3097 .type
= QEMU_OPT_STRING
,
3099 "VMDK flat extent format, can be one of "
3100 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
3103 .name
= BLOCK_OPT_ZEROED_GRAIN
,
3104 .type
= QEMU_OPT_BOOL
,
3105 .help
= "Enable efficient zero writes "
3106 "using the zeroed-grain GTE feature"
3108 { /* end of list */ }
3112 static BlockDriver bdrv_vmdk
= {
3113 .format_name
= "vmdk",
3114 .instance_size
= sizeof(BDRVVmdkState
),
3115 .bdrv_probe
= vmdk_probe
,
3116 .bdrv_open
= vmdk_open
,
3117 .bdrv_co_check
= vmdk_co_check
,
3118 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
3119 .bdrv_reopen_commit
= vmdk_reopen_commit
,
3120 .bdrv_reopen_abort
= vmdk_reopen_abort
,
3121 .bdrv_child_perm
= bdrv_default_perms
,
3122 .bdrv_co_preadv
= vmdk_co_preadv
,
3123 .bdrv_co_pwritev
= vmdk_co_pwritev
,
3124 .bdrv_co_pwritev_compressed
= vmdk_co_pwritev_compressed
,
3125 .bdrv_co_pwrite_zeroes
= vmdk_co_pwrite_zeroes
,
3126 .bdrv_close
= vmdk_close
,
3127 .bdrv_co_create_opts
= vmdk_co_create_opts
,
3128 .bdrv_co_create
= vmdk_co_create
,
3129 .bdrv_co_block_status
= vmdk_co_block_status
,
3130 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
3131 .bdrv_has_zero_init
= vmdk_has_zero_init
,
3132 .bdrv_get_specific_info
= vmdk_get_specific_info
,
3133 .bdrv_refresh_limits
= vmdk_refresh_limits
,
3134 .bdrv_get_info
= vmdk_get_info
,
3135 .bdrv_gather_child_options
= vmdk_gather_child_options
,
3138 .supports_backing
= true,
3139 .create_opts
= &vmdk_create_opts
,
3142 static void bdrv_vmdk_init(void)
3144 bdrv_register(&bdrv_vmdk
);
3147 block_init(bdrv_vmdk_init
);