2 * Block driver for the VMDK format
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu-common.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "migration/migration.h"
32 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
33 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
34 #define VMDK4_COMPRESSION_DEFLATE 1
35 #define VMDK4_FLAG_NL_DETECT (1 << 0)
36 #define VMDK4_FLAG_RGD (1 << 1)
37 /* Zeroed-grain enable bit */
38 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
39 #define VMDK4_FLAG_COMPRESS (1 << 16)
40 #define VMDK4_FLAG_MARKER (1 << 17)
41 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
43 #define VMDK_GTE_ZEROED 0x1
45 /* VMDK internal error codes */
47 #define VMDK_ERROR (-1)
48 /* Cluster not allocated */
49 #define VMDK_UNALLOC (-2)
50 #define VMDK_ZEROED (-3)
52 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
57 uint32_t disk_sectors
;
59 uint32_t l1dir_offset
;
61 uint32_t file_sectors
;
64 uint32_t sectors_per_track
;
65 } QEMU_PACKED VMDK3Header
;
74 /* Number of GrainTableEntries per GrainTable */
75 uint32_t num_gtes_per_gt
;
78 uint64_t grain_offset
;
81 uint16_t compressAlgorithm
;
82 } QEMU_PACKED VMDK4Header
;
84 #define L2_CACHE_SIZE 16
86 typedef struct VmdkExtent
{
87 BlockDriverState
*file
;
95 int64_t flat_start_offset
;
96 int64_t l1_table_offset
;
97 int64_t l1_backup_table_offset
;
99 uint32_t *l1_backup_table
;
100 unsigned int l1_size
;
101 uint32_t l1_entry_sectors
;
103 unsigned int l2_size
;
105 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
106 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
108 int64_t cluster_sectors
;
109 int64_t next_cluster_sector
;
113 typedef struct BDRVVmdkState
{
115 uint64_t desc_offset
;
121 /* Extent array with num_extents entries, ascend ordered by address */
123 Error
*migration_blocker
;
127 typedef struct VmdkMetaData
{
128 unsigned int l1_index
;
129 unsigned int l2_index
;
130 unsigned int l2_offset
;
132 uint32_t *l2_cache_entry
;
135 typedef struct VmdkGrainMarker
{
139 } QEMU_PACKED VmdkGrainMarker
;
142 MARKER_END_OF_STREAM
= 0,
143 MARKER_GRAIN_TABLE
= 1,
144 MARKER_GRAIN_DIRECTORY
= 2,
148 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
155 magic
= be32_to_cpu(*(uint32_t *)buf
);
156 if (magic
== VMDK3_MAGIC
||
157 magic
== VMDK4_MAGIC
) {
160 const char *p
= (const char *)buf
;
161 const char *end
= p
+ buf_size
;
164 /* skip comment line */
165 while (p
< end
&& *p
!= '\n') {
172 while (p
< end
&& *p
== ' ') {
175 /* skip '\r' if windows line endings used. */
176 if (p
< end
&& *p
== '\r') {
179 /* only accept blank lines before 'version=' line */
180 if (p
== end
|| *p
!= '\n') {
186 if (end
- p
>= strlen("version=X\n")) {
187 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
188 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
192 if (end
- p
>= strlen("version=X\r\n")) {
193 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
194 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
204 #define SECTOR_SIZE 512
205 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
206 #define BUF_SIZE 4096
207 #define HEADER_SIZE 512 /* first sector of 512 bytes */
209 static void vmdk_free_extents(BlockDriverState
*bs
)
212 BDRVVmdkState
*s
= bs
->opaque
;
215 for (i
= 0; i
< s
->num_extents
; i
++) {
219 g_free(e
->l1_backup_table
);
221 if (e
->file
!= bs
->file
) {
228 static void vmdk_free_last_extent(BlockDriverState
*bs
)
230 BDRVVmdkState
*s
= bs
->opaque
;
232 if (s
->num_extents
== 0) {
236 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
239 static uint32_t vmdk_read_cid(BlockDriverState
*bs
, int parent
)
241 char desc
[DESC_SIZE
];
242 uint32_t cid
= 0xffffffff;
243 const char *p_name
, *cid_str
;
245 BDRVVmdkState
*s
= bs
->opaque
;
248 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
254 cid_str
= "parentCID";
255 cid_str_size
= sizeof("parentCID");
258 cid_str_size
= sizeof("CID");
261 desc
[DESC_SIZE
- 1] = '\0';
262 p_name
= strstr(desc
, cid_str
);
263 if (p_name
!= NULL
) {
264 p_name
+= cid_str_size
;
265 sscanf(p_name
, "%" SCNx32
, &cid
);
271 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
273 char desc
[DESC_SIZE
], tmp_desc
[DESC_SIZE
];
274 char *p_name
, *tmp_str
;
275 BDRVVmdkState
*s
= bs
->opaque
;
278 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
283 desc
[DESC_SIZE
- 1] = '\0';
284 tmp_str
= strstr(desc
, "parentCID");
285 if (tmp_str
== NULL
) {
289 pstrcpy(tmp_desc
, sizeof(tmp_desc
), tmp_str
);
290 p_name
= strstr(desc
, "CID");
291 if (p_name
!= NULL
) {
292 p_name
+= sizeof("CID");
293 snprintf(p_name
, sizeof(desc
) - (p_name
- desc
), "%" PRIx32
"\n", cid
);
294 pstrcat(desc
, sizeof(desc
), tmp_desc
);
297 ret
= bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
305 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
307 BDRVVmdkState
*s
= bs
->opaque
;
308 BlockDriverState
*p_bs
= bs
->backing_hd
;
311 if (!s
->cid_checked
&& p_bs
) {
312 cur_pcid
= vmdk_read_cid(p_bs
, 0);
313 if (s
->parent_cid
!= cur_pcid
) {
318 s
->cid_checked
= true;
323 /* Queue extents, if any, for reopen() */
324 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
325 BlockReopenQueue
*queue
, Error
**errp
)
332 assert(state
!= NULL
);
333 assert(state
->bs
!= NULL
);
336 error_setg(errp
, "No reopen queue for VMDK extents");
340 s
= state
->bs
->opaque
;
344 for (i
= 0; i
< s
->num_extents
; i
++) {
346 if (e
->file
!= state
->bs
->file
) {
347 bdrv_reopen_queue(queue
, e
->file
, state
->flags
);
356 static int vmdk_parent_open(BlockDriverState
*bs
)
359 char desc
[DESC_SIZE
+ 1];
360 BDRVVmdkState
*s
= bs
->opaque
;
363 desc
[DESC_SIZE
] = '\0';
364 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
369 p_name
= strstr(desc
, "parentFileNameHint");
370 if (p_name
!= NULL
) {
373 p_name
+= sizeof("parentFileNameHint") + 1;
374 end_name
= strchr(p_name
, '\"');
375 if (end_name
== NULL
) {
378 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
382 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
388 /* Create and append extent to the extent array. Return the added VmdkExtent
389 * address. return NULL if allocation failed. */
390 static int vmdk_add_extent(BlockDriverState
*bs
,
391 BlockDriverState
*file
, bool flat
, int64_t sectors
,
392 int64_t l1_offset
, int64_t l1_backup_offset
,
394 int l2_size
, uint64_t cluster_sectors
,
395 VmdkExtent
**new_extent
,
399 BDRVVmdkState
*s
= bs
->opaque
;
402 if (cluster_sectors
> 0x200000) {
403 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
404 error_setg(errp
, "Invalid granularity, image may be corrupt");
407 if (l1_size
> 512 * 1024 * 1024) {
408 /* Although with big capacity and small l1_entry_sectors, we can get a
409 * big l1_size, we don't want unbounded value to allocate the table.
410 * Limit it to 512M, which is 16PB for default cluster and L2 table
412 error_setg(errp
, "L1 size too big");
416 nb_sectors
= bdrv_nb_sectors(file
);
417 if (nb_sectors
< 0) {
421 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
422 extent
= &s
->extents
[s
->num_extents
];
425 memset(extent
, 0, sizeof(VmdkExtent
));
428 extent
->sectors
= sectors
;
429 extent
->l1_table_offset
= l1_offset
;
430 extent
->l1_backup_table_offset
= l1_backup_offset
;
431 extent
->l1_size
= l1_size
;
432 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
433 extent
->l2_size
= l2_size
;
434 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
435 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
437 if (s
->num_extents
> 1) {
438 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
440 extent
->end_sector
= extent
->sectors
;
442 bs
->total_sectors
= extent
->end_sector
;
444 *new_extent
= extent
;
449 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
455 /* read the L1 table */
456 l1_size
= extent
->l1_size
* sizeof(uint32_t);
457 extent
->l1_table
= g_try_malloc(l1_size
);
458 if (l1_size
&& extent
->l1_table
== NULL
) {
462 ret
= bdrv_pread(extent
->file
,
463 extent
->l1_table_offset
,
467 error_setg_errno(errp
, -ret
,
468 "Could not read l1 table from extent '%s'",
469 extent
->file
->filename
);
472 for (i
= 0; i
< extent
->l1_size
; i
++) {
473 le32_to_cpus(&extent
->l1_table
[i
]);
476 if (extent
->l1_backup_table_offset
) {
477 extent
->l1_backup_table
= g_try_malloc(l1_size
);
478 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
482 ret
= bdrv_pread(extent
->file
,
483 extent
->l1_backup_table_offset
,
484 extent
->l1_backup_table
,
487 error_setg_errno(errp
, -ret
,
488 "Could not read l1 backup table from extent '%s'",
489 extent
->file
->filename
);
492 for (i
= 0; i
< extent
->l1_size
; i
++) {
493 le32_to_cpus(&extent
->l1_backup_table
[i
]);
498 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
501 g_free(extent
->l1_backup_table
);
503 g_free(extent
->l1_table
);
507 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
508 BlockDriverState
*file
,
509 int flags
, Error
**errp
)
516 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
518 error_setg_errno(errp
, -ret
,
519 "Could not read header from file '%s'",
523 ret
= vmdk_add_extent(bs
, file
, false,
524 le32_to_cpu(header
.disk_sectors
),
525 le32_to_cpu(header
.l1dir_offset
) << 9,
527 le32_to_cpu(header
.l1dir_size
),
529 le32_to_cpu(header
.granularity
),
535 ret
= vmdk_init_tables(bs
, extent
, errp
);
537 /* free extent allocated by vmdk_add_extent */
538 vmdk_free_last_extent(bs
);
543 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
546 static char *vmdk_read_desc(BlockDriverState
*file
, uint64_t desc_offset
,
553 size
= bdrv_getlength(file
);
555 error_setg_errno(errp
, -size
, "Could not access file");
559 size
= MIN(size
, 1 << 20); /* avoid unbounded allocation */
560 buf
= g_malloc0(size
+ 1);
562 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
564 error_setg_errno(errp
, -ret
, "Could not read from file");
572 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
573 BlockDriverState
*file
,
574 int flags
, Error
**errp
)
578 uint32_t l1_size
, l1_entry_sectors
;
581 BDRVVmdkState
*s
= bs
->opaque
;
582 int64_t l1_backup_offset
= 0;
584 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
586 error_setg_errno(errp
, -ret
,
587 "Could not read header from file '%s'",
591 if (header
.capacity
== 0) {
592 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
594 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
598 ret
= vmdk_open_desc_file(bs
, flags
, buf
, errp
);
604 if (!s
->create_type
) {
605 s
->create_type
= g_strdup("monolithicSparse");
608 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
610 * The footer takes precedence over the header, so read it in. The
611 * footer starts at offset -1024 from the end: One sector for the
612 * footer, and another one for the end-of-stream marker.
619 uint8_t pad
[512 - 16];
620 } QEMU_PACKED footer_marker
;
624 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
630 uint8_t pad
[512 - 16];
631 } QEMU_PACKED eos_marker
;
632 } QEMU_PACKED footer
;
634 ret
= bdrv_pread(file
,
635 bs
->file
->total_sectors
* 512 - 1536,
636 &footer
, sizeof(footer
));
641 /* Some sanity checks for the footer */
642 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
643 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
644 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
645 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
646 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
647 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
652 header
= footer
.header
;
655 if (le32_to_cpu(header
.version
) > 3) {
657 snprintf(buf
, sizeof(buf
), "VMDK version %" PRId32
,
658 le32_to_cpu(header
.version
));
659 error_set(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
,
660 bs
->device_name
, "vmdk", buf
);
662 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
)) {
663 /* VMware KB 2064959 explains that version 3 added support for
664 * persistent changed block tracking (CBT), and backup software can
665 * read it as version=1 if it doesn't care about the changed area
666 * information. So we are safe to enable read only. */
667 error_setg(errp
, "VMDK version 3 must be read only");
671 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
672 error_setg(errp
, "L2 table size too big");
676 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
677 * le64_to_cpu(header
.granularity
);
678 if (l1_entry_sectors
== 0) {
681 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
683 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
684 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
686 if (bdrv_nb_sectors(file
) < le64_to_cpu(header
.grain_offset
)) {
687 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
688 (int64_t)(le64_to_cpu(header
.grain_offset
)
689 * BDRV_SECTOR_SIZE
));
693 ret
= vmdk_add_extent(bs
, file
, false,
694 le64_to_cpu(header
.capacity
),
695 le64_to_cpu(header
.gd_offset
) << 9,
698 le32_to_cpu(header
.num_gtes_per_gt
),
699 le64_to_cpu(header
.granularity
),
706 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
707 if (extent
->compressed
) {
708 g_free(s
->create_type
);
709 s
->create_type
= g_strdup("streamOptimized");
711 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
712 extent
->version
= le32_to_cpu(header
.version
);
713 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
714 ret
= vmdk_init_tables(bs
, extent
, errp
);
716 /* free extent allocated by vmdk_add_extent */
717 vmdk_free_last_extent(bs
);
722 /* find an option value out of descriptor file */
723 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
724 char *buf
, int buf_size
)
726 char *opt_pos
, *opt_end
;
727 const char *end
= desc
+ strlen(desc
);
729 opt_pos
= strstr(desc
, opt_name
);
733 /* Skip "=\"" following opt_name */
734 opt_pos
+= strlen(opt_name
) + 2;
735 if (opt_pos
>= end
) {
739 while (opt_end
< end
&& *opt_end
!= '"') {
742 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
745 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
749 /* Open an extent file and append to bs array */
750 static int vmdk_open_sparse(BlockDriverState
*bs
,
751 BlockDriverState
*file
, int flags
,
752 char *buf
, Error
**errp
)
756 magic
= ldl_be_p(buf
);
759 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
762 return vmdk_open_vmdk4(bs
, file
, flags
, errp
);
765 error_setg(errp
, "Image not in VMDK format");
771 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
772 const char *desc_file_path
, Error
**errp
)
778 const char *p
= desc
;
781 char extent_path
[PATH_MAX
];
782 BlockDriverState
*extent_file
;
783 BDRVVmdkState
*s
= bs
->opaque
;
787 /* parse extent line:
788 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
790 * RW [size in sectors] SPARSE "file-name.vmdk"
793 ret
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
794 access
, §ors
, type
, fname
, &flat_offset
);
795 if (ret
< 4 || strcmp(access
, "RW")) {
797 } else if (!strcmp(type
, "FLAT")) {
798 if (ret
!= 5 || flat_offset
< 0) {
799 error_setg(errp
, "Invalid extent lines: \n%s", p
);
802 } else if (!strcmp(type
, "VMFS")) {
806 error_setg(errp
, "Invalid extent lines:\n%s", p
);
809 } else if (ret
!= 4) {
810 error_setg(errp
, "Invalid extent lines:\n%s", p
);
815 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
816 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
817 (strcmp(access
, "RW"))) {
821 path_combine(extent_path
, sizeof(extent_path
),
822 desc_file_path
, fname
);
824 ret
= bdrv_open(&extent_file
, extent_path
, NULL
, NULL
,
825 bs
->open_flags
| BDRV_O_PROTOCOL
, NULL
, errp
);
830 /* save to extents array */
831 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
834 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
835 0, 0, 0, 0, 0, &extent
, errp
);
839 extent
->flat_start_offset
= flat_offset
<< 9;
840 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
841 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
842 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
846 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
, errp
);
850 bdrv_unref(extent_file
);
853 extent
= &s
->extents
[s
->num_extents
- 1];
855 error_setg(errp
, "Unsupported extent type '%s'", type
);
858 extent
->type
= g_strdup(type
);
860 /* move to next line */
872 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
877 BDRVVmdkState
*s
= bs
->opaque
;
879 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
880 error_setg(errp
, "invalid VMDK image descriptor");
884 if (strcmp(ct
, "monolithicFlat") &&
885 strcmp(ct
, "vmfs") &&
886 strcmp(ct
, "vmfsSparse") &&
887 strcmp(ct
, "twoGbMaxExtentSparse") &&
888 strcmp(ct
, "twoGbMaxExtentFlat")) {
889 error_setg(errp
, "Unsupported image type '%s'", ct
);
893 s
->create_type
= g_strdup(ct
);
895 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->filename
, errp
);
900 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
905 BDRVVmdkState
*s
= bs
->opaque
;
908 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
913 magic
= ldl_be_p(buf
);
917 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, errp
);
918 s
->desc_offset
= 0x200;
921 ret
= vmdk_open_desc_file(bs
, flags
, buf
, errp
);
928 /* try to open parent images, if exist */
929 ret
= vmdk_parent_open(bs
);
933 s
->cid
= vmdk_read_cid(bs
, 0);
934 s
->parent_cid
= vmdk_read_cid(bs
, 1);
935 qemu_co_mutex_init(&s
->lock
);
937 /* Disable migration when VMDK images are used */
938 error_set(&s
->migration_blocker
,
939 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED
,
940 "vmdk", bs
->device_name
, "live migration");
941 migrate_add_blocker(s
->migration_blocker
);
947 g_free(s
->create_type
);
948 s
->create_type
= NULL
;
949 vmdk_free_extents(bs
);
954 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
956 BDRVVmdkState
*s
= bs
->opaque
;
959 for (i
= 0; i
< s
->num_extents
; i
++) {
960 if (!s
->extents
[i
].flat
) {
961 bs
->bl
.write_zeroes_alignment
=
962 MAX(bs
->bl
.write_zeroes_alignment
,
963 s
->extents
[i
].cluster_sectors
);
971 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
972 * to the cluster at @cluster_sector_num.
974 * If @skip_start_sector < @skip_end_sector, the relative range
975 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
976 * it for call to write user data in the request.
978 static int get_whole_cluster(BlockDriverState
*bs
,
980 uint64_t cluster_sector_num
,
982 uint64_t skip_start_sector
,
983 uint64_t skip_end_sector
)
986 int64_t cluster_bytes
;
987 uint8_t *whole_grain
;
989 /* For COW, align request sector_num to cluster start */
990 sector_num
= QEMU_ALIGN_DOWN(sector_num
, extent
->cluster_sectors
);
991 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
992 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
994 if (!bs
->backing_hd
) {
995 memset(whole_grain
, 0, skip_start_sector
<< BDRV_SECTOR_BITS
);
996 memset(whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
), 0,
997 cluster_bytes
- (skip_end_sector
<< BDRV_SECTOR_BITS
));
1000 assert(skip_end_sector
<= extent
->cluster_sectors
);
1001 /* we will be here if it's first write on non-exist grain(cluster).
1002 * try to read from parent image, if exist */
1003 if (bs
->backing_hd
&& !vmdk_is_cid_valid(bs
)) {
1008 /* Read backing data before skip range */
1009 if (skip_start_sector
> 0) {
1010 if (bs
->backing_hd
) {
1011 ret
= bdrv_read(bs
->backing_hd
, sector_num
,
1012 whole_grain
, skip_start_sector
);
1018 ret
= bdrv_write(extent
->file
, cluster_sector_num
, whole_grain
,
1025 /* Read backing data after skip range */
1026 if (skip_end_sector
< extent
->cluster_sectors
) {
1027 if (bs
->backing_hd
) {
1028 ret
= bdrv_read(bs
->backing_hd
, sector_num
+ skip_end_sector
,
1029 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1030 extent
->cluster_sectors
- skip_end_sector
);
1036 ret
= bdrv_write(extent
->file
, cluster_sector_num
+ skip_end_sector
,
1037 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1038 extent
->cluster_sectors
- skip_end_sector
);
1046 qemu_vfree(whole_grain
);
1050 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1053 offset
= cpu_to_le32(offset
);
1054 /* update L2 table */
1055 if (bdrv_pwrite_sync(
1057 ((int64_t)m_data
->l2_offset
* 512)
1058 + (m_data
->l2_index
* sizeof(offset
)),
1059 &offset
, sizeof(offset
)) < 0) {
1062 /* update backup L2 table */
1063 if (extent
->l1_backup_table_offset
!= 0) {
1064 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1065 if (bdrv_pwrite_sync(
1067 ((int64_t)m_data
->l2_offset
* 512)
1068 + (m_data
->l2_index
* sizeof(offset
)),
1069 &offset
, sizeof(offset
)) < 0) {
1073 if (m_data
->l2_cache_entry
) {
1074 *m_data
->l2_cache_entry
= offset
;
1081 * get_cluster_offset
1083 * Look up cluster offset in extent file by sector number, and store in
1086 * For flat extents, the start offset as parsed from the description file is
1089 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1090 * offset for a new cluster and update L2 cache. If there is a backing file,
1091 * COW is done before returning; otherwise, zeroes are written to the allocated
1092 * cluster. Both COW and zero writing skips the sector range
1093 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1094 * has new data to write there.
1096 * Returns: VMDK_OK if cluster exists and mapped in the image.
1097 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1098 * VMDK_ERROR if failed.
1100 static int get_cluster_offset(BlockDriverState
*bs
,
1102 VmdkMetaData
*m_data
,
1105 uint64_t *cluster_offset
,
1106 uint64_t skip_start_sector
,
1107 uint64_t skip_end_sector
)
1109 unsigned int l1_index
, l2_offset
, l2_index
;
1110 int min_index
, i
, j
;
1111 uint32_t min_count
, *l2_table
;
1112 bool zeroed
= false;
1114 int32_t cluster_sector
;
1120 *cluster_offset
= extent
->flat_start_offset
;
1124 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1125 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1126 if (l1_index
>= extent
->l1_size
) {
1129 l2_offset
= extent
->l1_table
[l1_index
];
1131 return VMDK_UNALLOC
;
1133 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1134 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1135 /* increment the hit count */
1136 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1137 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1138 extent
->l2_cache_counts
[j
] >>= 1;
1141 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1145 /* not found: load a new entry in the least used one */
1147 min_count
= 0xffffffff;
1148 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1149 if (extent
->l2_cache_counts
[i
] < min_count
) {
1150 min_count
= extent
->l2_cache_counts
[i
];
1154 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1157 (int64_t)l2_offset
* 512,
1159 extent
->l2_size
* sizeof(uint32_t)
1160 ) != extent
->l2_size
* sizeof(uint32_t)) {
1164 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1165 extent
->l2_cache_counts
[min_index
] = 1;
1167 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1168 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1172 m_data
->l1_index
= l1_index
;
1173 m_data
->l2_index
= l2_index
;
1174 m_data
->l2_offset
= l2_offset
;
1175 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1177 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1181 if (!cluster_sector
|| zeroed
) {
1183 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1186 cluster_sector
= extent
->next_cluster_sector
;
1187 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1189 /* First of all we write grain itself, to avoid race condition
1190 * that may to corrupt the image.
1191 * This problem may occur because of insufficient space on host disk
1192 * or inappropriate VM shutdown.
1194 ret
= get_whole_cluster(bs
, extent
,
1196 offset
>> BDRV_SECTOR_BITS
,
1197 skip_start_sector
, skip_end_sector
);
1202 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1206 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1207 int64_t sector_num
, VmdkExtent
*start_hint
)
1209 VmdkExtent
*extent
= start_hint
;
1212 extent
= &s
->extents
[0];
1214 while (extent
< &s
->extents
[s
->num_extents
]) {
1215 if (sector_num
< extent
->end_sector
) {
1223 static int64_t coroutine_fn
vmdk_co_get_block_status(BlockDriverState
*bs
,
1224 int64_t sector_num
, int nb_sectors
, int *pnum
)
1226 BDRVVmdkState
*s
= bs
->opaque
;
1227 int64_t index_in_cluster
, n
, ret
;
1231 extent
= find_extent(s
, sector_num
, NULL
);
1235 qemu_co_mutex_lock(&s
->lock
);
1236 ret
= get_cluster_offset(bs
, extent
, NULL
,
1237 sector_num
* 512, false, &offset
,
1239 qemu_co_mutex_unlock(&s
->lock
);
1249 ret
= BDRV_BLOCK_ZERO
;
1252 ret
= BDRV_BLOCK_DATA
;
1253 if (extent
->file
== bs
->file
&& !extent
->compressed
) {
1254 ret
|= BDRV_BLOCK_OFFSET_VALID
| offset
;
1260 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
1261 n
= extent
->cluster_sectors
- index_in_cluster
;
1262 if (n
> nb_sectors
) {
1269 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1270 int64_t offset_in_cluster
, const uint8_t *buf
,
1271 int nb_sectors
, int64_t sector_num
)
1274 VmdkGrainMarker
*data
= NULL
;
1276 const uint8_t *write_buf
= buf
;
1277 int write_len
= nb_sectors
* 512;
1279 if (extent
->compressed
) {
1280 if (!extent
->has_marker
) {
1284 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1285 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1286 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
1291 data
->lba
= sector_num
;
1292 data
->size
= buf_len
;
1293 write_buf
= (uint8_t *)data
;
1294 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
1296 ret
= bdrv_pwrite(extent
->file
,
1297 cluster_offset
+ offset_in_cluster
,
1300 if (ret
!= write_len
) {
1301 ret
= ret
< 0 ? ret
: -EIO
;
1310 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1311 int64_t offset_in_cluster
, uint8_t *buf
,
1315 int cluster_bytes
, buf_bytes
;
1316 uint8_t *cluster_buf
, *compressed_data
;
1317 uint8_t *uncomp_buf
;
1319 VmdkGrainMarker
*marker
;
1323 if (!extent
->compressed
) {
1324 ret
= bdrv_pread(extent
->file
,
1325 cluster_offset
+ offset_in_cluster
,
1326 buf
, nb_sectors
* 512);
1327 if (ret
== nb_sectors
* 512) {
1333 cluster_bytes
= extent
->cluster_sectors
* 512;
1334 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1335 buf_bytes
= cluster_bytes
* 2;
1336 cluster_buf
= g_malloc(buf_bytes
);
1337 uncomp_buf
= g_malloc(cluster_bytes
);
1338 ret
= bdrv_pread(extent
->file
,
1340 cluster_buf
, buf_bytes
);
1344 compressed_data
= cluster_buf
;
1345 buf_len
= cluster_bytes
;
1346 data_len
= cluster_bytes
;
1347 if (extent
->has_marker
) {
1348 marker
= (VmdkGrainMarker
*)cluster_buf
;
1349 compressed_data
= marker
->data
;
1350 data_len
= le32_to_cpu(marker
->size
);
1352 if (!data_len
|| data_len
> buf_bytes
) {
1356 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1362 if (offset_in_cluster
< 0 ||
1363 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
1367 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
1372 g_free(cluster_buf
);
1376 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
1377 uint8_t *buf
, int nb_sectors
)
1379 BDRVVmdkState
*s
= bs
->opaque
;
1381 uint64_t n
, index_in_cluster
;
1382 uint64_t extent_begin_sector
, extent_relative_sector_num
;
1383 VmdkExtent
*extent
= NULL
;
1384 uint64_t cluster_offset
;
1386 while (nb_sectors
> 0) {
1387 extent
= find_extent(s
, sector_num
, extent
);
1391 ret
= get_cluster_offset(bs
, extent
, NULL
,
1392 sector_num
<< 9, false, &cluster_offset
,
1394 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1395 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1396 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1397 n
= extent
->cluster_sectors
- index_in_cluster
;
1398 if (n
> nb_sectors
) {
1401 if (ret
!= VMDK_OK
) {
1402 /* if not allocated, try to read from parent image, if exist */
1403 if (bs
->backing_hd
&& ret
!= VMDK_ZEROED
) {
1404 if (!vmdk_is_cid_valid(bs
)) {
1407 ret
= bdrv_read(bs
->backing_hd
, sector_num
, buf
, n
);
1412 memset(buf
, 0, 512 * n
);
1415 ret
= vmdk_read_extent(extent
,
1416 cluster_offset
, index_in_cluster
* 512,
1429 static coroutine_fn
int vmdk_co_read(BlockDriverState
*bs
, int64_t sector_num
,
1430 uint8_t *buf
, int nb_sectors
)
1433 BDRVVmdkState
*s
= bs
->opaque
;
1434 qemu_co_mutex_lock(&s
->lock
);
1435 ret
= vmdk_read(bs
, sector_num
, buf
, nb_sectors
);
1436 qemu_co_mutex_unlock(&s
->lock
);
1442 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1443 * if possible, otherwise return -ENOTSUP.
1444 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1445 * with each cluster. By dry run we can find if the zero write
1446 * is possible without modifying image data.
1448 * Returns: error code with 0 for success.
1450 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1451 const uint8_t *buf
, int nb_sectors
,
1452 bool zeroed
, bool zero_dry_run
)
1454 BDRVVmdkState
*s
= bs
->opaque
;
1455 VmdkExtent
*extent
= NULL
;
1457 int64_t index_in_cluster
, n
;
1458 uint64_t extent_begin_sector
, extent_relative_sector_num
;
1459 uint64_t cluster_offset
;
1460 VmdkMetaData m_data
;
1462 if (sector_num
> bs
->total_sectors
) {
1463 error_report("Wrong offset: sector_num=0x%" PRIx64
1464 " total_sectors=0x%" PRIx64
"\n",
1465 sector_num
, bs
->total_sectors
);
1469 while (nb_sectors
> 0) {
1470 extent
= find_extent(s
, sector_num
, extent
);
1474 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1475 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1476 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1477 n
= extent
->cluster_sectors
- index_in_cluster
;
1478 if (n
> nb_sectors
) {
1481 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1482 !(extent
->compressed
|| zeroed
),
1484 index_in_cluster
, index_in_cluster
+ n
);
1485 if (extent
->compressed
) {
1486 if (ret
== VMDK_OK
) {
1487 /* Refuse write to allocated cluster for streamOptimized */
1488 error_report("Could not write to allocated cluster"
1489 " for streamOptimized");
1493 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1494 true, &cluster_offset
, 0, 0);
1497 if (ret
== VMDK_ERROR
) {
1501 /* Do zeroed write, buf is ignored */
1502 if (extent
->has_zero_grain
&&
1503 index_in_cluster
== 0 &&
1504 n
>= extent
->cluster_sectors
) {
1505 n
= extent
->cluster_sectors
;
1506 if (!zero_dry_run
) {
1507 /* update L2 tables */
1508 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1517 ret
= vmdk_write_extent(extent
,
1518 cluster_offset
, index_in_cluster
* 512,
1519 buf
, n
, sector_num
);
1524 /* update L2 tables */
1525 if (vmdk_L2update(extent
, &m_data
,
1526 cluster_offset
>> BDRV_SECTOR_BITS
)
1536 /* update CID on the first write every time the virtual disk is
1538 if (!s
->cid_updated
) {
1539 ret
= vmdk_write_cid(bs
, time(NULL
));
1543 s
->cid_updated
= true;
1549 static coroutine_fn
int vmdk_co_write(BlockDriverState
*bs
, int64_t sector_num
,
1550 const uint8_t *buf
, int nb_sectors
)
1553 BDRVVmdkState
*s
= bs
->opaque
;
1554 qemu_co_mutex_lock(&s
->lock
);
1555 ret
= vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1556 qemu_co_mutex_unlock(&s
->lock
);
1560 static int vmdk_write_compressed(BlockDriverState
*bs
,
1565 BDRVVmdkState
*s
= bs
->opaque
;
1566 if (s
->num_extents
== 1 && s
->extents
[0].compressed
) {
1567 return vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1573 static int coroutine_fn
vmdk_co_write_zeroes(BlockDriverState
*bs
,
1576 BdrvRequestFlags flags
)
1579 BDRVVmdkState
*s
= bs
->opaque
;
1580 qemu_co_mutex_lock(&s
->lock
);
1581 /* write zeroes could fail if sectors not aligned to cluster, test it with
1582 * dry_run == true before really updating image */
1583 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, true);
1585 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, false);
1587 qemu_co_mutex_unlock(&s
->lock
);
1591 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1592 bool flat
, bool compress
, bool zeroed_grain
,
1593 QemuOpts
*opts
, Error
**errp
)
1596 BlockDriverState
*bs
= NULL
;
1598 Error
*local_err
= NULL
;
1599 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1600 uint32_t *gd_buf
= NULL
;
1603 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1605 error_propagate(errp
, local_err
);
1610 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, BDRV_O_RDWR
| BDRV_O_PROTOCOL
,
1613 error_propagate(errp
, local_err
);
1618 ret
= bdrv_truncate(bs
, filesize
);
1620 error_setg_errno(errp
, -ret
, "Could not truncate file");
1624 magic
= cpu_to_be32(VMDK4_MAGIC
);
1625 memset(&header
, 0, sizeof(header
));
1626 header
.version
= zeroed_grain
? 2 : 1;
1627 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1628 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1629 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1630 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1631 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1632 header
.granularity
= 128;
1633 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1635 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1636 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1638 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1639 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1641 header
.desc_offset
= 1;
1642 header
.desc_size
= 20;
1643 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1644 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1645 header
.grain_offset
=
1646 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1647 header
.granularity
);
1648 /* swap endianness for all header fields */
1649 header
.version
= cpu_to_le32(header
.version
);
1650 header
.flags
= cpu_to_le32(header
.flags
);
1651 header
.capacity
= cpu_to_le64(header
.capacity
);
1652 header
.granularity
= cpu_to_le64(header
.granularity
);
1653 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1654 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1655 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1656 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1657 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1658 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1659 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1661 header
.check_bytes
[0] = 0xa;
1662 header
.check_bytes
[1] = 0x20;
1663 header
.check_bytes
[2] = 0xd;
1664 header
.check_bytes
[3] = 0xa;
1666 /* write all the data */
1667 ret
= bdrv_pwrite(bs
, 0, &magic
, sizeof(magic
));
1669 error_set(errp
, QERR_IO_ERROR
);
1672 ret
= bdrv_pwrite(bs
, sizeof(magic
), &header
, sizeof(header
));
1674 error_set(errp
, QERR_IO_ERROR
);
1678 ret
= bdrv_truncate(bs
, le64_to_cpu(header
.grain_offset
) << 9);
1680 error_setg_errno(errp
, -ret
, "Could not truncate file");
1684 /* write grain directory */
1685 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1686 gd_buf
= g_malloc0(gd_buf_size
);
1687 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1688 i
< gt_count
; i
++, tmp
+= gt_size
) {
1689 gd_buf
[i
] = cpu_to_le32(tmp
);
1691 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1692 gd_buf
, gd_buf_size
);
1694 error_set(errp
, QERR_IO_ERROR
);
1698 /* write backup grain directory */
1699 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1700 i
< gt_count
; i
++, tmp
+= gt_size
) {
1701 gd_buf
[i
] = cpu_to_le32(tmp
);
1703 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1704 gd_buf
, gd_buf_size
);
1706 error_set(errp
, QERR_IO_ERROR
);
1719 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1720 char *postfix
, size_t buf_len
, Error
**errp
)
1724 if (filename
== NULL
|| !strlen(filename
)) {
1725 error_setg(errp
, "No filename provided");
1728 p
= strrchr(filename
, '/');
1730 p
= strrchr(filename
, '\\');
1733 p
= strrchr(filename
, ':');
1737 if (p
- filename
>= buf_len
) {
1740 pstrcpy(path
, p
- filename
+ 1, filename
);
1745 q
= strrchr(p
, '.');
1747 pstrcpy(prefix
, buf_len
, p
);
1750 if (q
- p
>= buf_len
) {
1753 pstrcpy(prefix
, q
- p
+ 1, p
);
1754 pstrcpy(postfix
, buf_len
, q
);
1759 static int vmdk_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1762 BlockDriverState
*new_bs
= NULL
;
1763 Error
*local_err
= NULL
;
1765 int64_t total_size
= 0, filesize
;
1766 char *adapter_type
= NULL
;
1767 char *backing_file
= NULL
;
1771 bool flat
, split
, compress
;
1772 GString
*ext_desc_lines
;
1773 char path
[PATH_MAX
], prefix
[PATH_MAX
], postfix
[PATH_MAX
];
1774 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1775 const char *desc_extent_line
;
1776 char parent_desc_line
[BUF_SIZE
] = "";
1777 uint32_t parent_cid
= 0xffffffff;
1778 uint32_t number_heads
= 16;
1779 bool zeroed_grain
= false;
1780 uint32_t desc_offset
= 0, desc_len
;
1781 const char desc_template
[] =
1782 "# Disk DescriptorFile\n"
1785 "parentCID=%" PRIx32
"\n"
1786 "createType=\"%s\"\n"
1789 "# Extent description\n"
1792 "# The Disk Data Base\n"
1795 "ddb.virtualHWVersion = \"%d\"\n"
1796 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1797 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1798 "ddb.geometry.sectors = \"63\"\n"
1799 "ddb.adapterType = \"%s\"\n";
1801 ext_desc_lines
= g_string_new(NULL
);
1803 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1807 /* Read out options */
1808 total_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
1809 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1810 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1811 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1812 flags
|= BLOCK_FLAG_COMPAT6
;
1814 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1815 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1816 zeroed_grain
= true;
1819 if (!adapter_type
) {
1820 adapter_type
= g_strdup("ide");
1821 } else if (strcmp(adapter_type
, "ide") &&
1822 strcmp(adapter_type
, "buslogic") &&
1823 strcmp(adapter_type
, "lsilogic") &&
1824 strcmp(adapter_type
, "legacyESX")) {
1825 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1829 if (strcmp(adapter_type
, "ide") != 0) {
1830 /* that's the number of heads with which vmware operates when
1831 creating, exporting, etc. vmdk files with a non-ide adapter type */
1835 /* Default format to monolithicSparse */
1836 fmt
= g_strdup("monolithicSparse");
1837 } else if (strcmp(fmt
, "monolithicFlat") &&
1838 strcmp(fmt
, "monolithicSparse") &&
1839 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1840 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1841 strcmp(fmt
, "streamOptimized")) {
1842 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1846 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1847 strcmp(fmt
, "twoGbMaxExtentSparse"));
1848 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1849 strcmp(fmt
, "twoGbMaxExtentFlat"));
1850 compress
= !strcmp(fmt
, "streamOptimized");
1852 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
1854 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
1856 if (flat
&& backing_file
) {
1857 error_setg(errp
, "Flat image can't have backing file");
1861 if (flat
&& zeroed_grain
) {
1862 error_setg(errp
, "Flat image can't enable zeroed grain");
1867 BlockDriverState
*bs
= NULL
;
1868 ret
= bdrv_open(&bs
, backing_file
, NULL
, NULL
, BDRV_O_NO_BACKING
, NULL
,
1873 if (strcmp(bs
->drv
->format_name
, "vmdk")) {
1878 parent_cid
= vmdk_read_cid(bs
, 0);
1880 snprintf(parent_desc_line
, sizeof(parent_desc_line
),
1881 "parentFileNameHint=\"%s\"", backing_file
);
1884 /* Create extents */
1885 filesize
= total_size
;
1886 while (filesize
> 0) {
1887 char desc_line
[BUF_SIZE
];
1888 char ext_filename
[PATH_MAX
];
1889 char desc_filename
[PATH_MAX
];
1890 int64_t size
= filesize
;
1892 if (split
&& size
> split_size
) {
1896 snprintf(desc_filename
, sizeof(desc_filename
), "%s-%c%03d%s",
1897 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1899 snprintf(desc_filename
, sizeof(desc_filename
), "%s-flat%s",
1902 snprintf(desc_filename
, sizeof(desc_filename
), "%s%s",
1905 snprintf(ext_filename
, sizeof(ext_filename
), "%s%s",
1906 path
, desc_filename
);
1908 if (vmdk_create_extent(ext_filename
, size
,
1909 flat
, compress
, zeroed_grain
, opts
, errp
)) {
1915 /* Format description line */
1916 snprintf(desc_line
, sizeof(desc_line
),
1917 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
1918 g_string_append(ext_desc_lines
, desc_line
);
1920 /* generate descriptor file */
1921 desc
= g_strdup_printf(desc_template
,
1922 (uint32_t)time(NULL
),
1926 ext_desc_lines
->str
,
1927 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
1929 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
1932 desc_len
= strlen(desc
);
1933 /* the descriptor offset = 0x200 */
1934 if (!split
&& !flat
) {
1935 desc_offset
= 0x200;
1937 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1939 error_propagate(errp
, local_err
);
1943 assert(new_bs
== NULL
);
1944 ret
= bdrv_open(&new_bs
, filename
, NULL
, NULL
,
1945 BDRV_O_RDWR
| BDRV_O_PROTOCOL
, NULL
, &local_err
);
1947 error_propagate(errp
, local_err
);
1950 ret
= bdrv_pwrite(new_bs
, desc_offset
, desc
, desc_len
);
1952 error_setg_errno(errp
, -ret
, "Could not write description");
1955 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1956 * for description file */
1957 if (desc_offset
== 0) {
1958 ret
= bdrv_truncate(new_bs
, desc_len
);
1960 error_setg_errno(errp
, -ret
, "Could not truncate file");
1967 g_free(adapter_type
);
1968 g_free(backing_file
);
1971 g_string_free(ext_desc_lines
, true);
1975 static void vmdk_close(BlockDriverState
*bs
)
1977 BDRVVmdkState
*s
= bs
->opaque
;
1979 vmdk_free_extents(bs
);
1980 g_free(s
->create_type
);
1982 migrate_del_blocker(s
->migration_blocker
);
1983 error_free(s
->migration_blocker
);
1986 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
1988 BDRVVmdkState
*s
= bs
->opaque
;
1992 for (i
= 0; i
< s
->num_extents
; i
++) {
1993 err
= bdrv_co_flush(s
->extents
[i
].file
);
2001 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2006 BDRVVmdkState
*s
= bs
->opaque
;
2008 ret
= bdrv_get_allocated_file_size(bs
->file
);
2012 for (i
= 0; i
< s
->num_extents
; i
++) {
2013 if (s
->extents
[i
].file
== bs
->file
) {
2016 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
);
2025 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2028 BDRVVmdkState
*s
= bs
->opaque
;
2030 /* If has a flat extent and its underlying storage doesn't have zero init,
2032 for (i
= 0; i
< s
->num_extents
; i
++) {
2033 if (s
->extents
[i
].flat
) {
2034 if (!bdrv_has_zero_init(s
->extents
[i
].file
)) {
2042 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2044 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2046 *info
= (ImageInfo
){
2047 .filename
= g_strdup(extent
->file
->filename
),
2048 .format
= g_strdup(extent
->type
),
2049 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2050 .compressed
= extent
->compressed
,
2051 .has_compressed
= extent
->compressed
,
2052 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2053 .has_cluster_size
= !extent
->flat
,
2059 static int vmdk_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
2062 BDRVVmdkState
*s
= bs
->opaque
;
2063 VmdkExtent
*extent
= NULL
;
2064 int64_t sector_num
= 0;
2065 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2067 uint64_t cluster_offset
;
2074 if (sector_num
>= total_sectors
) {
2077 extent
= find_extent(s
, sector_num
, extent
);
2080 "ERROR: could not find extent for sector %" PRId64
"\n",
2084 ret
= get_cluster_offset(bs
, extent
, NULL
,
2085 sector_num
<< BDRV_SECTOR_BITS
,
2086 false, &cluster_offset
, 0, 0);
2087 if (ret
== VMDK_ERROR
) {
2089 "ERROR: could not get cluster_offset for sector %"
2090 PRId64
"\n", sector_num
);
2093 if (ret
== VMDK_OK
&& cluster_offset
>= bdrv_getlength(extent
->file
)) {
2095 "ERROR: cluster offset for sector %"
2096 PRId64
" points after EOF\n", sector_num
);
2099 sector_num
+= extent
->cluster_sectors
;
2102 result
->corruptions
++;
2106 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2109 BDRVVmdkState
*s
= bs
->opaque
;
2110 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2111 ImageInfoList
**next
;
2113 *spec_info
= (ImageInfoSpecific
){
2114 .kind
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2116 .vmdk
= g_new0(ImageInfoSpecificVmdk
, 1),
2120 *spec_info
->vmdk
= (ImageInfoSpecificVmdk
) {
2121 .create_type
= g_strdup(s
->create_type
),
2123 .parent_cid
= s
->parent_cid
,
2126 next
= &spec_info
->vmdk
->extents
;
2127 for (i
= 0; i
< s
->num_extents
; i
++) {
2128 *next
= g_new0(ImageInfoList
, 1);
2129 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2130 (*next
)->next
= NULL
;
2131 next
= &(*next
)->next
;
2137 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2140 BDRVVmdkState
*s
= bs
->opaque
;
2141 assert(s
->num_extents
);
2142 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2143 if (!s
->extents
[0].flat
) {
2144 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2146 /* See if we have multiple extents but they have different cases */
2147 for (i
= 1; i
< s
->num_extents
; i
++) {
2148 if (bdi
->needs_compressed_writes
!= s
->extents
[i
].compressed
||
2149 (bdi
->cluster_size
&& bdi
->cluster_size
!=
2150 s
->extents
[i
].cluster_sectors
<< BDRV_SECTOR_BITS
)) {
2157 static void vmdk_detach_aio_context(BlockDriverState
*bs
)
2159 BDRVVmdkState
*s
= bs
->opaque
;
2162 for (i
= 0; i
< s
->num_extents
; i
++) {
2163 bdrv_detach_aio_context(s
->extents
[i
].file
);
2167 static void vmdk_attach_aio_context(BlockDriverState
*bs
,
2168 AioContext
*new_context
)
2170 BDRVVmdkState
*s
= bs
->opaque
;
2173 for (i
= 0; i
< s
->num_extents
; i
++) {
2174 bdrv_attach_aio_context(s
->extents
[i
].file
, new_context
);
2178 static QemuOptsList vmdk_create_opts
= {
2179 .name
= "vmdk-create-opts",
2180 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2183 .name
= BLOCK_OPT_SIZE
,
2184 .type
= QEMU_OPT_SIZE
,
2185 .help
= "Virtual disk size"
2188 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2189 .type
= QEMU_OPT_STRING
,
2190 .help
= "Virtual adapter type, can be one of "
2191 "ide (default), lsilogic, buslogic or legacyESX"
2194 .name
= BLOCK_OPT_BACKING_FILE
,
2195 .type
= QEMU_OPT_STRING
,
2196 .help
= "File name of a base image"
2199 .name
= BLOCK_OPT_COMPAT6
,
2200 .type
= QEMU_OPT_BOOL
,
2201 .help
= "VMDK version 6 image",
2202 .def_value_str
= "off"
2205 .name
= BLOCK_OPT_SUBFMT
,
2206 .type
= QEMU_OPT_STRING
,
2208 "VMDK flat extent format, can be one of "
2209 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2212 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2213 .type
= QEMU_OPT_BOOL
,
2214 .help
= "Enable efficient zero writes "
2215 "using the zeroed-grain GTE feature"
2217 { /* end of list */ }
2221 static BlockDriver bdrv_vmdk
= {
2222 .format_name
= "vmdk",
2223 .instance_size
= sizeof(BDRVVmdkState
),
2224 .bdrv_probe
= vmdk_probe
,
2225 .bdrv_open
= vmdk_open
,
2226 .bdrv_check
= vmdk_check
,
2227 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2228 .bdrv_read
= vmdk_co_read
,
2229 .bdrv_write
= vmdk_co_write
,
2230 .bdrv_write_compressed
= vmdk_write_compressed
,
2231 .bdrv_co_write_zeroes
= vmdk_co_write_zeroes
,
2232 .bdrv_close
= vmdk_close
,
2233 .bdrv_create
= vmdk_create
,
2234 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2235 .bdrv_co_get_block_status
= vmdk_co_get_block_status
,
2236 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2237 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2238 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2239 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2240 .bdrv_get_info
= vmdk_get_info
,
2241 .bdrv_detach_aio_context
= vmdk_detach_aio_context
,
2242 .bdrv_attach_aio_context
= vmdk_attach_aio_context
,
2244 .supports_backing
= true,
2245 .create_opts
= &vmdk_create_opts
,
2248 static void bdrv_vmdk_init(void)
2250 bdrv_register(&bdrv_vmdk
);
2253 block_init(bdrv_vmdk_init
);