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/error-report.h"
29 #include "qemu/module.h"
30 #include "migration/migration.h"
34 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
35 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
36 #define VMDK4_COMPRESSION_DEFLATE 1
37 #define VMDK4_FLAG_NL_DETECT (1 << 0)
38 #define VMDK4_FLAG_RGD (1 << 1)
39 /* Zeroed-grain enable bit */
40 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
41 #define VMDK4_FLAG_COMPRESS (1 << 16)
42 #define VMDK4_FLAG_MARKER (1 << 17)
43 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
45 #define VMDK_GTE_ZEROED 0x1
47 /* VMDK internal error codes */
49 #define VMDK_ERROR (-1)
50 /* Cluster not allocated */
51 #define VMDK_UNALLOC (-2)
52 #define VMDK_ZEROED (-3)
54 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
59 uint32_t disk_sectors
;
61 uint32_t l1dir_offset
;
63 uint32_t file_sectors
;
66 uint32_t sectors_per_track
;
67 } QEMU_PACKED VMDK3Header
;
76 /* Number of GrainTableEntries per GrainTable */
77 uint32_t num_gtes_per_gt
;
80 uint64_t grain_offset
;
83 uint16_t compressAlgorithm
;
84 } QEMU_PACKED VMDK4Header
;
86 #define L2_CACHE_SIZE 16
88 typedef struct VmdkExtent
{
89 BlockDriverState
*file
;
97 int64_t flat_start_offset
;
98 int64_t l1_table_offset
;
99 int64_t l1_backup_table_offset
;
101 uint32_t *l1_backup_table
;
102 unsigned int l1_size
;
103 uint32_t l1_entry_sectors
;
105 unsigned int l2_size
;
107 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
108 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
110 int64_t cluster_sectors
;
111 int64_t next_cluster_sector
;
115 typedef struct BDRVVmdkState
{
117 uint64_t desc_offset
;
123 /* Extent array with num_extents entries, ascend ordered by address */
125 Error
*migration_blocker
;
129 typedef struct VmdkMetaData
{
130 unsigned int l1_index
;
131 unsigned int l2_index
;
132 unsigned int l2_offset
;
134 uint32_t *l2_cache_entry
;
137 typedef struct VmdkGrainMarker
{
141 } QEMU_PACKED VmdkGrainMarker
;
144 MARKER_END_OF_STREAM
= 0,
145 MARKER_GRAIN_TABLE
= 1,
146 MARKER_GRAIN_DIRECTORY
= 2,
150 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
157 magic
= be32_to_cpu(*(uint32_t *)buf
);
158 if (magic
== VMDK3_MAGIC
||
159 magic
== VMDK4_MAGIC
) {
162 const char *p
= (const char *)buf
;
163 const char *end
= p
+ buf_size
;
166 /* skip comment line */
167 while (p
< end
&& *p
!= '\n') {
174 while (p
< end
&& *p
== ' ') {
177 /* skip '\r' if windows line endings used. */
178 if (p
< end
&& *p
== '\r') {
181 /* only accept blank lines before 'version=' line */
182 if (p
== end
|| *p
!= '\n') {
188 if (end
- p
>= strlen("version=X\n")) {
189 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
190 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
194 if (end
- p
>= strlen("version=X\r\n")) {
195 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
196 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
206 #define SECTOR_SIZE 512
207 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
208 #define BUF_SIZE 4096
209 #define HEADER_SIZE 512 /* first sector of 512 bytes */
211 static void vmdk_free_extents(BlockDriverState
*bs
)
214 BDRVVmdkState
*s
= bs
->opaque
;
217 for (i
= 0; i
< s
->num_extents
; i
++) {
221 g_free(e
->l1_backup_table
);
223 if (e
->file
!= bs
->file
) {
230 static void vmdk_free_last_extent(BlockDriverState
*bs
)
232 BDRVVmdkState
*s
= bs
->opaque
;
234 if (s
->num_extents
== 0) {
238 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
);
241 static uint32_t vmdk_read_cid(BlockDriverState
*bs
, int parent
)
243 char desc
[DESC_SIZE
];
244 uint32_t cid
= 0xffffffff;
245 const char *p_name
, *cid_str
;
247 BDRVVmdkState
*s
= bs
->opaque
;
250 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
256 cid_str
= "parentCID";
257 cid_str_size
= sizeof("parentCID");
260 cid_str_size
= sizeof("CID");
263 desc
[DESC_SIZE
- 1] = '\0';
264 p_name
= strstr(desc
, cid_str
);
265 if (p_name
!= NULL
) {
266 p_name
+= cid_str_size
;
267 sscanf(p_name
, "%" SCNx32
, &cid
);
273 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
275 char desc
[DESC_SIZE
], tmp_desc
[DESC_SIZE
];
276 char *p_name
, *tmp_str
;
277 BDRVVmdkState
*s
= bs
->opaque
;
280 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
285 desc
[DESC_SIZE
- 1] = '\0';
286 tmp_str
= strstr(desc
, "parentCID");
287 if (tmp_str
== NULL
) {
291 pstrcpy(tmp_desc
, sizeof(tmp_desc
), tmp_str
);
292 p_name
= strstr(desc
, "CID");
293 if (p_name
!= NULL
) {
294 p_name
+= sizeof("CID");
295 snprintf(p_name
, sizeof(desc
) - (p_name
- desc
), "%" PRIx32
"\n", cid
);
296 pstrcat(desc
, sizeof(desc
), tmp_desc
);
299 ret
= bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
307 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
309 BDRVVmdkState
*s
= bs
->opaque
;
310 BlockDriverState
*p_bs
= bs
->backing_hd
;
313 if (!s
->cid_checked
&& p_bs
) {
314 cur_pcid
= vmdk_read_cid(p_bs
, 0);
315 if (s
->parent_cid
!= cur_pcid
) {
320 s
->cid_checked
= true;
325 /* We have nothing to do for VMDK reopen, stubs just return success */
326 static int vmdk_reopen_prepare(BDRVReopenState
*state
,
327 BlockReopenQueue
*queue
, Error
**errp
)
329 assert(state
!= NULL
);
330 assert(state
->bs
!= NULL
);
334 static int vmdk_parent_open(BlockDriverState
*bs
)
337 char desc
[DESC_SIZE
+ 1];
338 BDRVVmdkState
*s
= bs
->opaque
;
341 desc
[DESC_SIZE
] = '\0';
342 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
347 p_name
= strstr(desc
, "parentFileNameHint");
348 if (p_name
!= NULL
) {
351 p_name
+= sizeof("parentFileNameHint") + 1;
352 end_name
= strchr(p_name
, '\"');
353 if (end_name
== NULL
) {
356 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
360 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
366 /* Create and append extent to the extent array. Return the added VmdkExtent
367 * address. return NULL if allocation failed. */
368 static int vmdk_add_extent(BlockDriverState
*bs
,
369 BlockDriverState
*file
, bool flat
, int64_t sectors
,
370 int64_t l1_offset
, int64_t l1_backup_offset
,
372 int l2_size
, uint64_t cluster_sectors
,
373 VmdkExtent
**new_extent
,
377 BDRVVmdkState
*s
= bs
->opaque
;
380 if (cluster_sectors
> 0x200000) {
381 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
382 error_setg(errp
, "Invalid granularity, image may be corrupt");
385 if (l1_size
> 512 * 1024 * 1024) {
386 /* Although with big capacity and small l1_entry_sectors, we can get a
387 * big l1_size, we don't want unbounded value to allocate the table.
388 * Limit it to 512M, which is 16PB for default cluster and L2 table
390 error_setg(errp
, "L1 size too big");
394 nb_sectors
= bdrv_nb_sectors(file
);
395 if (nb_sectors
< 0) {
399 s
->extents
= g_renew(VmdkExtent
, s
->extents
, s
->num_extents
+ 1);
400 extent
= &s
->extents
[s
->num_extents
];
403 memset(extent
, 0, sizeof(VmdkExtent
));
406 extent
->sectors
= sectors
;
407 extent
->l1_table_offset
= l1_offset
;
408 extent
->l1_backup_table_offset
= l1_backup_offset
;
409 extent
->l1_size
= l1_size
;
410 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
411 extent
->l2_size
= l2_size
;
412 extent
->cluster_sectors
= flat
? sectors
: cluster_sectors
;
413 extent
->next_cluster_sector
= ROUND_UP(nb_sectors
, cluster_sectors
);
415 if (s
->num_extents
> 1) {
416 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
418 extent
->end_sector
= extent
->sectors
;
420 bs
->total_sectors
= extent
->end_sector
;
422 *new_extent
= extent
;
427 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
,
434 /* read the L1 table */
435 l1_size
= extent
->l1_size
* sizeof(uint32_t);
436 extent
->l1_table
= g_try_malloc(l1_size
);
437 if (l1_size
&& extent
->l1_table
== NULL
) {
441 ret
= bdrv_pread(extent
->file
,
442 extent
->l1_table_offset
,
446 error_setg_errno(errp
, -ret
,
447 "Could not read l1 table from extent '%s'",
448 extent
->file
->filename
);
451 for (i
= 0; i
< extent
->l1_size
; i
++) {
452 le32_to_cpus(&extent
->l1_table
[i
]);
455 if (extent
->l1_backup_table_offset
) {
456 extent
->l1_backup_table
= g_try_malloc(l1_size
);
457 if (l1_size
&& extent
->l1_backup_table
== NULL
) {
461 ret
= bdrv_pread(extent
->file
,
462 extent
->l1_backup_table_offset
,
463 extent
->l1_backup_table
,
466 error_setg_errno(errp
, -ret
,
467 "Could not read l1 backup table from extent '%s'",
468 extent
->file
->filename
);
471 for (i
= 0; i
< extent
->l1_size
; i
++) {
472 le32_to_cpus(&extent
->l1_backup_table
[i
]);
477 g_new(uint32_t, extent
->l2_size
* L2_CACHE_SIZE
);
480 g_free(extent
->l1_backup_table
);
482 g_free(extent
->l1_table
);
486 static int vmdk_open_vmfs_sparse(BlockDriverState
*bs
,
487 BlockDriverState
*file
,
488 int flags
, Error
**errp
)
495 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
497 error_setg_errno(errp
, -ret
,
498 "Could not read header from file '%s'",
502 ret
= vmdk_add_extent(bs
, file
, false,
503 le32_to_cpu(header
.disk_sectors
),
504 (int64_t)le32_to_cpu(header
.l1dir_offset
) << 9,
506 le32_to_cpu(header
.l1dir_size
),
508 le32_to_cpu(header
.granularity
),
514 ret
= vmdk_init_tables(bs
, extent
, errp
);
516 /* free extent allocated by vmdk_add_extent */
517 vmdk_free_last_extent(bs
);
522 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
523 QDict
*options
, Error
**errp
);
525 static char *vmdk_read_desc(BlockDriverState
*file
, uint64_t desc_offset
,
532 size
= bdrv_getlength(file
);
534 error_setg_errno(errp
, -size
, "Could not access file");
539 /* Both descriptor file and sparse image must be much larger than 4
540 * bytes, also callers of vmdk_read_desc want to compare the first 4
541 * bytes with VMDK4_MAGIC, let's error out if less is read. */
542 error_setg(errp
, "File is too small, not a valid image");
546 size
= MIN(size
, (1 << 20) - 1); /* avoid unbounded allocation */
547 buf
= g_malloc(size
+ 1);
549 ret
= bdrv_pread(file
, desc_offset
, buf
, size
);
551 error_setg_errno(errp
, -ret
, "Could not read from file");
560 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
561 BlockDriverState
*file
,
562 int flags
, QDict
*options
, Error
**errp
)
566 uint32_t l1_size
, l1_entry_sectors
;
569 BDRVVmdkState
*s
= bs
->opaque
;
570 int64_t l1_backup_offset
= 0;
572 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
574 error_setg_errno(errp
, -ret
,
575 "Could not read header from file '%s'",
579 if (header
.capacity
== 0) {
580 uint64_t desc_offset
= le64_to_cpu(header
.desc_offset
);
582 char *buf
= vmdk_read_desc(file
, desc_offset
<< 9, errp
);
586 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
592 if (!s
->create_type
) {
593 s
->create_type
= g_strdup("monolithicSparse");
596 if (le64_to_cpu(header
.gd_offset
) == VMDK4_GD_AT_END
) {
598 * The footer takes precedence over the header, so read it in. The
599 * footer starts at offset -1024 from the end: One sector for the
600 * footer, and another one for the end-of-stream marker.
607 uint8_t pad
[512 - 16];
608 } QEMU_PACKED footer_marker
;
612 uint8_t pad
[512 - 4 - sizeof(VMDK4Header
)];
618 uint8_t pad
[512 - 16];
619 } QEMU_PACKED eos_marker
;
620 } QEMU_PACKED footer
;
622 ret
= bdrv_pread(file
,
623 bs
->file
->total_sectors
* 512 - 1536,
624 &footer
, sizeof(footer
));
626 error_setg_errno(errp
, -ret
, "Failed to read footer");
630 /* Some sanity checks for the footer */
631 if (be32_to_cpu(footer
.magic
) != VMDK4_MAGIC
||
632 le32_to_cpu(footer
.footer_marker
.size
) != 0 ||
633 le32_to_cpu(footer
.footer_marker
.type
) != MARKER_FOOTER
||
634 le64_to_cpu(footer
.eos_marker
.val
) != 0 ||
635 le32_to_cpu(footer
.eos_marker
.size
) != 0 ||
636 le32_to_cpu(footer
.eos_marker
.type
) != MARKER_END_OF_STREAM
)
638 error_setg(errp
, "Invalid footer");
642 header
= footer
.header
;
645 if (le32_to_cpu(header
.version
) > 3) {
647 snprintf(buf
, sizeof(buf
), "VMDK version %" PRId32
,
648 le32_to_cpu(header
.version
));
649 error_setg(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
,
650 bdrv_get_device_or_node_name(bs
), "vmdk", buf
);
652 } else if (le32_to_cpu(header
.version
) == 3 && (flags
& BDRV_O_RDWR
)) {
653 /* VMware KB 2064959 explains that version 3 added support for
654 * persistent changed block tracking (CBT), and backup software can
655 * read it as version=1 if it doesn't care about the changed area
656 * information. So we are safe to enable read only. */
657 error_setg(errp
, "VMDK version 3 must be read only");
661 if (le32_to_cpu(header
.num_gtes_per_gt
) > 512) {
662 error_setg(errp
, "L2 table size too big");
666 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gt
)
667 * le64_to_cpu(header
.granularity
);
668 if (l1_entry_sectors
== 0) {
669 error_setg(errp
, "L1 entry size is invalid");
672 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
674 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
675 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
677 if (bdrv_nb_sectors(file
) < le64_to_cpu(header
.grain_offset
)) {
678 error_setg(errp
, "File truncated, expecting at least %" PRId64
" bytes",
679 (int64_t)(le64_to_cpu(header
.grain_offset
)
680 * BDRV_SECTOR_SIZE
));
684 ret
= vmdk_add_extent(bs
, file
, false,
685 le64_to_cpu(header
.capacity
),
686 le64_to_cpu(header
.gd_offset
) << 9,
689 le32_to_cpu(header
.num_gtes_per_gt
),
690 le64_to_cpu(header
.granularity
),
697 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
698 if (extent
->compressed
) {
699 g_free(s
->create_type
);
700 s
->create_type
= g_strdup("streamOptimized");
702 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
703 extent
->version
= le32_to_cpu(header
.version
);
704 extent
->has_zero_grain
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_ZERO_GRAIN
;
705 ret
= vmdk_init_tables(bs
, extent
, errp
);
707 /* free extent allocated by vmdk_add_extent */
708 vmdk_free_last_extent(bs
);
713 /* find an option value out of descriptor file */
714 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
715 char *buf
, int buf_size
)
717 char *opt_pos
, *opt_end
;
718 const char *end
= desc
+ strlen(desc
);
720 opt_pos
= strstr(desc
, opt_name
);
724 /* Skip "=\"" following opt_name */
725 opt_pos
+= strlen(opt_name
) + 2;
726 if (opt_pos
>= end
) {
730 while (opt_end
< end
&& *opt_end
!= '"') {
733 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
736 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
740 /* Open an extent file and append to bs array */
741 static int vmdk_open_sparse(BlockDriverState
*bs
,
742 BlockDriverState
*file
, int flags
,
743 char *buf
, QDict
*options
, Error
**errp
)
747 magic
= ldl_be_p(buf
);
750 return vmdk_open_vmfs_sparse(bs
, file
, flags
, errp
);
753 return vmdk_open_vmdk4(bs
, file
, flags
, options
, errp
);
756 error_setg(errp
, "Image not in VMDK format");
762 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
763 const char *desc_file_path
, QDict
*options
,
771 const char *p
= desc
;
775 BlockDriverState
*extent_file
;
776 BDRVVmdkState
*s
= bs
->opaque
;
778 char extent_opt_prefix
[32];
781 /* parse extent line in one of below formats:
783 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
784 * RW [size in sectors] SPARSE "file-name.vmdk"
785 * RW [size in sectors] VMFS "file-name.vmdk"
786 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
789 matches
= sscanf(p
, "%10s %" SCNd64
" %10s \"%511[^\n\r\"]\" %" SCNd64
,
790 access
, §ors
, type
, fname
, &flat_offset
);
791 if (matches
< 4 || strcmp(access
, "RW")) {
793 } else if (!strcmp(type
, "FLAT")) {
794 if (matches
!= 5 || flat_offset
< 0) {
795 error_setg(errp
, "Invalid extent lines: \n%s", p
);
798 } else if (!strcmp(type
, "VMFS")) {
802 error_setg(errp
, "Invalid extent lines:\n%s", p
);
805 } else if (matches
!= 4) {
806 error_setg(errp
, "Invalid extent lines:\n%s", p
);
811 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE") &&
812 strcmp(type
, "VMFS") && strcmp(type
, "VMFSSPARSE")) ||
813 (strcmp(access
, "RW"))) {
817 if (!path_is_absolute(fname
) && !path_has_protocol(fname
) &&
820 error_setg(errp
, "Cannot use relative extent paths with VMDK "
821 "descriptor file '%s'", bs
->file
->filename
);
825 extent_path
= g_malloc0(PATH_MAX
);
826 path_combine(extent_path
, PATH_MAX
, desc_file_path
, fname
);
829 ret
= snprintf(extent_opt_prefix
, 32, "extents.%d", s
->num_extents
);
832 ret
= bdrv_open_image(&extent_file
, extent_path
, options
,
833 extent_opt_prefix
, bs
, &child_file
, false, errp
);
839 /* save to extents array */
840 if (!strcmp(type
, "FLAT") || !strcmp(type
, "VMFS")) {
843 ret
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
844 0, 0, 0, 0, 0, &extent
, errp
);
846 bdrv_unref(extent_file
);
849 extent
->flat_start_offset
= flat_offset
<< 9;
850 } else if (!strcmp(type
, "SPARSE") || !strcmp(type
, "VMFSSPARSE")) {
851 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
852 char *buf
= vmdk_read_desc(extent_file
, 0, errp
);
856 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
, buf
,
861 bdrv_unref(extent_file
);
864 extent
= &s
->extents
[s
->num_extents
- 1];
866 error_setg(errp
, "Unsupported extent type '%s'", type
);
867 bdrv_unref(extent_file
);
870 extent
->type
= g_strdup(type
);
872 /* move to next line */
884 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
, char *buf
,
885 QDict
*options
, Error
**errp
)
889 BDRVVmdkState
*s
= bs
->opaque
;
891 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
892 error_setg(errp
, "invalid VMDK image descriptor");
896 if (strcmp(ct
, "monolithicFlat") &&
897 strcmp(ct
, "vmfs") &&
898 strcmp(ct
, "vmfsSparse") &&
899 strcmp(ct
, "twoGbMaxExtentSparse") &&
900 strcmp(ct
, "twoGbMaxExtentFlat")) {
901 error_setg(errp
, "Unsupported image type '%s'", ct
);
905 s
->create_type
= g_strdup(ct
);
907 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->exact_filename
, options
, errp
);
912 static int vmdk_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
917 BDRVVmdkState
*s
= bs
->opaque
;
920 buf
= vmdk_read_desc(bs
->file
, 0, errp
);
925 magic
= ldl_be_p(buf
);
929 ret
= vmdk_open_sparse(bs
, bs
->file
, flags
, buf
, options
, errp
);
930 s
->desc_offset
= 0x200;
933 ret
= vmdk_open_desc_file(bs
, flags
, buf
, options
, errp
);
940 /* try to open parent images, if exist */
941 ret
= vmdk_parent_open(bs
);
945 s
->cid
= vmdk_read_cid(bs
, 0);
946 s
->parent_cid
= vmdk_read_cid(bs
, 1);
947 qemu_co_mutex_init(&s
->lock
);
949 /* Disable migration when VMDK images are used */
950 error_setg(&s
->migration_blocker
, "The vmdk format used by node '%s' "
951 "does not support live migration",
952 bdrv_get_device_or_node_name(bs
));
953 migrate_add_blocker(s
->migration_blocker
);
959 g_free(s
->create_type
);
960 s
->create_type
= NULL
;
961 vmdk_free_extents(bs
);
966 static void vmdk_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
968 BDRVVmdkState
*s
= bs
->opaque
;
971 for (i
= 0; i
< s
->num_extents
; i
++) {
972 if (!s
->extents
[i
].flat
) {
973 bs
->bl
.write_zeroes_alignment
=
974 MAX(bs
->bl
.write_zeroes_alignment
,
975 s
->extents
[i
].cluster_sectors
);
983 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
984 * to the cluster at @cluster_sector_num.
986 * If @skip_start_sector < @skip_end_sector, the relative range
987 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
988 * it for call to write user data in the request.
990 static int get_whole_cluster(BlockDriverState
*bs
,
992 uint64_t cluster_sector_num
,
994 uint64_t skip_start_sector
,
995 uint64_t skip_end_sector
)
998 int64_t cluster_bytes
;
999 uint8_t *whole_grain
;
1001 /* For COW, align request sector_num to cluster start */
1002 sector_num
= QEMU_ALIGN_DOWN(sector_num
, extent
->cluster_sectors
);
1003 cluster_bytes
= extent
->cluster_sectors
<< BDRV_SECTOR_BITS
;
1004 whole_grain
= qemu_blockalign(bs
, cluster_bytes
);
1006 if (!bs
->backing_hd
) {
1007 memset(whole_grain
, 0, skip_start_sector
<< BDRV_SECTOR_BITS
);
1008 memset(whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
), 0,
1009 cluster_bytes
- (skip_end_sector
<< BDRV_SECTOR_BITS
));
1012 assert(skip_end_sector
<= extent
->cluster_sectors
);
1013 /* we will be here if it's first write on non-exist grain(cluster).
1014 * try to read from parent image, if exist */
1015 if (bs
->backing_hd
&& !vmdk_is_cid_valid(bs
)) {
1020 /* Read backing data before skip range */
1021 if (skip_start_sector
> 0) {
1022 if (bs
->backing_hd
) {
1023 ret
= bdrv_read(bs
->backing_hd
, sector_num
,
1024 whole_grain
, skip_start_sector
);
1030 ret
= bdrv_write(extent
->file
, cluster_sector_num
, whole_grain
,
1037 /* Read backing data after skip range */
1038 if (skip_end_sector
< extent
->cluster_sectors
) {
1039 if (bs
->backing_hd
) {
1040 ret
= bdrv_read(bs
->backing_hd
, sector_num
+ skip_end_sector
,
1041 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1042 extent
->cluster_sectors
- skip_end_sector
);
1048 ret
= bdrv_write(extent
->file
, cluster_sector_num
+ skip_end_sector
,
1049 whole_grain
+ (skip_end_sector
<< BDRV_SECTOR_BITS
),
1050 extent
->cluster_sectors
- skip_end_sector
);
1058 qemu_vfree(whole_grain
);
1062 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
,
1065 offset
= cpu_to_le32(offset
);
1066 /* update L2 table */
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) {
1074 /* update backup L2 table */
1075 if (extent
->l1_backup_table_offset
!= 0) {
1076 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
1077 if (bdrv_pwrite_sync(
1079 ((int64_t)m_data
->l2_offset
* 512)
1080 + (m_data
->l2_index
* sizeof(offset
)),
1081 &offset
, sizeof(offset
)) < 0) {
1085 if (m_data
->l2_cache_entry
) {
1086 *m_data
->l2_cache_entry
= offset
;
1093 * get_cluster_offset
1095 * Look up cluster offset in extent file by sector number, and store in
1098 * For flat extents, the start offset as parsed from the description file is
1101 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1102 * offset for a new cluster and update L2 cache. If there is a backing file,
1103 * COW is done before returning; otherwise, zeroes are written to the allocated
1104 * cluster. Both COW and zero writing skips the sector range
1105 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1106 * has new data to write there.
1108 * Returns: VMDK_OK if cluster exists and mapped in the image.
1109 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1110 * VMDK_ERROR if failed.
1112 static int get_cluster_offset(BlockDriverState
*bs
,
1114 VmdkMetaData
*m_data
,
1117 uint64_t *cluster_offset
,
1118 uint64_t skip_start_sector
,
1119 uint64_t skip_end_sector
)
1121 unsigned int l1_index
, l2_offset
, l2_index
;
1122 int min_index
, i
, j
;
1123 uint32_t min_count
, *l2_table
;
1124 bool zeroed
= false;
1126 int64_t cluster_sector
;
1132 *cluster_offset
= extent
->flat_start_offset
;
1136 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
1137 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
1138 if (l1_index
>= extent
->l1_size
) {
1141 l2_offset
= extent
->l1_table
[l1_index
];
1143 return VMDK_UNALLOC
;
1145 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1146 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
1147 /* increment the hit count */
1148 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
1149 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
1150 extent
->l2_cache_counts
[j
] >>= 1;
1153 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
1157 /* not found: load a new entry in the least used one */
1159 min_count
= 0xffffffff;
1160 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
1161 if (extent
->l2_cache_counts
[i
] < min_count
) {
1162 min_count
= extent
->l2_cache_counts
[i
];
1166 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
1169 (int64_t)l2_offset
* 512,
1171 extent
->l2_size
* sizeof(uint32_t)
1172 ) != extent
->l2_size
* sizeof(uint32_t)) {
1176 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
1177 extent
->l2_cache_counts
[min_index
] = 1;
1179 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
1180 cluster_sector
= le32_to_cpu(l2_table
[l2_index
]);
1184 m_data
->l1_index
= l1_index
;
1185 m_data
->l2_index
= l2_index
;
1186 m_data
->l2_offset
= l2_offset
;
1187 m_data
->l2_cache_entry
= &l2_table
[l2_index
];
1189 if (extent
->has_zero_grain
&& cluster_sector
== VMDK_GTE_ZEROED
) {
1193 if (!cluster_sector
|| zeroed
) {
1195 return zeroed
? VMDK_ZEROED
: VMDK_UNALLOC
;
1198 cluster_sector
= extent
->next_cluster_sector
;
1199 extent
->next_cluster_sector
+= extent
->cluster_sectors
;
1201 /* First of all we write grain itself, to avoid race condition
1202 * that may to corrupt the image.
1203 * This problem may occur because of insufficient space on host disk
1204 * or inappropriate VM shutdown.
1206 ret
= get_whole_cluster(bs
, extent
,
1208 offset
>> BDRV_SECTOR_BITS
,
1209 skip_start_sector
, skip_end_sector
);
1214 *cluster_offset
= cluster_sector
<< BDRV_SECTOR_BITS
;
1218 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
1219 int64_t sector_num
, VmdkExtent
*start_hint
)
1221 VmdkExtent
*extent
= start_hint
;
1224 extent
= &s
->extents
[0];
1226 while (extent
< &s
->extents
[s
->num_extents
]) {
1227 if (sector_num
< extent
->end_sector
) {
1235 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent
*extent
,
1238 uint64_t index_in_cluster
, extent_begin_sector
, extent_relative_sector_num
;
1240 extent_begin_sector
= extent
->end_sector
- extent
->sectors
;
1241 extent_relative_sector_num
= sector_num
- extent_begin_sector
;
1242 index_in_cluster
= extent_relative_sector_num
% extent
->cluster_sectors
;
1243 return index_in_cluster
;
1246 static int64_t coroutine_fn
vmdk_co_get_block_status(BlockDriverState
*bs
,
1247 int64_t sector_num
, int nb_sectors
, int *pnum
)
1249 BDRVVmdkState
*s
= bs
->opaque
;
1250 int64_t index_in_cluster
, n
, ret
;
1254 extent
= find_extent(s
, sector_num
, NULL
);
1258 qemu_co_mutex_lock(&s
->lock
);
1259 ret
= get_cluster_offset(bs
, extent
, NULL
,
1260 sector_num
* 512, false, &offset
,
1262 qemu_co_mutex_unlock(&s
->lock
);
1272 ret
= BDRV_BLOCK_ZERO
;
1275 ret
= BDRV_BLOCK_DATA
;
1276 if (extent
->file
== bs
->file
&& !extent
->compressed
) {
1277 ret
|= BDRV_BLOCK_OFFSET_VALID
| offset
;
1283 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1284 n
= extent
->cluster_sectors
- index_in_cluster
;
1285 if (n
> nb_sectors
) {
1292 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1293 int64_t offset_in_cluster
, const uint8_t *buf
,
1294 int nb_sectors
, int64_t sector_num
)
1297 VmdkGrainMarker
*data
= NULL
;
1299 const uint8_t *write_buf
= buf
;
1300 int write_len
= nb_sectors
* 512;
1301 int64_t write_offset
;
1302 int64_t write_end_sector
;
1304 if (extent
->compressed
) {
1305 if (!extent
->has_marker
) {
1309 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
1310 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
1311 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
1316 data
->lba
= sector_num
;
1317 data
->size
= buf_len
;
1318 write_buf
= (uint8_t *)data
;
1319 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
1321 write_offset
= cluster_offset
+ offset_in_cluster
,
1322 ret
= bdrv_pwrite(extent
->file
, write_offset
, write_buf
, write_len
);
1324 write_end_sector
= DIV_ROUND_UP(write_offset
+ write_len
, BDRV_SECTOR_SIZE
);
1326 extent
->next_cluster_sector
= MAX(extent
->next_cluster_sector
,
1329 if (ret
!= write_len
) {
1330 ret
= ret
< 0 ? ret
: -EIO
;
1339 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
1340 int64_t offset_in_cluster
, uint8_t *buf
,
1344 int cluster_bytes
, buf_bytes
;
1345 uint8_t *cluster_buf
, *compressed_data
;
1346 uint8_t *uncomp_buf
;
1348 VmdkGrainMarker
*marker
;
1352 if (!extent
->compressed
) {
1353 ret
= bdrv_pread(extent
->file
,
1354 cluster_offset
+ offset_in_cluster
,
1355 buf
, nb_sectors
* 512);
1356 if (ret
== nb_sectors
* 512) {
1362 cluster_bytes
= extent
->cluster_sectors
* 512;
1363 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1364 buf_bytes
= cluster_bytes
* 2;
1365 cluster_buf
= g_malloc(buf_bytes
);
1366 uncomp_buf
= g_malloc(cluster_bytes
);
1367 ret
= bdrv_pread(extent
->file
,
1369 cluster_buf
, buf_bytes
);
1373 compressed_data
= cluster_buf
;
1374 buf_len
= cluster_bytes
;
1375 data_len
= cluster_bytes
;
1376 if (extent
->has_marker
) {
1377 marker
= (VmdkGrainMarker
*)cluster_buf
;
1378 compressed_data
= marker
->data
;
1379 data_len
= le32_to_cpu(marker
->size
);
1381 if (!data_len
|| data_len
> buf_bytes
) {
1385 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
1391 if (offset_in_cluster
< 0 ||
1392 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
1396 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
1401 g_free(cluster_buf
);
1405 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
1406 uint8_t *buf
, int nb_sectors
)
1408 BDRVVmdkState
*s
= bs
->opaque
;
1410 uint64_t n
, index_in_cluster
;
1411 VmdkExtent
*extent
= NULL
;
1412 uint64_t cluster_offset
;
1414 while (nb_sectors
> 0) {
1415 extent
= find_extent(s
, sector_num
, extent
);
1419 ret
= get_cluster_offset(bs
, extent
, NULL
,
1420 sector_num
<< 9, false, &cluster_offset
,
1422 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1423 n
= extent
->cluster_sectors
- index_in_cluster
;
1424 if (n
> nb_sectors
) {
1427 if (ret
!= VMDK_OK
) {
1428 /* if not allocated, try to read from parent image, if exist */
1429 if (bs
->backing_hd
&& ret
!= VMDK_ZEROED
) {
1430 if (!vmdk_is_cid_valid(bs
)) {
1433 ret
= bdrv_read(bs
->backing_hd
, sector_num
, buf
, n
);
1438 memset(buf
, 0, 512 * n
);
1441 ret
= vmdk_read_extent(extent
,
1442 cluster_offset
, index_in_cluster
* 512,
1455 static coroutine_fn
int vmdk_co_read(BlockDriverState
*bs
, int64_t sector_num
,
1456 uint8_t *buf
, int nb_sectors
)
1459 BDRVVmdkState
*s
= bs
->opaque
;
1460 qemu_co_mutex_lock(&s
->lock
);
1461 ret
= vmdk_read(bs
, sector_num
, buf
, nb_sectors
);
1462 qemu_co_mutex_unlock(&s
->lock
);
1468 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1469 * if possible, otherwise return -ENOTSUP.
1470 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1471 * with each cluster. By dry run we can find if the zero write
1472 * is possible without modifying image data.
1474 * Returns: error code with 0 for success.
1476 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1477 const uint8_t *buf
, int nb_sectors
,
1478 bool zeroed
, bool zero_dry_run
)
1480 BDRVVmdkState
*s
= bs
->opaque
;
1481 VmdkExtent
*extent
= NULL
;
1483 int64_t index_in_cluster
, n
;
1484 uint64_t cluster_offset
;
1485 VmdkMetaData m_data
;
1487 if (sector_num
> bs
->total_sectors
) {
1488 error_report("Wrong offset: sector_num=0x%" PRIx64
1489 " total_sectors=0x%" PRIx64
"\n",
1490 sector_num
, bs
->total_sectors
);
1494 while (nb_sectors
> 0) {
1495 extent
= find_extent(s
, sector_num
, extent
);
1499 index_in_cluster
= vmdk_find_index_in_cluster(extent
, sector_num
);
1500 n
= extent
->cluster_sectors
- index_in_cluster
;
1501 if (n
> nb_sectors
) {
1504 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1505 !(extent
->compressed
|| zeroed
),
1507 index_in_cluster
, index_in_cluster
+ n
);
1508 if (extent
->compressed
) {
1509 if (ret
== VMDK_OK
) {
1510 /* Refuse write to allocated cluster for streamOptimized */
1511 error_report("Could not write to allocated cluster"
1512 " for streamOptimized");
1516 ret
= get_cluster_offset(bs
, extent
, &m_data
, sector_num
<< 9,
1517 true, &cluster_offset
, 0, 0);
1520 if (ret
== VMDK_ERROR
) {
1524 /* Do zeroed write, buf is ignored */
1525 if (extent
->has_zero_grain
&&
1526 index_in_cluster
== 0 &&
1527 n
>= extent
->cluster_sectors
) {
1528 n
= extent
->cluster_sectors
;
1529 if (!zero_dry_run
) {
1530 /* update L2 tables */
1531 if (vmdk_L2update(extent
, &m_data
, VMDK_GTE_ZEROED
)
1540 ret
= vmdk_write_extent(extent
,
1541 cluster_offset
, index_in_cluster
* 512,
1542 buf
, n
, sector_num
);
1547 /* update L2 tables */
1548 if (vmdk_L2update(extent
, &m_data
,
1549 cluster_offset
>> BDRV_SECTOR_BITS
)
1559 /* update CID on the first write every time the virtual disk is
1561 if (!s
->cid_updated
) {
1562 ret
= vmdk_write_cid(bs
, g_random_int());
1566 s
->cid_updated
= true;
1572 static coroutine_fn
int vmdk_co_write(BlockDriverState
*bs
, int64_t sector_num
,
1573 const uint8_t *buf
, int nb_sectors
)
1576 BDRVVmdkState
*s
= bs
->opaque
;
1577 qemu_co_mutex_lock(&s
->lock
);
1578 ret
= vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1579 qemu_co_mutex_unlock(&s
->lock
);
1583 static int vmdk_write_compressed(BlockDriverState
*bs
,
1588 BDRVVmdkState
*s
= bs
->opaque
;
1589 if (s
->num_extents
== 1 && s
->extents
[0].compressed
) {
1590 return vmdk_write(bs
, sector_num
, buf
, nb_sectors
, false, false);
1596 static int coroutine_fn
vmdk_co_write_zeroes(BlockDriverState
*bs
,
1599 BdrvRequestFlags flags
)
1602 BDRVVmdkState
*s
= bs
->opaque
;
1603 qemu_co_mutex_lock(&s
->lock
);
1604 /* write zeroes could fail if sectors not aligned to cluster, test it with
1605 * dry_run == true before really updating image */
1606 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, true);
1608 ret
= vmdk_write(bs
, sector_num
, NULL
, nb_sectors
, true, false);
1610 qemu_co_mutex_unlock(&s
->lock
);
1614 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1615 bool flat
, bool compress
, bool zeroed_grain
,
1616 QemuOpts
*opts
, Error
**errp
)
1619 BlockDriverState
*bs
= NULL
;
1621 Error
*local_err
= NULL
;
1622 uint32_t tmp
, magic
, grains
, gd_sectors
, gt_size
, gt_count
;
1623 uint32_t *gd_buf
= NULL
;
1626 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1628 error_propagate(errp
, local_err
);
1633 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, BDRV_O_RDWR
| BDRV_O_PROTOCOL
,
1636 error_propagate(errp
, local_err
);
1641 ret
= bdrv_truncate(bs
, filesize
);
1643 error_setg_errno(errp
, -ret
, "Could not truncate file");
1647 magic
= cpu_to_be32(VMDK4_MAGIC
);
1648 memset(&header
, 0, sizeof(header
));
1649 header
.version
= zeroed_grain
? 2 : 1;
1650 header
.flags
= VMDK4_FLAG_RGD
| VMDK4_FLAG_NL_DETECT
1651 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0)
1652 | (zeroed_grain
? VMDK4_FLAG_ZERO_GRAIN
: 0);
1653 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1654 header
.capacity
= filesize
/ BDRV_SECTOR_SIZE
;
1655 header
.granularity
= 128;
1656 header
.num_gtes_per_gt
= BDRV_SECTOR_SIZE
;
1658 grains
= DIV_ROUND_UP(filesize
/ BDRV_SECTOR_SIZE
, header
.granularity
);
1659 gt_size
= DIV_ROUND_UP(header
.num_gtes_per_gt
* sizeof(uint32_t),
1661 gt_count
= DIV_ROUND_UP(grains
, header
.num_gtes_per_gt
);
1662 gd_sectors
= DIV_ROUND_UP(gt_count
* sizeof(uint32_t), BDRV_SECTOR_SIZE
);
1664 header
.desc_offset
= 1;
1665 header
.desc_size
= 20;
1666 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1667 header
.gd_offset
= header
.rgd_offset
+ gd_sectors
+ (gt_size
* gt_count
);
1668 header
.grain_offset
=
1669 ROUND_UP(header
.gd_offset
+ gd_sectors
+ (gt_size
* gt_count
),
1670 header
.granularity
);
1671 /* swap endianness for all header fields */
1672 header
.version
= cpu_to_le32(header
.version
);
1673 header
.flags
= cpu_to_le32(header
.flags
);
1674 header
.capacity
= cpu_to_le64(header
.capacity
);
1675 header
.granularity
= cpu_to_le64(header
.granularity
);
1676 header
.num_gtes_per_gt
= cpu_to_le32(header
.num_gtes_per_gt
);
1677 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1678 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1679 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1680 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1681 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1682 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1684 header
.check_bytes
[0] = 0xa;
1685 header
.check_bytes
[1] = 0x20;
1686 header
.check_bytes
[2] = 0xd;
1687 header
.check_bytes
[3] = 0xa;
1689 /* write all the data */
1690 ret
= bdrv_pwrite(bs
, 0, &magic
, sizeof(magic
));
1692 error_setg(errp
, QERR_IO_ERROR
);
1695 ret
= bdrv_pwrite(bs
, sizeof(magic
), &header
, sizeof(header
));
1697 error_setg(errp
, QERR_IO_ERROR
);
1701 ret
= bdrv_truncate(bs
, le64_to_cpu(header
.grain_offset
) << 9);
1703 error_setg_errno(errp
, -ret
, "Could not truncate file");
1707 /* write grain directory */
1708 gd_buf_size
= gd_sectors
* BDRV_SECTOR_SIZE
;
1709 gd_buf
= g_malloc0(gd_buf_size
);
1710 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_sectors
;
1711 i
< gt_count
; i
++, tmp
+= gt_size
) {
1712 gd_buf
[i
] = cpu_to_le32(tmp
);
1714 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.rgd_offset
) * BDRV_SECTOR_SIZE
,
1715 gd_buf
, gd_buf_size
);
1717 error_setg(errp
, QERR_IO_ERROR
);
1721 /* write backup grain directory */
1722 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_sectors
;
1723 i
< gt_count
; i
++, tmp
+= gt_size
) {
1724 gd_buf
[i
] = cpu_to_le32(tmp
);
1726 ret
= bdrv_pwrite(bs
, le64_to_cpu(header
.gd_offset
) * BDRV_SECTOR_SIZE
,
1727 gd_buf
, gd_buf_size
);
1729 error_setg(errp
, QERR_IO_ERROR
);
1742 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1743 char *postfix
, size_t buf_len
, Error
**errp
)
1747 if (filename
== NULL
|| !strlen(filename
)) {
1748 error_setg(errp
, "No filename provided");
1751 p
= strrchr(filename
, '/');
1753 p
= strrchr(filename
, '\\');
1756 p
= strrchr(filename
, ':');
1760 if (p
- filename
>= buf_len
) {
1763 pstrcpy(path
, p
- filename
+ 1, filename
);
1768 q
= strrchr(p
, '.');
1770 pstrcpy(prefix
, buf_len
, p
);
1773 if (q
- p
>= buf_len
) {
1776 pstrcpy(prefix
, q
- p
+ 1, p
);
1777 pstrcpy(postfix
, buf_len
, q
);
1782 static int vmdk_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1785 BlockDriverState
*new_bs
= NULL
;
1786 Error
*local_err
= NULL
;
1788 int64_t total_size
= 0, filesize
;
1789 char *adapter_type
= NULL
;
1790 char *backing_file
= NULL
;
1794 bool flat
, split
, compress
;
1795 GString
*ext_desc_lines
;
1796 char *path
= g_malloc0(PATH_MAX
);
1797 char *prefix
= g_malloc0(PATH_MAX
);
1798 char *postfix
= g_malloc0(PATH_MAX
);
1799 char *desc_line
= g_malloc0(BUF_SIZE
);
1800 char *ext_filename
= g_malloc0(PATH_MAX
);
1801 char *desc_filename
= g_malloc0(PATH_MAX
);
1802 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1803 const char *desc_extent_line
;
1804 char *parent_desc_line
= g_malloc0(BUF_SIZE
);
1805 uint32_t parent_cid
= 0xffffffff;
1806 uint32_t number_heads
= 16;
1807 bool zeroed_grain
= false;
1808 uint32_t desc_offset
= 0, desc_len
;
1809 const char desc_template
[] =
1810 "# Disk DescriptorFile\n"
1813 "parentCID=%" PRIx32
"\n"
1814 "createType=\"%s\"\n"
1817 "# Extent description\n"
1820 "# The Disk Data Base\n"
1823 "ddb.virtualHWVersion = \"%d\"\n"
1824 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1825 "ddb.geometry.heads = \"%" PRIu32
"\"\n"
1826 "ddb.geometry.sectors = \"63\"\n"
1827 "ddb.adapterType = \"%s\"\n";
1829 ext_desc_lines
= g_string_new(NULL
);
1831 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
, errp
)) {
1835 /* Read out options */
1836 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1838 adapter_type
= qemu_opt_get_del(opts
, BLOCK_OPT_ADAPTER_TYPE
);
1839 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1840 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_COMPAT6
, false)) {
1841 flags
|= BLOCK_FLAG_COMPAT6
;
1843 fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_SUBFMT
);
1844 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ZEROED_GRAIN
, false)) {
1845 zeroed_grain
= true;
1848 if (!adapter_type
) {
1849 adapter_type
= g_strdup("ide");
1850 } else if (strcmp(adapter_type
, "ide") &&
1851 strcmp(adapter_type
, "buslogic") &&
1852 strcmp(adapter_type
, "lsilogic") &&
1853 strcmp(adapter_type
, "legacyESX")) {
1854 error_setg(errp
, "Unknown adapter type: '%s'", adapter_type
);
1858 if (strcmp(adapter_type
, "ide") != 0) {
1859 /* that's the number of heads with which vmware operates when
1860 creating, exporting, etc. vmdk files with a non-ide adapter type */
1864 /* Default format to monolithicSparse */
1865 fmt
= g_strdup("monolithicSparse");
1866 } else if (strcmp(fmt
, "monolithicFlat") &&
1867 strcmp(fmt
, "monolithicSparse") &&
1868 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1869 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1870 strcmp(fmt
, "streamOptimized")) {
1871 error_setg(errp
, "Unknown subformat: '%s'", fmt
);
1875 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1876 strcmp(fmt
, "twoGbMaxExtentSparse"));
1877 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1878 strcmp(fmt
, "twoGbMaxExtentFlat"));
1879 compress
= !strcmp(fmt
, "streamOptimized");
1881 desc_extent_line
= "RW %" PRId64
" FLAT \"%s\" 0\n";
1883 desc_extent_line
= "RW %" PRId64
" SPARSE \"%s\"\n";
1885 if (flat
&& backing_file
) {
1886 error_setg(errp
, "Flat image can't have backing file");
1890 if (flat
&& zeroed_grain
) {
1891 error_setg(errp
, "Flat image can't enable zeroed grain");
1896 BlockDriverState
*bs
= NULL
;
1897 char *full_backing
= g_new0(char, PATH_MAX
);
1898 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
1899 full_backing
, PATH_MAX
,
1902 g_free(full_backing
);
1903 error_propagate(errp
, local_err
);
1907 ret
= bdrv_open(&bs
, full_backing
, NULL
, NULL
, BDRV_O_NO_BACKING
, NULL
,
1909 g_free(full_backing
);
1913 if (strcmp(bs
->drv
->format_name
, "vmdk")) {
1918 parent_cid
= vmdk_read_cid(bs
, 0);
1920 snprintf(parent_desc_line
, BUF_SIZE
,
1921 "parentFileNameHint=\"%s\"", backing_file
);
1924 /* Create extents */
1925 filesize
= total_size
;
1926 while (filesize
> 0) {
1927 int64_t size
= filesize
;
1929 if (split
&& size
> split_size
) {
1933 snprintf(desc_filename
, PATH_MAX
, "%s-%c%03d%s",
1934 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1936 snprintf(desc_filename
, PATH_MAX
, "%s-flat%s", prefix
, postfix
);
1938 snprintf(desc_filename
, PATH_MAX
, "%s%s", prefix
, postfix
);
1940 snprintf(ext_filename
, PATH_MAX
, "%s%s", path
, desc_filename
);
1942 if (vmdk_create_extent(ext_filename
, size
,
1943 flat
, compress
, zeroed_grain
, opts
, errp
)) {
1949 /* Format description line */
1950 snprintf(desc_line
, BUF_SIZE
,
1951 desc_extent_line
, size
/ BDRV_SECTOR_SIZE
, desc_filename
);
1952 g_string_append(ext_desc_lines
, desc_line
);
1954 /* generate descriptor file */
1955 desc
= g_strdup_printf(desc_template
,
1960 ext_desc_lines
->str
,
1961 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
1963 (int64_t)(63 * number_heads
* BDRV_SECTOR_SIZE
),
1966 desc_len
= strlen(desc
);
1967 /* the descriptor offset = 0x200 */
1968 if (!split
&& !flat
) {
1969 desc_offset
= 0x200;
1971 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1973 error_propagate(errp
, local_err
);
1977 assert(new_bs
== NULL
);
1978 ret
= bdrv_open(&new_bs
, filename
, NULL
, NULL
,
1979 BDRV_O_RDWR
| BDRV_O_PROTOCOL
, NULL
, &local_err
);
1981 error_propagate(errp
, local_err
);
1984 ret
= bdrv_pwrite(new_bs
, desc_offset
, desc
, desc_len
);
1986 error_setg_errno(errp
, -ret
, "Could not write description");
1989 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1990 * for description file */
1991 if (desc_offset
== 0) {
1992 ret
= bdrv_truncate(new_bs
, desc_len
);
1994 error_setg_errno(errp
, -ret
, "Could not truncate file");
2001 g_free(adapter_type
);
2002 g_free(backing_file
);
2009 g_free(ext_filename
);
2010 g_free(desc_filename
);
2011 g_free(parent_desc_line
);
2012 g_string_free(ext_desc_lines
, true);
2016 static void vmdk_close(BlockDriverState
*bs
)
2018 BDRVVmdkState
*s
= bs
->opaque
;
2020 vmdk_free_extents(bs
);
2021 g_free(s
->create_type
);
2023 migrate_del_blocker(s
->migration_blocker
);
2024 error_free(s
->migration_blocker
);
2027 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
2029 BDRVVmdkState
*s
= bs
->opaque
;
2033 for (i
= 0; i
< s
->num_extents
; i
++) {
2034 err
= bdrv_co_flush(s
->extents
[i
].file
);
2042 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
2047 BDRVVmdkState
*s
= bs
->opaque
;
2049 ret
= bdrv_get_allocated_file_size(bs
->file
);
2053 for (i
= 0; i
< s
->num_extents
; i
++) {
2054 if (s
->extents
[i
].file
== bs
->file
) {
2057 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
);
2066 static int vmdk_has_zero_init(BlockDriverState
*bs
)
2069 BDRVVmdkState
*s
= bs
->opaque
;
2071 /* If has a flat extent and its underlying storage doesn't have zero init,
2073 for (i
= 0; i
< s
->num_extents
; i
++) {
2074 if (s
->extents
[i
].flat
) {
2075 if (!bdrv_has_zero_init(s
->extents
[i
].file
)) {
2083 static ImageInfo
*vmdk_get_extent_info(VmdkExtent
*extent
)
2085 ImageInfo
*info
= g_new0(ImageInfo
, 1);
2087 *info
= (ImageInfo
){
2088 .filename
= g_strdup(extent
->file
->filename
),
2089 .format
= g_strdup(extent
->type
),
2090 .virtual_size
= extent
->sectors
* BDRV_SECTOR_SIZE
,
2091 .compressed
= extent
->compressed
,
2092 .has_compressed
= extent
->compressed
,
2093 .cluster_size
= extent
->cluster_sectors
* BDRV_SECTOR_SIZE
,
2094 .has_cluster_size
= !extent
->flat
,
2100 static int vmdk_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
2103 BDRVVmdkState
*s
= bs
->opaque
;
2104 VmdkExtent
*extent
= NULL
;
2105 int64_t sector_num
= 0;
2106 int64_t total_sectors
= bdrv_nb_sectors(bs
);
2108 uint64_t cluster_offset
;
2115 if (sector_num
>= total_sectors
) {
2118 extent
= find_extent(s
, sector_num
, extent
);
2121 "ERROR: could not find extent for sector %" PRId64
"\n",
2125 ret
= get_cluster_offset(bs
, extent
, NULL
,
2126 sector_num
<< BDRV_SECTOR_BITS
,
2127 false, &cluster_offset
, 0, 0);
2128 if (ret
== VMDK_ERROR
) {
2130 "ERROR: could not get cluster_offset for sector %"
2131 PRId64
"\n", sector_num
);
2134 if (ret
== VMDK_OK
&& cluster_offset
>= bdrv_getlength(extent
->file
)) {
2136 "ERROR: cluster offset for sector %"
2137 PRId64
" points after EOF\n", sector_num
);
2140 sector_num
+= extent
->cluster_sectors
;
2143 result
->corruptions
++;
2147 static ImageInfoSpecific
*vmdk_get_specific_info(BlockDriverState
*bs
)
2150 BDRVVmdkState
*s
= bs
->opaque
;
2151 ImageInfoSpecific
*spec_info
= g_new0(ImageInfoSpecific
, 1);
2152 ImageInfoList
**next
;
2154 *spec_info
= (ImageInfoSpecific
){
2155 .kind
= IMAGE_INFO_SPECIFIC_KIND_VMDK
,
2157 .vmdk
= g_new0(ImageInfoSpecificVmdk
, 1),
2161 *spec_info
->vmdk
= (ImageInfoSpecificVmdk
) {
2162 .create_type
= g_strdup(s
->create_type
),
2164 .parent_cid
= s
->parent_cid
,
2167 next
= &spec_info
->vmdk
->extents
;
2168 for (i
= 0; i
< s
->num_extents
; i
++) {
2169 *next
= g_new0(ImageInfoList
, 1);
2170 (*next
)->value
= vmdk_get_extent_info(&s
->extents
[i
]);
2171 (*next
)->next
= NULL
;
2172 next
= &(*next
)->next
;
2178 static bool vmdk_extents_type_eq(const VmdkExtent
*a
, const VmdkExtent
*b
)
2180 return a
->flat
== b
->flat
&&
2181 a
->compressed
== b
->compressed
&&
2182 (a
->flat
|| a
->cluster_sectors
== b
->cluster_sectors
);
2185 static int vmdk_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2188 BDRVVmdkState
*s
= bs
->opaque
;
2189 assert(s
->num_extents
);
2191 /* See if we have multiple extents but they have different cases */
2192 for (i
= 1; i
< s
->num_extents
; i
++) {
2193 if (!vmdk_extents_type_eq(&s
->extents
[0], &s
->extents
[i
])) {
2197 bdi
->needs_compressed_writes
= s
->extents
[0].compressed
;
2198 if (!s
->extents
[0].flat
) {
2199 bdi
->cluster_size
= s
->extents
[0].cluster_sectors
<< BDRV_SECTOR_BITS
;
2204 static void vmdk_detach_aio_context(BlockDriverState
*bs
)
2206 BDRVVmdkState
*s
= bs
->opaque
;
2209 for (i
= 0; i
< s
->num_extents
; i
++) {
2210 bdrv_detach_aio_context(s
->extents
[i
].file
);
2214 static void vmdk_attach_aio_context(BlockDriverState
*bs
,
2215 AioContext
*new_context
)
2217 BDRVVmdkState
*s
= bs
->opaque
;
2220 for (i
= 0; i
< s
->num_extents
; i
++) {
2221 bdrv_attach_aio_context(s
->extents
[i
].file
, new_context
);
2225 static QemuOptsList vmdk_create_opts
= {
2226 .name
= "vmdk-create-opts",
2227 .head
= QTAILQ_HEAD_INITIALIZER(vmdk_create_opts
.head
),
2230 .name
= BLOCK_OPT_SIZE
,
2231 .type
= QEMU_OPT_SIZE
,
2232 .help
= "Virtual disk size"
2235 .name
= BLOCK_OPT_ADAPTER_TYPE
,
2236 .type
= QEMU_OPT_STRING
,
2237 .help
= "Virtual adapter type, can be one of "
2238 "ide (default), lsilogic, buslogic or legacyESX"
2241 .name
= BLOCK_OPT_BACKING_FILE
,
2242 .type
= QEMU_OPT_STRING
,
2243 .help
= "File name of a base image"
2246 .name
= BLOCK_OPT_COMPAT6
,
2247 .type
= QEMU_OPT_BOOL
,
2248 .help
= "VMDK version 6 image",
2249 .def_value_str
= "off"
2252 .name
= BLOCK_OPT_SUBFMT
,
2253 .type
= QEMU_OPT_STRING
,
2255 "VMDK flat extent format, can be one of "
2256 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2259 .name
= BLOCK_OPT_ZEROED_GRAIN
,
2260 .type
= QEMU_OPT_BOOL
,
2261 .help
= "Enable efficient zero writes "
2262 "using the zeroed-grain GTE feature"
2264 { /* end of list */ }
2268 static BlockDriver bdrv_vmdk
= {
2269 .format_name
= "vmdk",
2270 .instance_size
= sizeof(BDRVVmdkState
),
2271 .bdrv_probe
= vmdk_probe
,
2272 .bdrv_open
= vmdk_open
,
2273 .bdrv_check
= vmdk_check
,
2274 .bdrv_reopen_prepare
= vmdk_reopen_prepare
,
2275 .bdrv_read
= vmdk_co_read
,
2276 .bdrv_write
= vmdk_co_write
,
2277 .bdrv_write_compressed
= vmdk_write_compressed
,
2278 .bdrv_co_write_zeroes
= vmdk_co_write_zeroes
,
2279 .bdrv_close
= vmdk_close
,
2280 .bdrv_create
= vmdk_create
,
2281 .bdrv_co_flush_to_disk
= vmdk_co_flush
,
2282 .bdrv_co_get_block_status
= vmdk_co_get_block_status
,
2283 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
2284 .bdrv_has_zero_init
= vmdk_has_zero_init
,
2285 .bdrv_get_specific_info
= vmdk_get_specific_info
,
2286 .bdrv_refresh_limits
= vmdk_refresh_limits
,
2287 .bdrv_get_info
= vmdk_get_info
,
2288 .bdrv_detach_aio_context
= vmdk_detach_aio_context
,
2289 .bdrv_attach_aio_context
= vmdk_attach_aio_context
,
2291 .supports_backing
= true,
2292 .create_opts
= &vmdk_create_opts
,
2295 static void bdrv_vmdk_init(void)
2297 bdrv_register(&bdrv_vmdk
);
2300 block_init(bdrv_vmdk_init
);