qcow2.py: Add required padding for header extensions
[qemu/cris-port.git] / block / vmdk.c
blob2cbfd3e72e8547a33c831281db0188564bc2c491
1 /*
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
23 * THE SOFTWARE.
26 #include "qemu-common.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "migration/migration.h"
30 #include <zlib.h>
32 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
33 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
34 #define VMDK4_COMPRESSION_DEFLATE 1
35 #define VMDK4_FLAG_NL_DETECT (1 << 0)
36 #define VMDK4_FLAG_RGD (1 << 1)
37 /* Zeroed-grain enable bit */
38 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
39 #define VMDK4_FLAG_COMPRESS (1 << 16)
40 #define VMDK4_FLAG_MARKER (1 << 17)
41 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
43 #define VMDK_GTE_ZEROED 0x1
45 /* VMDK internal error codes */
46 #define VMDK_OK 0
47 #define VMDK_ERROR (-1)
48 /* Cluster not allocated */
49 #define VMDK_UNALLOC (-2)
50 #define VMDK_ZEROED (-3)
52 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
54 typedef struct {
55 uint32_t version;
56 uint32_t flags;
57 uint32_t disk_sectors;
58 uint32_t granularity;
59 uint32_t l1dir_offset;
60 uint32_t l1dir_size;
61 uint32_t file_sectors;
62 uint32_t cylinders;
63 uint32_t heads;
64 uint32_t sectors_per_track;
65 } QEMU_PACKED VMDK3Header;
67 typedef struct {
68 uint32_t version;
69 uint32_t flags;
70 uint64_t capacity;
71 uint64_t granularity;
72 uint64_t desc_offset;
73 uint64_t desc_size;
74 /* Number of GrainTableEntries per GrainTable */
75 uint32_t num_gtes_per_gt;
76 uint64_t rgd_offset;
77 uint64_t gd_offset;
78 uint64_t grain_offset;
79 char filler[1];
80 char check_bytes[4];
81 uint16_t compressAlgorithm;
82 } QEMU_PACKED VMDK4Header;
84 #define L2_CACHE_SIZE 16
86 typedef struct VmdkExtent {
87 BlockDriverState *file;
88 bool flat;
89 bool compressed;
90 bool has_marker;
91 bool has_zero_grain;
92 int version;
93 int64_t sectors;
94 int64_t end_sector;
95 int64_t flat_start_offset;
96 int64_t l1_table_offset;
97 int64_t l1_backup_table_offset;
98 uint32_t *l1_table;
99 uint32_t *l1_backup_table;
100 unsigned int l1_size;
101 uint32_t l1_entry_sectors;
103 unsigned int l2_size;
104 uint32_t *l2_cache;
105 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
106 uint32_t l2_cache_counts[L2_CACHE_SIZE];
108 int64_t cluster_sectors;
109 int64_t next_cluster_sector;
110 char *type;
111 } VmdkExtent;
113 typedef struct BDRVVmdkState {
114 CoMutex lock;
115 uint64_t desc_offset;
116 bool cid_updated;
117 bool cid_checked;
118 uint32_t cid;
119 uint32_t parent_cid;
120 int num_extents;
121 /* Extent array with num_extents entries, ascend ordered by address */
122 VmdkExtent *extents;
123 Error *migration_blocker;
124 char *create_type;
125 } BDRVVmdkState;
127 typedef struct VmdkMetaData {
128 unsigned int l1_index;
129 unsigned int l2_index;
130 unsigned int l2_offset;
131 int valid;
132 uint32_t *l2_cache_entry;
133 } VmdkMetaData;
135 typedef struct VmdkGrainMarker {
136 uint64_t lba;
137 uint32_t size;
138 uint8_t data[0];
139 } QEMU_PACKED VmdkGrainMarker;
141 enum {
142 MARKER_END_OF_STREAM = 0,
143 MARKER_GRAIN_TABLE = 1,
144 MARKER_GRAIN_DIRECTORY = 2,
145 MARKER_FOOTER = 3,
148 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
150 uint32_t magic;
152 if (buf_size < 4) {
153 return 0;
155 magic = be32_to_cpu(*(uint32_t *)buf);
156 if (magic == VMDK3_MAGIC ||
157 magic == VMDK4_MAGIC) {
158 return 100;
159 } else {
160 const char *p = (const char *)buf;
161 const char *end = p + buf_size;
162 while (p < end) {
163 if (*p == '#') {
164 /* skip comment line */
165 while (p < end && *p != '\n') {
166 p++;
168 p++;
169 continue;
171 if (*p == ' ') {
172 while (p < end && *p == ' ') {
173 p++;
175 /* skip '\r' if windows line endings used. */
176 if (p < end && *p == '\r') {
177 p++;
179 /* only accept blank lines before 'version=' line */
180 if (p == end || *p != '\n') {
181 return 0;
183 p++;
184 continue;
186 if (end - p >= strlen("version=X\n")) {
187 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
188 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
189 return 100;
192 if (end - p >= strlen("version=X\r\n")) {
193 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
194 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
195 return 100;
198 return 0;
200 return 0;
204 #define SECTOR_SIZE 512
205 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
206 #define BUF_SIZE 4096
207 #define HEADER_SIZE 512 /* first sector of 512 bytes */
209 static void vmdk_free_extents(BlockDriverState *bs)
211 int i;
212 BDRVVmdkState *s = bs->opaque;
213 VmdkExtent *e;
215 for (i = 0; i < s->num_extents; i++) {
216 e = &s->extents[i];
217 g_free(e->l1_table);
218 g_free(e->l2_cache);
219 g_free(e->l1_backup_table);
220 g_free(e->type);
221 if (e->file != bs->file) {
222 bdrv_unref(e->file);
225 g_free(s->extents);
228 static void vmdk_free_last_extent(BlockDriverState *bs)
230 BDRVVmdkState *s = bs->opaque;
232 if (s->num_extents == 0) {
233 return;
235 s->num_extents--;
236 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
239 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
241 char desc[DESC_SIZE];
242 uint32_t cid = 0xffffffff;
243 const char *p_name, *cid_str;
244 size_t cid_str_size;
245 BDRVVmdkState *s = bs->opaque;
246 int ret;
248 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
249 if (ret < 0) {
250 return 0;
253 if (parent) {
254 cid_str = "parentCID";
255 cid_str_size = sizeof("parentCID");
256 } else {
257 cid_str = "CID";
258 cid_str_size = sizeof("CID");
261 desc[DESC_SIZE - 1] = '\0';
262 p_name = strstr(desc, cid_str);
263 if (p_name != NULL) {
264 p_name += cid_str_size;
265 sscanf(p_name, "%" SCNx32, &cid);
268 return cid;
271 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
273 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
274 char *p_name, *tmp_str;
275 BDRVVmdkState *s = bs->opaque;
276 int ret;
278 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
279 if (ret < 0) {
280 return ret;
283 desc[DESC_SIZE - 1] = '\0';
284 tmp_str = strstr(desc, "parentCID");
285 if (tmp_str == NULL) {
286 return -EINVAL;
289 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
290 p_name = strstr(desc, "CID");
291 if (p_name != NULL) {
292 p_name += sizeof("CID");
293 snprintf(p_name, sizeof(desc) - (p_name - desc), "%" PRIx32 "\n", cid);
294 pstrcat(desc, sizeof(desc), tmp_desc);
297 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
298 if (ret < 0) {
299 return ret;
302 return 0;
305 static int vmdk_is_cid_valid(BlockDriverState *bs)
307 BDRVVmdkState *s = bs->opaque;
308 BlockDriverState *p_bs = bs->backing_hd;
309 uint32_t cur_pcid;
311 if (!s->cid_checked && p_bs) {
312 cur_pcid = vmdk_read_cid(p_bs, 0);
313 if (s->parent_cid != cur_pcid) {
314 /* CID not valid */
315 return 0;
318 s->cid_checked = true;
319 /* CID valid */
320 return 1;
323 /* Queue extents, if any, for reopen() */
324 static int vmdk_reopen_prepare(BDRVReopenState *state,
325 BlockReopenQueue *queue, Error **errp)
327 BDRVVmdkState *s;
328 int ret = -1;
329 int i;
330 VmdkExtent *e;
332 assert(state != NULL);
333 assert(state->bs != NULL);
335 if (queue == NULL) {
336 error_setg(errp, "No reopen queue for VMDK extents");
337 goto exit;
340 s = state->bs->opaque;
342 assert(s != NULL);
344 for (i = 0; i < s->num_extents; i++) {
345 e = &s->extents[i];
346 if (e->file != state->bs->file) {
347 bdrv_reopen_queue(queue, e->file, state->flags);
350 ret = 0;
352 exit:
353 return ret;
356 static int vmdk_parent_open(BlockDriverState *bs)
358 char *p_name;
359 char desc[DESC_SIZE + 1];
360 BDRVVmdkState *s = bs->opaque;
361 int ret;
363 desc[DESC_SIZE] = '\0';
364 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
365 if (ret < 0) {
366 return ret;
369 p_name = strstr(desc, "parentFileNameHint");
370 if (p_name != NULL) {
371 char *end_name;
373 p_name += sizeof("parentFileNameHint") + 1;
374 end_name = strchr(p_name, '\"');
375 if (end_name == NULL) {
376 return -EINVAL;
378 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
379 return -EINVAL;
382 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
385 return 0;
388 /* Create and append extent to the extent array. Return the added VmdkExtent
389 * address. return NULL if allocation failed. */
390 static int vmdk_add_extent(BlockDriverState *bs,
391 BlockDriverState *file, bool flat, int64_t sectors,
392 int64_t l1_offset, int64_t l1_backup_offset,
393 uint32_t l1_size,
394 int l2_size, uint64_t cluster_sectors,
395 VmdkExtent **new_extent,
396 Error **errp)
398 VmdkExtent *extent;
399 BDRVVmdkState *s = bs->opaque;
400 int64_t nb_sectors;
402 if (cluster_sectors > 0x200000) {
403 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
404 error_setg(errp, "Invalid granularity, image may be corrupt");
405 return -EFBIG;
407 if (l1_size > 512 * 1024 * 1024) {
408 /* Although with big capacity and small l1_entry_sectors, we can get a
409 * big l1_size, we don't want unbounded value to allocate the table.
410 * Limit it to 512M, which is 16PB for default cluster and L2 table
411 * size */
412 error_setg(errp, "L1 size too big");
413 return -EFBIG;
416 nb_sectors = bdrv_nb_sectors(file);
417 if (nb_sectors < 0) {
418 return nb_sectors;
421 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
422 extent = &s->extents[s->num_extents];
423 s->num_extents++;
425 memset(extent, 0, sizeof(VmdkExtent));
426 extent->file = file;
427 extent->flat = flat;
428 extent->sectors = sectors;
429 extent->l1_table_offset = l1_offset;
430 extent->l1_backup_table_offset = l1_backup_offset;
431 extent->l1_size = l1_size;
432 extent->l1_entry_sectors = l2_size * cluster_sectors;
433 extent->l2_size = l2_size;
434 extent->cluster_sectors = flat ? sectors : cluster_sectors;
435 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
437 if (s->num_extents > 1) {
438 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
439 } else {
440 extent->end_sector = extent->sectors;
442 bs->total_sectors = extent->end_sector;
443 if (new_extent) {
444 *new_extent = extent;
446 return 0;
449 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
450 Error **errp)
452 int ret;
453 int l1_size, i;
455 /* read the L1 table */
456 l1_size = extent->l1_size * sizeof(uint32_t);
457 extent->l1_table = g_try_malloc(l1_size);
458 if (l1_size && extent->l1_table == NULL) {
459 return -ENOMEM;
462 ret = bdrv_pread(extent->file,
463 extent->l1_table_offset,
464 extent->l1_table,
465 l1_size);
466 if (ret < 0) {
467 error_setg_errno(errp, -ret,
468 "Could not read l1 table from extent '%s'",
469 extent->file->filename);
470 goto fail_l1;
472 for (i = 0; i < extent->l1_size; i++) {
473 le32_to_cpus(&extent->l1_table[i]);
476 if (extent->l1_backup_table_offset) {
477 extent->l1_backup_table = g_try_malloc(l1_size);
478 if (l1_size && extent->l1_backup_table == NULL) {
479 ret = -ENOMEM;
480 goto fail_l1;
482 ret = bdrv_pread(extent->file,
483 extent->l1_backup_table_offset,
484 extent->l1_backup_table,
485 l1_size);
486 if (ret < 0) {
487 error_setg_errno(errp, -ret,
488 "Could not read l1 backup table from extent '%s'",
489 extent->file->filename);
490 goto fail_l1b;
492 for (i = 0; i < extent->l1_size; i++) {
493 le32_to_cpus(&extent->l1_backup_table[i]);
497 extent->l2_cache =
498 g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
499 return 0;
500 fail_l1b:
501 g_free(extent->l1_backup_table);
502 fail_l1:
503 g_free(extent->l1_table);
504 return ret;
507 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
508 BlockDriverState *file,
509 int flags, Error **errp)
511 int ret;
512 uint32_t magic;
513 VMDK3Header header;
514 VmdkExtent *extent;
516 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
517 if (ret < 0) {
518 error_setg_errno(errp, -ret,
519 "Could not read header from file '%s'",
520 file->filename);
521 return ret;
523 ret = vmdk_add_extent(bs, file, false,
524 le32_to_cpu(header.disk_sectors),
525 le32_to_cpu(header.l1dir_offset) << 9,
527 le32_to_cpu(header.l1dir_size),
528 4096,
529 le32_to_cpu(header.granularity),
530 &extent,
531 errp);
532 if (ret < 0) {
533 return ret;
535 ret = vmdk_init_tables(bs, extent, errp);
536 if (ret) {
537 /* free extent allocated by vmdk_add_extent */
538 vmdk_free_last_extent(bs);
540 return ret;
543 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
544 Error **errp);
546 static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset,
547 Error **errp)
549 int64_t size;
550 char *buf;
551 int ret;
553 size = bdrv_getlength(file);
554 if (size < 0) {
555 error_setg_errno(errp, -size, "Could not access file");
556 return NULL;
559 size = MIN(size, 1 << 20); /* avoid unbounded allocation */
560 buf = g_malloc0(size + 1);
562 ret = bdrv_pread(file, desc_offset, buf, size);
563 if (ret < 0) {
564 error_setg_errno(errp, -ret, "Could not read from file");
565 g_free(buf);
566 return NULL;
569 return buf;
572 static int vmdk_open_vmdk4(BlockDriverState *bs,
573 BlockDriverState *file,
574 int flags, Error **errp)
576 int ret;
577 uint32_t magic;
578 uint32_t l1_size, l1_entry_sectors;
579 VMDK4Header header;
580 VmdkExtent *extent;
581 BDRVVmdkState *s = bs->opaque;
582 int64_t l1_backup_offset = 0;
584 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
585 if (ret < 0) {
586 error_setg_errno(errp, -ret,
587 "Could not read header from file '%s'",
588 file->filename);
589 return -EINVAL;
591 if (header.capacity == 0) {
592 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
593 if (desc_offset) {
594 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
595 if (!buf) {
596 return -EINVAL;
598 ret = vmdk_open_desc_file(bs, flags, buf, errp);
599 g_free(buf);
600 return ret;
604 if (!s->create_type) {
605 s->create_type = g_strdup("monolithicSparse");
608 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
610 * The footer takes precedence over the header, so read it in. The
611 * footer starts at offset -1024 from the end: One sector for the
612 * footer, and another one for the end-of-stream marker.
614 struct {
615 struct {
616 uint64_t val;
617 uint32_t size;
618 uint32_t type;
619 uint8_t pad[512 - 16];
620 } QEMU_PACKED footer_marker;
622 uint32_t magic;
623 VMDK4Header header;
624 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
626 struct {
627 uint64_t val;
628 uint32_t size;
629 uint32_t type;
630 uint8_t pad[512 - 16];
631 } QEMU_PACKED eos_marker;
632 } QEMU_PACKED footer;
634 ret = bdrv_pread(file,
635 bs->file->total_sectors * 512 - 1536,
636 &footer, sizeof(footer));
637 if (ret < 0) {
638 return ret;
641 /* Some sanity checks for the footer */
642 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
643 le32_to_cpu(footer.footer_marker.size) != 0 ||
644 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
645 le64_to_cpu(footer.eos_marker.val) != 0 ||
646 le32_to_cpu(footer.eos_marker.size) != 0 ||
647 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
649 return -EINVAL;
652 header = footer.header;
655 if (le32_to_cpu(header.version) > 3) {
656 char buf[64];
657 snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
658 le32_to_cpu(header.version));
659 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
660 bdrv_get_device_name(bs), "vmdk", buf);
661 return -ENOTSUP;
662 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
663 /* VMware KB 2064959 explains that version 3 added support for
664 * persistent changed block tracking (CBT), and backup software can
665 * read it as version=1 if it doesn't care about the changed area
666 * information. So we are safe to enable read only. */
667 error_setg(errp, "VMDK version 3 must be read only");
668 return -EINVAL;
671 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
672 error_setg(errp, "L2 table size too big");
673 return -EINVAL;
676 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
677 * le64_to_cpu(header.granularity);
678 if (l1_entry_sectors == 0) {
679 return -EINVAL;
681 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
682 / l1_entry_sectors;
683 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
684 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
686 if (bdrv_nb_sectors(file) < le64_to_cpu(header.grain_offset)) {
687 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
688 (int64_t)(le64_to_cpu(header.grain_offset)
689 * BDRV_SECTOR_SIZE));
690 return -EINVAL;
693 ret = vmdk_add_extent(bs, file, false,
694 le64_to_cpu(header.capacity),
695 le64_to_cpu(header.gd_offset) << 9,
696 l1_backup_offset,
697 l1_size,
698 le32_to_cpu(header.num_gtes_per_gt),
699 le64_to_cpu(header.granularity),
700 &extent,
701 errp);
702 if (ret < 0) {
703 return ret;
705 extent->compressed =
706 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
707 if (extent->compressed) {
708 g_free(s->create_type);
709 s->create_type = g_strdup("streamOptimized");
711 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
712 extent->version = le32_to_cpu(header.version);
713 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
714 ret = vmdk_init_tables(bs, extent, errp);
715 if (ret) {
716 /* free extent allocated by vmdk_add_extent */
717 vmdk_free_last_extent(bs);
719 return ret;
722 /* find an option value out of descriptor file */
723 static int vmdk_parse_description(const char *desc, const char *opt_name,
724 char *buf, int buf_size)
726 char *opt_pos, *opt_end;
727 const char *end = desc + strlen(desc);
729 opt_pos = strstr(desc, opt_name);
730 if (!opt_pos) {
731 return VMDK_ERROR;
733 /* Skip "=\"" following opt_name */
734 opt_pos += strlen(opt_name) + 2;
735 if (opt_pos >= end) {
736 return VMDK_ERROR;
738 opt_end = opt_pos;
739 while (opt_end < end && *opt_end != '"') {
740 opt_end++;
742 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
743 return VMDK_ERROR;
745 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
746 return VMDK_OK;
749 /* Open an extent file and append to bs array */
750 static int vmdk_open_sparse(BlockDriverState *bs,
751 BlockDriverState *file, int flags,
752 char *buf, Error **errp)
754 uint32_t magic;
756 magic = ldl_be_p(buf);
757 switch (magic) {
758 case VMDK3_MAGIC:
759 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
760 break;
761 case VMDK4_MAGIC:
762 return vmdk_open_vmdk4(bs, file, flags, errp);
763 break;
764 default:
765 error_setg(errp, "Image not in VMDK format");
766 return -EINVAL;
767 break;
771 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
772 const char *desc_file_path, Error **errp)
774 int ret;
775 char access[11];
776 char type[11];
777 char fname[512];
778 const char *p = desc;
779 int64_t sectors = 0;
780 int64_t flat_offset;
781 char extent_path[PATH_MAX];
782 BlockDriverState *extent_file;
783 BDRVVmdkState *s = bs->opaque;
784 VmdkExtent *extent;
786 while (*p) {
787 /* parse extent line:
788 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
789 * or
790 * RW [size in sectors] SPARSE "file-name.vmdk"
792 flat_offset = -1;
793 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
794 access, &sectors, type, fname, &flat_offset);
795 if (ret < 4 || strcmp(access, "RW")) {
796 goto next_line;
797 } else if (!strcmp(type, "FLAT")) {
798 if (ret != 5 || flat_offset < 0) {
799 error_setg(errp, "Invalid extent lines: \n%s", p);
800 return -EINVAL;
802 } else if (!strcmp(type, "VMFS")) {
803 if (ret == 4) {
804 flat_offset = 0;
805 } else {
806 error_setg(errp, "Invalid extent lines:\n%s", p);
807 return -EINVAL;
809 } else if (ret != 4) {
810 error_setg(errp, "Invalid extent lines:\n%s", p);
811 return -EINVAL;
814 if (sectors <= 0 ||
815 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
816 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
817 (strcmp(access, "RW"))) {
818 goto next_line;
821 path_combine(extent_path, sizeof(extent_path),
822 desc_file_path, fname);
823 extent_file = NULL;
824 ret = bdrv_open(&extent_file, extent_path, NULL, NULL,
825 bs->open_flags | BDRV_O_PROTOCOL, NULL, errp);
826 if (ret) {
827 return ret;
830 /* save to extents array */
831 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
832 /* FLAT extent */
834 ret = vmdk_add_extent(bs, extent_file, true, sectors,
835 0, 0, 0, 0, 0, &extent, errp);
836 if (ret < 0) {
837 bdrv_unref(extent_file);
838 return ret;
840 extent->flat_start_offset = flat_offset << 9;
841 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
842 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
843 char *buf = vmdk_read_desc(extent_file, 0, errp);
844 if (!buf) {
845 ret = -EINVAL;
846 } else {
847 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf, errp);
849 g_free(buf);
850 if (ret) {
851 bdrv_unref(extent_file);
852 return ret;
854 extent = &s->extents[s->num_extents - 1];
855 } else {
856 error_setg(errp, "Unsupported extent type '%s'", type);
857 bdrv_unref(extent_file);
858 return -ENOTSUP;
860 extent->type = g_strdup(type);
861 next_line:
862 /* move to next line */
863 while (*p) {
864 if (*p == '\n') {
865 p++;
866 break;
868 p++;
871 return 0;
874 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
875 Error **errp)
877 int ret;
878 char ct[128];
879 BDRVVmdkState *s = bs->opaque;
881 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
882 error_setg(errp, "invalid VMDK image descriptor");
883 ret = -EINVAL;
884 goto exit;
886 if (strcmp(ct, "monolithicFlat") &&
887 strcmp(ct, "vmfs") &&
888 strcmp(ct, "vmfsSparse") &&
889 strcmp(ct, "twoGbMaxExtentSparse") &&
890 strcmp(ct, "twoGbMaxExtentFlat")) {
891 error_setg(errp, "Unsupported image type '%s'", ct);
892 ret = -ENOTSUP;
893 goto exit;
895 s->create_type = g_strdup(ct);
896 s->desc_offset = 0;
897 ret = vmdk_parse_extents(buf, bs, bs->file->filename, errp);
898 exit:
899 return ret;
902 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
903 Error **errp)
905 char *buf = NULL;
906 int ret;
907 BDRVVmdkState *s = bs->opaque;
908 uint32_t magic;
910 buf = vmdk_read_desc(bs->file, 0, errp);
911 if (!buf) {
912 return -EINVAL;
915 magic = ldl_be_p(buf);
916 switch (magic) {
917 case VMDK3_MAGIC:
918 case VMDK4_MAGIC:
919 ret = vmdk_open_sparse(bs, bs->file, flags, buf, errp);
920 s->desc_offset = 0x200;
921 break;
922 default:
923 ret = vmdk_open_desc_file(bs, flags, buf, errp);
924 break;
926 if (ret) {
927 goto fail;
930 /* try to open parent images, if exist */
931 ret = vmdk_parent_open(bs);
932 if (ret) {
933 goto fail;
935 s->cid = vmdk_read_cid(bs, 0);
936 s->parent_cid = vmdk_read_cid(bs, 1);
937 qemu_co_mutex_init(&s->lock);
939 /* Disable migration when VMDK images are used */
940 error_set(&s->migration_blocker,
941 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
942 "vmdk", bdrv_get_device_name(bs), "live migration");
943 migrate_add_blocker(s->migration_blocker);
944 g_free(buf);
945 return 0;
947 fail:
948 g_free(buf);
949 g_free(s->create_type);
950 s->create_type = NULL;
951 vmdk_free_extents(bs);
952 return ret;
956 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
958 BDRVVmdkState *s = bs->opaque;
959 int i;
961 for (i = 0; i < s->num_extents; i++) {
962 if (!s->extents[i].flat) {
963 bs->bl.write_zeroes_alignment =
964 MAX(bs->bl.write_zeroes_alignment,
965 s->extents[i].cluster_sectors);
971 * get_whole_cluster
973 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
974 * to the cluster at @cluster_sector_num.
976 * If @skip_start_sector < @skip_end_sector, the relative range
977 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
978 * it for call to write user data in the request.
980 static int get_whole_cluster(BlockDriverState *bs,
981 VmdkExtent *extent,
982 uint64_t cluster_sector_num,
983 uint64_t sector_num,
984 uint64_t skip_start_sector,
985 uint64_t skip_end_sector)
987 int ret = VMDK_OK;
988 int64_t cluster_bytes;
989 uint8_t *whole_grain;
991 /* For COW, align request sector_num to cluster start */
992 sector_num = QEMU_ALIGN_DOWN(sector_num, extent->cluster_sectors);
993 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
994 whole_grain = qemu_blockalign(bs, cluster_bytes);
996 if (!bs->backing_hd) {
997 memset(whole_grain, 0, skip_start_sector << BDRV_SECTOR_BITS);
998 memset(whole_grain + (skip_end_sector << BDRV_SECTOR_BITS), 0,
999 cluster_bytes - (skip_end_sector << BDRV_SECTOR_BITS));
1002 assert(skip_end_sector <= extent->cluster_sectors);
1003 /* we will be here if it's first write on non-exist grain(cluster).
1004 * try to read from parent image, if exist */
1005 if (bs->backing_hd && !vmdk_is_cid_valid(bs)) {
1006 ret = VMDK_ERROR;
1007 goto exit;
1010 /* Read backing data before skip range */
1011 if (skip_start_sector > 0) {
1012 if (bs->backing_hd) {
1013 ret = bdrv_read(bs->backing_hd, sector_num,
1014 whole_grain, skip_start_sector);
1015 if (ret < 0) {
1016 ret = VMDK_ERROR;
1017 goto exit;
1020 ret = bdrv_write(extent->file, cluster_sector_num, whole_grain,
1021 skip_start_sector);
1022 if (ret < 0) {
1023 ret = VMDK_ERROR;
1024 goto exit;
1027 /* Read backing data after skip range */
1028 if (skip_end_sector < extent->cluster_sectors) {
1029 if (bs->backing_hd) {
1030 ret = bdrv_read(bs->backing_hd, sector_num + skip_end_sector,
1031 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1032 extent->cluster_sectors - skip_end_sector);
1033 if (ret < 0) {
1034 ret = VMDK_ERROR;
1035 goto exit;
1038 ret = bdrv_write(extent->file, cluster_sector_num + skip_end_sector,
1039 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1040 extent->cluster_sectors - skip_end_sector);
1041 if (ret < 0) {
1042 ret = VMDK_ERROR;
1043 goto exit;
1047 exit:
1048 qemu_vfree(whole_grain);
1049 return ret;
1052 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1053 uint32_t offset)
1055 offset = cpu_to_le32(offset);
1056 /* update L2 table */
1057 if (bdrv_pwrite_sync(
1058 extent->file,
1059 ((int64_t)m_data->l2_offset * 512)
1060 + (m_data->l2_index * sizeof(offset)),
1061 &offset, sizeof(offset)) < 0) {
1062 return VMDK_ERROR;
1064 /* update backup L2 table */
1065 if (extent->l1_backup_table_offset != 0) {
1066 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1067 if (bdrv_pwrite_sync(
1068 extent->file,
1069 ((int64_t)m_data->l2_offset * 512)
1070 + (m_data->l2_index * sizeof(offset)),
1071 &offset, sizeof(offset)) < 0) {
1072 return VMDK_ERROR;
1075 if (m_data->l2_cache_entry) {
1076 *m_data->l2_cache_entry = offset;
1079 return VMDK_OK;
1083 * get_cluster_offset
1085 * Look up cluster offset in extent file by sector number, and store in
1086 * @cluster_offset.
1088 * For flat extents, the start offset as parsed from the description file is
1089 * returned.
1091 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1092 * offset for a new cluster and update L2 cache. If there is a backing file,
1093 * COW is done before returning; otherwise, zeroes are written to the allocated
1094 * cluster. Both COW and zero writing skips the sector range
1095 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1096 * has new data to write there.
1098 * Returns: VMDK_OK if cluster exists and mapped in the image.
1099 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1100 * VMDK_ERROR if failed.
1102 static int get_cluster_offset(BlockDriverState *bs,
1103 VmdkExtent *extent,
1104 VmdkMetaData *m_data,
1105 uint64_t offset,
1106 bool allocate,
1107 uint64_t *cluster_offset,
1108 uint64_t skip_start_sector,
1109 uint64_t skip_end_sector)
1111 unsigned int l1_index, l2_offset, l2_index;
1112 int min_index, i, j;
1113 uint32_t min_count, *l2_table;
1114 bool zeroed = false;
1115 int64_t ret;
1116 int64_t cluster_sector;
1118 if (m_data) {
1119 m_data->valid = 0;
1121 if (extent->flat) {
1122 *cluster_offset = extent->flat_start_offset;
1123 return VMDK_OK;
1126 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1127 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1128 if (l1_index >= extent->l1_size) {
1129 return VMDK_ERROR;
1131 l2_offset = extent->l1_table[l1_index];
1132 if (!l2_offset) {
1133 return VMDK_UNALLOC;
1135 for (i = 0; i < L2_CACHE_SIZE; i++) {
1136 if (l2_offset == extent->l2_cache_offsets[i]) {
1137 /* increment the hit count */
1138 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1139 for (j = 0; j < L2_CACHE_SIZE; j++) {
1140 extent->l2_cache_counts[j] >>= 1;
1143 l2_table = extent->l2_cache + (i * extent->l2_size);
1144 goto found;
1147 /* not found: load a new entry in the least used one */
1148 min_index = 0;
1149 min_count = 0xffffffff;
1150 for (i = 0; i < L2_CACHE_SIZE; i++) {
1151 if (extent->l2_cache_counts[i] < min_count) {
1152 min_count = extent->l2_cache_counts[i];
1153 min_index = i;
1156 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1157 if (bdrv_pread(
1158 extent->file,
1159 (int64_t)l2_offset * 512,
1160 l2_table,
1161 extent->l2_size * sizeof(uint32_t)
1162 ) != extent->l2_size * sizeof(uint32_t)) {
1163 return VMDK_ERROR;
1166 extent->l2_cache_offsets[min_index] = l2_offset;
1167 extent->l2_cache_counts[min_index] = 1;
1168 found:
1169 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1170 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1172 if (m_data) {
1173 m_data->valid = 1;
1174 m_data->l1_index = l1_index;
1175 m_data->l2_index = l2_index;
1176 m_data->l2_offset = l2_offset;
1177 m_data->l2_cache_entry = &l2_table[l2_index];
1179 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1180 zeroed = true;
1183 if (!cluster_sector || zeroed) {
1184 if (!allocate) {
1185 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1188 cluster_sector = extent->next_cluster_sector;
1189 extent->next_cluster_sector += extent->cluster_sectors;
1191 /* First of all we write grain itself, to avoid race condition
1192 * that may to corrupt the image.
1193 * This problem may occur because of insufficient space on host disk
1194 * or inappropriate VM shutdown.
1196 ret = get_whole_cluster(bs, extent,
1197 cluster_sector,
1198 offset >> BDRV_SECTOR_BITS,
1199 skip_start_sector, skip_end_sector);
1200 if (ret) {
1201 return ret;
1204 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1205 return VMDK_OK;
1208 static VmdkExtent *find_extent(BDRVVmdkState *s,
1209 int64_t sector_num, VmdkExtent *start_hint)
1211 VmdkExtent *extent = start_hint;
1213 if (!extent) {
1214 extent = &s->extents[0];
1216 while (extent < &s->extents[s->num_extents]) {
1217 if (sector_num < extent->end_sector) {
1218 return extent;
1220 extent++;
1222 return NULL;
1225 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1226 int64_t sector_num, int nb_sectors, int *pnum)
1228 BDRVVmdkState *s = bs->opaque;
1229 int64_t index_in_cluster, n, ret;
1230 uint64_t offset;
1231 VmdkExtent *extent;
1233 extent = find_extent(s, sector_num, NULL);
1234 if (!extent) {
1235 return 0;
1237 qemu_co_mutex_lock(&s->lock);
1238 ret = get_cluster_offset(bs, extent, NULL,
1239 sector_num * 512, false, &offset,
1240 0, 0);
1241 qemu_co_mutex_unlock(&s->lock);
1243 switch (ret) {
1244 case VMDK_ERROR:
1245 ret = -EIO;
1246 break;
1247 case VMDK_UNALLOC:
1248 ret = 0;
1249 break;
1250 case VMDK_ZEROED:
1251 ret = BDRV_BLOCK_ZERO;
1252 break;
1253 case VMDK_OK:
1254 ret = BDRV_BLOCK_DATA;
1255 if (extent->file == bs->file && !extent->compressed) {
1256 ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1259 break;
1262 index_in_cluster = sector_num % extent->cluster_sectors;
1263 n = extent->cluster_sectors - index_in_cluster;
1264 if (n > nb_sectors) {
1265 n = nb_sectors;
1267 *pnum = n;
1268 return ret;
1271 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1272 int64_t offset_in_cluster, const uint8_t *buf,
1273 int nb_sectors, int64_t sector_num)
1275 int ret;
1276 VmdkGrainMarker *data = NULL;
1277 uLongf buf_len;
1278 const uint8_t *write_buf = buf;
1279 int write_len = nb_sectors * 512;
1281 if (extent->compressed) {
1282 if (!extent->has_marker) {
1283 ret = -EINVAL;
1284 goto out;
1286 buf_len = (extent->cluster_sectors << 9) * 2;
1287 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1288 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1289 buf_len == 0) {
1290 ret = -EINVAL;
1291 goto out;
1293 data->lba = sector_num;
1294 data->size = buf_len;
1295 write_buf = (uint8_t *)data;
1296 write_len = buf_len + sizeof(VmdkGrainMarker);
1298 ret = bdrv_pwrite(extent->file,
1299 cluster_offset + offset_in_cluster,
1300 write_buf,
1301 write_len);
1302 if (ret != write_len) {
1303 ret = ret < 0 ? ret : -EIO;
1304 goto out;
1306 ret = 0;
1307 out:
1308 g_free(data);
1309 return ret;
1312 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1313 int64_t offset_in_cluster, uint8_t *buf,
1314 int nb_sectors)
1316 int ret;
1317 int cluster_bytes, buf_bytes;
1318 uint8_t *cluster_buf, *compressed_data;
1319 uint8_t *uncomp_buf;
1320 uint32_t data_len;
1321 VmdkGrainMarker *marker;
1322 uLongf buf_len;
1325 if (!extent->compressed) {
1326 ret = bdrv_pread(extent->file,
1327 cluster_offset + offset_in_cluster,
1328 buf, nb_sectors * 512);
1329 if (ret == nb_sectors * 512) {
1330 return 0;
1331 } else {
1332 return -EIO;
1335 cluster_bytes = extent->cluster_sectors * 512;
1336 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1337 buf_bytes = cluster_bytes * 2;
1338 cluster_buf = g_malloc(buf_bytes);
1339 uncomp_buf = g_malloc(cluster_bytes);
1340 ret = bdrv_pread(extent->file,
1341 cluster_offset,
1342 cluster_buf, buf_bytes);
1343 if (ret < 0) {
1344 goto out;
1346 compressed_data = cluster_buf;
1347 buf_len = cluster_bytes;
1348 data_len = cluster_bytes;
1349 if (extent->has_marker) {
1350 marker = (VmdkGrainMarker *)cluster_buf;
1351 compressed_data = marker->data;
1352 data_len = le32_to_cpu(marker->size);
1354 if (!data_len || data_len > buf_bytes) {
1355 ret = -EINVAL;
1356 goto out;
1358 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1359 if (ret != Z_OK) {
1360 ret = -EINVAL;
1361 goto out;
1364 if (offset_in_cluster < 0 ||
1365 offset_in_cluster + nb_sectors * 512 > buf_len) {
1366 ret = -EINVAL;
1367 goto out;
1369 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1370 ret = 0;
1372 out:
1373 g_free(uncomp_buf);
1374 g_free(cluster_buf);
1375 return ret;
1378 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1379 uint8_t *buf, int nb_sectors)
1381 BDRVVmdkState *s = bs->opaque;
1382 int ret;
1383 uint64_t n, index_in_cluster;
1384 uint64_t extent_begin_sector, extent_relative_sector_num;
1385 VmdkExtent *extent = NULL;
1386 uint64_t cluster_offset;
1388 while (nb_sectors > 0) {
1389 extent = find_extent(s, sector_num, extent);
1390 if (!extent) {
1391 return -EIO;
1393 ret = get_cluster_offset(bs, extent, NULL,
1394 sector_num << 9, false, &cluster_offset,
1395 0, 0);
1396 extent_begin_sector = extent->end_sector - extent->sectors;
1397 extent_relative_sector_num = sector_num - extent_begin_sector;
1398 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1399 n = extent->cluster_sectors - index_in_cluster;
1400 if (n > nb_sectors) {
1401 n = nb_sectors;
1403 if (ret != VMDK_OK) {
1404 /* if not allocated, try to read from parent image, if exist */
1405 if (bs->backing_hd && ret != VMDK_ZEROED) {
1406 if (!vmdk_is_cid_valid(bs)) {
1407 return -EINVAL;
1409 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1410 if (ret < 0) {
1411 return ret;
1413 } else {
1414 memset(buf, 0, 512 * n);
1416 } else {
1417 ret = vmdk_read_extent(extent,
1418 cluster_offset, index_in_cluster * 512,
1419 buf, n);
1420 if (ret) {
1421 return ret;
1424 nb_sectors -= n;
1425 sector_num += n;
1426 buf += n * 512;
1428 return 0;
1431 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1432 uint8_t *buf, int nb_sectors)
1434 int ret;
1435 BDRVVmdkState *s = bs->opaque;
1436 qemu_co_mutex_lock(&s->lock);
1437 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1438 qemu_co_mutex_unlock(&s->lock);
1439 return ret;
1443 * vmdk_write:
1444 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1445 * if possible, otherwise return -ENOTSUP.
1446 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1447 * with each cluster. By dry run we can find if the zero write
1448 * is possible without modifying image data.
1450 * Returns: error code with 0 for success.
1452 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1453 const uint8_t *buf, int nb_sectors,
1454 bool zeroed, bool zero_dry_run)
1456 BDRVVmdkState *s = bs->opaque;
1457 VmdkExtent *extent = NULL;
1458 int ret;
1459 int64_t index_in_cluster, n;
1460 uint64_t extent_begin_sector, extent_relative_sector_num;
1461 uint64_t cluster_offset;
1462 VmdkMetaData m_data;
1464 if (sector_num > bs->total_sectors) {
1465 error_report("Wrong offset: sector_num=0x%" PRIx64
1466 " total_sectors=0x%" PRIx64 "\n",
1467 sector_num, bs->total_sectors);
1468 return -EIO;
1471 while (nb_sectors > 0) {
1472 extent = find_extent(s, sector_num, extent);
1473 if (!extent) {
1474 return -EIO;
1476 extent_begin_sector = extent->end_sector - extent->sectors;
1477 extent_relative_sector_num = sector_num - extent_begin_sector;
1478 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1479 n = extent->cluster_sectors - index_in_cluster;
1480 if (n > nb_sectors) {
1481 n = nb_sectors;
1483 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1484 !(extent->compressed || zeroed),
1485 &cluster_offset,
1486 index_in_cluster, index_in_cluster + n);
1487 if (extent->compressed) {
1488 if (ret == VMDK_OK) {
1489 /* Refuse write to allocated cluster for streamOptimized */
1490 error_report("Could not write to allocated cluster"
1491 " for streamOptimized");
1492 return -EIO;
1493 } else {
1494 /* allocate */
1495 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1496 true, &cluster_offset, 0, 0);
1499 if (ret == VMDK_ERROR) {
1500 return -EINVAL;
1502 if (zeroed) {
1503 /* Do zeroed write, buf is ignored */
1504 if (extent->has_zero_grain &&
1505 index_in_cluster == 0 &&
1506 n >= extent->cluster_sectors) {
1507 n = extent->cluster_sectors;
1508 if (!zero_dry_run) {
1509 /* update L2 tables */
1510 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1511 != VMDK_OK) {
1512 return -EIO;
1515 } else {
1516 return -ENOTSUP;
1518 } else {
1519 ret = vmdk_write_extent(extent,
1520 cluster_offset, index_in_cluster * 512,
1521 buf, n, sector_num);
1522 if (ret) {
1523 return ret;
1525 if (m_data.valid) {
1526 /* update L2 tables */
1527 if (vmdk_L2update(extent, &m_data,
1528 cluster_offset >> BDRV_SECTOR_BITS)
1529 != VMDK_OK) {
1530 return -EIO;
1534 nb_sectors -= n;
1535 sector_num += n;
1536 buf += n * 512;
1538 /* update CID on the first write every time the virtual disk is
1539 * opened */
1540 if (!s->cid_updated) {
1541 ret = vmdk_write_cid(bs, time(NULL));
1542 if (ret < 0) {
1543 return ret;
1545 s->cid_updated = true;
1548 return 0;
1551 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1552 const uint8_t *buf, int nb_sectors)
1554 int ret;
1555 BDRVVmdkState *s = bs->opaque;
1556 qemu_co_mutex_lock(&s->lock);
1557 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1558 qemu_co_mutex_unlock(&s->lock);
1559 return ret;
1562 static int vmdk_write_compressed(BlockDriverState *bs,
1563 int64_t sector_num,
1564 const uint8_t *buf,
1565 int nb_sectors)
1567 BDRVVmdkState *s = bs->opaque;
1568 if (s->num_extents == 1 && s->extents[0].compressed) {
1569 return vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1570 } else {
1571 return -ENOTSUP;
1575 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1576 int64_t sector_num,
1577 int nb_sectors,
1578 BdrvRequestFlags flags)
1580 int ret;
1581 BDRVVmdkState *s = bs->opaque;
1582 qemu_co_mutex_lock(&s->lock);
1583 /* write zeroes could fail if sectors not aligned to cluster, test it with
1584 * dry_run == true before really updating image */
1585 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1586 if (!ret) {
1587 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1589 qemu_co_mutex_unlock(&s->lock);
1590 return ret;
1593 static int vmdk_create_extent(const char *filename, int64_t filesize,
1594 bool flat, bool compress, bool zeroed_grain,
1595 QemuOpts *opts, Error **errp)
1597 int ret, i;
1598 BlockDriverState *bs = NULL;
1599 VMDK4Header header;
1600 Error *local_err = NULL;
1601 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1602 uint32_t *gd_buf = NULL;
1603 int gd_buf_size;
1605 ret = bdrv_create_file(filename, opts, &local_err);
1606 if (ret < 0) {
1607 error_propagate(errp, local_err);
1608 goto exit;
1611 assert(bs == NULL);
1612 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1613 NULL, &local_err);
1614 if (ret < 0) {
1615 error_propagate(errp, local_err);
1616 goto exit;
1619 if (flat) {
1620 ret = bdrv_truncate(bs, filesize);
1621 if (ret < 0) {
1622 error_setg_errno(errp, -ret, "Could not truncate file");
1624 goto exit;
1626 magic = cpu_to_be32(VMDK4_MAGIC);
1627 memset(&header, 0, sizeof(header));
1628 header.version = zeroed_grain ? 2 : 1;
1629 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1630 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1631 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1632 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1633 header.capacity = filesize / BDRV_SECTOR_SIZE;
1634 header.granularity = 128;
1635 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1637 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1638 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1639 BDRV_SECTOR_SIZE);
1640 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1641 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1643 header.desc_offset = 1;
1644 header.desc_size = 20;
1645 header.rgd_offset = header.desc_offset + header.desc_size;
1646 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1647 header.grain_offset =
1648 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1649 header.granularity);
1650 /* swap endianness for all header fields */
1651 header.version = cpu_to_le32(header.version);
1652 header.flags = cpu_to_le32(header.flags);
1653 header.capacity = cpu_to_le64(header.capacity);
1654 header.granularity = cpu_to_le64(header.granularity);
1655 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1656 header.desc_offset = cpu_to_le64(header.desc_offset);
1657 header.desc_size = cpu_to_le64(header.desc_size);
1658 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1659 header.gd_offset = cpu_to_le64(header.gd_offset);
1660 header.grain_offset = cpu_to_le64(header.grain_offset);
1661 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1663 header.check_bytes[0] = 0xa;
1664 header.check_bytes[1] = 0x20;
1665 header.check_bytes[2] = 0xd;
1666 header.check_bytes[3] = 0xa;
1668 /* write all the data */
1669 ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1670 if (ret < 0) {
1671 error_set(errp, QERR_IO_ERROR);
1672 goto exit;
1674 ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1675 if (ret < 0) {
1676 error_set(errp, QERR_IO_ERROR);
1677 goto exit;
1680 ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1681 if (ret < 0) {
1682 error_setg_errno(errp, -ret, "Could not truncate file");
1683 goto exit;
1686 /* write grain directory */
1687 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1688 gd_buf = g_malloc0(gd_buf_size);
1689 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1690 i < gt_count; i++, tmp += gt_size) {
1691 gd_buf[i] = cpu_to_le32(tmp);
1693 ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1694 gd_buf, gd_buf_size);
1695 if (ret < 0) {
1696 error_set(errp, QERR_IO_ERROR);
1697 goto exit;
1700 /* write backup grain directory */
1701 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1702 i < gt_count; i++, tmp += gt_size) {
1703 gd_buf[i] = cpu_to_le32(tmp);
1705 ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1706 gd_buf, gd_buf_size);
1707 if (ret < 0) {
1708 error_set(errp, QERR_IO_ERROR);
1709 goto exit;
1712 ret = 0;
1713 exit:
1714 if (bs) {
1715 bdrv_unref(bs);
1717 g_free(gd_buf);
1718 return ret;
1721 static int filename_decompose(const char *filename, char *path, char *prefix,
1722 char *postfix, size_t buf_len, Error **errp)
1724 const char *p, *q;
1726 if (filename == NULL || !strlen(filename)) {
1727 error_setg(errp, "No filename provided");
1728 return VMDK_ERROR;
1730 p = strrchr(filename, '/');
1731 if (p == NULL) {
1732 p = strrchr(filename, '\\');
1734 if (p == NULL) {
1735 p = strrchr(filename, ':');
1737 if (p != NULL) {
1738 p++;
1739 if (p - filename >= buf_len) {
1740 return VMDK_ERROR;
1742 pstrcpy(path, p - filename + 1, filename);
1743 } else {
1744 p = filename;
1745 path[0] = '\0';
1747 q = strrchr(p, '.');
1748 if (q == NULL) {
1749 pstrcpy(prefix, buf_len, p);
1750 postfix[0] = '\0';
1751 } else {
1752 if (q - p >= buf_len) {
1753 return VMDK_ERROR;
1755 pstrcpy(prefix, q - p + 1, p);
1756 pstrcpy(postfix, buf_len, q);
1758 return VMDK_OK;
1761 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1763 int idx = 0;
1764 BlockDriverState *new_bs = NULL;
1765 Error *local_err = NULL;
1766 char *desc = NULL;
1767 int64_t total_size = 0, filesize;
1768 char *adapter_type = NULL;
1769 char *backing_file = NULL;
1770 char *fmt = NULL;
1771 int flags = 0;
1772 int ret = 0;
1773 bool flat, split, compress;
1774 GString *ext_desc_lines;
1775 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1776 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1777 const char *desc_extent_line;
1778 char parent_desc_line[BUF_SIZE] = "";
1779 uint32_t parent_cid = 0xffffffff;
1780 uint32_t number_heads = 16;
1781 bool zeroed_grain = false;
1782 uint32_t desc_offset = 0, desc_len;
1783 const char desc_template[] =
1784 "# Disk DescriptorFile\n"
1785 "version=1\n"
1786 "CID=%" PRIx32 "\n"
1787 "parentCID=%" PRIx32 "\n"
1788 "createType=\"%s\"\n"
1789 "%s"
1790 "\n"
1791 "# Extent description\n"
1792 "%s"
1793 "\n"
1794 "# The Disk Data Base\n"
1795 "#DDB\n"
1796 "\n"
1797 "ddb.virtualHWVersion = \"%d\"\n"
1798 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1799 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1800 "ddb.geometry.sectors = \"63\"\n"
1801 "ddb.adapterType = \"%s\"\n";
1803 ext_desc_lines = g_string_new(NULL);
1805 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1806 ret = -EINVAL;
1807 goto exit;
1809 /* Read out options */
1810 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1811 BDRV_SECTOR_SIZE);
1812 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1813 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1814 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1815 flags |= BLOCK_FLAG_COMPAT6;
1817 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1818 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1819 zeroed_grain = true;
1822 if (!adapter_type) {
1823 adapter_type = g_strdup("ide");
1824 } else if (strcmp(adapter_type, "ide") &&
1825 strcmp(adapter_type, "buslogic") &&
1826 strcmp(adapter_type, "lsilogic") &&
1827 strcmp(adapter_type, "legacyESX")) {
1828 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1829 ret = -EINVAL;
1830 goto exit;
1832 if (strcmp(adapter_type, "ide") != 0) {
1833 /* that's the number of heads with which vmware operates when
1834 creating, exporting, etc. vmdk files with a non-ide adapter type */
1835 number_heads = 255;
1837 if (!fmt) {
1838 /* Default format to monolithicSparse */
1839 fmt = g_strdup("monolithicSparse");
1840 } else if (strcmp(fmt, "monolithicFlat") &&
1841 strcmp(fmt, "monolithicSparse") &&
1842 strcmp(fmt, "twoGbMaxExtentSparse") &&
1843 strcmp(fmt, "twoGbMaxExtentFlat") &&
1844 strcmp(fmt, "streamOptimized")) {
1845 error_setg(errp, "Unknown subformat: '%s'", fmt);
1846 ret = -EINVAL;
1847 goto exit;
1849 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1850 strcmp(fmt, "twoGbMaxExtentSparse"));
1851 flat = !(strcmp(fmt, "monolithicFlat") &&
1852 strcmp(fmt, "twoGbMaxExtentFlat"));
1853 compress = !strcmp(fmt, "streamOptimized");
1854 if (flat) {
1855 desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1856 } else {
1857 desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1859 if (flat && backing_file) {
1860 error_setg(errp, "Flat image can't have backing file");
1861 ret = -ENOTSUP;
1862 goto exit;
1864 if (flat && zeroed_grain) {
1865 error_setg(errp, "Flat image can't enable zeroed grain");
1866 ret = -ENOTSUP;
1867 goto exit;
1869 if (backing_file) {
1870 BlockDriverState *bs = NULL;
1871 ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_NO_BACKING, NULL,
1872 errp);
1873 if (ret != 0) {
1874 goto exit;
1876 if (strcmp(bs->drv->format_name, "vmdk")) {
1877 bdrv_unref(bs);
1878 ret = -EINVAL;
1879 goto exit;
1881 parent_cid = vmdk_read_cid(bs, 0);
1882 bdrv_unref(bs);
1883 snprintf(parent_desc_line, sizeof(parent_desc_line),
1884 "parentFileNameHint=\"%s\"", backing_file);
1887 /* Create extents */
1888 filesize = total_size;
1889 while (filesize > 0) {
1890 char desc_line[BUF_SIZE];
1891 char ext_filename[PATH_MAX];
1892 char desc_filename[PATH_MAX];
1893 int64_t size = filesize;
1895 if (split && size > split_size) {
1896 size = split_size;
1898 if (split) {
1899 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1900 prefix, flat ? 'f' : 's', ++idx, postfix);
1901 } else if (flat) {
1902 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1903 prefix, postfix);
1904 } else {
1905 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1906 prefix, postfix);
1908 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1909 path, desc_filename);
1911 if (vmdk_create_extent(ext_filename, size,
1912 flat, compress, zeroed_grain, opts, errp)) {
1913 ret = -EINVAL;
1914 goto exit;
1916 filesize -= size;
1918 /* Format description line */
1919 snprintf(desc_line, sizeof(desc_line),
1920 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1921 g_string_append(ext_desc_lines, desc_line);
1923 /* generate descriptor file */
1924 desc = g_strdup_printf(desc_template,
1925 (uint32_t)time(NULL),
1926 parent_cid,
1927 fmt,
1928 parent_desc_line,
1929 ext_desc_lines->str,
1930 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1931 total_size /
1932 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1933 number_heads,
1934 adapter_type);
1935 desc_len = strlen(desc);
1936 /* the descriptor offset = 0x200 */
1937 if (!split && !flat) {
1938 desc_offset = 0x200;
1939 } else {
1940 ret = bdrv_create_file(filename, opts, &local_err);
1941 if (ret < 0) {
1942 error_propagate(errp, local_err);
1943 goto exit;
1946 assert(new_bs == NULL);
1947 ret = bdrv_open(&new_bs, filename, NULL, NULL,
1948 BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
1949 if (ret < 0) {
1950 error_propagate(errp, local_err);
1951 goto exit;
1953 ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1954 if (ret < 0) {
1955 error_setg_errno(errp, -ret, "Could not write description");
1956 goto exit;
1958 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1959 * for description file */
1960 if (desc_offset == 0) {
1961 ret = bdrv_truncate(new_bs, desc_len);
1962 if (ret < 0) {
1963 error_setg_errno(errp, -ret, "Could not truncate file");
1966 exit:
1967 if (new_bs) {
1968 bdrv_unref(new_bs);
1970 g_free(adapter_type);
1971 g_free(backing_file);
1972 g_free(fmt);
1973 g_free(desc);
1974 g_string_free(ext_desc_lines, true);
1975 return ret;
1978 static void vmdk_close(BlockDriverState *bs)
1980 BDRVVmdkState *s = bs->opaque;
1982 vmdk_free_extents(bs);
1983 g_free(s->create_type);
1985 migrate_del_blocker(s->migration_blocker);
1986 error_free(s->migration_blocker);
1989 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1991 BDRVVmdkState *s = bs->opaque;
1992 int i, err;
1993 int ret = 0;
1995 for (i = 0; i < s->num_extents; i++) {
1996 err = bdrv_co_flush(s->extents[i].file);
1997 if (err < 0) {
1998 ret = err;
2001 return ret;
2004 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2006 int i;
2007 int64_t ret = 0;
2008 int64_t r;
2009 BDRVVmdkState *s = bs->opaque;
2011 ret = bdrv_get_allocated_file_size(bs->file);
2012 if (ret < 0) {
2013 return ret;
2015 for (i = 0; i < s->num_extents; i++) {
2016 if (s->extents[i].file == bs->file) {
2017 continue;
2019 r = bdrv_get_allocated_file_size(s->extents[i].file);
2020 if (r < 0) {
2021 return r;
2023 ret += r;
2025 return ret;
2028 static int vmdk_has_zero_init(BlockDriverState *bs)
2030 int i;
2031 BDRVVmdkState *s = bs->opaque;
2033 /* If has a flat extent and its underlying storage doesn't have zero init,
2034 * return 0. */
2035 for (i = 0; i < s->num_extents; i++) {
2036 if (s->extents[i].flat) {
2037 if (!bdrv_has_zero_init(s->extents[i].file)) {
2038 return 0;
2042 return 1;
2045 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2047 ImageInfo *info = g_new0(ImageInfo, 1);
2049 *info = (ImageInfo){
2050 .filename = g_strdup(extent->file->filename),
2051 .format = g_strdup(extent->type),
2052 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2053 .compressed = extent->compressed,
2054 .has_compressed = extent->compressed,
2055 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2056 .has_cluster_size = !extent->flat,
2059 return info;
2062 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2063 BdrvCheckMode fix)
2065 BDRVVmdkState *s = bs->opaque;
2066 VmdkExtent *extent = NULL;
2067 int64_t sector_num = 0;
2068 int64_t total_sectors = bdrv_nb_sectors(bs);
2069 int ret;
2070 uint64_t cluster_offset;
2072 if (fix) {
2073 return -ENOTSUP;
2076 for (;;) {
2077 if (sector_num >= total_sectors) {
2078 return 0;
2080 extent = find_extent(s, sector_num, extent);
2081 if (!extent) {
2082 fprintf(stderr,
2083 "ERROR: could not find extent for sector %" PRId64 "\n",
2084 sector_num);
2085 break;
2087 ret = get_cluster_offset(bs, extent, NULL,
2088 sector_num << BDRV_SECTOR_BITS,
2089 false, &cluster_offset, 0, 0);
2090 if (ret == VMDK_ERROR) {
2091 fprintf(stderr,
2092 "ERROR: could not get cluster_offset for sector %"
2093 PRId64 "\n", sector_num);
2094 break;
2096 if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2097 fprintf(stderr,
2098 "ERROR: cluster offset for sector %"
2099 PRId64 " points after EOF\n", sector_num);
2100 break;
2102 sector_num += extent->cluster_sectors;
2105 result->corruptions++;
2106 return 0;
2109 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2111 int i;
2112 BDRVVmdkState *s = bs->opaque;
2113 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2114 ImageInfoList **next;
2116 *spec_info = (ImageInfoSpecific){
2117 .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2119 .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2123 *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2124 .create_type = g_strdup(s->create_type),
2125 .cid = s->cid,
2126 .parent_cid = s->parent_cid,
2129 next = &spec_info->vmdk->extents;
2130 for (i = 0; i < s->num_extents; i++) {
2131 *next = g_new0(ImageInfoList, 1);
2132 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2133 (*next)->next = NULL;
2134 next = &(*next)->next;
2137 return spec_info;
2140 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2142 return a->flat == b->flat &&
2143 a->compressed == b->compressed &&
2144 (a->flat || a->cluster_sectors == b->cluster_sectors);
2147 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2149 int i;
2150 BDRVVmdkState *s = bs->opaque;
2151 assert(s->num_extents);
2153 /* See if we have multiple extents but they have different cases */
2154 for (i = 1; i < s->num_extents; i++) {
2155 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2156 return -ENOTSUP;
2159 bdi->needs_compressed_writes = s->extents[0].compressed;
2160 if (!s->extents[0].flat) {
2161 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2163 return 0;
2166 static void vmdk_detach_aio_context(BlockDriverState *bs)
2168 BDRVVmdkState *s = bs->opaque;
2169 int i;
2171 for (i = 0; i < s->num_extents; i++) {
2172 bdrv_detach_aio_context(s->extents[i].file);
2176 static void vmdk_attach_aio_context(BlockDriverState *bs,
2177 AioContext *new_context)
2179 BDRVVmdkState *s = bs->opaque;
2180 int i;
2182 for (i = 0; i < s->num_extents; i++) {
2183 bdrv_attach_aio_context(s->extents[i].file, new_context);
2187 static QemuOptsList vmdk_create_opts = {
2188 .name = "vmdk-create-opts",
2189 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2190 .desc = {
2192 .name = BLOCK_OPT_SIZE,
2193 .type = QEMU_OPT_SIZE,
2194 .help = "Virtual disk size"
2197 .name = BLOCK_OPT_ADAPTER_TYPE,
2198 .type = QEMU_OPT_STRING,
2199 .help = "Virtual adapter type, can be one of "
2200 "ide (default), lsilogic, buslogic or legacyESX"
2203 .name = BLOCK_OPT_BACKING_FILE,
2204 .type = QEMU_OPT_STRING,
2205 .help = "File name of a base image"
2208 .name = BLOCK_OPT_COMPAT6,
2209 .type = QEMU_OPT_BOOL,
2210 .help = "VMDK version 6 image",
2211 .def_value_str = "off"
2214 .name = BLOCK_OPT_SUBFMT,
2215 .type = QEMU_OPT_STRING,
2216 .help =
2217 "VMDK flat extent format, can be one of "
2218 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2221 .name = BLOCK_OPT_ZEROED_GRAIN,
2222 .type = QEMU_OPT_BOOL,
2223 .help = "Enable efficient zero writes "
2224 "using the zeroed-grain GTE feature"
2226 { /* end of list */ }
2230 static BlockDriver bdrv_vmdk = {
2231 .format_name = "vmdk",
2232 .instance_size = sizeof(BDRVVmdkState),
2233 .bdrv_probe = vmdk_probe,
2234 .bdrv_open = vmdk_open,
2235 .bdrv_check = vmdk_check,
2236 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2237 .bdrv_read = vmdk_co_read,
2238 .bdrv_write = vmdk_co_write,
2239 .bdrv_write_compressed = vmdk_write_compressed,
2240 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
2241 .bdrv_close = vmdk_close,
2242 .bdrv_create = vmdk_create,
2243 .bdrv_co_flush_to_disk = vmdk_co_flush,
2244 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2245 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2246 .bdrv_has_zero_init = vmdk_has_zero_init,
2247 .bdrv_get_specific_info = vmdk_get_specific_info,
2248 .bdrv_refresh_limits = vmdk_refresh_limits,
2249 .bdrv_get_info = vmdk_get_info,
2250 .bdrv_detach_aio_context = vmdk_detach_aio_context,
2251 .bdrv_attach_aio_context = vmdk_attach_aio_context,
2253 .supports_backing = true,
2254 .create_opts = &vmdk_create_opts,
2257 static void bdrv_vmdk_init(void)
2259 bdrv_register(&bdrv_vmdk);
2262 block_init(bdrv_vmdk_init);