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_int.h"
31 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
32 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
33 #define VMDK4_COMPRESSION_DEFLATE 1
34 #define VMDK4_FLAG_RGD (1 << 1)
35 #define VMDK4_FLAG_COMPRESS (1 << 16)
36 #define VMDK4_FLAG_MARKER (1 << 17)
41 uint32_t disk_sectors
;
43 uint32_t l1dir_offset
;
45 uint32_t file_sectors
;
48 uint32_t sectors_per_track
;
58 int32_t num_gtes_per_gte
;
64 uint16_t compressAlgorithm
;
65 } QEMU_PACKED VMDK4Header
;
67 #define L2_CACHE_SIZE 16
69 typedef struct VmdkExtent
{
70 BlockDriverState
*file
;
76 int64_t flat_start_offset
;
77 int64_t l1_table_offset
;
78 int64_t l1_backup_table_offset
;
80 uint32_t *l1_backup_table
;
82 uint32_t l1_entry_sectors
;
86 uint32_t l2_cache_offsets
[L2_CACHE_SIZE
];
87 uint32_t l2_cache_counts
[L2_CACHE_SIZE
];
89 unsigned int cluster_sectors
;
92 typedef struct BDRVVmdkState
{
97 /* Extent array with num_extents entries, ascend ordered by address */
101 typedef struct VmdkMetaData
{
103 unsigned int l1_index
;
104 unsigned int l2_index
;
105 unsigned int l2_offset
;
109 typedef struct VmdkGrainMarker
{
115 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
122 magic
= be32_to_cpu(*(uint32_t *)buf
);
123 if (magic
== VMDK3_MAGIC
||
124 magic
== VMDK4_MAGIC
) {
127 const char *p
= (const char *)buf
;
128 const char *end
= p
+ buf_size
;
131 /* skip comment line */
132 while (p
< end
&& *p
!= '\n') {
139 while (p
< end
&& *p
== ' ') {
142 /* skip '\r' if windows line endings used. */
143 if (p
< end
&& *p
== '\r') {
146 /* only accept blank lines before 'version=' line */
147 if (p
== end
|| *p
!= '\n') {
153 if (end
- p
>= strlen("version=X\n")) {
154 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
155 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
159 if (end
- p
>= strlen("version=X\r\n")) {
160 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
161 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
173 #define SECTOR_SIZE 512
174 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
175 #define BUF_SIZE 4096
176 #define HEADER_SIZE 512 /* first sector of 512 bytes */
178 static void vmdk_free_extents(BlockDriverState
*bs
)
181 BDRVVmdkState
*s
= bs
->opaque
;
184 for (i
= 0; i
< s
->num_extents
; i
++) {
188 g_free(e
->l1_backup_table
);
189 if (e
->file
!= bs
->file
) {
190 bdrv_delete(e
->file
);
196 static void vmdk_free_last_extent(BlockDriverState
*bs
)
198 BDRVVmdkState
*s
= bs
->opaque
;
200 if (s
->num_extents
== 0) {
204 s
->extents
= g_realloc(s
->extents
, s
->num_extents
* sizeof(VmdkExtent
));
207 static uint32_t vmdk_read_cid(BlockDriverState
*bs
, int parent
)
209 char desc
[DESC_SIZE
];
210 uint32_t cid
= 0xffffffff;
211 const char *p_name
, *cid_str
;
213 BDRVVmdkState
*s
= bs
->opaque
;
215 if (bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
) != DESC_SIZE
) {
220 cid_str
= "parentCID";
221 cid_str_size
= sizeof("parentCID");
224 cid_str_size
= sizeof("CID");
227 p_name
= strstr(desc
, cid_str
);
228 if (p_name
!= NULL
) {
229 p_name
+= cid_str_size
;
230 sscanf(p_name
, "%x", &cid
);
236 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
238 char desc
[DESC_SIZE
], tmp_desc
[DESC_SIZE
];
239 char *p_name
, *tmp_str
;
240 BDRVVmdkState
*s
= bs
->opaque
;
242 memset(desc
, 0, sizeof(desc
));
243 if (bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
) != DESC_SIZE
) {
247 tmp_str
= strstr(desc
, "parentCID");
248 pstrcpy(tmp_desc
, sizeof(tmp_desc
), tmp_str
);
249 p_name
= strstr(desc
, "CID");
250 if (p_name
!= NULL
) {
251 p_name
+= sizeof("CID");
252 snprintf(p_name
, sizeof(desc
) - (p_name
- desc
), "%x\n", cid
);
253 pstrcat(desc
, sizeof(desc
), tmp_desc
);
256 if (bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
) < 0) {
262 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
265 BDRVVmdkState
*s
= bs
->opaque
;
266 BlockDriverState
*p_bs
= bs
->backing_hd
;
270 cur_pcid
= vmdk_read_cid(p_bs
, 0);
271 if (s
->parent_cid
!= cur_pcid
) {
281 static int vmdk_parent_open(BlockDriverState
*bs
)
284 char desc
[DESC_SIZE
+ 1];
285 BDRVVmdkState
*s
= bs
->opaque
;
287 desc
[DESC_SIZE
] = '\0';
288 if (bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
) != DESC_SIZE
) {
292 p_name
= strstr(desc
, "parentFileNameHint");
293 if (p_name
!= NULL
) {
296 p_name
+= sizeof("parentFileNameHint") + 1;
297 end_name
= strchr(p_name
, '\"');
298 if (end_name
== NULL
) {
301 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
305 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
311 /* Create and append extent to the extent array. Return the added VmdkExtent
312 * address. return NULL if allocation failed. */
313 static VmdkExtent
*vmdk_add_extent(BlockDriverState
*bs
,
314 BlockDriverState
*file
, bool flat
, int64_t sectors
,
315 int64_t l1_offset
, int64_t l1_backup_offset
,
317 int l2_size
, unsigned int cluster_sectors
)
320 BDRVVmdkState
*s
= bs
->opaque
;
322 s
->extents
= g_realloc(s
->extents
,
323 (s
->num_extents
+ 1) * sizeof(VmdkExtent
));
324 extent
= &s
->extents
[s
->num_extents
];
327 memset(extent
, 0, sizeof(VmdkExtent
));
330 extent
->sectors
= sectors
;
331 extent
->l1_table_offset
= l1_offset
;
332 extent
->l1_backup_table_offset
= l1_backup_offset
;
333 extent
->l1_size
= l1_size
;
334 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
335 extent
->l2_size
= l2_size
;
336 extent
->cluster_sectors
= cluster_sectors
;
338 if (s
->num_extents
> 1) {
339 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
341 extent
->end_sector
= extent
->sectors
;
343 bs
->total_sectors
= extent
->end_sector
;
347 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
)
352 /* read the L1 table */
353 l1_size
= extent
->l1_size
* sizeof(uint32_t);
354 extent
->l1_table
= g_malloc(l1_size
);
355 ret
= bdrv_pread(extent
->file
,
356 extent
->l1_table_offset
,
362 for (i
= 0; i
< extent
->l1_size
; i
++) {
363 le32_to_cpus(&extent
->l1_table
[i
]);
366 if (extent
->l1_backup_table_offset
) {
367 extent
->l1_backup_table
= g_malloc(l1_size
);
368 ret
= bdrv_pread(extent
->file
,
369 extent
->l1_backup_table_offset
,
370 extent
->l1_backup_table
,
375 for (i
= 0; i
< extent
->l1_size
; i
++) {
376 le32_to_cpus(&extent
->l1_backup_table
[i
]);
381 g_malloc(extent
->l2_size
* L2_CACHE_SIZE
* sizeof(uint32_t));
384 g_free(extent
->l1_backup_table
);
386 g_free(extent
->l1_table
);
390 static int vmdk_open_vmdk3(BlockDriverState
*bs
,
391 BlockDriverState
*file
,
399 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
403 extent
= vmdk_add_extent(bs
,
405 le32_to_cpu(header
.disk_sectors
),
406 le32_to_cpu(header
.l1dir_offset
) << 9,
408 le32_to_cpu(header
.granularity
));
409 ret
= vmdk_init_tables(bs
, extent
);
411 /* free extent allocated by vmdk_add_extent */
412 vmdk_free_last_extent(bs
);
417 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
,
418 int64_t desc_offset
);
420 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
421 BlockDriverState
*file
,
426 uint32_t l1_size
, l1_entry_sectors
;
429 int64_t l1_backup_offset
= 0;
431 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
435 if (header
.capacity
== 0 && header
.desc_offset
) {
436 return vmdk_open_desc_file(bs
, flags
, header
.desc_offset
<< 9);
438 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gte
)
439 * le64_to_cpu(header
.granularity
);
440 if (l1_entry_sectors
<= 0) {
443 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
445 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
446 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
448 extent
= vmdk_add_extent(bs
, file
, false,
449 le64_to_cpu(header
.capacity
),
450 le64_to_cpu(header
.gd_offset
) << 9,
453 le32_to_cpu(header
.num_gtes_per_gte
),
454 le64_to_cpu(header
.granularity
));
456 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
457 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
458 ret
= vmdk_init_tables(bs
, extent
);
460 /* free extent allocated by vmdk_add_extent */
461 vmdk_free_last_extent(bs
);
466 /* find an option value out of descriptor file */
467 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
468 char *buf
, int buf_size
)
470 char *opt_pos
, *opt_end
;
471 const char *end
= desc
+ strlen(desc
);
473 opt_pos
= strstr(desc
, opt_name
);
477 /* Skip "=\"" following opt_name */
478 opt_pos
+= strlen(opt_name
) + 2;
479 if (opt_pos
>= end
) {
483 while (opt_end
< end
&& *opt_end
!= '"') {
486 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
489 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
493 /* Open an extent file and append to bs array */
494 static int vmdk_open_sparse(BlockDriverState
*bs
,
495 BlockDriverState
*file
,
500 if (bdrv_pread(file
, 0, &magic
, sizeof(magic
)) != sizeof(magic
)) {
504 magic
= be32_to_cpu(magic
);
507 return vmdk_open_vmdk3(bs
, file
, flags
);
510 return vmdk_open_vmdk4(bs
, file
, flags
);
518 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
519 const char *desc_file_path
)
525 const char *p
= desc
;
528 char extent_path
[PATH_MAX
];
529 BlockDriverState
*extent_file
;
532 /* parse extent line:
533 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
535 * RW [size in sectors] SPARSE "file-name.vmdk"
538 ret
= sscanf(p
, "%10s %" SCNd64
" %10s %511s %" SCNd64
,
539 access
, §ors
, type
, fname
, &flat_offset
);
540 if (ret
< 4 || strcmp(access
, "RW")) {
542 } else if (!strcmp(type
, "FLAT")) {
543 if (ret
!= 5 || flat_offset
< 0) {
546 } else if (ret
!= 4) {
550 /* trim the quotation marks around */
551 if (fname
[0] == '"') {
552 memmove(fname
, fname
+ 1, strlen(fname
));
553 if (strlen(fname
) <= 1 || fname
[strlen(fname
) - 1] != '"') {
556 fname
[strlen(fname
) - 1] = '\0';
559 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE")) ||
560 (strcmp(access
, "RW"))) {
564 path_combine(extent_path
, sizeof(extent_path
),
565 desc_file_path
, fname
);
566 ret
= bdrv_file_open(&extent_file
, extent_path
, bs
->open_flags
);
571 /* save to extents array */
572 if (!strcmp(type
, "FLAT")) {
576 extent
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
577 0, 0, 0, 0, sectors
);
578 extent
->flat_start_offset
= flat_offset
<< 9;
579 } else if (!strcmp(type
, "SPARSE")) {
581 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
);
583 bdrv_delete(extent_file
);
588 "VMDK: Not supported extent type \"%s\""".\n", type
);
592 /* move to next line */
593 while (*p
&& *p
!= '\n') {
601 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
,
607 BDRVVmdkState
*s
= bs
->opaque
;
609 ret
= bdrv_pread(bs
->file
, desc_offset
, buf
, sizeof(buf
));
614 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
617 if (strcmp(ct
, "monolithicFlat") &&
618 strcmp(ct
, "twoGbMaxExtentSparse") &&
619 strcmp(ct
, "twoGbMaxExtentFlat")) {
621 "VMDK: Not supported image type \"%s\""".\n", ct
);
625 ret
= vmdk_parse_extents(buf
, bs
, bs
->file
->filename
);
627 vmdk_free_extents(bs
);
631 /* try to open parent images, if exist */
632 if (vmdk_parent_open(bs
)) {
633 vmdk_free_extents(bs
);
636 s
->parent_cid
= vmdk_read_cid(bs
, 1);
640 static int vmdk_open(BlockDriverState
*bs
, int flags
)
643 BDRVVmdkState
*s
= bs
->opaque
;
645 if (vmdk_open_sparse(bs
, bs
->file
, flags
) == 0) {
646 s
->desc_offset
= 0x200;
647 /* try to open parent images, if exist */
648 ret
= vmdk_parent_open(bs
);
650 vmdk_free_extents(bs
);
653 s
->parent_cid
= vmdk_read_cid(bs
, 1);
656 return vmdk_open_desc_file(bs
, flags
, 0);
660 static int get_whole_cluster(BlockDriverState
*bs
,
662 uint64_t cluster_offset
,
666 /* 128 sectors * 512 bytes each = grain size 64KB */
667 uint8_t whole_grain
[extent
->cluster_sectors
* 512];
669 /* we will be here if it's first write on non-exist grain(cluster).
670 * try to read from parent image, if exist */
671 if (bs
->backing_hd
) {
674 if (!vmdk_is_cid_valid(bs
)) {
678 /* floor offset to cluster */
679 offset
-= offset
% (extent
->cluster_sectors
* 512);
680 ret
= bdrv_read(bs
->backing_hd
, offset
>> 9, whole_grain
,
681 extent
->cluster_sectors
);
686 /* Write grain only into the active image */
687 ret
= bdrv_write(extent
->file
, cluster_offset
, whole_grain
,
688 extent
->cluster_sectors
);
696 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
)
698 /* update L2 table */
699 if (bdrv_pwrite_sync(
701 ((int64_t)m_data
->l2_offset
* 512)
702 + (m_data
->l2_index
* sizeof(m_data
->offset
)),
704 sizeof(m_data
->offset
)
708 /* update backup L2 table */
709 if (extent
->l1_backup_table_offset
!= 0) {
710 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
711 if (bdrv_pwrite_sync(
713 ((int64_t)m_data
->l2_offset
* 512)
714 + (m_data
->l2_index
* sizeof(m_data
->offset
)),
715 &(m_data
->offset
), sizeof(m_data
->offset
)
724 static int get_cluster_offset(BlockDriverState
*bs
,
726 VmdkMetaData
*m_data
,
729 uint64_t *cluster_offset
)
731 unsigned int l1_index
, l2_offset
, l2_index
;
733 uint32_t min_count
, *l2_table
, tmp
= 0;
739 *cluster_offset
= extent
->flat_start_offset
;
743 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
744 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
745 if (l1_index
>= extent
->l1_size
) {
748 l2_offset
= extent
->l1_table
[l1_index
];
752 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
753 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
754 /* increment the hit count */
755 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
756 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
757 extent
->l2_cache_counts
[j
] >>= 1;
760 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
764 /* not found: load a new entry in the least used one */
766 min_count
= 0xffffffff;
767 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
768 if (extent
->l2_cache_counts
[i
] < min_count
) {
769 min_count
= extent
->l2_cache_counts
[i
];
773 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
776 (int64_t)l2_offset
* 512,
778 extent
->l2_size
* sizeof(uint32_t)
779 ) != extent
->l2_size
* sizeof(uint32_t)) {
783 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
784 extent
->l2_cache_counts
[min_index
] = 1;
786 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
787 *cluster_offset
= le32_to_cpu(l2_table
[l2_index
]);
789 if (!*cluster_offset
) {
794 /* Avoid the L2 tables update for the images that have snapshots. */
795 *cluster_offset
= bdrv_getlength(extent
->file
);
796 if (!extent
->compressed
) {
799 *cluster_offset
+ (extent
->cluster_sectors
<< 9)
803 *cluster_offset
>>= 9;
804 tmp
= cpu_to_le32(*cluster_offset
);
805 l2_table
[l2_index
] = tmp
;
807 /* First of all we write grain itself, to avoid race condition
808 * that may to corrupt the image.
809 * This problem may occur because of insufficient space on host disk
810 * or inappropriate VM shutdown.
812 if (get_whole_cluster(
813 bs
, extent
, *cluster_offset
, offset
, allocate
) == -1) {
818 m_data
->offset
= tmp
;
819 m_data
->l1_index
= l1_index
;
820 m_data
->l2_index
= l2_index
;
821 m_data
->l2_offset
= l2_offset
;
825 *cluster_offset
<<= 9;
829 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
830 int64_t sector_num
, VmdkExtent
*start_hint
)
832 VmdkExtent
*extent
= start_hint
;
835 extent
= &s
->extents
[0];
837 while (extent
< &s
->extents
[s
->num_extents
]) {
838 if (sector_num
< extent
->end_sector
) {
846 static int vmdk_is_allocated(BlockDriverState
*bs
, int64_t sector_num
,
847 int nb_sectors
, int *pnum
)
849 BDRVVmdkState
*s
= bs
->opaque
;
850 int64_t index_in_cluster
, n
, ret
;
854 extent
= find_extent(s
, sector_num
, NULL
);
858 ret
= get_cluster_offset(bs
, extent
, NULL
,
859 sector_num
* 512, 0, &offset
);
860 /* get_cluster_offset returning 0 means success */
863 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
864 n
= extent
->cluster_sectors
- index_in_cluster
;
865 if (n
> nb_sectors
) {
872 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
873 int64_t offset_in_cluster
, const uint8_t *buf
,
874 int nb_sectors
, int64_t sector_num
)
877 VmdkGrainMarker
*data
= NULL
;
879 const uint8_t *write_buf
= buf
;
880 int write_len
= nb_sectors
* 512;
882 if (extent
->compressed
) {
883 if (!extent
->has_marker
) {
887 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
888 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
889 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
894 data
->lba
= sector_num
;
895 data
->size
= buf_len
;
896 write_buf
= (uint8_t *)data
;
897 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
899 ret
= bdrv_pwrite(extent
->file
,
900 cluster_offset
+ offset_in_cluster
,
903 if (ret
!= write_len
) {
904 ret
= ret
< 0 ? ret
: -EIO
;
913 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
914 int64_t offset_in_cluster
, uint8_t *buf
,
918 int cluster_bytes
, buf_bytes
;
919 uint8_t *cluster_buf
, *compressed_data
;
922 VmdkGrainMarker
*marker
;
926 if (!extent
->compressed
) {
927 ret
= bdrv_pread(extent
->file
,
928 cluster_offset
+ offset_in_cluster
,
929 buf
, nb_sectors
* 512);
930 if (ret
== nb_sectors
* 512) {
936 cluster_bytes
= extent
->cluster_sectors
* 512;
937 /* Read two clusters in case GrainMarker + compressed data > one cluster */
938 buf_bytes
= cluster_bytes
* 2;
939 cluster_buf
= g_malloc(buf_bytes
);
940 uncomp_buf
= g_malloc(cluster_bytes
);
941 ret
= bdrv_pread(extent
->file
,
943 cluster_buf
, buf_bytes
);
947 compressed_data
= cluster_buf
;
948 buf_len
= cluster_bytes
;
949 data_len
= cluster_bytes
;
950 if (extent
->has_marker
) {
951 marker
= (VmdkGrainMarker
*)cluster_buf
;
952 compressed_data
= marker
->data
;
953 data_len
= le32_to_cpu(marker
->size
);
955 if (!data_len
|| data_len
> buf_bytes
) {
959 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
965 if (offset_in_cluster
< 0 ||
966 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
970 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
979 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
980 uint8_t *buf
, int nb_sectors
)
982 BDRVVmdkState
*s
= bs
->opaque
;
984 uint64_t n
, index_in_cluster
;
985 VmdkExtent
*extent
= NULL
;
986 uint64_t cluster_offset
;
988 while (nb_sectors
> 0) {
989 extent
= find_extent(s
, sector_num
, extent
);
993 ret
= get_cluster_offset(
995 sector_num
<< 9, 0, &cluster_offset
);
996 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
997 n
= extent
->cluster_sectors
- index_in_cluster
;
998 if (n
> nb_sectors
) {
1002 /* if not allocated, try to read from parent image, if exist */
1003 if (bs
->backing_hd
) {
1004 if (!vmdk_is_cid_valid(bs
)) {
1007 ret
= bdrv_read(bs
->backing_hd
, sector_num
, buf
, n
);
1012 memset(buf
, 0, 512 * n
);
1015 ret
= vmdk_read_extent(extent
,
1016 cluster_offset
, index_in_cluster
* 512,
1029 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1030 const uint8_t *buf
, int nb_sectors
)
1032 BDRVVmdkState
*s
= bs
->opaque
;
1033 VmdkExtent
*extent
= NULL
;
1035 int64_t index_in_cluster
;
1036 uint64_t cluster_offset
;
1037 VmdkMetaData m_data
;
1039 if (sector_num
> bs
->total_sectors
) {
1041 "(VMDK) Wrong offset: sector_num=0x%" PRIx64
1042 " total_sectors=0x%" PRIx64
"\n",
1043 sector_num
, bs
->total_sectors
);
1047 while (nb_sectors
> 0) {
1048 extent
= find_extent(s
, sector_num
, extent
);
1052 ret
= get_cluster_offset(
1056 sector_num
<< 9, !extent
->compressed
,
1058 if (extent
->compressed
) {
1060 /* Refuse write to allocated cluster for streamOptimized */
1062 "VMDK: can't write to allocated cluster"
1063 " for streamOptimized\n");
1067 ret
= get_cluster_offset(
1078 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
1079 n
= extent
->cluster_sectors
- index_in_cluster
;
1080 if (n
> nb_sectors
) {
1084 ret
= vmdk_write_extent(extent
,
1085 cluster_offset
, index_in_cluster
* 512,
1086 buf
, n
, sector_num
);
1091 /* update L2 tables */
1092 if (vmdk_L2update(extent
, &m_data
) == -1) {
1100 /* update CID on the first write every time the virtual disk is
1102 if (!s
->cid_updated
) {
1103 vmdk_write_cid(bs
, time(NULL
));
1104 s
->cid_updated
= true;
1111 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1112 bool flat
, bool compress
)
1117 uint32_t tmp
, magic
, grains
, gd_size
, gt_size
, gt_count
;
1121 O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
| O_LARGEFILE
,
1127 ret
= ftruncate(fd
, filesize
);
1133 magic
= cpu_to_be32(VMDK4_MAGIC
);
1134 memset(&header
, 0, sizeof(header
));
1137 3 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0);
1138 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1139 header
.capacity
= filesize
/ 512;
1140 header
.granularity
= 128;
1141 header
.num_gtes_per_gte
= 512;
1143 grains
= (filesize
/ 512 + header
.granularity
- 1) / header
.granularity
;
1144 gt_size
= ((header
.num_gtes_per_gte
* sizeof(uint32_t)) + 511) >> 9;
1146 (grains
+ header
.num_gtes_per_gte
- 1) / header
.num_gtes_per_gte
;
1147 gd_size
= (gt_count
* sizeof(uint32_t) + 511) >> 9;
1149 header
.desc_offset
= 1;
1150 header
.desc_size
= 20;
1151 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1152 header
.gd_offset
= header
.rgd_offset
+ gd_size
+ (gt_size
* gt_count
);
1153 header
.grain_offset
=
1154 ((header
.gd_offset
+ gd_size
+ (gt_size
* gt_count
) +
1155 header
.granularity
- 1) / header
.granularity
) *
1157 /* swap endianness for all header fields */
1158 header
.version
= cpu_to_le32(header
.version
);
1159 header
.flags
= cpu_to_le32(header
.flags
);
1160 header
.capacity
= cpu_to_le64(header
.capacity
);
1161 header
.granularity
= cpu_to_le64(header
.granularity
);
1162 header
.num_gtes_per_gte
= cpu_to_le32(header
.num_gtes_per_gte
);
1163 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1164 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1165 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1166 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1167 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1168 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1170 header
.check_bytes
[0] = 0xa;
1171 header
.check_bytes
[1] = 0x20;
1172 header
.check_bytes
[2] = 0xd;
1173 header
.check_bytes
[3] = 0xa;
1175 /* write all the data */
1176 ret
= qemu_write_full(fd
, &magic
, sizeof(magic
));
1177 if (ret
!= sizeof(magic
)) {
1181 ret
= qemu_write_full(fd
, &header
, sizeof(header
));
1182 if (ret
!= sizeof(header
)) {
1187 ret
= ftruncate(fd
, le64_to_cpu(header
.grain_offset
) << 9);
1193 /* write grain directory */
1194 lseek(fd
, le64_to_cpu(header
.rgd_offset
) << 9, SEEK_SET
);
1195 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_size
;
1196 i
< gt_count
; i
++, tmp
+= gt_size
) {
1197 ret
= qemu_write_full(fd
, &tmp
, sizeof(tmp
));
1198 if (ret
!= sizeof(tmp
)) {
1204 /* write backup grain directory */
1205 lseek(fd
, le64_to_cpu(header
.gd_offset
) << 9, SEEK_SET
);
1206 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_size
;
1207 i
< gt_count
; i
++, tmp
+= gt_size
) {
1208 ret
= qemu_write_full(fd
, &tmp
, sizeof(tmp
));
1209 if (ret
!= sizeof(tmp
)) {
1221 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1222 char *postfix
, size_t buf_len
)
1226 if (filename
== NULL
|| !strlen(filename
)) {
1227 fprintf(stderr
, "Vmdk: no filename provided.\n");
1230 p
= strrchr(filename
, '/');
1232 p
= strrchr(filename
, '\\');
1235 p
= strrchr(filename
, ':');
1239 if (p
- filename
>= buf_len
) {
1242 pstrcpy(path
, p
- filename
+ 1, filename
);
1247 q
= strrchr(p
, '.');
1249 pstrcpy(prefix
, buf_len
, p
);
1252 if (q
- p
>= buf_len
) {
1255 pstrcpy(prefix
, q
- p
+ 1, p
);
1256 pstrcpy(postfix
, buf_len
, q
);
1261 static int relative_path(char *dest
, int dest_size
,
1262 const char *base
, const char *target
)
1268 const char *sep
= "\\";
1270 const char *sep
= "/";
1273 if (!(dest
&& base
&& target
)) {
1276 if (path_is_absolute(target
)) {
1277 dest
[dest_size
- 1] = '\0';
1278 strncpy(dest
, target
, dest_size
- 1);
1281 while (base
[i
] == target
[i
]) {
1294 pstrcat(dest
, dest_size
, "..");
1295 pstrcat(dest
, dest_size
, sep
);
1297 pstrcat(dest
, dest_size
, q
);
1301 static int vmdk_create(const char *filename
, QEMUOptionParameter
*options
)
1304 char desc
[BUF_SIZE
];
1305 int64_t total_size
= 0, filesize
;
1306 const char *backing_file
= NULL
;
1307 const char *fmt
= NULL
;
1310 bool flat
, split
, compress
;
1311 char ext_desc_lines
[BUF_SIZE
] = "";
1312 char path
[PATH_MAX
], prefix
[PATH_MAX
], postfix
[PATH_MAX
];
1313 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1314 const char *desc_extent_line
;
1315 char parent_desc_line
[BUF_SIZE
] = "";
1316 uint32_t parent_cid
= 0xffffffff;
1317 const char desc_template
[] =
1318 "# Disk DescriptorFile\n"
1322 "createType=\"%s\"\n"
1325 "# Extent description\n"
1328 "# The Disk Data Base\n"
1331 "ddb.virtualHWVersion = \"%d\"\n"
1332 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1333 "ddb.geometry.heads = \"16\"\n"
1334 "ddb.geometry.sectors = \"63\"\n"
1335 "ddb.adapterType = \"ide\"\n";
1337 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
)) {
1340 /* Read out options */
1341 while (options
&& options
->name
) {
1342 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1343 total_size
= options
->value
.n
;
1344 } else if (!strcmp(options
->name
, BLOCK_OPT_BACKING_FILE
)) {
1345 backing_file
= options
->value
.s
;
1346 } else if (!strcmp(options
->name
, BLOCK_OPT_COMPAT6
)) {
1347 flags
|= options
->value
.n
? BLOCK_FLAG_COMPAT6
: 0;
1348 } else if (!strcmp(options
->name
, BLOCK_OPT_SUBFMT
)) {
1349 fmt
= options
->value
.s
;
1354 /* Default format to monolithicSparse */
1355 fmt
= "monolithicSparse";
1356 } else if (strcmp(fmt
, "monolithicFlat") &&
1357 strcmp(fmt
, "monolithicSparse") &&
1358 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1359 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1360 strcmp(fmt
, "streamOptimized")) {
1361 fprintf(stderr
, "VMDK: Unknown subformat: %s\n", fmt
);
1364 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1365 strcmp(fmt
, "twoGbMaxExtentSparse"));
1366 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1367 strcmp(fmt
, "twoGbMaxExtentFlat"));
1368 compress
= !strcmp(fmt
, "streamOptimized");
1370 desc_extent_line
= "RW %lld FLAT \"%s\" 0\n";
1372 desc_extent_line
= "RW %lld SPARSE \"%s\"\n";
1374 if (flat
&& backing_file
) {
1375 /* not supporting backing file for flat image */
1379 char parent_filename
[PATH_MAX
];
1380 BlockDriverState
*bs
= bdrv_new("");
1381 ret
= bdrv_open(bs
, backing_file
, 0, NULL
);
1386 if (strcmp(bs
->drv
->format_name
, "vmdk")) {
1390 parent_cid
= vmdk_read_cid(bs
, 0);
1392 relative_path(parent_filename
, sizeof(parent_filename
),
1393 filename
, backing_file
);
1394 snprintf(parent_desc_line
, sizeof(parent_desc_line
),
1395 "parentFileNameHint=\"%s\"", parent_filename
);
1398 /* Create extents */
1399 filesize
= total_size
;
1400 while (filesize
> 0) {
1401 char desc_line
[BUF_SIZE
];
1402 char ext_filename
[PATH_MAX
];
1403 char desc_filename
[PATH_MAX
];
1404 int64_t size
= filesize
;
1406 if (split
&& size
> split_size
) {
1410 snprintf(desc_filename
, sizeof(desc_filename
), "%s-%c%03d%s",
1411 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1413 snprintf(desc_filename
, sizeof(desc_filename
), "%s-flat%s",
1416 snprintf(desc_filename
, sizeof(desc_filename
), "%s%s",
1419 snprintf(ext_filename
, sizeof(ext_filename
), "%s%s",
1420 path
, desc_filename
);
1422 if (vmdk_create_extent(ext_filename
, size
, flat
, compress
)) {
1427 /* Format description line */
1428 snprintf(desc_line
, sizeof(desc_line
),
1429 desc_extent_line
, size
/ 512, desc_filename
);
1430 pstrcat(ext_desc_lines
, sizeof(ext_desc_lines
), desc_line
);
1432 /* generate descriptor file */
1433 snprintf(desc
, sizeof(desc
), desc_template
,
1434 (unsigned int)time(NULL
),
1439 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
1440 total_size
/ (int64_t)(63 * 16 * 512));
1441 if (split
|| flat
) {
1444 O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
| O_LARGEFILE
,
1449 O_WRONLY
| O_BINARY
| O_LARGEFILE
,
1455 /* the descriptor offset = 0x200 */
1456 if (!split
&& !flat
&& 0x200 != lseek(fd
, 0x200, SEEK_SET
)) {
1460 ret
= qemu_write_full(fd
, desc
, strlen(desc
));
1461 if (ret
!= strlen(desc
)) {
1471 static void vmdk_close(BlockDriverState
*bs
)
1473 vmdk_free_extents(bs
);
1476 static int vmdk_flush(BlockDriverState
*bs
)
1479 BDRVVmdkState
*s
= bs
->opaque
;
1481 ret
= bdrv_flush(bs
->file
);
1482 for (i
= 0; i
< s
->num_extents
; i
++) {
1483 err
= bdrv_flush(s
->extents
[i
].file
);
1491 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
1496 BDRVVmdkState
*s
= bs
->opaque
;
1498 ret
= bdrv_get_allocated_file_size(bs
->file
);
1502 for (i
= 0; i
< s
->num_extents
; i
++) {
1503 if (s
->extents
[i
].file
== bs
->file
) {
1506 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
);
1515 static QEMUOptionParameter vmdk_create_options
[] = {
1517 .name
= BLOCK_OPT_SIZE
,
1519 .help
= "Virtual disk size"
1522 .name
= BLOCK_OPT_BACKING_FILE
,
1524 .help
= "File name of a base image"
1527 .name
= BLOCK_OPT_COMPAT6
,
1529 .help
= "VMDK version 6 image"
1532 .name
= BLOCK_OPT_SUBFMT
,
1535 "VMDK flat extent format, can be one of "
1536 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
1541 static BlockDriver bdrv_vmdk
= {
1542 .format_name
= "vmdk",
1543 .instance_size
= sizeof(BDRVVmdkState
),
1544 .bdrv_probe
= vmdk_probe
,
1545 .bdrv_open
= vmdk_open
,
1546 .bdrv_read
= vmdk_read
,
1547 .bdrv_write
= vmdk_write
,
1548 .bdrv_close
= vmdk_close
,
1549 .bdrv_create
= vmdk_create
,
1550 .bdrv_flush
= vmdk_flush
,
1551 .bdrv_is_allocated
= vmdk_is_allocated
,
1552 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
1554 .create_options
= vmdk_create_options
,
1557 static void bdrv_vmdk_init(void)
1559 bdrv_register(&bdrv_vmdk
);
1562 block_init(bdrv_vmdk_init
);