vfio/pci: Remove old config window and mirror quirks
[qemu/ar7.git] / block / vmdk.c
blobbe0d6401afd0c0f3d335c04ced0a603c249a07c8
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 "qapi/qmp/qerror.h"
29 #include "qemu/error-report.h"
30 #include "qemu/module.h"
31 #include "migration/migration.h"
32 #include <zlib.h>
33 #include <glib.h>
35 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
36 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
37 #define VMDK4_COMPRESSION_DEFLATE 1
38 #define VMDK4_FLAG_NL_DETECT (1 << 0)
39 #define VMDK4_FLAG_RGD (1 << 1)
40 /* Zeroed-grain enable bit */
41 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
42 #define VMDK4_FLAG_COMPRESS (1 << 16)
43 #define VMDK4_FLAG_MARKER (1 << 17)
44 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
46 #define VMDK_GTE_ZEROED 0x1
48 /* VMDK internal error codes */
49 #define VMDK_OK 0
50 #define VMDK_ERROR (-1)
51 /* Cluster not allocated */
52 #define VMDK_UNALLOC (-2)
53 #define VMDK_ZEROED (-3)
55 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
57 typedef struct {
58 uint32_t version;
59 uint32_t flags;
60 uint32_t disk_sectors;
61 uint32_t granularity;
62 uint32_t l1dir_offset;
63 uint32_t l1dir_size;
64 uint32_t file_sectors;
65 uint32_t cylinders;
66 uint32_t heads;
67 uint32_t sectors_per_track;
68 } QEMU_PACKED VMDK3Header;
70 typedef struct {
71 uint32_t version;
72 uint32_t flags;
73 uint64_t capacity;
74 uint64_t granularity;
75 uint64_t desc_offset;
76 uint64_t desc_size;
77 /* Number of GrainTableEntries per GrainTable */
78 uint32_t num_gtes_per_gt;
79 uint64_t rgd_offset;
80 uint64_t gd_offset;
81 uint64_t grain_offset;
82 char filler[1];
83 char check_bytes[4];
84 uint16_t compressAlgorithm;
85 } QEMU_PACKED VMDK4Header;
87 #define L2_CACHE_SIZE 16
89 typedef struct VmdkExtent {
90 BlockDriverState *file;
91 bool flat;
92 bool compressed;
93 bool has_marker;
94 bool has_zero_grain;
95 int version;
96 int64_t sectors;
97 int64_t end_sector;
98 int64_t flat_start_offset;
99 int64_t l1_table_offset;
100 int64_t l1_backup_table_offset;
101 uint32_t *l1_table;
102 uint32_t *l1_backup_table;
103 unsigned int l1_size;
104 uint32_t l1_entry_sectors;
106 unsigned int l2_size;
107 uint32_t *l2_cache;
108 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
109 uint32_t l2_cache_counts[L2_CACHE_SIZE];
111 int64_t cluster_sectors;
112 int64_t next_cluster_sector;
113 char *type;
114 } VmdkExtent;
116 typedef struct BDRVVmdkState {
117 CoMutex lock;
118 uint64_t desc_offset;
119 bool cid_updated;
120 bool cid_checked;
121 uint32_t cid;
122 uint32_t parent_cid;
123 int num_extents;
124 /* Extent array with num_extents entries, ascend ordered by address */
125 VmdkExtent *extents;
126 Error *migration_blocker;
127 char *create_type;
128 } BDRVVmdkState;
130 typedef struct VmdkMetaData {
131 unsigned int l1_index;
132 unsigned int l2_index;
133 unsigned int l2_offset;
134 int valid;
135 uint32_t *l2_cache_entry;
136 } VmdkMetaData;
138 typedef struct VmdkGrainMarker {
139 uint64_t lba;
140 uint32_t size;
141 uint8_t data[0];
142 } QEMU_PACKED VmdkGrainMarker;
144 enum {
145 MARKER_END_OF_STREAM = 0,
146 MARKER_GRAIN_TABLE = 1,
147 MARKER_GRAIN_DIRECTORY = 2,
148 MARKER_FOOTER = 3,
151 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
153 uint32_t magic;
155 if (buf_size < 4) {
156 return 0;
158 magic = be32_to_cpu(*(uint32_t *)buf);
159 if (magic == VMDK3_MAGIC ||
160 magic == VMDK4_MAGIC) {
161 return 100;
162 } else {
163 const char *p = (const char *)buf;
164 const char *end = p + buf_size;
165 while (p < end) {
166 if (*p == '#') {
167 /* skip comment line */
168 while (p < end && *p != '\n') {
169 p++;
171 p++;
172 continue;
174 if (*p == ' ') {
175 while (p < end && *p == ' ') {
176 p++;
178 /* skip '\r' if windows line endings used. */
179 if (p < end && *p == '\r') {
180 p++;
182 /* only accept blank lines before 'version=' line */
183 if (p == end || *p != '\n') {
184 return 0;
186 p++;
187 continue;
189 if (end - p >= strlen("version=X\n")) {
190 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
191 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
192 return 100;
195 if (end - p >= strlen("version=X\r\n")) {
196 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
197 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
198 return 100;
201 return 0;
203 return 0;
207 #define SECTOR_SIZE 512
208 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
209 #define BUF_SIZE 4096
210 #define HEADER_SIZE 512 /* first sector of 512 bytes */
212 static void vmdk_free_extents(BlockDriverState *bs)
214 int i;
215 BDRVVmdkState *s = bs->opaque;
216 VmdkExtent *e;
218 for (i = 0; i < s->num_extents; i++) {
219 e = &s->extents[i];
220 g_free(e->l1_table);
221 g_free(e->l2_cache);
222 g_free(e->l1_backup_table);
223 g_free(e->type);
224 if (e->file != bs->file) {
225 bdrv_unref(e->file);
228 g_free(s->extents);
231 static void vmdk_free_last_extent(BlockDriverState *bs)
233 BDRVVmdkState *s = bs->opaque;
235 if (s->num_extents == 0) {
236 return;
238 s->num_extents--;
239 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
242 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
244 char desc[DESC_SIZE];
245 uint32_t cid = 0xffffffff;
246 const char *p_name, *cid_str;
247 size_t cid_str_size;
248 BDRVVmdkState *s = bs->opaque;
249 int ret;
251 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
252 if (ret < 0) {
253 return 0;
256 if (parent) {
257 cid_str = "parentCID";
258 cid_str_size = sizeof("parentCID");
259 } else {
260 cid_str = "CID";
261 cid_str_size = sizeof("CID");
264 desc[DESC_SIZE - 1] = '\0';
265 p_name = strstr(desc, cid_str);
266 if (p_name != NULL) {
267 p_name += cid_str_size;
268 sscanf(p_name, "%" SCNx32, &cid);
271 return cid;
274 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
276 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
277 char *p_name, *tmp_str;
278 BDRVVmdkState *s = bs->opaque;
279 int ret;
281 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
282 if (ret < 0) {
283 return ret;
286 desc[DESC_SIZE - 1] = '\0';
287 tmp_str = strstr(desc, "parentCID");
288 if (tmp_str == NULL) {
289 return -EINVAL;
292 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
293 p_name = strstr(desc, "CID");
294 if (p_name != NULL) {
295 p_name += sizeof("CID");
296 snprintf(p_name, sizeof(desc) - (p_name - desc), "%" PRIx32 "\n", cid);
297 pstrcat(desc, sizeof(desc), tmp_desc);
300 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
301 if (ret < 0) {
302 return ret;
305 return 0;
308 static int vmdk_is_cid_valid(BlockDriverState *bs)
310 BDRVVmdkState *s = bs->opaque;
311 BlockDriverState *p_bs = bs->backing_hd;
312 uint32_t cur_pcid;
314 if (!s->cid_checked && p_bs) {
315 cur_pcid = vmdk_read_cid(p_bs, 0);
316 if (s->parent_cid != cur_pcid) {
317 /* CID not valid */
318 return 0;
321 s->cid_checked = true;
322 /* CID valid */
323 return 1;
326 /* We have nothing to do for VMDK reopen, stubs just return success */
327 static int vmdk_reopen_prepare(BDRVReopenState *state,
328 BlockReopenQueue *queue, Error **errp)
330 assert(state != NULL);
331 assert(state->bs != NULL);
332 return 0;
335 static int vmdk_parent_open(BlockDriverState *bs)
337 char *p_name;
338 char desc[DESC_SIZE + 1];
339 BDRVVmdkState *s = bs->opaque;
340 int ret;
342 desc[DESC_SIZE] = '\0';
343 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
344 if (ret < 0) {
345 return ret;
348 p_name = strstr(desc, "parentFileNameHint");
349 if (p_name != NULL) {
350 char *end_name;
352 p_name += sizeof("parentFileNameHint") + 1;
353 end_name = strchr(p_name, '\"');
354 if (end_name == NULL) {
355 return -EINVAL;
357 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
358 return -EINVAL;
361 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
364 return 0;
367 /* Create and append extent to the extent array. Return the added VmdkExtent
368 * address. return NULL if allocation failed. */
369 static int vmdk_add_extent(BlockDriverState *bs,
370 BlockDriverState *file, bool flat, int64_t sectors,
371 int64_t l1_offset, int64_t l1_backup_offset,
372 uint32_t l1_size,
373 int l2_size, uint64_t cluster_sectors,
374 VmdkExtent **new_extent,
375 Error **errp)
377 VmdkExtent *extent;
378 BDRVVmdkState *s = bs->opaque;
379 int64_t nb_sectors;
381 if (cluster_sectors > 0x200000) {
382 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
383 error_setg(errp, "Invalid granularity, image may be corrupt");
384 return -EFBIG;
386 if (l1_size > 512 * 1024 * 1024) {
387 /* Although with big capacity and small l1_entry_sectors, we can get a
388 * big l1_size, we don't want unbounded value to allocate the table.
389 * Limit it to 512M, which is 16PB for default cluster and L2 table
390 * size */
391 error_setg(errp, "L1 size too big");
392 return -EFBIG;
395 nb_sectors = bdrv_nb_sectors(file);
396 if (nb_sectors < 0) {
397 return nb_sectors;
400 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
401 extent = &s->extents[s->num_extents];
402 s->num_extents++;
404 memset(extent, 0, sizeof(VmdkExtent));
405 extent->file = file;
406 extent->flat = flat;
407 extent->sectors = sectors;
408 extent->l1_table_offset = l1_offset;
409 extent->l1_backup_table_offset = l1_backup_offset;
410 extent->l1_size = l1_size;
411 extent->l1_entry_sectors = l2_size * cluster_sectors;
412 extent->l2_size = l2_size;
413 extent->cluster_sectors = flat ? sectors : cluster_sectors;
414 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
416 if (s->num_extents > 1) {
417 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
418 } else {
419 extent->end_sector = extent->sectors;
421 bs->total_sectors = extent->end_sector;
422 if (new_extent) {
423 *new_extent = extent;
425 return 0;
428 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
429 Error **errp)
431 int ret;
432 size_t l1_size;
433 int i;
435 /* read the L1 table */
436 l1_size = extent->l1_size * sizeof(uint32_t);
437 extent->l1_table = g_try_malloc(l1_size);
438 if (l1_size && extent->l1_table == NULL) {
439 return -ENOMEM;
442 ret = bdrv_pread(extent->file,
443 extent->l1_table_offset,
444 extent->l1_table,
445 l1_size);
446 if (ret < 0) {
447 error_setg_errno(errp, -ret,
448 "Could not read l1 table from extent '%s'",
449 extent->file->filename);
450 goto fail_l1;
452 for (i = 0; i < extent->l1_size; i++) {
453 le32_to_cpus(&extent->l1_table[i]);
456 if (extent->l1_backup_table_offset) {
457 extent->l1_backup_table = g_try_malloc(l1_size);
458 if (l1_size && extent->l1_backup_table == NULL) {
459 ret = -ENOMEM;
460 goto fail_l1;
462 ret = bdrv_pread(extent->file,
463 extent->l1_backup_table_offset,
464 extent->l1_backup_table,
465 l1_size);
466 if (ret < 0) {
467 error_setg_errno(errp, -ret,
468 "Could not read l1 backup table from extent '%s'",
469 extent->file->filename);
470 goto fail_l1b;
472 for (i = 0; i < extent->l1_size; i++) {
473 le32_to_cpus(&extent->l1_backup_table[i]);
477 extent->l2_cache =
478 g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
479 return 0;
480 fail_l1b:
481 g_free(extent->l1_backup_table);
482 fail_l1:
483 g_free(extent->l1_table);
484 return ret;
487 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
488 BlockDriverState *file,
489 int flags, Error **errp)
491 int ret;
492 uint32_t magic;
493 VMDK3Header header;
494 VmdkExtent *extent;
496 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
497 if (ret < 0) {
498 error_setg_errno(errp, -ret,
499 "Could not read header from file '%s'",
500 file->filename);
501 return ret;
503 ret = vmdk_add_extent(bs, file, false,
504 le32_to_cpu(header.disk_sectors),
505 (int64_t)le32_to_cpu(header.l1dir_offset) << 9,
507 le32_to_cpu(header.l1dir_size),
508 4096,
509 le32_to_cpu(header.granularity),
510 &extent,
511 errp);
512 if (ret < 0) {
513 return ret;
515 ret = vmdk_init_tables(bs, extent, errp);
516 if (ret) {
517 /* free extent allocated by vmdk_add_extent */
518 vmdk_free_last_extent(bs);
520 return ret;
523 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
524 QDict *options, Error **errp);
526 static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset,
527 Error **errp)
529 int64_t size;
530 char *buf;
531 int ret;
533 size = bdrv_getlength(file);
534 if (size < 0) {
535 error_setg_errno(errp, -size, "Could not access file");
536 return NULL;
539 if (size < 4) {
540 /* Both descriptor file and sparse image must be much larger than 4
541 * bytes, also callers of vmdk_read_desc want to compare the first 4
542 * bytes with VMDK4_MAGIC, let's error out if less is read. */
543 error_setg(errp, "File is too small, not a valid image");
544 return NULL;
547 size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */
548 buf = g_malloc(size + 1);
550 ret = bdrv_pread(file, desc_offset, buf, size);
551 if (ret < 0) {
552 error_setg_errno(errp, -ret, "Could not read from file");
553 g_free(buf);
554 return NULL;
556 buf[ret] = 0;
558 return buf;
561 static int vmdk_open_vmdk4(BlockDriverState *bs,
562 BlockDriverState *file,
563 int flags, QDict *options, Error **errp)
565 int ret;
566 uint32_t magic;
567 uint32_t l1_size, l1_entry_sectors;
568 VMDK4Header header;
569 VmdkExtent *extent;
570 BDRVVmdkState *s = bs->opaque;
571 int64_t l1_backup_offset = 0;
573 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
574 if (ret < 0) {
575 error_setg_errno(errp, -ret,
576 "Could not read header from file '%s'",
577 file->filename);
578 return -EINVAL;
580 if (header.capacity == 0) {
581 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
582 if (desc_offset) {
583 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
584 if (!buf) {
585 return -EINVAL;
587 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
588 g_free(buf);
589 return ret;
593 if (!s->create_type) {
594 s->create_type = g_strdup("monolithicSparse");
597 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
599 * The footer takes precedence over the header, so read it in. The
600 * footer starts at offset -1024 from the end: One sector for the
601 * footer, and another one for the end-of-stream marker.
603 struct {
604 struct {
605 uint64_t val;
606 uint32_t size;
607 uint32_t type;
608 uint8_t pad[512 - 16];
609 } QEMU_PACKED footer_marker;
611 uint32_t magic;
612 VMDK4Header header;
613 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
615 struct {
616 uint64_t val;
617 uint32_t size;
618 uint32_t type;
619 uint8_t pad[512 - 16];
620 } QEMU_PACKED eos_marker;
621 } QEMU_PACKED footer;
623 ret = bdrv_pread(file,
624 bs->file->total_sectors * 512 - 1536,
625 &footer, sizeof(footer));
626 if (ret < 0) {
627 error_setg_errno(errp, -ret, "Failed to read footer");
628 return ret;
631 /* Some sanity checks for the footer */
632 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
633 le32_to_cpu(footer.footer_marker.size) != 0 ||
634 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
635 le64_to_cpu(footer.eos_marker.val) != 0 ||
636 le32_to_cpu(footer.eos_marker.size) != 0 ||
637 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
639 error_setg(errp, "Invalid footer");
640 return -EINVAL;
643 header = footer.header;
646 if (le32_to_cpu(header.version) > 3) {
647 char buf[64];
648 snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
649 le32_to_cpu(header.version));
650 error_setg(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
651 bdrv_get_device_or_node_name(bs), "vmdk", buf);
652 return -ENOTSUP;
653 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
654 /* VMware KB 2064959 explains that version 3 added support for
655 * persistent changed block tracking (CBT), and backup software can
656 * read it as version=1 if it doesn't care about the changed area
657 * information. So we are safe to enable read only. */
658 error_setg(errp, "VMDK version 3 must be read only");
659 return -EINVAL;
662 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
663 error_setg(errp, "L2 table size too big");
664 return -EINVAL;
667 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
668 * le64_to_cpu(header.granularity);
669 if (l1_entry_sectors == 0) {
670 error_setg(errp, "L1 entry size is invalid");
671 return -EINVAL;
673 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
674 / l1_entry_sectors;
675 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
676 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
678 if (bdrv_nb_sectors(file) < le64_to_cpu(header.grain_offset)) {
679 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
680 (int64_t)(le64_to_cpu(header.grain_offset)
681 * BDRV_SECTOR_SIZE));
682 return -EINVAL;
685 ret = vmdk_add_extent(bs, file, false,
686 le64_to_cpu(header.capacity),
687 le64_to_cpu(header.gd_offset) << 9,
688 l1_backup_offset,
689 l1_size,
690 le32_to_cpu(header.num_gtes_per_gt),
691 le64_to_cpu(header.granularity),
692 &extent,
693 errp);
694 if (ret < 0) {
695 return ret;
697 extent->compressed =
698 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
699 if (extent->compressed) {
700 g_free(s->create_type);
701 s->create_type = g_strdup("streamOptimized");
703 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
704 extent->version = le32_to_cpu(header.version);
705 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
706 ret = vmdk_init_tables(bs, extent, errp);
707 if (ret) {
708 /* free extent allocated by vmdk_add_extent */
709 vmdk_free_last_extent(bs);
711 return ret;
714 /* find an option value out of descriptor file */
715 static int vmdk_parse_description(const char *desc, const char *opt_name,
716 char *buf, int buf_size)
718 char *opt_pos, *opt_end;
719 const char *end = desc + strlen(desc);
721 opt_pos = strstr(desc, opt_name);
722 if (!opt_pos) {
723 return VMDK_ERROR;
725 /* Skip "=\"" following opt_name */
726 opt_pos += strlen(opt_name) + 2;
727 if (opt_pos >= end) {
728 return VMDK_ERROR;
730 opt_end = opt_pos;
731 while (opt_end < end && *opt_end != '"') {
732 opt_end++;
734 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
735 return VMDK_ERROR;
737 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
738 return VMDK_OK;
741 /* Open an extent file and append to bs array */
742 static int vmdk_open_sparse(BlockDriverState *bs,
743 BlockDriverState *file, int flags,
744 char *buf, QDict *options, Error **errp)
746 uint32_t magic;
748 magic = ldl_be_p(buf);
749 switch (magic) {
750 case VMDK3_MAGIC:
751 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
752 break;
753 case VMDK4_MAGIC:
754 return vmdk_open_vmdk4(bs, file, flags, options, errp);
755 break;
756 default:
757 error_setg(errp, "Image not in VMDK format");
758 return -EINVAL;
759 break;
763 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
764 const char *desc_file_path, QDict *options,
765 Error **errp)
767 int ret;
768 int matches;
769 char access[11];
770 char type[11];
771 char fname[512];
772 const char *p = desc;
773 int64_t sectors = 0;
774 int64_t flat_offset;
775 char *extent_path;
776 BlockDriverState *extent_file;
777 BDRVVmdkState *s = bs->opaque;
778 VmdkExtent *extent;
779 char extent_opt_prefix[32];
781 while (*p) {
782 /* parse extent line in one of below formats:
784 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
785 * RW [size in sectors] SPARSE "file-name.vmdk"
786 * RW [size in sectors] VMFS "file-name.vmdk"
787 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
789 flat_offset = -1;
790 matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
791 access, &sectors, type, fname, &flat_offset);
792 if (matches < 4 || strcmp(access, "RW")) {
793 goto next_line;
794 } else if (!strcmp(type, "FLAT")) {
795 if (matches != 5 || flat_offset < 0) {
796 error_setg(errp, "Invalid extent lines: \n%s", p);
797 return -EINVAL;
799 } else if (!strcmp(type, "VMFS")) {
800 if (matches == 4) {
801 flat_offset = 0;
802 } else {
803 error_setg(errp, "Invalid extent lines:\n%s", p);
804 return -EINVAL;
806 } else if (matches != 4) {
807 error_setg(errp, "Invalid extent lines:\n%s", p);
808 return -EINVAL;
811 if (sectors <= 0 ||
812 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
813 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
814 (strcmp(access, "RW"))) {
815 goto next_line;
818 if (!path_is_absolute(fname) && !path_has_protocol(fname) &&
819 !desc_file_path[0])
821 error_setg(errp, "Cannot use relative extent paths with VMDK "
822 "descriptor file '%s'", bs->file->filename);
823 return -EINVAL;
826 extent_path = g_malloc0(PATH_MAX);
827 path_combine(extent_path, PATH_MAX, desc_file_path, fname);
828 extent_file = NULL;
830 ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents);
831 assert(ret < 32);
833 ret = bdrv_open_image(&extent_file, extent_path, options,
834 extent_opt_prefix, bs, &child_file, false, errp);
835 g_free(extent_path);
836 if (ret) {
837 return ret;
840 /* save to extents array */
841 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
842 /* FLAT extent */
844 ret = vmdk_add_extent(bs, extent_file, true, sectors,
845 0, 0, 0, 0, 0, &extent, errp);
846 if (ret < 0) {
847 bdrv_unref(extent_file);
848 return ret;
850 extent->flat_start_offset = flat_offset << 9;
851 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
852 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
853 char *buf = vmdk_read_desc(extent_file, 0, errp);
854 if (!buf) {
855 ret = -EINVAL;
856 } else {
857 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf,
858 options, errp);
860 g_free(buf);
861 if (ret) {
862 bdrv_unref(extent_file);
863 return ret;
865 extent = &s->extents[s->num_extents - 1];
866 } else {
867 error_setg(errp, "Unsupported extent type '%s'", type);
868 bdrv_unref(extent_file);
869 return -ENOTSUP;
871 extent->type = g_strdup(type);
872 next_line:
873 /* move to next line */
874 while (*p) {
875 if (*p == '\n') {
876 p++;
877 break;
879 p++;
882 return 0;
885 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
886 QDict *options, Error **errp)
888 int ret;
889 char ct[128];
890 BDRVVmdkState *s = bs->opaque;
892 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
893 error_setg(errp, "invalid VMDK image descriptor");
894 ret = -EINVAL;
895 goto exit;
897 if (strcmp(ct, "monolithicFlat") &&
898 strcmp(ct, "vmfs") &&
899 strcmp(ct, "vmfsSparse") &&
900 strcmp(ct, "twoGbMaxExtentSparse") &&
901 strcmp(ct, "twoGbMaxExtentFlat")) {
902 error_setg(errp, "Unsupported image type '%s'", ct);
903 ret = -ENOTSUP;
904 goto exit;
906 s->create_type = g_strdup(ct);
907 s->desc_offset = 0;
908 ret = vmdk_parse_extents(buf, bs, bs->file->exact_filename, options, errp);
909 exit:
910 return ret;
913 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
914 Error **errp)
916 char *buf;
917 int ret;
918 BDRVVmdkState *s = bs->opaque;
919 uint32_t magic;
921 buf = vmdk_read_desc(bs->file, 0, errp);
922 if (!buf) {
923 return -EINVAL;
926 magic = ldl_be_p(buf);
927 switch (magic) {
928 case VMDK3_MAGIC:
929 case VMDK4_MAGIC:
930 ret = vmdk_open_sparse(bs, bs->file, flags, buf, options, errp);
931 s->desc_offset = 0x200;
932 break;
933 default:
934 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
935 break;
937 if (ret) {
938 goto fail;
941 /* try to open parent images, if exist */
942 ret = vmdk_parent_open(bs);
943 if (ret) {
944 goto fail;
946 s->cid = vmdk_read_cid(bs, 0);
947 s->parent_cid = vmdk_read_cid(bs, 1);
948 qemu_co_mutex_init(&s->lock);
950 /* Disable migration when VMDK images are used */
951 error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "
952 "does not support live migration",
953 bdrv_get_device_or_node_name(bs));
954 migrate_add_blocker(s->migration_blocker);
955 g_free(buf);
956 return 0;
958 fail:
959 g_free(buf);
960 g_free(s->create_type);
961 s->create_type = NULL;
962 vmdk_free_extents(bs);
963 return ret;
967 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
969 BDRVVmdkState *s = bs->opaque;
970 int i;
972 for (i = 0; i < s->num_extents; i++) {
973 if (!s->extents[i].flat) {
974 bs->bl.write_zeroes_alignment =
975 MAX(bs->bl.write_zeroes_alignment,
976 s->extents[i].cluster_sectors);
982 * get_whole_cluster
984 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
985 * to the cluster at @cluster_sector_num.
987 * If @skip_start_sector < @skip_end_sector, the relative range
988 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
989 * it for call to write user data in the request.
991 static int get_whole_cluster(BlockDriverState *bs,
992 VmdkExtent *extent,
993 uint64_t cluster_sector_num,
994 uint64_t sector_num,
995 uint64_t skip_start_sector,
996 uint64_t skip_end_sector)
998 int ret = VMDK_OK;
999 int64_t cluster_bytes;
1000 uint8_t *whole_grain;
1002 /* For COW, align request sector_num to cluster start */
1003 sector_num = QEMU_ALIGN_DOWN(sector_num, extent->cluster_sectors);
1004 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
1005 whole_grain = qemu_blockalign(bs, cluster_bytes);
1007 if (!bs->backing_hd) {
1008 memset(whole_grain, 0, skip_start_sector << BDRV_SECTOR_BITS);
1009 memset(whole_grain + (skip_end_sector << BDRV_SECTOR_BITS), 0,
1010 cluster_bytes - (skip_end_sector << BDRV_SECTOR_BITS));
1013 assert(skip_end_sector <= extent->cluster_sectors);
1014 /* we will be here if it's first write on non-exist grain(cluster).
1015 * try to read from parent image, if exist */
1016 if (bs->backing_hd && !vmdk_is_cid_valid(bs)) {
1017 ret = VMDK_ERROR;
1018 goto exit;
1021 /* Read backing data before skip range */
1022 if (skip_start_sector > 0) {
1023 if (bs->backing_hd) {
1024 ret = bdrv_read(bs->backing_hd, sector_num,
1025 whole_grain, skip_start_sector);
1026 if (ret < 0) {
1027 ret = VMDK_ERROR;
1028 goto exit;
1031 ret = bdrv_write(extent->file, cluster_sector_num, whole_grain,
1032 skip_start_sector);
1033 if (ret < 0) {
1034 ret = VMDK_ERROR;
1035 goto exit;
1038 /* Read backing data after skip range */
1039 if (skip_end_sector < extent->cluster_sectors) {
1040 if (bs->backing_hd) {
1041 ret = bdrv_read(bs->backing_hd, sector_num + skip_end_sector,
1042 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1043 extent->cluster_sectors - skip_end_sector);
1044 if (ret < 0) {
1045 ret = VMDK_ERROR;
1046 goto exit;
1049 ret = bdrv_write(extent->file, cluster_sector_num + skip_end_sector,
1050 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1051 extent->cluster_sectors - skip_end_sector);
1052 if (ret < 0) {
1053 ret = VMDK_ERROR;
1054 goto exit;
1058 exit:
1059 qemu_vfree(whole_grain);
1060 return ret;
1063 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1064 uint32_t offset)
1066 offset = cpu_to_le32(offset);
1067 /* update L2 table */
1068 if (bdrv_pwrite_sync(
1069 extent->file,
1070 ((int64_t)m_data->l2_offset * 512)
1071 + (m_data->l2_index * sizeof(offset)),
1072 &offset, sizeof(offset)) < 0) {
1073 return VMDK_ERROR;
1075 /* update backup L2 table */
1076 if (extent->l1_backup_table_offset != 0) {
1077 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1078 if (bdrv_pwrite_sync(
1079 extent->file,
1080 ((int64_t)m_data->l2_offset * 512)
1081 + (m_data->l2_index * sizeof(offset)),
1082 &offset, sizeof(offset)) < 0) {
1083 return VMDK_ERROR;
1086 if (m_data->l2_cache_entry) {
1087 *m_data->l2_cache_entry = offset;
1090 return VMDK_OK;
1094 * get_cluster_offset
1096 * Look up cluster offset in extent file by sector number, and store in
1097 * @cluster_offset.
1099 * For flat extents, the start offset as parsed from the description file is
1100 * returned.
1102 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1103 * offset for a new cluster and update L2 cache. If there is a backing file,
1104 * COW is done before returning; otherwise, zeroes are written to the allocated
1105 * cluster. Both COW and zero writing skips the sector range
1106 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1107 * has new data to write there.
1109 * Returns: VMDK_OK if cluster exists and mapped in the image.
1110 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1111 * VMDK_ERROR if failed.
1113 static int get_cluster_offset(BlockDriverState *bs,
1114 VmdkExtent *extent,
1115 VmdkMetaData *m_data,
1116 uint64_t offset,
1117 bool allocate,
1118 uint64_t *cluster_offset,
1119 uint64_t skip_start_sector,
1120 uint64_t skip_end_sector)
1122 unsigned int l1_index, l2_offset, l2_index;
1123 int min_index, i, j;
1124 uint32_t min_count, *l2_table;
1125 bool zeroed = false;
1126 int64_t ret;
1127 int64_t cluster_sector;
1129 if (m_data) {
1130 m_data->valid = 0;
1132 if (extent->flat) {
1133 *cluster_offset = extent->flat_start_offset;
1134 return VMDK_OK;
1137 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1138 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1139 if (l1_index >= extent->l1_size) {
1140 return VMDK_ERROR;
1142 l2_offset = extent->l1_table[l1_index];
1143 if (!l2_offset) {
1144 return VMDK_UNALLOC;
1146 for (i = 0; i < L2_CACHE_SIZE; i++) {
1147 if (l2_offset == extent->l2_cache_offsets[i]) {
1148 /* increment the hit count */
1149 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1150 for (j = 0; j < L2_CACHE_SIZE; j++) {
1151 extent->l2_cache_counts[j] >>= 1;
1154 l2_table = extent->l2_cache + (i * extent->l2_size);
1155 goto found;
1158 /* not found: load a new entry in the least used one */
1159 min_index = 0;
1160 min_count = 0xffffffff;
1161 for (i = 0; i < L2_CACHE_SIZE; i++) {
1162 if (extent->l2_cache_counts[i] < min_count) {
1163 min_count = extent->l2_cache_counts[i];
1164 min_index = i;
1167 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1168 if (bdrv_pread(
1169 extent->file,
1170 (int64_t)l2_offset * 512,
1171 l2_table,
1172 extent->l2_size * sizeof(uint32_t)
1173 ) != extent->l2_size * sizeof(uint32_t)) {
1174 return VMDK_ERROR;
1177 extent->l2_cache_offsets[min_index] = l2_offset;
1178 extent->l2_cache_counts[min_index] = 1;
1179 found:
1180 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1181 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1183 if (m_data) {
1184 m_data->valid = 1;
1185 m_data->l1_index = l1_index;
1186 m_data->l2_index = l2_index;
1187 m_data->l2_offset = l2_offset;
1188 m_data->l2_cache_entry = &l2_table[l2_index];
1190 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1191 zeroed = true;
1194 if (!cluster_sector || zeroed) {
1195 if (!allocate) {
1196 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1199 cluster_sector = extent->next_cluster_sector;
1200 extent->next_cluster_sector += extent->cluster_sectors;
1202 /* First of all we write grain itself, to avoid race condition
1203 * that may to corrupt the image.
1204 * This problem may occur because of insufficient space on host disk
1205 * or inappropriate VM shutdown.
1207 ret = get_whole_cluster(bs, extent,
1208 cluster_sector,
1209 offset >> BDRV_SECTOR_BITS,
1210 skip_start_sector, skip_end_sector);
1211 if (ret) {
1212 return ret;
1215 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1216 return VMDK_OK;
1219 static VmdkExtent *find_extent(BDRVVmdkState *s,
1220 int64_t sector_num, VmdkExtent *start_hint)
1222 VmdkExtent *extent = start_hint;
1224 if (!extent) {
1225 extent = &s->extents[0];
1227 while (extent < &s->extents[s->num_extents]) {
1228 if (sector_num < extent->end_sector) {
1229 return extent;
1231 extent++;
1233 return NULL;
1236 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent *extent,
1237 int64_t sector_num)
1239 uint64_t index_in_cluster, extent_begin_sector, extent_relative_sector_num;
1241 extent_begin_sector = extent->end_sector - extent->sectors;
1242 extent_relative_sector_num = sector_num - extent_begin_sector;
1243 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1244 return index_in_cluster;
1247 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1248 int64_t sector_num, int nb_sectors, int *pnum)
1250 BDRVVmdkState *s = bs->opaque;
1251 int64_t index_in_cluster, n, ret;
1252 uint64_t offset;
1253 VmdkExtent *extent;
1255 extent = find_extent(s, sector_num, NULL);
1256 if (!extent) {
1257 return 0;
1259 qemu_co_mutex_lock(&s->lock);
1260 ret = get_cluster_offset(bs, extent, NULL,
1261 sector_num * 512, false, &offset,
1262 0, 0);
1263 qemu_co_mutex_unlock(&s->lock);
1265 switch (ret) {
1266 case VMDK_ERROR:
1267 ret = -EIO;
1268 break;
1269 case VMDK_UNALLOC:
1270 ret = 0;
1271 break;
1272 case VMDK_ZEROED:
1273 ret = BDRV_BLOCK_ZERO;
1274 break;
1275 case VMDK_OK:
1276 ret = BDRV_BLOCK_DATA;
1277 if (extent->file == bs->file && !extent->compressed) {
1278 ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1281 break;
1284 index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1285 n = extent->cluster_sectors - index_in_cluster;
1286 if (n > nb_sectors) {
1287 n = nb_sectors;
1289 *pnum = n;
1290 return ret;
1293 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1294 int64_t offset_in_cluster, const uint8_t *buf,
1295 int nb_sectors, int64_t sector_num)
1297 int ret;
1298 VmdkGrainMarker *data = NULL;
1299 uLongf buf_len;
1300 const uint8_t *write_buf = buf;
1301 int write_len = nb_sectors * 512;
1302 int64_t write_offset;
1303 int64_t write_end_sector;
1305 if (extent->compressed) {
1306 if (!extent->has_marker) {
1307 ret = -EINVAL;
1308 goto out;
1310 buf_len = (extent->cluster_sectors << 9) * 2;
1311 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1312 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1313 buf_len == 0) {
1314 ret = -EINVAL;
1315 goto out;
1317 data->lba = sector_num;
1318 data->size = buf_len;
1319 write_buf = (uint8_t *)data;
1320 write_len = buf_len + sizeof(VmdkGrainMarker);
1322 write_offset = cluster_offset + offset_in_cluster,
1323 ret = bdrv_pwrite(extent->file, write_offset, write_buf, write_len);
1325 write_end_sector = DIV_ROUND_UP(write_offset + write_len, BDRV_SECTOR_SIZE);
1327 if (extent->compressed) {
1328 extent->next_cluster_sector = write_end_sector;
1329 } else {
1330 extent->next_cluster_sector = MAX(extent->next_cluster_sector,
1331 write_end_sector);
1334 if (ret != write_len) {
1335 ret = ret < 0 ? ret : -EIO;
1336 goto out;
1338 ret = 0;
1339 out:
1340 g_free(data);
1341 return ret;
1344 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1345 int64_t offset_in_cluster, uint8_t *buf,
1346 int nb_sectors)
1348 int ret;
1349 int cluster_bytes, buf_bytes;
1350 uint8_t *cluster_buf, *compressed_data;
1351 uint8_t *uncomp_buf;
1352 uint32_t data_len;
1353 VmdkGrainMarker *marker;
1354 uLongf buf_len;
1357 if (!extent->compressed) {
1358 ret = bdrv_pread(extent->file,
1359 cluster_offset + offset_in_cluster,
1360 buf, nb_sectors * 512);
1361 if (ret == nb_sectors * 512) {
1362 return 0;
1363 } else {
1364 return -EIO;
1367 cluster_bytes = extent->cluster_sectors * 512;
1368 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1369 buf_bytes = cluster_bytes * 2;
1370 cluster_buf = g_malloc(buf_bytes);
1371 uncomp_buf = g_malloc(cluster_bytes);
1372 ret = bdrv_pread(extent->file,
1373 cluster_offset,
1374 cluster_buf, buf_bytes);
1375 if (ret < 0) {
1376 goto out;
1378 compressed_data = cluster_buf;
1379 buf_len = cluster_bytes;
1380 data_len = cluster_bytes;
1381 if (extent->has_marker) {
1382 marker = (VmdkGrainMarker *)cluster_buf;
1383 compressed_data = marker->data;
1384 data_len = le32_to_cpu(marker->size);
1386 if (!data_len || data_len > buf_bytes) {
1387 ret = -EINVAL;
1388 goto out;
1390 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1391 if (ret != Z_OK) {
1392 ret = -EINVAL;
1393 goto out;
1396 if (offset_in_cluster < 0 ||
1397 offset_in_cluster + nb_sectors * 512 > buf_len) {
1398 ret = -EINVAL;
1399 goto out;
1401 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1402 ret = 0;
1404 out:
1405 g_free(uncomp_buf);
1406 g_free(cluster_buf);
1407 return ret;
1410 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1411 uint8_t *buf, int nb_sectors)
1413 BDRVVmdkState *s = bs->opaque;
1414 int ret;
1415 uint64_t n, index_in_cluster;
1416 VmdkExtent *extent = NULL;
1417 uint64_t cluster_offset;
1419 while (nb_sectors > 0) {
1420 extent = find_extent(s, sector_num, extent);
1421 if (!extent) {
1422 return -EIO;
1424 ret = get_cluster_offset(bs, extent, NULL,
1425 sector_num << 9, false, &cluster_offset,
1426 0, 0);
1427 index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1428 n = extent->cluster_sectors - index_in_cluster;
1429 if (n > nb_sectors) {
1430 n = nb_sectors;
1432 if (ret != VMDK_OK) {
1433 /* if not allocated, try to read from parent image, if exist */
1434 if (bs->backing_hd && ret != VMDK_ZEROED) {
1435 if (!vmdk_is_cid_valid(bs)) {
1436 return -EINVAL;
1438 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1439 if (ret < 0) {
1440 return ret;
1442 } else {
1443 memset(buf, 0, 512 * n);
1445 } else {
1446 ret = vmdk_read_extent(extent,
1447 cluster_offset, index_in_cluster * 512,
1448 buf, n);
1449 if (ret) {
1450 return ret;
1453 nb_sectors -= n;
1454 sector_num += n;
1455 buf += n * 512;
1457 return 0;
1460 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1461 uint8_t *buf, int nb_sectors)
1463 int ret;
1464 BDRVVmdkState *s = bs->opaque;
1465 qemu_co_mutex_lock(&s->lock);
1466 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1467 qemu_co_mutex_unlock(&s->lock);
1468 return ret;
1472 * vmdk_write:
1473 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1474 * if possible, otherwise return -ENOTSUP.
1475 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1476 * with each cluster. By dry run we can find if the zero write
1477 * is possible without modifying image data.
1479 * Returns: error code with 0 for success.
1481 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1482 const uint8_t *buf, int nb_sectors,
1483 bool zeroed, bool zero_dry_run)
1485 BDRVVmdkState *s = bs->opaque;
1486 VmdkExtent *extent = NULL;
1487 int ret;
1488 int64_t index_in_cluster, n;
1489 uint64_t cluster_offset;
1490 VmdkMetaData m_data;
1492 if (sector_num > bs->total_sectors) {
1493 error_report("Wrong offset: sector_num=0x%" PRIx64
1494 " total_sectors=0x%" PRIx64 "\n",
1495 sector_num, bs->total_sectors);
1496 return -EIO;
1499 while (nb_sectors > 0) {
1500 extent = find_extent(s, sector_num, extent);
1501 if (!extent) {
1502 return -EIO;
1504 index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1505 n = extent->cluster_sectors - index_in_cluster;
1506 if (n > nb_sectors) {
1507 n = nb_sectors;
1509 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1510 !(extent->compressed || zeroed),
1511 &cluster_offset,
1512 index_in_cluster, index_in_cluster + n);
1513 if (extent->compressed) {
1514 if (ret == VMDK_OK) {
1515 /* Refuse write to allocated cluster for streamOptimized */
1516 error_report("Could not write to allocated cluster"
1517 " for streamOptimized");
1518 return -EIO;
1519 } else {
1520 /* allocate */
1521 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1522 true, &cluster_offset, 0, 0);
1525 if (ret == VMDK_ERROR) {
1526 return -EINVAL;
1528 if (zeroed) {
1529 /* Do zeroed write, buf is ignored */
1530 if (extent->has_zero_grain &&
1531 index_in_cluster == 0 &&
1532 n >= extent->cluster_sectors) {
1533 n = extent->cluster_sectors;
1534 if (!zero_dry_run) {
1535 /* update L2 tables */
1536 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1537 != VMDK_OK) {
1538 return -EIO;
1541 } else {
1542 return -ENOTSUP;
1544 } else {
1545 ret = vmdk_write_extent(extent,
1546 cluster_offset, index_in_cluster * 512,
1547 buf, n, sector_num);
1548 if (ret) {
1549 return ret;
1551 if (m_data.valid) {
1552 /* update L2 tables */
1553 if (vmdk_L2update(extent, &m_data,
1554 cluster_offset >> BDRV_SECTOR_BITS)
1555 != VMDK_OK) {
1556 return -EIO;
1560 nb_sectors -= n;
1561 sector_num += n;
1562 buf += n * 512;
1564 /* update CID on the first write every time the virtual disk is
1565 * opened */
1566 if (!s->cid_updated) {
1567 ret = vmdk_write_cid(bs, g_random_int());
1568 if (ret < 0) {
1569 return ret;
1571 s->cid_updated = true;
1574 return 0;
1577 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1578 const uint8_t *buf, int nb_sectors)
1580 int ret;
1581 BDRVVmdkState *s = bs->opaque;
1582 qemu_co_mutex_lock(&s->lock);
1583 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1584 qemu_co_mutex_unlock(&s->lock);
1585 return ret;
1588 static int vmdk_write_compressed(BlockDriverState *bs,
1589 int64_t sector_num,
1590 const uint8_t *buf,
1591 int nb_sectors)
1593 BDRVVmdkState *s = bs->opaque;
1594 if (s->num_extents == 1 && s->extents[0].compressed) {
1595 return vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1596 } else {
1597 return -ENOTSUP;
1601 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1602 int64_t sector_num,
1603 int nb_sectors,
1604 BdrvRequestFlags flags)
1606 int ret;
1607 BDRVVmdkState *s = bs->opaque;
1608 qemu_co_mutex_lock(&s->lock);
1609 /* write zeroes could fail if sectors not aligned to cluster, test it with
1610 * dry_run == true before really updating image */
1611 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1612 if (!ret) {
1613 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1615 qemu_co_mutex_unlock(&s->lock);
1616 return ret;
1619 static int vmdk_create_extent(const char *filename, int64_t filesize,
1620 bool flat, bool compress, bool zeroed_grain,
1621 QemuOpts *opts, Error **errp)
1623 int ret, i;
1624 BlockDriverState *bs = NULL;
1625 VMDK4Header header;
1626 Error *local_err = NULL;
1627 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1628 uint32_t *gd_buf = NULL;
1629 int gd_buf_size;
1631 ret = bdrv_create_file(filename, opts, &local_err);
1632 if (ret < 0) {
1633 error_propagate(errp, local_err);
1634 goto exit;
1637 assert(bs == NULL);
1638 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1639 &local_err);
1640 if (ret < 0) {
1641 error_propagate(errp, local_err);
1642 goto exit;
1645 if (flat) {
1646 ret = bdrv_truncate(bs, filesize);
1647 if (ret < 0) {
1648 error_setg_errno(errp, -ret, "Could not truncate file");
1650 goto exit;
1652 magic = cpu_to_be32(VMDK4_MAGIC);
1653 memset(&header, 0, sizeof(header));
1654 header.version = zeroed_grain ? 2 : 1;
1655 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1656 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1657 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1658 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1659 header.capacity = filesize / BDRV_SECTOR_SIZE;
1660 header.granularity = 128;
1661 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1663 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1664 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1665 BDRV_SECTOR_SIZE);
1666 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1667 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1669 header.desc_offset = 1;
1670 header.desc_size = 20;
1671 header.rgd_offset = header.desc_offset + header.desc_size;
1672 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1673 header.grain_offset =
1674 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1675 header.granularity);
1676 /* swap endianness for all header fields */
1677 header.version = cpu_to_le32(header.version);
1678 header.flags = cpu_to_le32(header.flags);
1679 header.capacity = cpu_to_le64(header.capacity);
1680 header.granularity = cpu_to_le64(header.granularity);
1681 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1682 header.desc_offset = cpu_to_le64(header.desc_offset);
1683 header.desc_size = cpu_to_le64(header.desc_size);
1684 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1685 header.gd_offset = cpu_to_le64(header.gd_offset);
1686 header.grain_offset = cpu_to_le64(header.grain_offset);
1687 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1689 header.check_bytes[0] = 0xa;
1690 header.check_bytes[1] = 0x20;
1691 header.check_bytes[2] = 0xd;
1692 header.check_bytes[3] = 0xa;
1694 /* write all the data */
1695 ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1696 if (ret < 0) {
1697 error_setg(errp, QERR_IO_ERROR);
1698 goto exit;
1700 ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1701 if (ret < 0) {
1702 error_setg(errp, QERR_IO_ERROR);
1703 goto exit;
1706 ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1707 if (ret < 0) {
1708 error_setg_errno(errp, -ret, "Could not truncate file");
1709 goto exit;
1712 /* write grain directory */
1713 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1714 gd_buf = g_malloc0(gd_buf_size);
1715 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1716 i < gt_count; i++, tmp += gt_size) {
1717 gd_buf[i] = cpu_to_le32(tmp);
1719 ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1720 gd_buf, gd_buf_size);
1721 if (ret < 0) {
1722 error_setg(errp, QERR_IO_ERROR);
1723 goto exit;
1726 /* write backup grain directory */
1727 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1728 i < gt_count; i++, tmp += gt_size) {
1729 gd_buf[i] = cpu_to_le32(tmp);
1731 ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1732 gd_buf, gd_buf_size);
1733 if (ret < 0) {
1734 error_setg(errp, QERR_IO_ERROR);
1735 goto exit;
1738 ret = 0;
1739 exit:
1740 if (bs) {
1741 bdrv_unref(bs);
1743 g_free(gd_buf);
1744 return ret;
1747 static int filename_decompose(const char *filename, char *path, char *prefix,
1748 char *postfix, size_t buf_len, Error **errp)
1750 const char *p, *q;
1752 if (filename == NULL || !strlen(filename)) {
1753 error_setg(errp, "No filename provided");
1754 return VMDK_ERROR;
1756 p = strrchr(filename, '/');
1757 if (p == NULL) {
1758 p = strrchr(filename, '\\');
1760 if (p == NULL) {
1761 p = strrchr(filename, ':');
1763 if (p != NULL) {
1764 p++;
1765 if (p - filename >= buf_len) {
1766 return VMDK_ERROR;
1768 pstrcpy(path, p - filename + 1, filename);
1769 } else {
1770 p = filename;
1771 path[0] = '\0';
1773 q = strrchr(p, '.');
1774 if (q == NULL) {
1775 pstrcpy(prefix, buf_len, p);
1776 postfix[0] = '\0';
1777 } else {
1778 if (q - p >= buf_len) {
1779 return VMDK_ERROR;
1781 pstrcpy(prefix, q - p + 1, p);
1782 pstrcpy(postfix, buf_len, q);
1784 return VMDK_OK;
1787 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1789 int idx = 0;
1790 BlockDriverState *new_bs = NULL;
1791 Error *local_err = NULL;
1792 char *desc = NULL;
1793 int64_t total_size = 0, filesize;
1794 char *adapter_type = NULL;
1795 char *backing_file = NULL;
1796 char *fmt = NULL;
1797 int flags = 0;
1798 int ret = 0;
1799 bool flat, split, compress;
1800 GString *ext_desc_lines;
1801 char *path = g_malloc0(PATH_MAX);
1802 char *prefix = g_malloc0(PATH_MAX);
1803 char *postfix = g_malloc0(PATH_MAX);
1804 char *desc_line = g_malloc0(BUF_SIZE);
1805 char *ext_filename = g_malloc0(PATH_MAX);
1806 char *desc_filename = g_malloc0(PATH_MAX);
1807 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1808 const char *desc_extent_line;
1809 char *parent_desc_line = g_malloc0(BUF_SIZE);
1810 uint32_t parent_cid = 0xffffffff;
1811 uint32_t number_heads = 16;
1812 bool zeroed_grain = false;
1813 uint32_t desc_offset = 0, desc_len;
1814 const char desc_template[] =
1815 "# Disk DescriptorFile\n"
1816 "version=1\n"
1817 "CID=%" PRIx32 "\n"
1818 "parentCID=%" PRIx32 "\n"
1819 "createType=\"%s\"\n"
1820 "%s"
1821 "\n"
1822 "# Extent description\n"
1823 "%s"
1824 "\n"
1825 "# The Disk Data Base\n"
1826 "#DDB\n"
1827 "\n"
1828 "ddb.virtualHWVersion = \"%d\"\n"
1829 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1830 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1831 "ddb.geometry.sectors = \"63\"\n"
1832 "ddb.adapterType = \"%s\"\n";
1834 ext_desc_lines = g_string_new(NULL);
1836 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1837 ret = -EINVAL;
1838 goto exit;
1840 /* Read out options */
1841 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1842 BDRV_SECTOR_SIZE);
1843 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1844 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1845 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1846 flags |= BLOCK_FLAG_COMPAT6;
1848 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1849 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1850 zeroed_grain = true;
1853 if (!adapter_type) {
1854 adapter_type = g_strdup("ide");
1855 } else if (strcmp(adapter_type, "ide") &&
1856 strcmp(adapter_type, "buslogic") &&
1857 strcmp(adapter_type, "lsilogic") &&
1858 strcmp(adapter_type, "legacyESX")) {
1859 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1860 ret = -EINVAL;
1861 goto exit;
1863 if (strcmp(adapter_type, "ide") != 0) {
1864 /* that's the number of heads with which vmware operates when
1865 creating, exporting, etc. vmdk files with a non-ide adapter type */
1866 number_heads = 255;
1868 if (!fmt) {
1869 /* Default format to monolithicSparse */
1870 fmt = g_strdup("monolithicSparse");
1871 } else if (strcmp(fmt, "monolithicFlat") &&
1872 strcmp(fmt, "monolithicSparse") &&
1873 strcmp(fmt, "twoGbMaxExtentSparse") &&
1874 strcmp(fmt, "twoGbMaxExtentFlat") &&
1875 strcmp(fmt, "streamOptimized")) {
1876 error_setg(errp, "Unknown subformat: '%s'", fmt);
1877 ret = -EINVAL;
1878 goto exit;
1880 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1881 strcmp(fmt, "twoGbMaxExtentSparse"));
1882 flat = !(strcmp(fmt, "monolithicFlat") &&
1883 strcmp(fmt, "twoGbMaxExtentFlat"));
1884 compress = !strcmp(fmt, "streamOptimized");
1885 if (flat) {
1886 desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1887 } else {
1888 desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1890 if (flat && backing_file) {
1891 error_setg(errp, "Flat image can't have backing file");
1892 ret = -ENOTSUP;
1893 goto exit;
1895 if (flat && zeroed_grain) {
1896 error_setg(errp, "Flat image can't enable zeroed grain");
1897 ret = -ENOTSUP;
1898 goto exit;
1900 if (backing_file) {
1901 BlockDriverState *bs = NULL;
1902 char *full_backing = g_new0(char, PATH_MAX);
1903 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
1904 full_backing, PATH_MAX,
1905 &local_err);
1906 if (local_err) {
1907 g_free(full_backing);
1908 error_propagate(errp, local_err);
1909 ret = -ENOENT;
1910 goto exit;
1912 ret = bdrv_open(&bs, full_backing, NULL, NULL, BDRV_O_NO_BACKING, errp);
1913 g_free(full_backing);
1914 if (ret != 0) {
1915 goto exit;
1917 if (strcmp(bs->drv->format_name, "vmdk")) {
1918 bdrv_unref(bs);
1919 ret = -EINVAL;
1920 goto exit;
1922 parent_cid = vmdk_read_cid(bs, 0);
1923 bdrv_unref(bs);
1924 snprintf(parent_desc_line, BUF_SIZE,
1925 "parentFileNameHint=\"%s\"", backing_file);
1928 /* Create extents */
1929 filesize = total_size;
1930 while (filesize > 0) {
1931 int64_t size = filesize;
1933 if (split && size > split_size) {
1934 size = split_size;
1936 if (split) {
1937 snprintf(desc_filename, PATH_MAX, "%s-%c%03d%s",
1938 prefix, flat ? 'f' : 's', ++idx, postfix);
1939 } else if (flat) {
1940 snprintf(desc_filename, PATH_MAX, "%s-flat%s", prefix, postfix);
1941 } else {
1942 snprintf(desc_filename, PATH_MAX, "%s%s", prefix, postfix);
1944 snprintf(ext_filename, PATH_MAX, "%s%s", path, desc_filename);
1946 if (vmdk_create_extent(ext_filename, size,
1947 flat, compress, zeroed_grain, opts, errp)) {
1948 ret = -EINVAL;
1949 goto exit;
1951 filesize -= size;
1953 /* Format description line */
1954 snprintf(desc_line, BUF_SIZE,
1955 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1956 g_string_append(ext_desc_lines, desc_line);
1958 /* generate descriptor file */
1959 desc = g_strdup_printf(desc_template,
1960 g_random_int(),
1961 parent_cid,
1962 fmt,
1963 parent_desc_line,
1964 ext_desc_lines->str,
1965 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1966 total_size /
1967 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1968 number_heads,
1969 adapter_type);
1970 desc_len = strlen(desc);
1971 /* the descriptor offset = 0x200 */
1972 if (!split && !flat) {
1973 desc_offset = 0x200;
1974 } else {
1975 ret = bdrv_create_file(filename, opts, &local_err);
1976 if (ret < 0) {
1977 error_propagate(errp, local_err);
1978 goto exit;
1981 assert(new_bs == NULL);
1982 ret = bdrv_open(&new_bs, filename, NULL, NULL,
1983 BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
1984 if (ret < 0) {
1985 error_propagate(errp, local_err);
1986 goto exit;
1988 ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1989 if (ret < 0) {
1990 error_setg_errno(errp, -ret, "Could not write description");
1991 goto exit;
1993 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1994 * for description file */
1995 if (desc_offset == 0) {
1996 ret = bdrv_truncate(new_bs, desc_len);
1997 if (ret < 0) {
1998 error_setg_errno(errp, -ret, "Could not truncate file");
2001 exit:
2002 if (new_bs) {
2003 bdrv_unref(new_bs);
2005 g_free(adapter_type);
2006 g_free(backing_file);
2007 g_free(fmt);
2008 g_free(desc);
2009 g_free(path);
2010 g_free(prefix);
2011 g_free(postfix);
2012 g_free(desc_line);
2013 g_free(ext_filename);
2014 g_free(desc_filename);
2015 g_free(parent_desc_line);
2016 g_string_free(ext_desc_lines, true);
2017 return ret;
2020 static void vmdk_close(BlockDriverState *bs)
2022 BDRVVmdkState *s = bs->opaque;
2024 vmdk_free_extents(bs);
2025 g_free(s->create_type);
2027 migrate_del_blocker(s->migration_blocker);
2028 error_free(s->migration_blocker);
2031 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
2033 BDRVVmdkState *s = bs->opaque;
2034 int i, err;
2035 int ret = 0;
2037 for (i = 0; i < s->num_extents; i++) {
2038 err = bdrv_co_flush(s->extents[i].file);
2039 if (err < 0) {
2040 ret = err;
2043 return ret;
2046 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2048 int i;
2049 int64_t ret = 0;
2050 int64_t r;
2051 BDRVVmdkState *s = bs->opaque;
2053 ret = bdrv_get_allocated_file_size(bs->file);
2054 if (ret < 0) {
2055 return ret;
2057 for (i = 0; i < s->num_extents; i++) {
2058 if (s->extents[i].file == bs->file) {
2059 continue;
2061 r = bdrv_get_allocated_file_size(s->extents[i].file);
2062 if (r < 0) {
2063 return r;
2065 ret += r;
2067 return ret;
2070 static int vmdk_has_zero_init(BlockDriverState *bs)
2072 int i;
2073 BDRVVmdkState *s = bs->opaque;
2075 /* If has a flat extent and its underlying storage doesn't have zero init,
2076 * return 0. */
2077 for (i = 0; i < s->num_extents; i++) {
2078 if (s->extents[i].flat) {
2079 if (!bdrv_has_zero_init(s->extents[i].file)) {
2080 return 0;
2084 return 1;
2087 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2089 ImageInfo *info = g_new0(ImageInfo, 1);
2091 *info = (ImageInfo){
2092 .filename = g_strdup(extent->file->filename),
2093 .format = g_strdup(extent->type),
2094 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2095 .compressed = extent->compressed,
2096 .has_compressed = extent->compressed,
2097 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2098 .has_cluster_size = !extent->flat,
2101 return info;
2104 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2105 BdrvCheckMode fix)
2107 BDRVVmdkState *s = bs->opaque;
2108 VmdkExtent *extent = NULL;
2109 int64_t sector_num = 0;
2110 int64_t total_sectors = bdrv_nb_sectors(bs);
2111 int ret;
2112 uint64_t cluster_offset;
2114 if (fix) {
2115 return -ENOTSUP;
2118 for (;;) {
2119 if (sector_num >= total_sectors) {
2120 return 0;
2122 extent = find_extent(s, sector_num, extent);
2123 if (!extent) {
2124 fprintf(stderr,
2125 "ERROR: could not find extent for sector %" PRId64 "\n",
2126 sector_num);
2127 break;
2129 ret = get_cluster_offset(bs, extent, NULL,
2130 sector_num << BDRV_SECTOR_BITS,
2131 false, &cluster_offset, 0, 0);
2132 if (ret == VMDK_ERROR) {
2133 fprintf(stderr,
2134 "ERROR: could not get cluster_offset for sector %"
2135 PRId64 "\n", sector_num);
2136 break;
2138 if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2139 fprintf(stderr,
2140 "ERROR: cluster offset for sector %"
2141 PRId64 " points after EOF\n", sector_num);
2142 break;
2144 sector_num += extent->cluster_sectors;
2147 result->corruptions++;
2148 return 0;
2151 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2153 int i;
2154 BDRVVmdkState *s = bs->opaque;
2155 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2156 ImageInfoList **next;
2158 *spec_info = (ImageInfoSpecific){
2159 .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2161 .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2165 *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2166 .create_type = g_strdup(s->create_type),
2167 .cid = s->cid,
2168 .parent_cid = s->parent_cid,
2171 next = &spec_info->vmdk->extents;
2172 for (i = 0; i < s->num_extents; i++) {
2173 *next = g_new0(ImageInfoList, 1);
2174 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2175 (*next)->next = NULL;
2176 next = &(*next)->next;
2179 return spec_info;
2182 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2184 return a->flat == b->flat &&
2185 a->compressed == b->compressed &&
2186 (a->flat || a->cluster_sectors == b->cluster_sectors);
2189 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2191 int i;
2192 BDRVVmdkState *s = bs->opaque;
2193 assert(s->num_extents);
2195 /* See if we have multiple extents but they have different cases */
2196 for (i = 1; i < s->num_extents; i++) {
2197 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2198 return -ENOTSUP;
2201 bdi->needs_compressed_writes = s->extents[0].compressed;
2202 if (!s->extents[0].flat) {
2203 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2205 return 0;
2208 static void vmdk_detach_aio_context(BlockDriverState *bs)
2210 BDRVVmdkState *s = bs->opaque;
2211 int i;
2213 for (i = 0; i < s->num_extents; i++) {
2214 bdrv_detach_aio_context(s->extents[i].file);
2218 static void vmdk_attach_aio_context(BlockDriverState *bs,
2219 AioContext *new_context)
2221 BDRVVmdkState *s = bs->opaque;
2222 int i;
2224 for (i = 0; i < s->num_extents; i++) {
2225 bdrv_attach_aio_context(s->extents[i].file, new_context);
2229 static QemuOptsList vmdk_create_opts = {
2230 .name = "vmdk-create-opts",
2231 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2232 .desc = {
2234 .name = BLOCK_OPT_SIZE,
2235 .type = QEMU_OPT_SIZE,
2236 .help = "Virtual disk size"
2239 .name = BLOCK_OPT_ADAPTER_TYPE,
2240 .type = QEMU_OPT_STRING,
2241 .help = "Virtual adapter type, can be one of "
2242 "ide (default), lsilogic, buslogic or legacyESX"
2245 .name = BLOCK_OPT_BACKING_FILE,
2246 .type = QEMU_OPT_STRING,
2247 .help = "File name of a base image"
2250 .name = BLOCK_OPT_COMPAT6,
2251 .type = QEMU_OPT_BOOL,
2252 .help = "VMDK version 6 image",
2253 .def_value_str = "off"
2256 .name = BLOCK_OPT_SUBFMT,
2257 .type = QEMU_OPT_STRING,
2258 .help =
2259 "VMDK flat extent format, can be one of "
2260 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2263 .name = BLOCK_OPT_ZEROED_GRAIN,
2264 .type = QEMU_OPT_BOOL,
2265 .help = "Enable efficient zero writes "
2266 "using the zeroed-grain GTE feature"
2268 { /* end of list */ }
2272 static BlockDriver bdrv_vmdk = {
2273 .format_name = "vmdk",
2274 .instance_size = sizeof(BDRVVmdkState),
2275 .bdrv_probe = vmdk_probe,
2276 .bdrv_open = vmdk_open,
2277 .bdrv_check = vmdk_check,
2278 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2279 .bdrv_read = vmdk_co_read,
2280 .bdrv_write = vmdk_co_write,
2281 .bdrv_write_compressed = vmdk_write_compressed,
2282 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
2283 .bdrv_close = vmdk_close,
2284 .bdrv_create = vmdk_create,
2285 .bdrv_co_flush_to_disk = vmdk_co_flush,
2286 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2287 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2288 .bdrv_has_zero_init = vmdk_has_zero_init,
2289 .bdrv_get_specific_info = vmdk_get_specific_info,
2290 .bdrv_refresh_limits = vmdk_refresh_limits,
2291 .bdrv_get_info = vmdk_get_info,
2292 .bdrv_detach_aio_context = vmdk_detach_aio_context,
2293 .bdrv_attach_aio_context = vmdk_attach_aio_context,
2295 .supports_backing = true,
2296 .create_opts = &vmdk_create_opts,
2299 static void bdrv_vmdk_init(void)
2301 bdrv_register(&bdrv_vmdk);
2304 block_init(bdrv_vmdk_init);