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
{
98 /* Extent array with num_extents entries, ascend ordered by address */
102 typedef struct VmdkMetaData
{
104 unsigned int l1_index
;
105 unsigned int l2_index
;
106 unsigned int l2_offset
;
110 typedef struct VmdkGrainMarker
{
116 static int vmdk_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
123 magic
= be32_to_cpu(*(uint32_t *)buf
);
124 if (magic
== VMDK3_MAGIC
||
125 magic
== VMDK4_MAGIC
) {
128 const char *p
= (const char *)buf
;
129 const char *end
= p
+ buf_size
;
132 /* skip comment line */
133 while (p
< end
&& *p
!= '\n') {
140 while (p
< end
&& *p
== ' ') {
143 /* skip '\r' if windows line endings used. */
144 if (p
< end
&& *p
== '\r') {
147 /* only accept blank lines before 'version=' line */
148 if (p
== end
|| *p
!= '\n') {
154 if (end
- p
>= strlen("version=X\n")) {
155 if (strncmp("version=1\n", p
, strlen("version=1\n")) == 0 ||
156 strncmp("version=2\n", p
, strlen("version=2\n")) == 0) {
160 if (end
- p
>= strlen("version=X\r\n")) {
161 if (strncmp("version=1\r\n", p
, strlen("version=1\r\n")) == 0 ||
162 strncmp("version=2\r\n", p
, strlen("version=2\r\n")) == 0) {
174 #define SECTOR_SIZE 512
175 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
176 #define BUF_SIZE 4096
177 #define HEADER_SIZE 512 /* first sector of 512 bytes */
179 static void vmdk_free_extents(BlockDriverState
*bs
)
182 BDRVVmdkState
*s
= bs
->opaque
;
185 for (i
= 0; i
< s
->num_extents
; i
++) {
189 g_free(e
->l1_backup_table
);
190 if (e
->file
!= bs
->file
) {
191 bdrv_delete(e
->file
);
197 static void vmdk_free_last_extent(BlockDriverState
*bs
)
199 BDRVVmdkState
*s
= bs
->opaque
;
201 if (s
->num_extents
== 0) {
205 s
->extents
= g_realloc(s
->extents
, s
->num_extents
* sizeof(VmdkExtent
));
208 static uint32_t vmdk_read_cid(BlockDriverState
*bs
, int parent
)
210 char desc
[DESC_SIZE
];
212 const char *p_name
, *cid_str
;
214 BDRVVmdkState
*s
= bs
->opaque
;
216 if (bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
) != DESC_SIZE
) {
221 cid_str
= "parentCID";
222 cid_str_size
= sizeof("parentCID");
225 cid_str_size
= sizeof("CID");
228 p_name
= strstr(desc
, cid_str
);
229 if (p_name
!= NULL
) {
230 p_name
+= cid_str_size
;
231 sscanf(p_name
, "%x", &cid
);
237 static int vmdk_write_cid(BlockDriverState
*bs
, uint32_t cid
)
239 char desc
[DESC_SIZE
], tmp_desc
[DESC_SIZE
];
240 char *p_name
, *tmp_str
;
241 BDRVVmdkState
*s
= bs
->opaque
;
243 memset(desc
, 0, sizeof(desc
));
244 if (bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
) != DESC_SIZE
) {
248 tmp_str
= strstr(desc
, "parentCID");
249 pstrcpy(tmp_desc
, sizeof(tmp_desc
), tmp_str
);
250 p_name
= strstr(desc
, "CID");
251 if (p_name
!= NULL
) {
252 p_name
+= sizeof("CID");
253 snprintf(p_name
, sizeof(desc
) - (p_name
- desc
), "%x\n", cid
);
254 pstrcat(desc
, sizeof(desc
), tmp_desc
);
257 if (bdrv_pwrite_sync(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
) < 0) {
263 static int vmdk_is_cid_valid(BlockDriverState
*bs
)
266 BDRVVmdkState
*s
= bs
->opaque
;
267 BlockDriverState
*p_bs
= bs
->backing_hd
;
271 cur_pcid
= vmdk_read_cid(p_bs
, 0);
272 if (s
->parent_cid
!= cur_pcid
) {
282 static int vmdk_parent_open(BlockDriverState
*bs
)
285 char desc
[DESC_SIZE
+ 1];
286 BDRVVmdkState
*s
= bs
->opaque
;
289 desc
[DESC_SIZE
] = '\0';
290 ret
= bdrv_pread(bs
->file
, s
->desc_offset
, desc
, DESC_SIZE
);
295 p_name
= strstr(desc
, "parentFileNameHint");
296 if (p_name
!= NULL
) {
299 p_name
+= sizeof("parentFileNameHint") + 1;
300 end_name
= strchr(p_name
, '\"');
301 if (end_name
== NULL
) {
304 if ((end_name
- p_name
) > sizeof(bs
->backing_file
) - 1) {
308 pstrcpy(bs
->backing_file
, end_name
- p_name
+ 1, p_name
);
314 /* Create and append extent to the extent array. Return the added VmdkExtent
315 * address. return NULL if allocation failed. */
316 static VmdkExtent
*vmdk_add_extent(BlockDriverState
*bs
,
317 BlockDriverState
*file
, bool flat
, int64_t sectors
,
318 int64_t l1_offset
, int64_t l1_backup_offset
,
320 int l2_size
, unsigned int cluster_sectors
)
323 BDRVVmdkState
*s
= bs
->opaque
;
325 s
->extents
= g_realloc(s
->extents
,
326 (s
->num_extents
+ 1) * sizeof(VmdkExtent
));
327 extent
= &s
->extents
[s
->num_extents
];
330 memset(extent
, 0, sizeof(VmdkExtent
));
333 extent
->sectors
= sectors
;
334 extent
->l1_table_offset
= l1_offset
;
335 extent
->l1_backup_table_offset
= l1_backup_offset
;
336 extent
->l1_size
= l1_size
;
337 extent
->l1_entry_sectors
= l2_size
* cluster_sectors
;
338 extent
->l2_size
= l2_size
;
339 extent
->cluster_sectors
= cluster_sectors
;
341 if (s
->num_extents
> 1) {
342 extent
->end_sector
= (*(extent
- 1)).end_sector
+ extent
->sectors
;
344 extent
->end_sector
= extent
->sectors
;
346 bs
->total_sectors
= extent
->end_sector
;
350 static int vmdk_init_tables(BlockDriverState
*bs
, VmdkExtent
*extent
)
355 /* read the L1 table */
356 l1_size
= extent
->l1_size
* sizeof(uint32_t);
357 extent
->l1_table
= g_malloc(l1_size
);
358 ret
= bdrv_pread(extent
->file
,
359 extent
->l1_table_offset
,
365 for (i
= 0; i
< extent
->l1_size
; i
++) {
366 le32_to_cpus(&extent
->l1_table
[i
]);
369 if (extent
->l1_backup_table_offset
) {
370 extent
->l1_backup_table
= g_malloc(l1_size
);
371 ret
= bdrv_pread(extent
->file
,
372 extent
->l1_backup_table_offset
,
373 extent
->l1_backup_table
,
378 for (i
= 0; i
< extent
->l1_size
; i
++) {
379 le32_to_cpus(&extent
->l1_backup_table
[i
]);
384 g_malloc(extent
->l2_size
* L2_CACHE_SIZE
* sizeof(uint32_t));
387 g_free(extent
->l1_backup_table
);
389 g_free(extent
->l1_table
);
393 static int vmdk_open_vmdk3(BlockDriverState
*bs
,
394 BlockDriverState
*file
,
402 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
406 extent
= vmdk_add_extent(bs
,
408 le32_to_cpu(header
.disk_sectors
),
409 le32_to_cpu(header
.l1dir_offset
) << 9,
411 le32_to_cpu(header
.granularity
));
412 ret
= vmdk_init_tables(bs
, extent
);
414 /* free extent allocated by vmdk_add_extent */
415 vmdk_free_last_extent(bs
);
420 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
,
421 int64_t desc_offset
);
423 static int vmdk_open_vmdk4(BlockDriverState
*bs
,
424 BlockDriverState
*file
,
429 uint32_t l1_size
, l1_entry_sectors
;
432 int64_t l1_backup_offset
= 0;
434 ret
= bdrv_pread(file
, sizeof(magic
), &header
, sizeof(header
));
438 if (header
.capacity
== 0 && header
.desc_offset
) {
439 return vmdk_open_desc_file(bs
, flags
, header
.desc_offset
<< 9);
441 l1_entry_sectors
= le32_to_cpu(header
.num_gtes_per_gte
)
442 * le64_to_cpu(header
.granularity
);
443 if (l1_entry_sectors
<= 0) {
446 l1_size
= (le64_to_cpu(header
.capacity
) + l1_entry_sectors
- 1)
448 if (le32_to_cpu(header
.flags
) & VMDK4_FLAG_RGD
) {
449 l1_backup_offset
= le64_to_cpu(header
.rgd_offset
) << 9;
451 extent
= vmdk_add_extent(bs
, file
, false,
452 le64_to_cpu(header
.capacity
),
453 le64_to_cpu(header
.gd_offset
) << 9,
456 le32_to_cpu(header
.num_gtes_per_gte
),
457 le64_to_cpu(header
.granularity
));
459 le16_to_cpu(header
.compressAlgorithm
) == VMDK4_COMPRESSION_DEFLATE
;
460 extent
->has_marker
= le32_to_cpu(header
.flags
) & VMDK4_FLAG_MARKER
;
461 ret
= vmdk_init_tables(bs
, extent
);
463 /* free extent allocated by vmdk_add_extent */
464 vmdk_free_last_extent(bs
);
469 /* find an option value out of descriptor file */
470 static int vmdk_parse_description(const char *desc
, const char *opt_name
,
471 char *buf
, int buf_size
)
473 char *opt_pos
, *opt_end
;
474 const char *end
= desc
+ strlen(desc
);
476 opt_pos
= strstr(desc
, opt_name
);
480 /* Skip "=\"" following opt_name */
481 opt_pos
+= strlen(opt_name
) + 2;
482 if (opt_pos
>= end
) {
486 while (opt_end
< end
&& *opt_end
!= '"') {
489 if (opt_end
== end
|| buf_size
< opt_end
- opt_pos
+ 1) {
492 pstrcpy(buf
, opt_end
- opt_pos
+ 1, opt_pos
);
496 /* Open an extent file and append to bs array */
497 static int vmdk_open_sparse(BlockDriverState
*bs
,
498 BlockDriverState
*file
,
503 if (bdrv_pread(file
, 0, &magic
, sizeof(magic
)) != sizeof(magic
)) {
507 magic
= be32_to_cpu(magic
);
510 return vmdk_open_vmdk3(bs
, file
, flags
);
513 return vmdk_open_vmdk4(bs
, file
, flags
);
521 static int vmdk_parse_extents(const char *desc
, BlockDriverState
*bs
,
522 const char *desc_file_path
)
528 const char *p
= desc
;
531 char extent_path
[PATH_MAX
];
532 BlockDriverState
*extent_file
;
535 /* parse extent line:
536 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
538 * RW [size in sectors] SPARSE "file-name.vmdk"
541 ret
= sscanf(p
, "%10s %" SCNd64
" %10s %511s %" SCNd64
,
542 access
, §ors
, type
, fname
, &flat_offset
);
543 if (ret
< 4 || strcmp(access
, "RW")) {
545 } else if (!strcmp(type
, "FLAT")) {
546 if (ret
!= 5 || flat_offset
< 0) {
549 } else if (ret
!= 4) {
553 /* trim the quotation marks around */
554 if (fname
[0] == '"') {
555 memmove(fname
, fname
+ 1, strlen(fname
));
556 if (strlen(fname
) <= 1 || fname
[strlen(fname
) - 1] != '"') {
559 fname
[strlen(fname
) - 1] = '\0';
562 (strcmp(type
, "FLAT") && strcmp(type
, "SPARSE")) ||
563 (strcmp(access
, "RW"))) {
567 path_combine(extent_path
, sizeof(extent_path
),
568 desc_file_path
, fname
);
569 ret
= bdrv_file_open(&extent_file
, extent_path
, bs
->open_flags
);
574 /* save to extents array */
575 if (!strcmp(type
, "FLAT")) {
579 extent
= vmdk_add_extent(bs
, extent_file
, true, sectors
,
580 0, 0, 0, 0, sectors
);
581 extent
->flat_start_offset
= flat_offset
<< 9;
582 } else if (!strcmp(type
, "SPARSE")) {
584 ret
= vmdk_open_sparse(bs
, extent_file
, bs
->open_flags
);
586 bdrv_delete(extent_file
);
591 "VMDK: Not supported extent type \"%s\""".\n", type
);
595 /* move to next line */
596 while (*p
&& *p
!= '\n') {
604 static int vmdk_open_desc_file(BlockDriverState
*bs
, int flags
,
610 BDRVVmdkState
*s
= bs
->opaque
;
612 ret
= bdrv_pread(bs
->file
, desc_offset
, buf
, sizeof(buf
));
617 if (vmdk_parse_description(buf
, "createType", ct
, sizeof(ct
))) {
620 if (strcmp(ct
, "monolithicFlat") &&
621 strcmp(ct
, "twoGbMaxExtentSparse") &&
622 strcmp(ct
, "twoGbMaxExtentFlat")) {
624 "VMDK: Not supported image type \"%s\""".\n", ct
);
628 return vmdk_parse_extents(buf
, bs
, bs
->file
->filename
);
631 static int vmdk_open(BlockDriverState
*bs
, int flags
)
634 BDRVVmdkState
*s
= bs
->opaque
;
636 if (vmdk_open_sparse(bs
, bs
->file
, flags
) == 0) {
637 s
->desc_offset
= 0x200;
639 ret
= vmdk_open_desc_file(bs
, flags
, 0);
644 /* try to open parent images, if exist */
645 ret
= vmdk_parent_open(bs
);
649 s
->parent_cid
= vmdk_read_cid(bs
, 1);
650 qemu_co_mutex_init(&s
->lock
);
654 vmdk_free_extents(bs
);
658 static int get_whole_cluster(BlockDriverState
*bs
,
660 uint64_t cluster_offset
,
664 /* 128 sectors * 512 bytes each = grain size 64KB */
665 uint8_t whole_grain
[extent
->cluster_sectors
* 512];
667 /* we will be here if it's first write on non-exist grain(cluster).
668 * try to read from parent image, if exist */
669 if (bs
->backing_hd
) {
672 if (!vmdk_is_cid_valid(bs
)) {
676 /* floor offset to cluster */
677 offset
-= offset
% (extent
->cluster_sectors
* 512);
678 ret
= bdrv_read(bs
->backing_hd
, offset
>> 9, whole_grain
,
679 extent
->cluster_sectors
);
684 /* Write grain only into the active image */
685 ret
= bdrv_write(extent
->file
, cluster_offset
, whole_grain
,
686 extent
->cluster_sectors
);
694 static int vmdk_L2update(VmdkExtent
*extent
, VmdkMetaData
*m_data
)
696 /* update L2 table */
697 if (bdrv_pwrite_sync(
699 ((int64_t)m_data
->l2_offset
* 512)
700 + (m_data
->l2_index
* sizeof(m_data
->offset
)),
702 sizeof(m_data
->offset
)
706 /* update backup L2 table */
707 if (extent
->l1_backup_table_offset
!= 0) {
708 m_data
->l2_offset
= extent
->l1_backup_table
[m_data
->l1_index
];
709 if (bdrv_pwrite_sync(
711 ((int64_t)m_data
->l2_offset
* 512)
712 + (m_data
->l2_index
* sizeof(m_data
->offset
)),
713 &(m_data
->offset
), sizeof(m_data
->offset
)
722 static int get_cluster_offset(BlockDriverState
*bs
,
724 VmdkMetaData
*m_data
,
727 uint64_t *cluster_offset
)
729 unsigned int l1_index
, l2_offset
, l2_index
;
731 uint32_t min_count
, *l2_table
, tmp
= 0;
737 *cluster_offset
= extent
->flat_start_offset
;
741 offset
-= (extent
->end_sector
- extent
->sectors
) * SECTOR_SIZE
;
742 l1_index
= (offset
>> 9) / extent
->l1_entry_sectors
;
743 if (l1_index
>= extent
->l1_size
) {
746 l2_offset
= extent
->l1_table
[l1_index
];
750 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
751 if (l2_offset
== extent
->l2_cache_offsets
[i
]) {
752 /* increment the hit count */
753 if (++extent
->l2_cache_counts
[i
] == 0xffffffff) {
754 for (j
= 0; j
< L2_CACHE_SIZE
; j
++) {
755 extent
->l2_cache_counts
[j
] >>= 1;
758 l2_table
= extent
->l2_cache
+ (i
* extent
->l2_size
);
762 /* not found: load a new entry in the least used one */
764 min_count
= 0xffffffff;
765 for (i
= 0; i
< L2_CACHE_SIZE
; i
++) {
766 if (extent
->l2_cache_counts
[i
] < min_count
) {
767 min_count
= extent
->l2_cache_counts
[i
];
771 l2_table
= extent
->l2_cache
+ (min_index
* extent
->l2_size
);
774 (int64_t)l2_offset
* 512,
776 extent
->l2_size
* sizeof(uint32_t)
777 ) != extent
->l2_size
* sizeof(uint32_t)) {
781 extent
->l2_cache_offsets
[min_index
] = l2_offset
;
782 extent
->l2_cache_counts
[min_index
] = 1;
784 l2_index
= ((offset
>> 9) / extent
->cluster_sectors
) % extent
->l2_size
;
785 *cluster_offset
= le32_to_cpu(l2_table
[l2_index
]);
787 if (!*cluster_offset
) {
792 /* Avoid the L2 tables update for the images that have snapshots. */
793 *cluster_offset
= bdrv_getlength(extent
->file
);
794 if (!extent
->compressed
) {
797 *cluster_offset
+ (extent
->cluster_sectors
<< 9)
801 *cluster_offset
>>= 9;
802 tmp
= cpu_to_le32(*cluster_offset
);
803 l2_table
[l2_index
] = tmp
;
805 /* First of all we write grain itself, to avoid race condition
806 * that may to corrupt the image.
807 * This problem may occur because of insufficient space on host disk
808 * or inappropriate VM shutdown.
810 if (get_whole_cluster(
811 bs
, extent
, *cluster_offset
, offset
, allocate
) == -1) {
816 m_data
->offset
= tmp
;
817 m_data
->l1_index
= l1_index
;
818 m_data
->l2_index
= l2_index
;
819 m_data
->l2_offset
= l2_offset
;
823 *cluster_offset
<<= 9;
827 static VmdkExtent
*find_extent(BDRVVmdkState
*s
,
828 int64_t sector_num
, VmdkExtent
*start_hint
)
830 VmdkExtent
*extent
= start_hint
;
833 extent
= &s
->extents
[0];
835 while (extent
< &s
->extents
[s
->num_extents
]) {
836 if (sector_num
< extent
->end_sector
) {
844 static int vmdk_is_allocated(BlockDriverState
*bs
, int64_t sector_num
,
845 int nb_sectors
, int *pnum
)
847 BDRVVmdkState
*s
= bs
->opaque
;
848 int64_t index_in_cluster
, n
, ret
;
852 extent
= find_extent(s
, sector_num
, NULL
);
856 ret
= get_cluster_offset(bs
, extent
, NULL
,
857 sector_num
* 512, 0, &offset
);
858 /* get_cluster_offset returning 0 means success */
861 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
862 n
= extent
->cluster_sectors
- index_in_cluster
;
863 if (n
> nb_sectors
) {
870 static int vmdk_write_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
871 int64_t offset_in_cluster
, const uint8_t *buf
,
872 int nb_sectors
, int64_t sector_num
)
875 VmdkGrainMarker
*data
= NULL
;
877 const uint8_t *write_buf
= buf
;
878 int write_len
= nb_sectors
* 512;
880 if (extent
->compressed
) {
881 if (!extent
->has_marker
) {
885 buf_len
= (extent
->cluster_sectors
<< 9) * 2;
886 data
= g_malloc(buf_len
+ sizeof(VmdkGrainMarker
));
887 if (compress(data
->data
, &buf_len
, buf
, nb_sectors
<< 9) != Z_OK
||
892 data
->lba
= sector_num
;
893 data
->size
= buf_len
;
894 write_buf
= (uint8_t *)data
;
895 write_len
= buf_len
+ sizeof(VmdkGrainMarker
);
897 ret
= bdrv_pwrite(extent
->file
,
898 cluster_offset
+ offset_in_cluster
,
901 if (ret
!= write_len
) {
902 ret
= ret
< 0 ? ret
: -EIO
;
911 static int vmdk_read_extent(VmdkExtent
*extent
, int64_t cluster_offset
,
912 int64_t offset_in_cluster
, uint8_t *buf
,
916 int cluster_bytes
, buf_bytes
;
917 uint8_t *cluster_buf
, *compressed_data
;
920 VmdkGrainMarker
*marker
;
924 if (!extent
->compressed
) {
925 ret
= bdrv_pread(extent
->file
,
926 cluster_offset
+ offset_in_cluster
,
927 buf
, nb_sectors
* 512);
928 if (ret
== nb_sectors
* 512) {
934 cluster_bytes
= extent
->cluster_sectors
* 512;
935 /* Read two clusters in case GrainMarker + compressed data > one cluster */
936 buf_bytes
= cluster_bytes
* 2;
937 cluster_buf
= g_malloc(buf_bytes
);
938 uncomp_buf
= g_malloc(cluster_bytes
);
939 ret
= bdrv_pread(extent
->file
,
941 cluster_buf
, buf_bytes
);
945 compressed_data
= cluster_buf
;
946 buf_len
= cluster_bytes
;
947 data_len
= cluster_bytes
;
948 if (extent
->has_marker
) {
949 marker
= (VmdkGrainMarker
*)cluster_buf
;
950 compressed_data
= marker
->data
;
951 data_len
= le32_to_cpu(marker
->size
);
953 if (!data_len
|| data_len
> buf_bytes
) {
957 ret
= uncompress(uncomp_buf
, &buf_len
, compressed_data
, data_len
);
963 if (offset_in_cluster
< 0 ||
964 offset_in_cluster
+ nb_sectors
* 512 > buf_len
) {
968 memcpy(buf
, uncomp_buf
+ offset_in_cluster
, nb_sectors
* 512);
977 static int vmdk_read(BlockDriverState
*bs
, int64_t sector_num
,
978 uint8_t *buf
, int nb_sectors
)
980 BDRVVmdkState
*s
= bs
->opaque
;
982 uint64_t n
, index_in_cluster
;
983 VmdkExtent
*extent
= NULL
;
984 uint64_t cluster_offset
;
986 while (nb_sectors
> 0) {
987 extent
= find_extent(s
, sector_num
, extent
);
991 ret
= get_cluster_offset(
993 sector_num
<< 9, 0, &cluster_offset
);
994 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
995 n
= extent
->cluster_sectors
- index_in_cluster
;
996 if (n
> nb_sectors
) {
1000 /* if not allocated, try to read from parent image, if exist */
1001 if (bs
->backing_hd
) {
1002 if (!vmdk_is_cid_valid(bs
)) {
1005 ret
= bdrv_read(bs
->backing_hd
, sector_num
, buf
, n
);
1010 memset(buf
, 0, 512 * n
);
1013 ret
= vmdk_read_extent(extent
,
1014 cluster_offset
, index_in_cluster
* 512,
1027 static coroutine_fn
int vmdk_co_read(BlockDriverState
*bs
, int64_t sector_num
,
1028 uint8_t *buf
, int nb_sectors
)
1031 BDRVVmdkState
*s
= bs
->opaque
;
1032 qemu_co_mutex_lock(&s
->lock
);
1033 ret
= vmdk_read(bs
, sector_num
, buf
, nb_sectors
);
1034 qemu_co_mutex_unlock(&s
->lock
);
1038 static int vmdk_write(BlockDriverState
*bs
, int64_t sector_num
,
1039 const uint8_t *buf
, int nb_sectors
)
1041 BDRVVmdkState
*s
= bs
->opaque
;
1042 VmdkExtent
*extent
= NULL
;
1044 int64_t index_in_cluster
;
1045 uint64_t cluster_offset
;
1046 VmdkMetaData m_data
;
1048 if (sector_num
> bs
->total_sectors
) {
1050 "(VMDK) Wrong offset: sector_num=0x%" PRIx64
1051 " total_sectors=0x%" PRIx64
"\n",
1052 sector_num
, bs
->total_sectors
);
1056 while (nb_sectors
> 0) {
1057 extent
= find_extent(s
, sector_num
, extent
);
1061 ret
= get_cluster_offset(
1065 sector_num
<< 9, !extent
->compressed
,
1067 if (extent
->compressed
) {
1069 /* Refuse write to allocated cluster for streamOptimized */
1071 "VMDK: can't write to allocated cluster"
1072 " for streamOptimized\n");
1076 ret
= get_cluster_offset(
1087 index_in_cluster
= sector_num
% extent
->cluster_sectors
;
1088 n
= extent
->cluster_sectors
- index_in_cluster
;
1089 if (n
> nb_sectors
) {
1093 ret
= vmdk_write_extent(extent
,
1094 cluster_offset
, index_in_cluster
* 512,
1095 buf
, n
, sector_num
);
1100 /* update L2 tables */
1101 if (vmdk_L2update(extent
, &m_data
) == -1) {
1109 /* update CID on the first write every time the virtual disk is
1111 if (!s
->cid_updated
) {
1112 vmdk_write_cid(bs
, time(NULL
));
1113 s
->cid_updated
= true;
1119 static coroutine_fn
int vmdk_co_write(BlockDriverState
*bs
, int64_t sector_num
,
1120 const uint8_t *buf
, int nb_sectors
)
1123 BDRVVmdkState
*s
= bs
->opaque
;
1124 qemu_co_mutex_lock(&s
->lock
);
1125 ret
= vmdk_write(bs
, sector_num
, buf
, nb_sectors
);
1126 qemu_co_mutex_unlock(&s
->lock
);
1131 static int vmdk_create_extent(const char *filename
, int64_t filesize
,
1132 bool flat
, bool compress
)
1137 uint32_t tmp
, magic
, grains
, gd_size
, gt_size
, gt_count
;
1141 O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
| O_LARGEFILE
,
1147 ret
= ftruncate(fd
, filesize
);
1153 magic
= cpu_to_be32(VMDK4_MAGIC
);
1154 memset(&header
, 0, sizeof(header
));
1157 3 | (compress
? VMDK4_FLAG_COMPRESS
| VMDK4_FLAG_MARKER
: 0);
1158 header
.compressAlgorithm
= compress
? VMDK4_COMPRESSION_DEFLATE
: 0;
1159 header
.capacity
= filesize
/ 512;
1160 header
.granularity
= 128;
1161 header
.num_gtes_per_gte
= 512;
1163 grains
= (filesize
/ 512 + header
.granularity
- 1) / header
.granularity
;
1164 gt_size
= ((header
.num_gtes_per_gte
* sizeof(uint32_t)) + 511) >> 9;
1166 (grains
+ header
.num_gtes_per_gte
- 1) / header
.num_gtes_per_gte
;
1167 gd_size
= (gt_count
* sizeof(uint32_t) + 511) >> 9;
1169 header
.desc_offset
= 1;
1170 header
.desc_size
= 20;
1171 header
.rgd_offset
= header
.desc_offset
+ header
.desc_size
;
1172 header
.gd_offset
= header
.rgd_offset
+ gd_size
+ (gt_size
* gt_count
);
1173 header
.grain_offset
=
1174 ((header
.gd_offset
+ gd_size
+ (gt_size
* gt_count
) +
1175 header
.granularity
- 1) / header
.granularity
) *
1177 /* swap endianness for all header fields */
1178 header
.version
= cpu_to_le32(header
.version
);
1179 header
.flags
= cpu_to_le32(header
.flags
);
1180 header
.capacity
= cpu_to_le64(header
.capacity
);
1181 header
.granularity
= cpu_to_le64(header
.granularity
);
1182 header
.num_gtes_per_gte
= cpu_to_le32(header
.num_gtes_per_gte
);
1183 header
.desc_offset
= cpu_to_le64(header
.desc_offset
);
1184 header
.desc_size
= cpu_to_le64(header
.desc_size
);
1185 header
.rgd_offset
= cpu_to_le64(header
.rgd_offset
);
1186 header
.gd_offset
= cpu_to_le64(header
.gd_offset
);
1187 header
.grain_offset
= cpu_to_le64(header
.grain_offset
);
1188 header
.compressAlgorithm
= cpu_to_le16(header
.compressAlgorithm
);
1190 header
.check_bytes
[0] = 0xa;
1191 header
.check_bytes
[1] = 0x20;
1192 header
.check_bytes
[2] = 0xd;
1193 header
.check_bytes
[3] = 0xa;
1195 /* write all the data */
1196 ret
= qemu_write_full(fd
, &magic
, sizeof(magic
));
1197 if (ret
!= sizeof(magic
)) {
1201 ret
= qemu_write_full(fd
, &header
, sizeof(header
));
1202 if (ret
!= sizeof(header
)) {
1207 ret
= ftruncate(fd
, le64_to_cpu(header
.grain_offset
) << 9);
1213 /* write grain directory */
1214 lseek(fd
, le64_to_cpu(header
.rgd_offset
) << 9, SEEK_SET
);
1215 for (i
= 0, tmp
= le64_to_cpu(header
.rgd_offset
) + gd_size
;
1216 i
< gt_count
; i
++, tmp
+= gt_size
) {
1217 ret
= qemu_write_full(fd
, &tmp
, sizeof(tmp
));
1218 if (ret
!= sizeof(tmp
)) {
1224 /* write backup grain directory */
1225 lseek(fd
, le64_to_cpu(header
.gd_offset
) << 9, SEEK_SET
);
1226 for (i
= 0, tmp
= le64_to_cpu(header
.gd_offset
) + gd_size
;
1227 i
< gt_count
; i
++, tmp
+= gt_size
) {
1228 ret
= qemu_write_full(fd
, &tmp
, sizeof(tmp
));
1229 if (ret
!= sizeof(tmp
)) {
1241 static int filename_decompose(const char *filename
, char *path
, char *prefix
,
1242 char *postfix
, size_t buf_len
)
1246 if (filename
== NULL
|| !strlen(filename
)) {
1247 fprintf(stderr
, "Vmdk: no filename provided.\n");
1250 p
= strrchr(filename
, '/');
1252 p
= strrchr(filename
, '\\');
1255 p
= strrchr(filename
, ':');
1259 if (p
- filename
>= buf_len
) {
1262 pstrcpy(path
, p
- filename
+ 1, filename
);
1267 q
= strrchr(p
, '.');
1269 pstrcpy(prefix
, buf_len
, p
);
1272 if (q
- p
>= buf_len
) {
1275 pstrcpy(prefix
, q
- p
+ 1, p
);
1276 pstrcpy(postfix
, buf_len
, q
);
1281 static int relative_path(char *dest
, int dest_size
,
1282 const char *base
, const char *target
)
1288 const char *sep
= "\\";
1290 const char *sep
= "/";
1293 if (!(dest
&& base
&& target
)) {
1296 if (path_is_absolute(target
)) {
1297 dest
[dest_size
- 1] = '\0';
1298 strncpy(dest
, target
, dest_size
- 1);
1301 while (base
[i
] == target
[i
]) {
1314 pstrcat(dest
, dest_size
, "..");
1315 pstrcat(dest
, dest_size
, sep
);
1317 pstrcat(dest
, dest_size
, q
);
1321 static int vmdk_create(const char *filename
, QEMUOptionParameter
*options
)
1324 char desc
[BUF_SIZE
];
1325 int64_t total_size
= 0, filesize
;
1326 const char *backing_file
= NULL
;
1327 const char *fmt
= NULL
;
1330 bool flat
, split
, compress
;
1331 char ext_desc_lines
[BUF_SIZE
] = "";
1332 char path
[PATH_MAX
], prefix
[PATH_MAX
], postfix
[PATH_MAX
];
1333 const int64_t split_size
= 0x80000000; /* VMDK has constant split size */
1334 const char *desc_extent_line
;
1335 char parent_desc_line
[BUF_SIZE
] = "";
1336 uint32_t parent_cid
= 0xffffffff;
1337 const char desc_template
[] =
1338 "# Disk DescriptorFile\n"
1342 "createType=\"%s\"\n"
1345 "# Extent description\n"
1348 "# The Disk Data Base\n"
1351 "ddb.virtualHWVersion = \"%d\"\n"
1352 "ddb.geometry.cylinders = \"%" PRId64
"\"\n"
1353 "ddb.geometry.heads = \"16\"\n"
1354 "ddb.geometry.sectors = \"63\"\n"
1355 "ddb.adapterType = \"ide\"\n";
1357 if (filename_decompose(filename
, path
, prefix
, postfix
, PATH_MAX
)) {
1360 /* Read out options */
1361 while (options
&& options
->name
) {
1362 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1363 total_size
= options
->value
.n
;
1364 } else if (!strcmp(options
->name
, BLOCK_OPT_BACKING_FILE
)) {
1365 backing_file
= options
->value
.s
;
1366 } else if (!strcmp(options
->name
, BLOCK_OPT_COMPAT6
)) {
1367 flags
|= options
->value
.n
? BLOCK_FLAG_COMPAT6
: 0;
1368 } else if (!strcmp(options
->name
, BLOCK_OPT_SUBFMT
)) {
1369 fmt
= options
->value
.s
;
1374 /* Default format to monolithicSparse */
1375 fmt
= "monolithicSparse";
1376 } else if (strcmp(fmt
, "monolithicFlat") &&
1377 strcmp(fmt
, "monolithicSparse") &&
1378 strcmp(fmt
, "twoGbMaxExtentSparse") &&
1379 strcmp(fmt
, "twoGbMaxExtentFlat") &&
1380 strcmp(fmt
, "streamOptimized")) {
1381 fprintf(stderr
, "VMDK: Unknown subformat: %s\n", fmt
);
1384 split
= !(strcmp(fmt
, "twoGbMaxExtentFlat") &&
1385 strcmp(fmt
, "twoGbMaxExtentSparse"));
1386 flat
= !(strcmp(fmt
, "monolithicFlat") &&
1387 strcmp(fmt
, "twoGbMaxExtentFlat"));
1388 compress
= !strcmp(fmt
, "streamOptimized");
1390 desc_extent_line
= "RW %lld FLAT \"%s\" 0\n";
1392 desc_extent_line
= "RW %lld SPARSE \"%s\"\n";
1394 if (flat
&& backing_file
) {
1395 /* not supporting backing file for flat image */
1399 char parent_filename
[PATH_MAX
];
1400 BlockDriverState
*bs
= bdrv_new("");
1401 ret
= bdrv_open(bs
, backing_file
, 0, NULL
);
1406 if (strcmp(bs
->drv
->format_name
, "vmdk")) {
1410 filesize
= bdrv_getlength(bs
);
1411 parent_cid
= vmdk_read_cid(bs
, 0);
1413 relative_path(parent_filename
, sizeof(parent_filename
),
1414 filename
, backing_file
);
1415 snprintf(parent_desc_line
, sizeof(parent_desc_line
),
1416 "parentFileNameHint=\"%s\"", parent_filename
);
1419 /* Create extents */
1420 filesize
= total_size
;
1421 while (filesize
> 0) {
1422 char desc_line
[BUF_SIZE
];
1423 char ext_filename
[PATH_MAX
];
1424 char desc_filename
[PATH_MAX
];
1425 int64_t size
= filesize
;
1427 if (split
&& size
> split_size
) {
1431 snprintf(desc_filename
, sizeof(desc_filename
), "%s-%c%03d%s",
1432 prefix
, flat
? 'f' : 's', ++idx
, postfix
);
1434 snprintf(desc_filename
, sizeof(desc_filename
), "%s-flat%s",
1437 snprintf(desc_filename
, sizeof(desc_filename
), "%s%s",
1440 snprintf(ext_filename
, sizeof(ext_filename
), "%s%s",
1441 path
, desc_filename
);
1443 if (vmdk_create_extent(ext_filename
, size
, flat
, compress
)) {
1448 /* Format description line */
1449 snprintf(desc_line
, sizeof(desc_line
),
1450 desc_extent_line
, size
/ 512, desc_filename
);
1451 pstrcat(ext_desc_lines
, sizeof(ext_desc_lines
), desc_line
);
1453 /* generate descriptor file */
1454 snprintf(desc
, sizeof(desc
), desc_template
,
1455 (unsigned int)time(NULL
),
1460 (flags
& BLOCK_FLAG_COMPAT6
? 6 : 4),
1461 total_size
/ (int64_t)(63 * 16 * 512));
1462 if (split
|| flat
) {
1465 O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
| O_LARGEFILE
,
1470 O_WRONLY
| O_BINARY
| O_LARGEFILE
,
1476 /* the descriptor offset = 0x200 */
1477 if (!split
&& !flat
&& 0x200 != lseek(fd
, 0x200, SEEK_SET
)) {
1481 ret
= qemu_write_full(fd
, desc
, strlen(desc
));
1482 if (ret
!= strlen(desc
)) {
1492 static void vmdk_close(BlockDriverState
*bs
)
1494 vmdk_free_extents(bs
);
1497 static coroutine_fn
int vmdk_co_flush(BlockDriverState
*bs
)
1500 BDRVVmdkState
*s
= bs
->opaque
;
1502 ret
= bdrv_co_flush(bs
->file
);
1503 for (i
= 0; i
< s
->num_extents
; i
++) {
1504 err
= bdrv_co_flush(s
->extents
[i
].file
);
1512 static int64_t vmdk_get_allocated_file_size(BlockDriverState
*bs
)
1517 BDRVVmdkState
*s
= bs
->opaque
;
1519 ret
= bdrv_get_allocated_file_size(bs
->file
);
1523 for (i
= 0; i
< s
->num_extents
; i
++) {
1524 if (s
->extents
[i
].file
== bs
->file
) {
1527 r
= bdrv_get_allocated_file_size(s
->extents
[i
].file
);
1536 static QEMUOptionParameter vmdk_create_options
[] = {
1538 .name
= BLOCK_OPT_SIZE
,
1540 .help
= "Virtual disk size"
1543 .name
= BLOCK_OPT_BACKING_FILE
,
1545 .help
= "File name of a base image"
1548 .name
= BLOCK_OPT_COMPAT6
,
1550 .help
= "VMDK version 6 image"
1553 .name
= BLOCK_OPT_SUBFMT
,
1556 "VMDK flat extent format, can be one of "
1557 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
1562 static BlockDriver bdrv_vmdk
= {
1563 .format_name
= "vmdk",
1564 .instance_size
= sizeof(BDRVVmdkState
),
1565 .bdrv_probe
= vmdk_probe
,
1566 .bdrv_open
= vmdk_open
,
1567 .bdrv_read
= vmdk_co_read
,
1568 .bdrv_write
= vmdk_co_write
,
1569 .bdrv_close
= vmdk_close
,
1570 .bdrv_create
= vmdk_create
,
1571 .bdrv_co_flush
= vmdk_co_flush
,
1572 .bdrv_is_allocated
= vmdk_is_allocated
,
1573 .bdrv_get_allocated_file_size
= vmdk_get_allocated_file_size
,
1575 .create_options
= vmdk_create_options
,
1578 static void bdrv_vmdk_init(void)
1580 bdrv_register(&bdrv_vmdk
);
1583 block_init(bdrv_vmdk_init
);