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
);
837 bdrv_unref(extent_file
);
840 extent
->flat_start_offset
= flat_offset
<< 9;
841 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
842 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
843 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
847 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
, errp
);
851 bdrv_unref(extent_file
);
854 extent
= &s
->extents
[s
->num_extents
- 1];
856 error_setg(errp
, "Unsupported extent type '%s'", type
);
857 bdrv_unref(extent_file
);
860 extent
->type
= g_strdup(type
);
862 /* move to next line */
874 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
879 BDRVVmdkState
*s
= bs
->opaque
;
881 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
882 error_setg(errp
, "invalid VMDK image descriptor");
886 if (strcmp(ct
, "monolithicFlat") &&
887 strcmp(ct
, "vmfs") &&
888 strcmp(ct
, "vmfsSparse") &&
889 strcmp(ct
, "twoGbMaxExtentSparse") &&
890 strcmp(ct
, "twoGbMaxExtentFlat")) {
891 error_setg(errp
, "Unsupported image type '%s'", ct
);
895 s
->create_type
= g_strdup(ct
);
897 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->filename
, errp
);
902 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
907 BDRVVmdkState
*s
= bs
->opaque
;
910 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
915 magic
= ldl_be_p(buf
);
919 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, errp
);
920 s
->desc_offset
= 0x200;
923 ret
= vmdk_open_desc_file(bs
, flags
, buf
, errp
);
930 /* try to open parent images, if exist */
931 ret
= vmdk_parent_open(bs
);
935 s
->cid
= vmdk_read_cid(bs
, 0);
936 s
->parent_cid
= vmdk_read_cid(bs
, 1);
937 qemu_co_mutex_init(&s
->lock
);
939 /* Disable migration when VMDK images are used */
940 error_set(&s
->migration_blocker
,
941 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED
,
942 "vmdk", bs
->device_name
, "live migration");
943 migrate_add_blocker(s
->migration_blocker
);
949 g_free(s
->create_type
);
950 s
->create_type
= NULL
;
951 vmdk_free_extents(bs
);
956 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
958 BDRVVmdkState
*s
= bs
->opaque
;
961 for (i
= 0; i
< s
->num_extents
; i
++) {
962 if (!s
->extents
[i
].flat
) {
963 bs
->bl
.write_zeroes_alignment
=
964 MAX(bs
->bl
.write_zeroes_alignment
,
965 s
->extents
[i
].cluster_sectors
);
973 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
974 * to the cluster at @cluster_sector_num.
976 * If @skip_start_sector < @skip_end_sector, the relative range
977 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
978 * it for call to write user data in the request.
980 static int get_whole_cluster(BlockDriverState
*bs
,
982 uint64_t cluster_sector_num
,
984 uint64_t skip_start_sector
,
985 uint64_t skip_end_sector
)
988 int64_t cluster_bytes
;
989 uint8_t *whole_grain
;
991 /* For COW, align request sector_num to cluster start */
992 sector_num
= QEMU_ALIGN_DOWN(sector_num
, extent
->cluster_sectors
);
993 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
994 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
996 if (!bs
->backing_hd
) {
997 memset(whole_grain
, 0, skip_start_sector
<< BDRV_SECTOR_BITS
);
998 memset(whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
), 0,
999 cluster_bytes
- (skip_end_sector
<< BDRV_SECTOR_BITS
));
1002 assert(skip_end_sector
<= extent
->cluster_sectors
);
1003 /* we will be here if it's first write on non-exist grain(cluster).
1004 * try to read from parent image, if exist */
1005 if (bs
->backing_hd
&& !vmdk_is_cid_valid(bs
)) {
1010 /* Read backing data before skip range */
1011 if (skip_start_sector
> 0) {
1012 if (bs
->backing_hd
) {
1013 ret
= bdrv_read(bs
->backing_hd
, sector_num
,
1014 whole_grain
, skip_start_sector
);
1020 ret
= bdrv_write(extent
->file
, cluster_sector_num
, whole_grain
,
1027 /* Read backing data after skip range */
1028 if (skip_end_sector
< extent
->cluster_sectors
) {
1029 if (bs
->backing_hd
) {
1030 ret
= bdrv_read(bs
->backing_hd
, sector_num
+ skip_end_sector
,
1031 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1032 extent
->cluster_sectors
- skip_end_sector
);
1038 ret
= bdrv_write(extent
->file
, cluster_sector_num
+ skip_end_sector
,
1039 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1040 extent
->cluster_sectors
- skip_end_sector
);
1048 qemu_vfree(whole_grain
);
1052 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1055 offset
= cpu_to_le32(offset
);
1056 /* update L2 table */
1057 if (bdrv_pwrite_sync(
1059 ((int64_t)m_data
->l2_offset
* 512)
1060 + (m_data
->l2_index
* sizeof(offset
)),
1061 &offset
, sizeof(offset
)) < 0) {
1064 /* update backup L2 table */
1065 if (extent
->l1_backup_table_offset
!= 0) {
1066 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1067 if (bdrv_pwrite_sync(
1069 ((int64_t)m_data
->l2_offset
* 512)
1070 + (m_data
->l2_index
* sizeof(offset
)),
1071 &offset
, sizeof(offset
)) < 0) {
1075 if (m_data
->l2_cache_entry
) {
1076 *m_data
->l2_cache_entry
= offset
;
1083 * get_cluster_offset
1085 * Look up cluster offset in extent file by sector number, and store in
1088 * For flat extents, the start offset as parsed from the description file is
1091 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1092 * offset for a new cluster and update L2 cache. If there is a backing file,
1093 * COW is done before returning; otherwise, zeroes are written to the allocated
1094 * cluster. Both COW and zero writing skips the sector range
1095 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1096 * has new data to write there.
1098 * Returns: VMDK_OK if cluster exists and mapped in the image.
1099 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1100 * VMDK_ERROR if failed.
1102 static int get_cluster_offset(BlockDriverState
*bs
,
1104 VmdkMetaData
*m_data
,
1107 uint64_t *cluster_offset
,
1108 uint64_t skip_start_sector
,
1109 uint64_t skip_end_sector
)
1111 unsigned int l1_index
, l2_offset
, l2_index
;
1112 int min_index
, i
, j
;
1113 uint32_t min_count
, *l2_table
;
1114 bool zeroed
= false;
1116 int64_t cluster_sector
;
1122 *cluster_offset
= extent
->flat_start_offset
;
1126 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1127 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1128 if (l1_index
>= extent
->l1_size
) {
1131 l2_offset
= extent
->l1_table
[l1_index
];
1133 return VMDK_UNALLOC
;
1135 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1136 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1137 /* increment the hit count */
1138 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1139 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1140 extent
->l2_cache_counts
[j
] >>= 1;
1143 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1147 /* not found: load a new entry in the least used one */
1149 min_count
= 0xffffffff;
1150 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1151 if (extent
->l2_cache_counts
[i
] < min_count
) {
1152 min_count
= extent
->l2_cache_counts
[i
];
1156 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1159 (int64_t)l2_offset
* 512,
1161 extent
->l2_size
* sizeof(uint32_t)
1162 ) != extent
->l2_size
* sizeof(uint32_t)) {
1166 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1167 extent
->l2_cache_counts
[min_index
] = 1;
1169 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1170 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1174 m_data
->l1_index
= l1_index
;
1175 m_data
->l2_index
= l2_index
;
1176 m_data
->l2_offset
= l2_offset
;
1177 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1179 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1183 if (!cluster_sector
|| zeroed
) {
1185 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1188 cluster_sector
= extent
->next_cluster_sector
;
1189 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1191 /* First of all we write grain itself, to avoid race condition
1192 * that may to corrupt the image.
1193 * This problem may occur because of insufficient space on host disk
1194 * or inappropriate VM shutdown.
1196 ret
= get_whole_cluster(bs
, extent
,
1198 offset
>> BDRV_SECTOR_BITS
,
1199 skip_start_sector
, skip_end_sector
);
1204 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1208 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1209 int64_t sector_num
, VmdkExtent
*start_hint
)
1211 VmdkExtent
*extent
= start_hint
;
1214 extent
= &s
->extents
[0];
1216 while (extent
< &s
->extents
[s
->num_extents
]) {
1217 if (sector_num
< extent
->end_sector
) {
1225 static int64_t coroutine_fn
vmdk_co_get_block_status(BlockDriverState
*bs
,
1226 int64_t sector_num
, int nb_sectors
, int *pnum
)
1228 BDRVVmdkState
*s
= bs
->opaque
;
1229 int64_t index_in_cluster
, n
, ret
;
1233 extent
= find_extent(s
, sector_num
, NULL
);
1237 qemu_co_mutex_lock(&s
->lock
);
1238 ret
= get_cluster_offset(bs
, extent
, NULL
,
1239 sector_num
* 512, false, &offset
,
1241 qemu_co_mutex_unlock(&s
->lock
);
1251 ret
= BDRV_BLOCK_ZERO
;
1254 ret
= BDRV_BLOCK_DATA
;
1255 if (extent
->file
== bs
->file
&& !extent
->compressed
) {
1256 ret
|= BDRV_BLOCK_OFFSET_VALID
| offset
;
1262 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
1263 n
= extent
->cluster_sectors
- index_in_cluster
;
1264 if (n
> nb_sectors
) {
1271 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1272 int64_t offset_in_cluster
, const uint8_t *buf
,
1273 int nb_sectors
, int64_t sector_num
)
1276 VmdkGrainMarker
*data
= NULL
;
1278 const uint8_t *write_buf
= buf
;
1279 int write_len
= nb_sectors
* 512;
1281 if (extent
->compressed
) {
1282 if (!extent
->has_marker
) {
1286 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1287 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1288 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
1293 data
->lba
= sector_num
;
1294 data
->size
= buf_len
;
1295 write_buf
= (uint8_t *)data
;
1296 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
1298 ret
= bdrv_pwrite(extent
->file
,
1299 cluster_offset
+ offset_in_cluster
,
1302 if (ret
!= write_len
) {
1303 ret
= ret
< 0 ? ret
: -EIO
;
1312 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1313 int64_t offset_in_cluster
, uint8_t *buf
,
1317 int cluster_bytes
, buf_bytes
;
1318 uint8_t *cluster_buf
, *compressed_data
;
1319 uint8_t *uncomp_buf
;
1321 VmdkGrainMarker
*marker
;
1325 if (!extent
->compressed
) {
1326 ret
= bdrv_pread(extent
->file
,
1327 cluster_offset
+ offset_in_cluster
,
1328 buf
, nb_sectors
* 512);
1329 if (ret
== nb_sectors
* 512) {
1335 cluster_bytes
= extent
->cluster_sectors
* 512;
1336 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1337 buf_bytes
= cluster_bytes
* 2;
1338 cluster_buf
= g_malloc(buf_bytes
);
1339 uncomp_buf
= g_malloc(cluster_bytes
);
1340 ret
= bdrv_pread(extent
->file
,
1342 cluster_buf
, buf_bytes
);
1346 compressed_data
= cluster_buf
;
1347 buf_len
= cluster_bytes
;
1348 data_len
= cluster_bytes
;
1349 if (extent
->has_marker
) {
1350 marker
= (VmdkGrainMarker
*)cluster_buf
;
1351 compressed_data
= marker
->data
;
1352 data_len
= le32_to_cpu(marker
->size
);
1354 if (!data_len
|| data_len
> buf_bytes
) {
1358 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1364 if (offset_in_cluster
< 0 ||
1365 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
1369 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
1374 g_free(cluster_buf
);
1378 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
1379 uint8_t *buf
, int nb_sectors
)
1381 BDRVVmdkState
*s
= bs
->opaque
;
1383 uint64_t n
, index_in_cluster
;
1384 uint64_t extent_begin_sector
, extent_relative_sector_num
;
1385 VmdkExtent
*extent
= NULL
;
1386 uint64_t cluster_offset
;
1388 while (nb_sectors
> 0) {
1389 extent
= find_extent(s
, sector_num
, extent
);
1393 ret
= get_cluster_offset(bs
, extent
, NULL
,
1394 sector_num
<< 9, false, &cluster_offset
,
1396 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1397 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1398 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1399 n
= extent
->cluster_sectors
- index_in_cluster
;
1400 if (n
> nb_sectors
) {
1403 if (ret
!= VMDK_OK
) {
1404 /* if not allocated, try to read from parent image, if exist */
1405 if (bs
->backing_hd
&& ret
!= VMDK_ZEROED
) {
1406 if (!vmdk_is_cid_valid(bs
)) {
1409 ret
= bdrv_read(bs
->backing_hd
, sector_num
, buf
, n
);
1414 memset(buf
, 0, 512 * n
);
1417 ret
= vmdk_read_extent(extent
,
1418 cluster_offset
, index_in_cluster
* 512,
1431 static coroutine_fn
int vmdk_co_read(BlockDriverState
*bs
, int64_t sector_num
,
1432 uint8_t *buf
, int nb_sectors
)
1435 BDRVVmdkState
*s
= bs
->opaque
;
1436 qemu_co_mutex_lock(&s
->lock
);
1437 ret
= vmdk_read(bs
, sector_num
, buf
, nb_sectors
);
1438 qemu_co_mutex_unlock(&s
->lock
);
1444 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1445 * if possible, otherwise return -ENOTSUP.
1446 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1447 * with each cluster. By dry run we can find if the zero write
1448 * is possible without modifying image data.
1450 * Returns: error code with 0 for success.
1452 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1453 const uint8_t *buf
, int nb_sectors
,
1454 bool zeroed
, bool zero_dry_run
)
1456 BDRVVmdkState
*s
= bs
->opaque
;
1457 VmdkExtent
*extent
= NULL
;
1459 int64_t index_in_cluster
, n
;
1460 uint64_t extent_begin_sector
, extent_relative_sector_num
;
1461 uint64_t cluster_offset
;
1462 VmdkMetaData m_data
;
1464 if (sector_num
> bs
->total_sectors
) {
1465 error_report("Wrong offset: sector_num=0x%" PRIx64
1466 " total_sectors=0x%" PRIx64
"\n",
1467 sector_num
, bs
->total_sectors
);
1471 while (nb_sectors
> 0) {
1472 extent
= find_extent(s
, sector_num
, extent
);
1476 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1477 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1478 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1479 n
= extent
->cluster_sectors
- index_in_cluster
;
1480 if (n
> nb_sectors
) {
1483 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1484 !(extent
->compressed
|| zeroed
),
1486 index_in_cluster
, index_in_cluster
+ n
);
1487 if (extent
->compressed
) {
1488 if (ret
== VMDK_OK
) {
1489 /* Refuse write to allocated cluster for streamOptimized */
1490 error_report("Could not write to allocated cluster"
1491 " for streamOptimized");
1495 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1496 true, &cluster_offset
, 0, 0);
1499 if (ret
== VMDK_ERROR
) {
1503 /* Do zeroed write, buf is ignored */
1504 if (extent
->has_zero_grain
&&
1505 index_in_cluster
== 0 &&
1506 n
>= extent
->cluster_sectors
) {
1507 n
= extent
->cluster_sectors
;
1508 if (!zero_dry_run
) {
1509 /* update L2 tables */
1510 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1519 ret
= vmdk_write_extent(extent
,
1520 cluster_offset
, index_in_cluster
* 512,
1521 buf
, n
, sector_num
);
1526 /* update L2 tables */
1527 if (vmdk_L2update(extent
, &m_data
,
1528 cluster_offset
>> BDRV_SECTOR_BITS
)
1538 /* update CID on the first write every time the virtual disk is
1540 if (!s
->cid_updated
) {
1541 ret
= vmdk_write_cid(bs
, time(NULL
));
1545 s
->cid_updated
= true;
1551 static coroutine_fn
int vmdk_co_write(BlockDriverState
*bs
, int64_t sector_num
,
1552 const uint8_t *buf
, int nb_sectors
)
1555 BDRVVmdkState
*s
= bs
->opaque
;
1556 qemu_co_mutex_lock(&s
->lock
);
1557 ret
= vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1558 qemu_co_mutex_unlock(&s
->lock
);
1562 static int vmdk_write_compressed(BlockDriverState
*bs
,
1567 BDRVVmdkState
*s
= bs
->opaque
;
1568 if (s
->num_extents
== 1 && s
->extents
[0].compressed
) {
1569 return vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1575 static int coroutine_fn
vmdk_co_write_zeroes(BlockDriverState
*bs
,
1578 BdrvRequestFlags flags
)
1581 BDRVVmdkState
*s
= bs
->opaque
;
1582 qemu_co_mutex_lock(&s
->lock
);
1583 /* write zeroes could fail if sectors not aligned to cluster, test it with
1584 * dry_run == true before really updating image */
1585 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, true);
1587 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, false);
1589 qemu_co_mutex_unlock(&s
->lock
);
1593 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1594 bool flat
, bool compress
, bool zeroed_grain
,
1595 QemuOpts
*opts
, Error
**errp
)
1598 BlockDriverState
*bs
= NULL
;
1600 Error
*local_err
= NULL
;
1601 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1602 uint32_t *gd_buf
= NULL
;
1605 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1607 error_propagate(errp
, local_err
);
1612 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, BDRV_O_RDWR
| BDRV_O_PROTOCOL
,
1615 error_propagate(errp
, local_err
);
1620 ret
= bdrv_truncate(bs
, filesize
);
1622 error_setg_errno(errp
, -ret
, "Could not truncate file");
1626 magic
= cpu_to_be32(VMDK4_MAGIC
);
1627 memset(&header
, 0, sizeof(header
));
1628 header
.version
= zeroed_grain
? 2 : 1;
1629 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1630 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1631 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1632 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1633 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1634 header
.granularity
= 128;
1635 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1637 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1638 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1640 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1641 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1643 header
.desc_offset
= 1;
1644 header
.desc_size
= 20;
1645 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1646 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1647 header
.grain_offset
=
1648 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1649 header
.granularity
);
1650 /* swap endianness for all header fields */
1651 header
.version
= cpu_to_le32(header
.version
);
1652 header
.flags
= cpu_to_le32(header
.flags
);
1653 header
.capacity
= cpu_to_le64(header
.capacity
);
1654 header
.granularity
= cpu_to_le64(header
.granularity
);
1655 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1656 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1657 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1658 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1659 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1660 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1661 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1663 header
.check_bytes
[0] = 0xa;
1664 header
.check_bytes
[1] = 0x20;
1665 header
.check_bytes
[2] = 0xd;
1666 header
.check_bytes
[3] = 0xa;
1668 /* write all the data */
1669 ret
= bdrv_pwrite(bs
, 0, &magic
, sizeof(magic
));
1671 error_set(errp
, QERR_IO_ERROR
);
1674 ret
= bdrv_pwrite(bs
, sizeof(magic
), &header
, sizeof(header
));
1676 error_set(errp
, QERR_IO_ERROR
);
1680 ret
= bdrv_truncate(bs
, le64_to_cpu(header
.grain_offset
) << 9);
1682 error_setg_errno(errp
, -ret
, "Could not truncate file");
1686 /* write grain directory */
1687 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1688 gd_buf
= g_malloc0(gd_buf_size
);
1689 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1690 i
< gt_count
; i
++, tmp
+= gt_size
) {
1691 gd_buf
[i
] = cpu_to_le32(tmp
);
1693 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1694 gd_buf
, gd_buf_size
);
1696 error_set(errp
, QERR_IO_ERROR
);
1700 /* write backup grain directory */
1701 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1702 i
< gt_count
; i
++, tmp
+= gt_size
) {
1703 gd_buf
[i
] = cpu_to_le32(tmp
);
1705 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1706 gd_buf
, gd_buf_size
);
1708 error_set(errp
, QERR_IO_ERROR
);
1721 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1722 char *postfix
, size_t buf_len
, Error
**errp
)
1726 if (filename
== NULL
|| !strlen(filename
)) {
1727 error_setg(errp
, "No filename provided");
1730 p
= strrchr(filename
, '/');
1732 p
= strrchr(filename
, '\\');
1735 p
= strrchr(filename
, ':');
1739 if (p
- filename
>= buf_len
) {
1742 pstrcpy(path
, p
- filename
+ 1, filename
);
1747 q
= strrchr(p
, '.');
1749 pstrcpy(prefix
, buf_len
, p
);
1752 if (q
- p
>= buf_len
) {
1755 pstrcpy(prefix
, q
- p
+ 1, p
);
1756 pstrcpy(postfix
, buf_len
, q
);
1761 static int vmdk_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1764 BlockDriverState
*new_bs
= NULL
;
1765 Error
*local_err
= NULL
;
1767 int64_t total_size
= 0, filesize
;
1768 char *adapter_type
= NULL
;
1769 char *backing_file
= NULL
;
1773 bool flat
, split
, compress
;
1774 GString
*ext_desc_lines
;
1775 char path
[PATH_MAX
], prefix
[PATH_MAX
], postfix
[PATH_MAX
];
1776 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1777 const char *desc_extent_line
;
1778 char parent_desc_line
[BUF_SIZE
] = "";
1779 uint32_t parent_cid
= 0xffffffff;
1780 uint32_t number_heads
= 16;
1781 bool zeroed_grain
= false;
1782 uint32_t desc_offset
= 0, desc_len
;
1783 const char desc_template
[] =
1784 "# Disk DescriptorFile\n"
1787 "parentCID=%" PRIx32
"\n"
1788 "createType=\"%s\"\n"
1791 "# Extent description\n"
1794 "# The Disk Data Base\n"
1797 "ddb.virtualHWVersion = \"%d\"\n"
1798 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1799 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1800 "ddb.geometry.sectors = \"63\"\n"
1801 "ddb.adapterType = \"%s\"\n";
1803 ext_desc_lines
= g_string_new(NULL
);
1805 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1809 /* Read out options */
1810 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1812 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1813 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1814 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1815 flags
|= BLOCK_FLAG_COMPAT6
;
1817 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1818 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1819 zeroed_grain
= true;
1822 if (!adapter_type
) {
1823 adapter_type
= g_strdup("ide");
1824 } else if (strcmp(adapter_type
, "ide") &&
1825 strcmp(adapter_type
, "buslogic") &&
1826 strcmp(adapter_type
, "lsilogic") &&
1827 strcmp(adapter_type
, "legacyESX")) {
1828 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1832 if (strcmp(adapter_type
, "ide") != 0) {
1833 /* that's the number of heads with which vmware operates when
1834 creating, exporting, etc. vmdk files with a non-ide adapter type */
1838 /* Default format to monolithicSparse */
1839 fmt
= g_strdup("monolithicSparse");
1840 } else if (strcmp(fmt
, "monolithicFlat") &&
1841 strcmp(fmt
, "monolithicSparse") &&
1842 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1843 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1844 strcmp(fmt
, "streamOptimized")) {
1845 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1849 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1850 strcmp(fmt
, "twoGbMaxExtentSparse"));
1851 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1852 strcmp(fmt
, "twoGbMaxExtentFlat"));
1853 compress
= !strcmp(fmt
, "streamOptimized");
1855 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
1857 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
1859 if (flat
&& backing_file
) {
1860 error_setg(errp
, "Flat image can't have backing file");
1864 if (flat
&& zeroed_grain
) {
1865 error_setg(errp
, "Flat image can't enable zeroed grain");
1870 BlockDriverState
*bs
= NULL
;
1871 ret
= bdrv_open(&bs
, backing_file
, NULL
, NULL
, BDRV_O_NO_BACKING
, NULL
,
1876 if (strcmp(bs
->drv
->format_name
, "vmdk")) {
1881 parent_cid
= vmdk_read_cid(bs
, 0);
1883 snprintf(parent_desc_line
, sizeof(parent_desc_line
),
1884 "parentFileNameHint=\"%s\"", backing_file
);
1887 /* Create extents */
1888 filesize
= total_size
;
1889 while (filesize
> 0) {
1890 char desc_line
[BUF_SIZE
];
1891 char ext_filename
[PATH_MAX
];
1892 char desc_filename
[PATH_MAX
];
1893 int64_t size
= filesize
;
1895 if (split
&& size
> split_size
) {
1899 snprintf(desc_filename
, sizeof(desc_filename
), "%s-%c%03d%s",
1900 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1902 snprintf(desc_filename
, sizeof(desc_filename
), "%s-flat%s",
1905 snprintf(desc_filename
, sizeof(desc_filename
), "%s%s",
1908 snprintf(ext_filename
, sizeof(ext_filename
), "%s%s",
1909 path
, desc_filename
);
1911 if (vmdk_create_extent(ext_filename
, size
,
1912 flat
, compress
, zeroed_grain
, opts
, errp
)) {
1918 /* Format description line */
1919 snprintf(desc_line
, sizeof(desc_line
),
1920 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
1921 g_string_append(ext_desc_lines
, desc_line
);
1923 /* generate descriptor file */
1924 desc
= g_strdup_printf(desc_template
,
1925 (uint32_t)time(NULL
),
1929 ext_desc_lines
->str
,
1930 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
1932 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
1935 desc_len
= strlen(desc
);
1936 /* the descriptor offset = 0x200 */
1937 if (!split
&& !flat
) {
1938 desc_offset
= 0x200;
1940 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1942 error_propagate(errp
, local_err
);
1946 assert(new_bs
== NULL
);
1947 ret
= bdrv_open(&new_bs
, filename
, NULL
, NULL
,
1948 BDRV_O_RDWR
| BDRV_O_PROTOCOL
, NULL
, &local_err
);
1950 error_propagate(errp
, local_err
);
1953 ret
= bdrv_pwrite(new_bs
, desc_offset
, desc
, desc_len
);
1955 error_setg_errno(errp
, -ret
, "Could not write description");
1958 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1959 * for description file */
1960 if (desc_offset
== 0) {
1961 ret
= bdrv_truncate(new_bs
, desc_len
);
1963 error_setg_errno(errp
, -ret
, "Could not truncate file");
1970 g_free(adapter_type
);
1971 g_free(backing_file
);
1974 g_string_free(ext_desc_lines
, true);
1978 static void vmdk_close(BlockDriverState
*bs
)
1980 BDRVVmdkState
*s
= bs
->opaque
;
1982 vmdk_free_extents(bs
);
1983 g_free(s
->create_type
);
1985 migrate_del_blocker(s
->migration_blocker
);
1986 error_free(s
->migration_blocker
);
1989 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
1991 BDRVVmdkState
*s
= bs
->opaque
;
1995 for (i
= 0; i
< s
->num_extents
; i
++) {
1996 err
= bdrv_co_flush(s
->extents
[i
].file
);
2004 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2009 BDRVVmdkState
*s
= bs
->opaque
;
2011 ret
= bdrv_get_allocated_file_size(bs
->file
);
2015 for (i
= 0; i
< s
->num_extents
; i
++) {
2016 if (s
->extents
[i
].file
== bs
->file
) {
2019 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
);
2028 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2031 BDRVVmdkState
*s
= bs
->opaque
;
2033 /* If has a flat extent and its underlying storage doesn't have zero init,
2035 for (i
= 0; i
< s
->num_extents
; i
++) {
2036 if (s
->extents
[i
].flat
) {
2037 if (!bdrv_has_zero_init(s
->extents
[i
].file
)) {
2045 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2047 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2049 *info
= (ImageInfo
){
2050 .filename
= g_strdup(extent
->file
->filename
),
2051 .format
= g_strdup(extent
->type
),
2052 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2053 .compressed
= extent
->compressed
,
2054 .has_compressed
= extent
->compressed
,
2055 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2056 .has_cluster_size
= !extent
->flat
,
2062 static int vmdk_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
2065 BDRVVmdkState
*s
= bs
->opaque
;
2066 VmdkExtent
*extent
= NULL
;
2067 int64_t sector_num
= 0;
2068 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2070 uint64_t cluster_offset
;
2077 if (sector_num
>= total_sectors
) {
2080 extent
= find_extent(s
, sector_num
, extent
);
2083 "ERROR: could not find extent for sector %" PRId64
"\n",
2087 ret
= get_cluster_offset(bs
, extent
, NULL
,
2088 sector_num
<< BDRV_SECTOR_BITS
,
2089 false, &cluster_offset
, 0, 0);
2090 if (ret
== VMDK_ERROR
) {
2092 "ERROR: could not get cluster_offset for sector %"
2093 PRId64
"\n", sector_num
);
2096 if (ret
== VMDK_OK
&& cluster_offset
>= bdrv_getlength(extent
->file
)) {
2098 "ERROR: cluster offset for sector %"
2099 PRId64
" points after EOF\n", sector_num
);
2102 sector_num
+= extent
->cluster_sectors
;
2105 result
->corruptions
++;
2109 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2112 BDRVVmdkState
*s
= bs
->opaque
;
2113 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2114 ImageInfoList
**next
;
2116 *spec_info
= (ImageInfoSpecific
){
2117 .kind
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2119 .vmdk
= g_new0(ImageInfoSpecificVmdk
, 1),
2123 *spec_info
->vmdk
= (ImageInfoSpecificVmdk
) {
2124 .create_type
= g_strdup(s
->create_type
),
2126 .parent_cid
= s
->parent_cid
,
2129 next
= &spec_info
->vmdk
->extents
;
2130 for (i
= 0; i
< s
->num_extents
; i
++) {
2131 *next
= g_new0(ImageInfoList
, 1);
2132 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2133 (*next
)->next
= NULL
;
2134 next
= &(*next
)->next
;
2140 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2143 BDRVVmdkState
*s
= bs
->opaque
;
2144 assert(s
->num_extents
);
2145 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2146 if (!s
->extents
[0].flat
) {
2147 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2149 /* See if we have multiple extents but they have different cases */
2150 for (i
= 1; i
< s
->num_extents
; i
++) {
2151 if (bdi
->needs_compressed_writes
!= s
->extents
[i
].compressed
||
2152 (bdi
->cluster_size
&& bdi
->cluster_size
!=
2153 s
->extents
[i
].cluster_sectors
<< BDRV_SECTOR_BITS
)) {
2160 static void vmdk_detach_aio_context(BlockDriverState
*bs
)
2162 BDRVVmdkState
*s
= bs
->opaque
;
2165 for (i
= 0; i
< s
->num_extents
; i
++) {
2166 bdrv_detach_aio_context(s
->extents
[i
].file
);
2170 static void vmdk_attach_aio_context(BlockDriverState
*bs
,
2171 AioContext
*new_context
)
2173 BDRVVmdkState
*s
= bs
->opaque
;
2176 for (i
= 0; i
< s
->num_extents
; i
++) {
2177 bdrv_attach_aio_context(s
->extents
[i
].file
, new_context
);
2181 static QemuOptsList vmdk_create_opts
= {
2182 .name
= "vmdk-create-opts",
2183 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2186 .name
= BLOCK_OPT_SIZE
,
2187 .type
= QEMU_OPT_SIZE
,
2188 .help
= "Virtual disk size"
2191 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2192 .type
= QEMU_OPT_STRING
,
2193 .help
= "Virtual adapter type, can be one of "
2194 "ide (default), lsilogic, buslogic or legacyESX"
2197 .name
= BLOCK_OPT_BACKING_FILE
,
2198 .type
= QEMU_OPT_STRING
,
2199 .help
= "File name of a base image"
2202 .name
= BLOCK_OPT_COMPAT6
,
2203 .type
= QEMU_OPT_BOOL
,
2204 .help
= "VMDK version 6 image",
2205 .def_value_str
= "off"
2208 .name
= BLOCK_OPT_SUBFMT
,
2209 .type
= QEMU_OPT_STRING
,
2211 "VMDK flat extent format, can be one of "
2212 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2215 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2216 .type
= QEMU_OPT_BOOL
,
2217 .help
= "Enable efficient zero writes "
2218 "using the zeroed-grain GTE feature"
2220 { /* end of list */ }
2224 static BlockDriver bdrv_vmdk
= {
2225 .format_name
= "vmdk",
2226 .instance_size
= sizeof(BDRVVmdkState
),
2227 .bdrv_probe
= vmdk_probe
,
2228 .bdrv_open
= vmdk_open
,
2229 .bdrv_check
= vmdk_check
,
2230 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2231 .bdrv_read
= vmdk_co_read
,
2232 .bdrv_write
= vmdk_co_write
,
2233 .bdrv_write_compressed
= vmdk_write_compressed
,
2234 .bdrv_co_write_zeroes
= vmdk_co_write_zeroes
,
2235 .bdrv_close
= vmdk_close
,
2236 .bdrv_create
= vmdk_create
,
2237 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2238 .bdrv_co_get_block_status
= vmdk_co_get_block_status
,
2239 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2240 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2241 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2242 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2243 .bdrv_get_info
= vmdk_get_info
,
2244 .bdrv_detach_aio_context
= vmdk_detach_aio_context
,
2245 .bdrv_attach_aio_context
= vmdk_attach_aio_context
,
2247 .supports_backing
= true,
2248 .create_opts
= &vmdk_create_opts
,
2251 static void bdrv_vmdk_init(void)
2253 bdrv_register(&bdrv_vmdk
);
2256 block_init(bdrv_vmdk_init
);