qapi: add support for mice with extra/side buttons
[qemu/kevin.git] / block / vmdk.c
blob7750212969feaa512385777c5101e9d93d15df47
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/osdep.h"
27 #include "qapi/error.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qemu/error-report.h"
32 #include "qemu/module.h"
33 #include "qemu/bswap.h"
34 #include "migration/migration.h"
35 #include "qemu/cutils.h"
36 #include <zlib.h>
38 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
39 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
40 #define VMDK4_COMPRESSION_DEFLATE 1
41 #define VMDK4_FLAG_NL_DETECT (1 << 0)
42 #define VMDK4_FLAG_RGD (1 << 1)
43 /* Zeroed-grain enable bit */
44 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
45 #define VMDK4_FLAG_COMPRESS (1 << 16)
46 #define VMDK4_FLAG_MARKER (1 << 17)
47 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
49 #define VMDK_GTE_ZEROED 0x1
51 /* VMDK internal error codes */
52 #define VMDK_OK 0
53 #define VMDK_ERROR (-1)
54 /* Cluster not allocated */
55 #define VMDK_UNALLOC (-2)
56 #define VMDK_ZEROED (-3)
58 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
60 typedef struct {
61 uint32_t version;
62 uint32_t flags;
63 uint32_t disk_sectors;
64 uint32_t granularity;
65 uint32_t l1dir_offset;
66 uint32_t l1dir_size;
67 uint32_t file_sectors;
68 uint32_t cylinders;
69 uint32_t heads;
70 uint32_t sectors_per_track;
71 } QEMU_PACKED VMDK3Header;
73 typedef struct {
74 uint32_t version;
75 uint32_t flags;
76 uint64_t capacity;
77 uint64_t granularity;
78 uint64_t desc_offset;
79 uint64_t desc_size;
80 /* Number of GrainTableEntries per GrainTable */
81 uint32_t num_gtes_per_gt;
82 uint64_t rgd_offset;
83 uint64_t gd_offset;
84 uint64_t grain_offset;
85 char filler[1];
86 char check_bytes[4];
87 uint16_t compressAlgorithm;
88 } QEMU_PACKED VMDK4Header;
90 #define L2_CACHE_SIZE 16
92 typedef struct VmdkExtent {
93 BdrvChild *file;
94 bool flat;
95 bool compressed;
96 bool has_marker;
97 bool has_zero_grain;
98 int version;
99 int64_t sectors;
100 int64_t end_sector;
101 int64_t flat_start_offset;
102 int64_t l1_table_offset;
103 int64_t l1_backup_table_offset;
104 uint32_t *l1_table;
105 uint32_t *l1_backup_table;
106 unsigned int l1_size;
107 uint32_t l1_entry_sectors;
109 unsigned int l2_size;
110 uint32_t *l2_cache;
111 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
112 uint32_t l2_cache_counts[L2_CACHE_SIZE];
114 int64_t cluster_sectors;
115 int64_t next_cluster_sector;
116 char *type;
117 } VmdkExtent;
119 typedef struct BDRVVmdkState {
120 CoMutex lock;
121 uint64_t desc_offset;
122 bool cid_updated;
123 bool cid_checked;
124 uint32_t cid;
125 uint32_t parent_cid;
126 int num_extents;
127 /* Extent array with num_extents entries, ascend ordered by address */
128 VmdkExtent *extents;
129 Error *migration_blocker;
130 char *create_type;
131 } BDRVVmdkState;
133 typedef struct VmdkMetaData {
134 unsigned int l1_index;
135 unsigned int l2_index;
136 unsigned int l2_offset;
137 int valid;
138 uint32_t *l2_cache_entry;
139 } VmdkMetaData;
141 typedef struct VmdkGrainMarker {
142 uint64_t lba;
143 uint32_t size;
144 uint8_t data[0];
145 } QEMU_PACKED VmdkGrainMarker;
147 enum {
148 MARKER_END_OF_STREAM = 0,
149 MARKER_GRAIN_TABLE = 1,
150 MARKER_GRAIN_DIRECTORY = 2,
151 MARKER_FOOTER = 3,
154 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
156 uint32_t magic;
158 if (buf_size < 4) {
159 return 0;
161 magic = be32_to_cpu(*(uint32_t *)buf);
162 if (magic == VMDK3_MAGIC ||
163 magic == VMDK4_MAGIC) {
164 return 100;
165 } else {
166 const char *p = (const char *)buf;
167 const char *end = p + buf_size;
168 while (p < end) {
169 if (*p == '#') {
170 /* skip comment line */
171 while (p < end && *p != '\n') {
172 p++;
174 p++;
175 continue;
177 if (*p == ' ') {
178 while (p < end && *p == ' ') {
179 p++;
181 /* skip '\r' if windows line endings used. */
182 if (p < end && *p == '\r') {
183 p++;
185 /* only accept blank lines before 'version=' line */
186 if (p == end || *p != '\n') {
187 return 0;
189 p++;
190 continue;
192 if (end - p >= strlen("version=X\n")) {
193 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
194 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
195 return 100;
198 if (end - p >= strlen("version=X\r\n")) {
199 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
200 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
201 return 100;
204 return 0;
206 return 0;
210 #define SECTOR_SIZE 512
211 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
212 #define BUF_SIZE 4096
213 #define HEADER_SIZE 512 /* first sector of 512 bytes */
215 static void vmdk_free_extents(BlockDriverState *bs)
217 int i;
218 BDRVVmdkState *s = bs->opaque;
219 VmdkExtent *e;
221 for (i = 0; i < s->num_extents; i++) {
222 e = &s->extents[i];
223 g_free(e->l1_table);
224 g_free(e->l2_cache);
225 g_free(e->l1_backup_table);
226 g_free(e->type);
227 if (e->file != bs->file) {
228 bdrv_unref_child(bs, e->file);
231 g_free(s->extents);
234 static void vmdk_free_last_extent(BlockDriverState *bs)
236 BDRVVmdkState *s = bs->opaque;
238 if (s->num_extents == 0) {
239 return;
241 s->num_extents--;
242 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
245 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
247 char *desc;
248 uint32_t cid = 0xffffffff;
249 const char *p_name, *cid_str;
250 size_t cid_str_size;
251 BDRVVmdkState *s = bs->opaque;
252 int ret;
254 desc = g_malloc0(DESC_SIZE);
255 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
256 if (ret < 0) {
257 g_free(desc);
258 return 0;
261 if (parent) {
262 cid_str = "parentCID";
263 cid_str_size = sizeof("parentCID");
264 } else {
265 cid_str = "CID";
266 cid_str_size = sizeof("CID");
269 desc[DESC_SIZE - 1] = '\0';
270 p_name = strstr(desc, cid_str);
271 if (p_name != NULL) {
272 p_name += cid_str_size;
273 sscanf(p_name, "%" SCNx32, &cid);
276 g_free(desc);
277 return cid;
280 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
282 char *desc, *tmp_desc;
283 char *p_name, *tmp_str;
284 BDRVVmdkState *s = bs->opaque;
285 int ret = 0;
287 desc = g_malloc0(DESC_SIZE);
288 tmp_desc = g_malloc0(DESC_SIZE);
289 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
290 if (ret < 0) {
291 goto out;
294 desc[DESC_SIZE - 1] = '\0';
295 tmp_str = strstr(desc, "parentCID");
296 if (tmp_str == NULL) {
297 ret = -EINVAL;
298 goto out;
301 pstrcpy(tmp_desc, DESC_SIZE, tmp_str);
302 p_name = strstr(desc, "CID");
303 if (p_name != NULL) {
304 p_name += sizeof("CID");
305 snprintf(p_name, DESC_SIZE - (p_name - desc), "%" PRIx32 "\n", cid);
306 pstrcat(desc, DESC_SIZE, tmp_desc);
309 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
311 out:
312 g_free(desc);
313 g_free(tmp_desc);
314 return ret;
317 static int vmdk_is_cid_valid(BlockDriverState *bs)
319 BDRVVmdkState *s = bs->opaque;
320 uint32_t cur_pcid;
322 if (!s->cid_checked && bs->backing) {
323 BlockDriverState *p_bs = bs->backing->bs;
325 cur_pcid = vmdk_read_cid(p_bs, 0);
326 if (s->parent_cid != cur_pcid) {
327 /* CID not valid */
328 return 0;
331 s->cid_checked = true;
332 /* CID valid */
333 return 1;
336 /* We have nothing to do for VMDK reopen, stubs just return success */
337 static int vmdk_reopen_prepare(BDRVReopenState *state,
338 BlockReopenQueue *queue, Error **errp)
340 assert(state != NULL);
341 assert(state->bs != NULL);
342 return 0;
345 static int vmdk_parent_open(BlockDriverState *bs)
347 char *p_name;
348 char *desc;
349 BDRVVmdkState *s = bs->opaque;
350 int ret;
352 desc = g_malloc0(DESC_SIZE + 1);
353 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
354 if (ret < 0) {
355 goto out;
357 ret = 0;
359 p_name = strstr(desc, "parentFileNameHint");
360 if (p_name != NULL) {
361 char *end_name;
363 p_name += sizeof("parentFileNameHint") + 1;
364 end_name = strchr(p_name, '\"');
365 if (end_name == NULL) {
366 ret = -EINVAL;
367 goto out;
369 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
370 ret = -EINVAL;
371 goto out;
374 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
377 out:
378 g_free(desc);
379 return ret;
382 /* Create and append extent to the extent array. Return the added VmdkExtent
383 * address. return NULL if allocation failed. */
384 static int vmdk_add_extent(BlockDriverState *bs,
385 BdrvChild *file, bool flat, int64_t sectors,
386 int64_t l1_offset, int64_t l1_backup_offset,
387 uint32_t l1_size,
388 int l2_size, uint64_t cluster_sectors,
389 VmdkExtent **new_extent,
390 Error **errp)
392 VmdkExtent *extent;
393 BDRVVmdkState *s = bs->opaque;
394 int64_t nb_sectors;
396 if (cluster_sectors > 0x200000) {
397 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
398 error_setg(errp, "Invalid granularity, image may be corrupt");
399 return -EFBIG;
401 if (l1_size > 512 * 1024 * 1024) {
402 /* Although with big capacity and small l1_entry_sectors, we can get a
403 * big l1_size, we don't want unbounded value to allocate the table.
404 * Limit it to 512M, which is 16PB for default cluster and L2 table
405 * size */
406 error_setg(errp, "L1 size too big");
407 return -EFBIG;
410 nb_sectors = bdrv_nb_sectors(file->bs);
411 if (nb_sectors < 0) {
412 return nb_sectors;
415 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
416 extent = &s->extents[s->num_extents];
417 s->num_extents++;
419 memset(extent, 0, sizeof(VmdkExtent));
420 extent->file = file;
421 extent->flat = flat;
422 extent->sectors = sectors;
423 extent->l1_table_offset = l1_offset;
424 extent->l1_backup_table_offset = l1_backup_offset;
425 extent->l1_size = l1_size;
426 extent->l1_entry_sectors = l2_size * cluster_sectors;
427 extent->l2_size = l2_size;
428 extent->cluster_sectors = flat ? sectors : cluster_sectors;
429 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
431 if (s->num_extents > 1) {
432 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
433 } else {
434 extent->end_sector = extent->sectors;
436 bs->total_sectors = extent->end_sector;
437 if (new_extent) {
438 *new_extent = extent;
440 return 0;
443 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
444 Error **errp)
446 int ret;
447 size_t l1_size;
448 int i;
450 /* read the L1 table */
451 l1_size = extent->l1_size * sizeof(uint32_t);
452 extent->l1_table = g_try_malloc(l1_size);
453 if (l1_size && extent->l1_table == NULL) {
454 return -ENOMEM;
457 ret = bdrv_pread(extent->file,
458 extent->l1_table_offset,
459 extent->l1_table,
460 l1_size);
461 if (ret < 0) {
462 error_setg_errno(errp, -ret,
463 "Could not read l1 table from extent '%s'",
464 extent->file->bs->filename);
465 goto fail_l1;
467 for (i = 0; i < extent->l1_size; i++) {
468 le32_to_cpus(&extent->l1_table[i]);
471 if (extent->l1_backup_table_offset) {
472 extent->l1_backup_table = g_try_malloc(l1_size);
473 if (l1_size && extent->l1_backup_table == NULL) {
474 ret = -ENOMEM;
475 goto fail_l1;
477 ret = bdrv_pread(extent->file,
478 extent->l1_backup_table_offset,
479 extent->l1_backup_table,
480 l1_size);
481 if (ret < 0) {
482 error_setg_errno(errp, -ret,
483 "Could not read l1 backup table from extent '%s'",
484 extent->file->bs->filename);
485 goto fail_l1b;
487 for (i = 0; i < extent->l1_size; i++) {
488 le32_to_cpus(&extent->l1_backup_table[i]);
492 extent->l2_cache =
493 g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
494 return 0;
495 fail_l1b:
496 g_free(extent->l1_backup_table);
497 fail_l1:
498 g_free(extent->l1_table);
499 return ret;
502 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
503 BdrvChild *file,
504 int flags, Error **errp)
506 int ret;
507 uint32_t magic;
508 VMDK3Header header;
509 VmdkExtent *extent;
511 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
512 if (ret < 0) {
513 error_setg_errno(errp, -ret,
514 "Could not read header from file '%s'",
515 file->bs->filename);
516 return ret;
518 ret = vmdk_add_extent(bs, file, false,
519 le32_to_cpu(header.disk_sectors),
520 (int64_t)le32_to_cpu(header.l1dir_offset) << 9,
522 le32_to_cpu(header.l1dir_size),
523 4096,
524 le32_to_cpu(header.granularity),
525 &extent,
526 errp);
527 if (ret < 0) {
528 return ret;
530 ret = vmdk_init_tables(bs, extent, errp);
531 if (ret) {
532 /* free extent allocated by vmdk_add_extent */
533 vmdk_free_last_extent(bs);
535 return ret;
538 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
539 QDict *options, Error **errp);
541 static char *vmdk_read_desc(BdrvChild *file, uint64_t desc_offset, Error **errp)
543 int64_t size;
544 char *buf;
545 int ret;
547 size = bdrv_getlength(file->bs);
548 if (size < 0) {
549 error_setg_errno(errp, -size, "Could not access file");
550 return NULL;
553 if (size < 4) {
554 /* Both descriptor file and sparse image must be much larger than 4
555 * bytes, also callers of vmdk_read_desc want to compare the first 4
556 * bytes with VMDK4_MAGIC, let's error out if less is read. */
557 error_setg(errp, "File is too small, not a valid image");
558 return NULL;
561 size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */
562 buf = g_malloc(size + 1);
564 ret = bdrv_pread(file, desc_offset, buf, size);
565 if (ret < 0) {
566 error_setg_errno(errp, -ret, "Could not read from file");
567 g_free(buf);
568 return NULL;
570 buf[ret] = 0;
572 return buf;
575 static int vmdk_open_vmdk4(BlockDriverState *bs,
576 BdrvChild *file,
577 int flags, QDict *options, Error **errp)
579 int ret;
580 uint32_t magic;
581 uint32_t l1_size, l1_entry_sectors;
582 VMDK4Header header;
583 VmdkExtent *extent;
584 BDRVVmdkState *s = bs->opaque;
585 int64_t l1_backup_offset = 0;
586 bool compressed;
588 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
589 if (ret < 0) {
590 error_setg_errno(errp, -ret,
591 "Could not read header from file '%s'",
592 file->bs->filename);
593 return -EINVAL;
595 if (header.capacity == 0) {
596 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
597 if (desc_offset) {
598 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
599 if (!buf) {
600 return -EINVAL;
602 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
603 g_free(buf);
604 return ret;
608 if (!s->create_type) {
609 s->create_type = g_strdup("monolithicSparse");
612 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
614 * The footer takes precedence over the header, so read it in. The
615 * footer starts at offset -1024 from the end: One sector for the
616 * footer, and another one for the end-of-stream marker.
618 struct {
619 struct {
620 uint64_t val;
621 uint32_t size;
622 uint32_t type;
623 uint8_t pad[512 - 16];
624 } QEMU_PACKED footer_marker;
626 uint32_t magic;
627 VMDK4Header header;
628 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
630 struct {
631 uint64_t val;
632 uint32_t size;
633 uint32_t type;
634 uint8_t pad[512 - 16];
635 } QEMU_PACKED eos_marker;
636 } QEMU_PACKED footer;
638 ret = bdrv_pread(file,
639 bs->file->bs->total_sectors * 512 - 1536,
640 &footer, sizeof(footer));
641 if (ret < 0) {
642 error_setg_errno(errp, -ret, "Failed to read footer");
643 return ret;
646 /* Some sanity checks for the footer */
647 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
648 le32_to_cpu(footer.footer_marker.size) != 0 ||
649 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
650 le64_to_cpu(footer.eos_marker.val) != 0 ||
651 le32_to_cpu(footer.eos_marker.size) != 0 ||
652 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
654 error_setg(errp, "Invalid footer");
655 return -EINVAL;
658 header = footer.header;
661 compressed =
662 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
663 if (le32_to_cpu(header.version) > 3) {
664 error_setg(errp, "Unsupported VMDK version %" PRIu32,
665 le32_to_cpu(header.version));
666 return -ENOTSUP;
667 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR) &&
668 !compressed) {
669 /* VMware KB 2064959 explains that version 3 added support for
670 * persistent changed block tracking (CBT), and backup software can
671 * read it as version=1 if it doesn't care about the changed area
672 * information. So we are safe to enable read only. */
673 error_setg(errp, "VMDK version 3 must be read only");
674 return -EINVAL;
677 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
678 error_setg(errp, "L2 table size too big");
679 return -EINVAL;
682 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
683 * le64_to_cpu(header.granularity);
684 if (l1_entry_sectors == 0) {
685 error_setg(errp, "L1 entry size is invalid");
686 return -EINVAL;
688 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
689 / l1_entry_sectors;
690 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
691 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
693 if (bdrv_nb_sectors(file->bs) < le64_to_cpu(header.grain_offset)) {
694 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
695 (int64_t)(le64_to_cpu(header.grain_offset)
696 * BDRV_SECTOR_SIZE));
697 return -EINVAL;
700 ret = vmdk_add_extent(bs, file, false,
701 le64_to_cpu(header.capacity),
702 le64_to_cpu(header.gd_offset) << 9,
703 l1_backup_offset,
704 l1_size,
705 le32_to_cpu(header.num_gtes_per_gt),
706 le64_to_cpu(header.granularity),
707 &extent,
708 errp);
709 if (ret < 0) {
710 return ret;
712 extent->compressed =
713 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
714 if (extent->compressed) {
715 g_free(s->create_type);
716 s->create_type = g_strdup("streamOptimized");
718 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
719 extent->version = le32_to_cpu(header.version);
720 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
721 ret = vmdk_init_tables(bs, extent, errp);
722 if (ret) {
723 /* free extent allocated by vmdk_add_extent */
724 vmdk_free_last_extent(bs);
726 return ret;
729 /* find an option value out of descriptor file */
730 static int vmdk_parse_description(const char *desc, const char *opt_name,
731 char *buf, int buf_size)
733 char *opt_pos, *opt_end;
734 const char *end = desc + strlen(desc);
736 opt_pos = strstr(desc, opt_name);
737 if (!opt_pos) {
738 return VMDK_ERROR;
740 /* Skip "=\"" following opt_name */
741 opt_pos += strlen(opt_name) + 2;
742 if (opt_pos >= end) {
743 return VMDK_ERROR;
745 opt_end = opt_pos;
746 while (opt_end < end && *opt_end != '"') {
747 opt_end++;
749 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
750 return VMDK_ERROR;
752 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
753 return VMDK_OK;
756 /* Open an extent file and append to bs array */
757 static int vmdk_open_sparse(BlockDriverState *bs, BdrvChild *file, int flags,
758 char *buf, QDict *options, Error **errp)
760 uint32_t magic;
762 magic = ldl_be_p(buf);
763 switch (magic) {
764 case VMDK3_MAGIC:
765 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
766 break;
767 case VMDK4_MAGIC:
768 return vmdk_open_vmdk4(bs, file, flags, options, errp);
769 break;
770 default:
771 error_setg(errp, "Image not in VMDK format");
772 return -EINVAL;
773 break;
777 static const char *next_line(const char *s)
779 while (*s) {
780 if (*s == '\n') {
781 return s + 1;
783 s++;
785 return s;
788 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
789 const char *desc_file_path, QDict *options,
790 Error **errp)
792 int ret;
793 int matches;
794 char access[11];
795 char type[11];
796 char fname[512];
797 const char *p, *np;
798 int64_t sectors = 0;
799 int64_t flat_offset;
800 char *extent_path;
801 BdrvChild *extent_file;
802 BDRVVmdkState *s = bs->opaque;
803 VmdkExtent *extent;
804 char extent_opt_prefix[32];
805 Error *local_err = NULL;
807 for (p = desc; *p; p = next_line(p)) {
808 /* parse extent line in one of below formats:
810 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
811 * RW [size in sectors] SPARSE "file-name.vmdk"
812 * RW [size in sectors] VMFS "file-name.vmdk"
813 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
815 flat_offset = -1;
816 matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
817 access, &sectors, type, fname, &flat_offset);
818 if (matches < 4 || strcmp(access, "RW")) {
819 continue;
820 } else if (!strcmp(type, "FLAT")) {
821 if (matches != 5 || flat_offset < 0) {
822 goto invalid;
824 } else if (!strcmp(type, "VMFS")) {
825 if (matches == 4) {
826 flat_offset = 0;
827 } else {
828 goto invalid;
830 } else if (matches != 4) {
831 goto invalid;
834 if (sectors <= 0 ||
835 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
836 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
837 (strcmp(access, "RW"))) {
838 continue;
841 if (!path_is_absolute(fname) && !path_has_protocol(fname) &&
842 !desc_file_path[0])
844 error_setg(errp, "Cannot use relative extent paths with VMDK "
845 "descriptor file '%s'", bs->file->bs->filename);
846 return -EINVAL;
849 extent_path = g_malloc0(PATH_MAX);
850 path_combine(extent_path, PATH_MAX, desc_file_path, fname);
852 ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents);
853 assert(ret < 32);
855 extent_file = bdrv_open_child(extent_path, options, extent_opt_prefix,
856 bs, &child_file, false, &local_err);
857 g_free(extent_path);
858 if (local_err) {
859 error_propagate(errp, local_err);
860 return -EINVAL;
863 /* save to extents array */
864 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
865 /* FLAT extent */
867 ret = vmdk_add_extent(bs, extent_file, true, sectors,
868 0, 0, 0, 0, 0, &extent, errp);
869 if (ret < 0) {
870 bdrv_unref_child(bs, extent_file);
871 return ret;
873 extent->flat_start_offset = flat_offset << 9;
874 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
875 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
876 char *buf = vmdk_read_desc(extent_file, 0, errp);
877 if (!buf) {
878 ret = -EINVAL;
879 } else {
880 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf,
881 options, errp);
883 g_free(buf);
884 if (ret) {
885 bdrv_unref_child(bs, extent_file);
886 return ret;
888 extent = &s->extents[s->num_extents - 1];
889 } else {
890 error_setg(errp, "Unsupported extent type '%s'", type);
891 bdrv_unref_child(bs, extent_file);
892 return -ENOTSUP;
894 extent->type = g_strdup(type);
896 return 0;
898 invalid:
899 np = next_line(p);
900 assert(np != p);
901 if (np[-1] == '\n') {
902 np--;
904 error_setg(errp, "Invalid extent line: %.*s", (int)(np - p), p);
905 return -EINVAL;
908 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
909 QDict *options, Error **errp)
911 int ret;
912 char ct[128];
913 BDRVVmdkState *s = bs->opaque;
915 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
916 error_setg(errp, "invalid VMDK image descriptor");
917 ret = -EINVAL;
918 goto exit;
920 if (strcmp(ct, "monolithicFlat") &&
921 strcmp(ct, "vmfs") &&
922 strcmp(ct, "vmfsSparse") &&
923 strcmp(ct, "twoGbMaxExtentSparse") &&
924 strcmp(ct, "twoGbMaxExtentFlat")) {
925 error_setg(errp, "Unsupported image type '%s'", ct);
926 ret = -ENOTSUP;
927 goto exit;
929 s->create_type = g_strdup(ct);
930 s->desc_offset = 0;
931 ret = vmdk_parse_extents(buf, bs, bs->file->bs->exact_filename, options,
932 errp);
933 exit:
934 return ret;
937 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
938 Error **errp)
940 char *buf;
941 int ret;
942 BDRVVmdkState *s = bs->opaque;
943 uint32_t magic;
944 Error *local_err = NULL;
946 buf = vmdk_read_desc(bs->file, 0, errp);
947 if (!buf) {
948 return -EINVAL;
951 magic = ldl_be_p(buf);
952 switch (magic) {
953 case VMDK3_MAGIC:
954 case VMDK4_MAGIC:
955 ret = vmdk_open_sparse(bs, bs->file, flags, buf, options,
956 errp);
957 s->desc_offset = 0x200;
958 break;
959 default:
960 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
961 break;
963 if (ret) {
964 goto fail;
967 /* try to open parent images, if exist */
968 ret = vmdk_parent_open(bs);
969 if (ret) {
970 goto fail;
972 s->cid = vmdk_read_cid(bs, 0);
973 s->parent_cid = vmdk_read_cid(bs, 1);
974 qemu_co_mutex_init(&s->lock);
976 /* Disable migration when VMDK images are used */
977 error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "
978 "does not support live migration",
979 bdrv_get_device_or_node_name(bs));
980 ret = migrate_add_blocker(s->migration_blocker, &local_err);
981 if (local_err) {
982 error_propagate(errp, local_err);
983 error_free(s->migration_blocker);
984 goto fail;
987 g_free(buf);
988 return 0;
990 fail:
991 g_free(buf);
992 g_free(s->create_type);
993 s->create_type = NULL;
994 vmdk_free_extents(bs);
995 return ret;
999 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
1001 BDRVVmdkState *s = bs->opaque;
1002 int i;
1004 for (i = 0; i < s->num_extents; i++) {
1005 if (!s->extents[i].flat) {
1006 bs->bl.pwrite_zeroes_alignment =
1007 MAX(bs->bl.pwrite_zeroes_alignment,
1008 s->extents[i].cluster_sectors << BDRV_SECTOR_BITS);
1014 * get_whole_cluster
1016 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1017 * to the cluster at @cluster_sector_num.
1019 * If @skip_start_sector < @skip_end_sector, the relative range
1020 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1021 * it for call to write user data in the request.
1023 static int get_whole_cluster(BlockDriverState *bs,
1024 VmdkExtent *extent,
1025 uint64_t cluster_offset,
1026 uint64_t offset,
1027 uint64_t skip_start_bytes,
1028 uint64_t skip_end_bytes)
1030 int ret = VMDK_OK;
1031 int64_t cluster_bytes;
1032 uint8_t *whole_grain;
1034 /* For COW, align request sector_num to cluster start */
1035 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
1036 offset = QEMU_ALIGN_DOWN(offset, cluster_bytes);
1037 whole_grain = qemu_blockalign(bs, cluster_bytes);
1039 if (!bs->backing) {
1040 memset(whole_grain, 0, skip_start_bytes);
1041 memset(whole_grain + skip_end_bytes, 0, cluster_bytes - skip_end_bytes);
1044 assert(skip_end_bytes <= cluster_bytes);
1045 /* we will be here if it's first write on non-exist grain(cluster).
1046 * try to read from parent image, if exist */
1047 if (bs->backing && !vmdk_is_cid_valid(bs)) {
1048 ret = VMDK_ERROR;
1049 goto exit;
1052 /* Read backing data before skip range */
1053 if (skip_start_bytes > 0) {
1054 if (bs->backing) {
1055 ret = bdrv_pread(bs->backing, offset, whole_grain,
1056 skip_start_bytes);
1057 if (ret < 0) {
1058 ret = VMDK_ERROR;
1059 goto exit;
1062 ret = bdrv_pwrite(extent->file, cluster_offset, whole_grain,
1063 skip_start_bytes);
1064 if (ret < 0) {
1065 ret = VMDK_ERROR;
1066 goto exit;
1069 /* Read backing data after skip range */
1070 if (skip_end_bytes < cluster_bytes) {
1071 if (bs->backing) {
1072 ret = bdrv_pread(bs->backing, offset + skip_end_bytes,
1073 whole_grain + skip_end_bytes,
1074 cluster_bytes - skip_end_bytes);
1075 if (ret < 0) {
1076 ret = VMDK_ERROR;
1077 goto exit;
1080 ret = bdrv_pwrite(extent->file, cluster_offset + skip_end_bytes,
1081 whole_grain + skip_end_bytes,
1082 cluster_bytes - skip_end_bytes);
1083 if (ret < 0) {
1084 ret = VMDK_ERROR;
1085 goto exit;
1089 ret = VMDK_OK;
1090 exit:
1091 qemu_vfree(whole_grain);
1092 return ret;
1095 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1096 uint32_t offset)
1098 offset = cpu_to_le32(offset);
1099 /* update L2 table */
1100 if (bdrv_pwrite_sync(extent->file,
1101 ((int64_t)m_data->l2_offset * 512)
1102 + (m_data->l2_index * sizeof(offset)),
1103 &offset, sizeof(offset)) < 0) {
1104 return VMDK_ERROR;
1106 /* update backup L2 table */
1107 if (extent->l1_backup_table_offset != 0) {
1108 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1109 if (bdrv_pwrite_sync(extent->file,
1110 ((int64_t)m_data->l2_offset * 512)
1111 + (m_data->l2_index * sizeof(offset)),
1112 &offset, sizeof(offset)) < 0) {
1113 return VMDK_ERROR;
1116 if (m_data->l2_cache_entry) {
1117 *m_data->l2_cache_entry = offset;
1120 return VMDK_OK;
1124 * get_cluster_offset
1126 * Look up cluster offset in extent file by sector number, and store in
1127 * @cluster_offset.
1129 * For flat extents, the start offset as parsed from the description file is
1130 * returned.
1132 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1133 * offset for a new cluster and update L2 cache. If there is a backing file,
1134 * COW is done before returning; otherwise, zeroes are written to the allocated
1135 * cluster. Both COW and zero writing skips the sector range
1136 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1137 * has new data to write there.
1139 * Returns: VMDK_OK if cluster exists and mapped in the image.
1140 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1141 * VMDK_ERROR if failed.
1143 static int get_cluster_offset(BlockDriverState *bs,
1144 VmdkExtent *extent,
1145 VmdkMetaData *m_data,
1146 uint64_t offset,
1147 bool allocate,
1148 uint64_t *cluster_offset,
1149 uint64_t skip_start_bytes,
1150 uint64_t skip_end_bytes)
1152 unsigned int l1_index, l2_offset, l2_index;
1153 int min_index, i, j;
1154 uint32_t min_count, *l2_table;
1155 bool zeroed = false;
1156 int64_t ret;
1157 int64_t cluster_sector;
1159 if (m_data) {
1160 m_data->valid = 0;
1162 if (extent->flat) {
1163 *cluster_offset = extent->flat_start_offset;
1164 return VMDK_OK;
1167 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1168 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1169 if (l1_index >= extent->l1_size) {
1170 return VMDK_ERROR;
1172 l2_offset = extent->l1_table[l1_index];
1173 if (!l2_offset) {
1174 return VMDK_UNALLOC;
1176 for (i = 0; i < L2_CACHE_SIZE; i++) {
1177 if (l2_offset == extent->l2_cache_offsets[i]) {
1178 /* increment the hit count */
1179 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1180 for (j = 0; j < L2_CACHE_SIZE; j++) {
1181 extent->l2_cache_counts[j] >>= 1;
1184 l2_table = extent->l2_cache + (i * extent->l2_size);
1185 goto found;
1188 /* not found: load a new entry in the least used one */
1189 min_index = 0;
1190 min_count = 0xffffffff;
1191 for (i = 0; i < L2_CACHE_SIZE; i++) {
1192 if (extent->l2_cache_counts[i] < min_count) {
1193 min_count = extent->l2_cache_counts[i];
1194 min_index = i;
1197 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1198 if (bdrv_pread(extent->file,
1199 (int64_t)l2_offset * 512,
1200 l2_table,
1201 extent->l2_size * sizeof(uint32_t)
1202 ) != extent->l2_size * sizeof(uint32_t)) {
1203 return VMDK_ERROR;
1206 extent->l2_cache_offsets[min_index] = l2_offset;
1207 extent->l2_cache_counts[min_index] = 1;
1208 found:
1209 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1210 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1212 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1213 zeroed = true;
1216 if (!cluster_sector || zeroed) {
1217 if (!allocate) {
1218 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1221 cluster_sector = extent->next_cluster_sector;
1222 extent->next_cluster_sector += extent->cluster_sectors;
1224 /* First of all we write grain itself, to avoid race condition
1225 * that may to corrupt the image.
1226 * This problem may occur because of insufficient space on host disk
1227 * or inappropriate VM shutdown.
1229 ret = get_whole_cluster(bs, extent, cluster_sector * BDRV_SECTOR_SIZE,
1230 offset, skip_start_bytes, skip_end_bytes);
1231 if (ret) {
1232 return ret;
1234 if (m_data) {
1235 m_data->valid = 1;
1236 m_data->l1_index = l1_index;
1237 m_data->l2_index = l2_index;
1238 m_data->l2_offset = l2_offset;
1239 m_data->l2_cache_entry = &l2_table[l2_index];
1242 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1243 return VMDK_OK;
1246 static VmdkExtent *find_extent(BDRVVmdkState *s,
1247 int64_t sector_num, VmdkExtent *start_hint)
1249 VmdkExtent *extent = start_hint;
1251 if (!extent) {
1252 extent = &s->extents[0];
1254 while (extent < &s->extents[s->num_extents]) {
1255 if (sector_num < extent->end_sector) {
1256 return extent;
1258 extent++;
1260 return NULL;
1263 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent *extent,
1264 int64_t offset)
1266 uint64_t extent_begin_offset, extent_relative_offset;
1267 uint64_t cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1269 extent_begin_offset =
1270 (extent->end_sector - extent->sectors) * BDRV_SECTOR_SIZE;
1271 extent_relative_offset = offset - extent_begin_offset;
1272 return extent_relative_offset % cluster_size;
1275 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent *extent,
1276 int64_t sector_num)
1278 uint64_t offset;
1279 offset = vmdk_find_offset_in_cluster(extent, sector_num * BDRV_SECTOR_SIZE);
1280 return offset / BDRV_SECTOR_SIZE;
1283 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1284 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1286 BDRVVmdkState *s = bs->opaque;
1287 int64_t index_in_cluster, n, ret;
1288 uint64_t offset;
1289 VmdkExtent *extent;
1291 extent = find_extent(s, sector_num, NULL);
1292 if (!extent) {
1293 return 0;
1295 qemu_co_mutex_lock(&s->lock);
1296 ret = get_cluster_offset(bs, extent, NULL,
1297 sector_num * 512, false, &offset,
1298 0, 0);
1299 qemu_co_mutex_unlock(&s->lock);
1301 index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1302 switch (ret) {
1303 case VMDK_ERROR:
1304 ret = -EIO;
1305 break;
1306 case VMDK_UNALLOC:
1307 ret = 0;
1308 break;
1309 case VMDK_ZEROED:
1310 ret = BDRV_BLOCK_ZERO;
1311 break;
1312 case VMDK_OK:
1313 ret = BDRV_BLOCK_DATA;
1314 if (!extent->compressed) {
1315 ret |= BDRV_BLOCK_OFFSET_VALID;
1316 ret |= (offset + (index_in_cluster << BDRV_SECTOR_BITS))
1317 & BDRV_BLOCK_OFFSET_MASK;
1319 *file = extent->file->bs;
1320 break;
1323 n = extent->cluster_sectors - index_in_cluster;
1324 if (n > nb_sectors) {
1325 n = nb_sectors;
1327 *pnum = n;
1328 return ret;
1331 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1332 int64_t offset_in_cluster, QEMUIOVector *qiov,
1333 uint64_t qiov_offset, uint64_t n_bytes,
1334 uint64_t offset)
1336 int ret;
1337 VmdkGrainMarker *data = NULL;
1338 uLongf buf_len;
1339 QEMUIOVector local_qiov;
1340 struct iovec iov;
1341 int64_t write_offset;
1342 int64_t write_end_sector;
1344 if (extent->compressed) {
1345 void *compressed_data;
1347 if (!extent->has_marker) {
1348 ret = -EINVAL;
1349 goto out;
1351 buf_len = (extent->cluster_sectors << 9) * 2;
1352 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1354 compressed_data = g_malloc(n_bytes);
1355 qemu_iovec_to_buf(qiov, qiov_offset, compressed_data, n_bytes);
1356 ret = compress(data->data, &buf_len, compressed_data, n_bytes);
1357 g_free(compressed_data);
1359 if (ret != Z_OK || buf_len == 0) {
1360 ret = -EINVAL;
1361 goto out;
1364 data->lba = offset >> BDRV_SECTOR_BITS;
1365 data->size = buf_len;
1367 n_bytes = buf_len + sizeof(VmdkGrainMarker);
1368 iov = (struct iovec) {
1369 .iov_base = data,
1370 .iov_len = n_bytes,
1372 qemu_iovec_init_external(&local_qiov, &iov, 1);
1373 } else {
1374 qemu_iovec_init(&local_qiov, qiov->niov);
1375 qemu_iovec_concat(&local_qiov, qiov, qiov_offset, n_bytes);
1378 write_offset = cluster_offset + offset_in_cluster,
1379 ret = bdrv_co_pwritev(extent->file, write_offset, n_bytes,
1380 &local_qiov, 0);
1382 write_end_sector = DIV_ROUND_UP(write_offset + n_bytes, BDRV_SECTOR_SIZE);
1384 if (extent->compressed) {
1385 extent->next_cluster_sector = write_end_sector;
1386 } else {
1387 extent->next_cluster_sector = MAX(extent->next_cluster_sector,
1388 write_end_sector);
1391 if (ret < 0) {
1392 goto out;
1394 ret = 0;
1395 out:
1396 g_free(data);
1397 if (!extent->compressed) {
1398 qemu_iovec_destroy(&local_qiov);
1400 return ret;
1403 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1404 int64_t offset_in_cluster, QEMUIOVector *qiov,
1405 int bytes)
1407 int ret;
1408 int cluster_bytes, buf_bytes;
1409 uint8_t *cluster_buf, *compressed_data;
1410 uint8_t *uncomp_buf;
1411 uint32_t data_len;
1412 VmdkGrainMarker *marker;
1413 uLongf buf_len;
1416 if (!extent->compressed) {
1417 ret = bdrv_co_preadv(extent->file,
1418 cluster_offset + offset_in_cluster, bytes,
1419 qiov, 0);
1420 if (ret < 0) {
1421 return ret;
1423 return 0;
1425 cluster_bytes = extent->cluster_sectors * 512;
1426 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1427 buf_bytes = cluster_bytes * 2;
1428 cluster_buf = g_malloc(buf_bytes);
1429 uncomp_buf = g_malloc(cluster_bytes);
1430 ret = bdrv_pread(extent->file,
1431 cluster_offset,
1432 cluster_buf, buf_bytes);
1433 if (ret < 0) {
1434 goto out;
1436 compressed_data = cluster_buf;
1437 buf_len = cluster_bytes;
1438 data_len = cluster_bytes;
1439 if (extent->has_marker) {
1440 marker = (VmdkGrainMarker *)cluster_buf;
1441 compressed_data = marker->data;
1442 data_len = le32_to_cpu(marker->size);
1444 if (!data_len || data_len > buf_bytes) {
1445 ret = -EINVAL;
1446 goto out;
1448 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1449 if (ret != Z_OK) {
1450 ret = -EINVAL;
1451 goto out;
1454 if (offset_in_cluster < 0 ||
1455 offset_in_cluster + bytes > buf_len) {
1456 ret = -EINVAL;
1457 goto out;
1459 qemu_iovec_from_buf(qiov, 0, uncomp_buf + offset_in_cluster, bytes);
1460 ret = 0;
1462 out:
1463 g_free(uncomp_buf);
1464 g_free(cluster_buf);
1465 return ret;
1468 static int coroutine_fn
1469 vmdk_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1470 QEMUIOVector *qiov, int flags)
1472 BDRVVmdkState *s = bs->opaque;
1473 int ret;
1474 uint64_t n_bytes, offset_in_cluster;
1475 VmdkExtent *extent = NULL;
1476 QEMUIOVector local_qiov;
1477 uint64_t cluster_offset;
1478 uint64_t bytes_done = 0;
1480 qemu_iovec_init(&local_qiov, qiov->niov);
1481 qemu_co_mutex_lock(&s->lock);
1483 while (bytes > 0) {
1484 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1485 if (!extent) {
1486 ret = -EIO;
1487 goto fail;
1489 ret = get_cluster_offset(bs, extent, NULL,
1490 offset, false, &cluster_offset, 0, 0);
1491 offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1493 n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1494 - offset_in_cluster);
1496 if (ret != VMDK_OK) {
1497 /* if not allocated, try to read from parent image, if exist */
1498 if (bs->backing && ret != VMDK_ZEROED) {
1499 if (!vmdk_is_cid_valid(bs)) {
1500 ret = -EINVAL;
1501 goto fail;
1504 qemu_iovec_reset(&local_qiov);
1505 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1507 ret = bdrv_co_preadv(bs->backing, offset, n_bytes,
1508 &local_qiov, 0);
1509 if (ret < 0) {
1510 goto fail;
1512 } else {
1513 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
1515 } else {
1516 qemu_iovec_reset(&local_qiov);
1517 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1519 ret = vmdk_read_extent(extent, cluster_offset, offset_in_cluster,
1520 &local_qiov, n_bytes);
1521 if (ret) {
1522 goto fail;
1525 bytes -= n_bytes;
1526 offset += n_bytes;
1527 bytes_done += n_bytes;
1530 ret = 0;
1531 fail:
1532 qemu_co_mutex_unlock(&s->lock);
1533 qemu_iovec_destroy(&local_qiov);
1535 return ret;
1539 * vmdk_write:
1540 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1541 * if possible, otherwise return -ENOTSUP.
1542 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1543 * with each cluster. By dry run we can find if the zero write
1544 * is possible without modifying image data.
1546 * Returns: error code with 0 for success.
1548 static int vmdk_pwritev(BlockDriverState *bs, uint64_t offset,
1549 uint64_t bytes, QEMUIOVector *qiov,
1550 bool zeroed, bool zero_dry_run)
1552 BDRVVmdkState *s = bs->opaque;
1553 VmdkExtent *extent = NULL;
1554 int ret;
1555 int64_t offset_in_cluster, n_bytes;
1556 uint64_t cluster_offset;
1557 uint64_t bytes_done = 0;
1558 VmdkMetaData m_data;
1560 if (DIV_ROUND_UP(offset, BDRV_SECTOR_SIZE) > bs->total_sectors) {
1561 error_report("Wrong offset: offset=0x%" PRIx64
1562 " total_sectors=0x%" PRIx64,
1563 offset, bs->total_sectors);
1564 return -EIO;
1567 while (bytes > 0) {
1568 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1569 if (!extent) {
1570 return -EIO;
1572 offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1573 n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1574 - offset_in_cluster);
1576 ret = get_cluster_offset(bs, extent, &m_data, offset,
1577 !(extent->compressed || zeroed),
1578 &cluster_offset, offset_in_cluster,
1579 offset_in_cluster + n_bytes);
1580 if (extent->compressed) {
1581 if (ret == VMDK_OK) {
1582 /* Refuse write to allocated cluster for streamOptimized */
1583 error_report("Could not write to allocated cluster"
1584 " for streamOptimized");
1585 return -EIO;
1586 } else {
1587 /* allocate */
1588 ret = get_cluster_offset(bs, extent, &m_data, offset,
1589 true, &cluster_offset, 0, 0);
1592 if (ret == VMDK_ERROR) {
1593 return -EINVAL;
1595 if (zeroed) {
1596 /* Do zeroed write, buf is ignored */
1597 if (extent->has_zero_grain &&
1598 offset_in_cluster == 0 &&
1599 n_bytes >= extent->cluster_sectors * BDRV_SECTOR_SIZE) {
1600 n_bytes = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1601 if (!zero_dry_run) {
1602 /* update L2 tables */
1603 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1604 != VMDK_OK) {
1605 return -EIO;
1608 } else {
1609 return -ENOTSUP;
1611 } else {
1612 ret = vmdk_write_extent(extent, cluster_offset, offset_in_cluster,
1613 qiov, bytes_done, n_bytes, offset);
1614 if (ret) {
1615 return ret;
1617 if (m_data.valid) {
1618 /* update L2 tables */
1619 if (vmdk_L2update(extent, &m_data,
1620 cluster_offset >> BDRV_SECTOR_BITS)
1621 != VMDK_OK) {
1622 return -EIO;
1626 bytes -= n_bytes;
1627 offset += n_bytes;
1628 bytes_done += n_bytes;
1630 /* update CID on the first write every time the virtual disk is
1631 * opened */
1632 if (!s->cid_updated) {
1633 ret = vmdk_write_cid(bs, g_random_int());
1634 if (ret < 0) {
1635 return ret;
1637 s->cid_updated = true;
1640 return 0;
1643 static int coroutine_fn
1644 vmdk_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1645 QEMUIOVector *qiov, int flags)
1647 int ret;
1648 BDRVVmdkState *s = bs->opaque;
1649 qemu_co_mutex_lock(&s->lock);
1650 ret = vmdk_pwritev(bs, offset, bytes, qiov, false, false);
1651 qemu_co_mutex_unlock(&s->lock);
1652 return ret;
1655 static int coroutine_fn
1656 vmdk_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1657 uint64_t bytes, QEMUIOVector *qiov)
1659 return vmdk_co_pwritev(bs, offset, bytes, qiov, 0);
1662 static int coroutine_fn vmdk_co_pwrite_zeroes(BlockDriverState *bs,
1663 int64_t offset,
1664 int bytes,
1665 BdrvRequestFlags flags)
1667 int ret;
1668 BDRVVmdkState *s = bs->opaque;
1670 qemu_co_mutex_lock(&s->lock);
1671 /* write zeroes could fail if sectors not aligned to cluster, test it with
1672 * dry_run == true before really updating image */
1673 ret = vmdk_pwritev(bs, offset, bytes, NULL, true, true);
1674 if (!ret) {
1675 ret = vmdk_pwritev(bs, offset, bytes, NULL, true, false);
1677 qemu_co_mutex_unlock(&s->lock);
1678 return ret;
1681 static int vmdk_create_extent(const char *filename, int64_t filesize,
1682 bool flat, bool compress, bool zeroed_grain,
1683 QemuOpts *opts, Error **errp)
1685 int ret, i;
1686 BlockBackend *blk = NULL;
1687 VMDK4Header header;
1688 Error *local_err = NULL;
1689 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1690 uint32_t *gd_buf = NULL;
1691 int gd_buf_size;
1693 ret = bdrv_create_file(filename, opts, &local_err);
1694 if (ret < 0) {
1695 error_propagate(errp, local_err);
1696 goto exit;
1699 blk = blk_new_open(filename, NULL, NULL,
1700 BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
1701 if (blk == NULL) {
1702 error_propagate(errp, local_err);
1703 ret = -EIO;
1704 goto exit;
1707 blk_set_allow_write_beyond_eof(blk, true);
1709 if (flat) {
1710 ret = blk_truncate(blk, filesize);
1711 if (ret < 0) {
1712 error_setg_errno(errp, -ret, "Could not truncate file");
1714 goto exit;
1716 magic = cpu_to_be32(VMDK4_MAGIC);
1717 memset(&header, 0, sizeof(header));
1718 if (compress) {
1719 header.version = 3;
1720 } else if (zeroed_grain) {
1721 header.version = 2;
1722 } else {
1723 header.version = 1;
1725 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1726 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1727 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1728 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1729 header.capacity = filesize / BDRV_SECTOR_SIZE;
1730 header.granularity = 128;
1731 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1733 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1734 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1735 BDRV_SECTOR_SIZE);
1736 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1737 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1739 header.desc_offset = 1;
1740 header.desc_size = 20;
1741 header.rgd_offset = header.desc_offset + header.desc_size;
1742 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1743 header.grain_offset =
1744 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1745 header.granularity);
1746 /* swap endianness for all header fields */
1747 header.version = cpu_to_le32(header.version);
1748 header.flags = cpu_to_le32(header.flags);
1749 header.capacity = cpu_to_le64(header.capacity);
1750 header.granularity = cpu_to_le64(header.granularity);
1751 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1752 header.desc_offset = cpu_to_le64(header.desc_offset);
1753 header.desc_size = cpu_to_le64(header.desc_size);
1754 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1755 header.gd_offset = cpu_to_le64(header.gd_offset);
1756 header.grain_offset = cpu_to_le64(header.grain_offset);
1757 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1759 header.check_bytes[0] = 0xa;
1760 header.check_bytes[1] = 0x20;
1761 header.check_bytes[2] = 0xd;
1762 header.check_bytes[3] = 0xa;
1764 /* write all the data */
1765 ret = blk_pwrite(blk, 0, &magic, sizeof(magic), 0);
1766 if (ret < 0) {
1767 error_setg(errp, QERR_IO_ERROR);
1768 goto exit;
1770 ret = blk_pwrite(blk, sizeof(magic), &header, sizeof(header), 0);
1771 if (ret < 0) {
1772 error_setg(errp, QERR_IO_ERROR);
1773 goto exit;
1776 ret = blk_truncate(blk, le64_to_cpu(header.grain_offset) << 9);
1777 if (ret < 0) {
1778 error_setg_errno(errp, -ret, "Could not truncate file");
1779 goto exit;
1782 /* write grain directory */
1783 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1784 gd_buf = g_malloc0(gd_buf_size);
1785 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1786 i < gt_count; i++, tmp += gt_size) {
1787 gd_buf[i] = cpu_to_le32(tmp);
1789 ret = blk_pwrite(blk, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1790 gd_buf, gd_buf_size, 0);
1791 if (ret < 0) {
1792 error_setg(errp, QERR_IO_ERROR);
1793 goto exit;
1796 /* write backup grain directory */
1797 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1798 i < gt_count; i++, tmp += gt_size) {
1799 gd_buf[i] = cpu_to_le32(tmp);
1801 ret = blk_pwrite(blk, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1802 gd_buf, gd_buf_size, 0);
1803 if (ret < 0) {
1804 error_setg(errp, QERR_IO_ERROR);
1805 goto exit;
1808 ret = 0;
1809 exit:
1810 if (blk) {
1811 blk_unref(blk);
1813 g_free(gd_buf);
1814 return ret;
1817 static int filename_decompose(const char *filename, char *path, char *prefix,
1818 char *postfix, size_t buf_len, Error **errp)
1820 const char *p, *q;
1822 if (filename == NULL || !strlen(filename)) {
1823 error_setg(errp, "No filename provided");
1824 return VMDK_ERROR;
1826 p = strrchr(filename, '/');
1827 if (p == NULL) {
1828 p = strrchr(filename, '\\');
1830 if (p == NULL) {
1831 p = strrchr(filename, ':');
1833 if (p != NULL) {
1834 p++;
1835 if (p - filename >= buf_len) {
1836 return VMDK_ERROR;
1838 pstrcpy(path, p - filename + 1, filename);
1839 } else {
1840 p = filename;
1841 path[0] = '\0';
1843 q = strrchr(p, '.');
1844 if (q == NULL) {
1845 pstrcpy(prefix, buf_len, p);
1846 postfix[0] = '\0';
1847 } else {
1848 if (q - p >= buf_len) {
1849 return VMDK_ERROR;
1851 pstrcpy(prefix, q - p + 1, p);
1852 pstrcpy(postfix, buf_len, q);
1854 return VMDK_OK;
1857 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1859 int idx = 0;
1860 BlockBackend *new_blk = NULL;
1861 Error *local_err = NULL;
1862 char *desc = NULL;
1863 int64_t total_size = 0, filesize;
1864 char *adapter_type = NULL;
1865 char *backing_file = NULL;
1866 char *hw_version = NULL;
1867 char *fmt = NULL;
1868 int ret = 0;
1869 bool flat, split, compress;
1870 GString *ext_desc_lines;
1871 char *path = g_malloc0(PATH_MAX);
1872 char *prefix = g_malloc0(PATH_MAX);
1873 char *postfix = g_malloc0(PATH_MAX);
1874 char *desc_line = g_malloc0(BUF_SIZE);
1875 char *ext_filename = g_malloc0(PATH_MAX);
1876 char *desc_filename = g_malloc0(PATH_MAX);
1877 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1878 const char *desc_extent_line;
1879 char *parent_desc_line = g_malloc0(BUF_SIZE);
1880 uint32_t parent_cid = 0xffffffff;
1881 uint32_t number_heads = 16;
1882 bool zeroed_grain = false;
1883 uint32_t desc_offset = 0, desc_len;
1884 const char desc_template[] =
1885 "# Disk DescriptorFile\n"
1886 "version=1\n"
1887 "CID=%" PRIx32 "\n"
1888 "parentCID=%" PRIx32 "\n"
1889 "createType=\"%s\"\n"
1890 "%s"
1891 "\n"
1892 "# Extent description\n"
1893 "%s"
1894 "\n"
1895 "# The Disk Data Base\n"
1896 "#DDB\n"
1897 "\n"
1898 "ddb.virtualHWVersion = \"%s\"\n"
1899 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1900 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1901 "ddb.geometry.sectors = \"63\"\n"
1902 "ddb.adapterType = \"%s\"\n";
1904 ext_desc_lines = g_string_new(NULL);
1906 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1907 ret = -EINVAL;
1908 goto exit;
1910 /* Read out options */
1911 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1912 BDRV_SECTOR_SIZE);
1913 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1914 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1915 hw_version = qemu_opt_get_del(opts, BLOCK_OPT_HWVERSION);
1916 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1917 if (strcmp(hw_version, "undefined")) {
1918 error_setg(errp,
1919 "compat6 cannot be enabled with hwversion set");
1920 ret = -EINVAL;
1921 goto exit;
1923 g_free(hw_version);
1924 hw_version = g_strdup("6");
1926 if (strcmp(hw_version, "undefined") == 0) {
1927 g_free(hw_version);
1928 hw_version = g_strdup("4");
1930 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1931 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1932 zeroed_grain = true;
1935 if (!adapter_type) {
1936 adapter_type = g_strdup("ide");
1937 } else if (strcmp(adapter_type, "ide") &&
1938 strcmp(adapter_type, "buslogic") &&
1939 strcmp(adapter_type, "lsilogic") &&
1940 strcmp(adapter_type, "legacyESX")) {
1941 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1942 ret = -EINVAL;
1943 goto exit;
1945 if (strcmp(adapter_type, "ide") != 0) {
1946 /* that's the number of heads with which vmware operates when
1947 creating, exporting, etc. vmdk files with a non-ide adapter type */
1948 number_heads = 255;
1950 if (!fmt) {
1951 /* Default format to monolithicSparse */
1952 fmt = g_strdup("monolithicSparse");
1953 } else if (strcmp(fmt, "monolithicFlat") &&
1954 strcmp(fmt, "monolithicSparse") &&
1955 strcmp(fmt, "twoGbMaxExtentSparse") &&
1956 strcmp(fmt, "twoGbMaxExtentFlat") &&
1957 strcmp(fmt, "streamOptimized")) {
1958 error_setg(errp, "Unknown subformat: '%s'", fmt);
1959 ret = -EINVAL;
1960 goto exit;
1962 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1963 strcmp(fmt, "twoGbMaxExtentSparse"));
1964 flat = !(strcmp(fmt, "monolithicFlat") &&
1965 strcmp(fmt, "twoGbMaxExtentFlat"));
1966 compress = !strcmp(fmt, "streamOptimized");
1967 if (flat) {
1968 desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1969 } else {
1970 desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1972 if (flat && backing_file) {
1973 error_setg(errp, "Flat image can't have backing file");
1974 ret = -ENOTSUP;
1975 goto exit;
1977 if (flat && zeroed_grain) {
1978 error_setg(errp, "Flat image can't enable zeroed grain");
1979 ret = -ENOTSUP;
1980 goto exit;
1982 if (backing_file) {
1983 BlockBackend *blk;
1984 char *full_backing = g_new0(char, PATH_MAX);
1985 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
1986 full_backing, PATH_MAX,
1987 &local_err);
1988 if (local_err) {
1989 g_free(full_backing);
1990 error_propagate(errp, local_err);
1991 ret = -ENOENT;
1992 goto exit;
1995 blk = blk_new_open(full_backing, NULL, NULL,
1996 BDRV_O_NO_BACKING, errp);
1997 g_free(full_backing);
1998 if (blk == NULL) {
1999 ret = -EIO;
2000 goto exit;
2002 if (strcmp(blk_bs(blk)->drv->format_name, "vmdk")) {
2003 blk_unref(blk);
2004 ret = -EINVAL;
2005 goto exit;
2007 parent_cid = vmdk_read_cid(blk_bs(blk), 0);
2008 blk_unref(blk);
2009 snprintf(parent_desc_line, BUF_SIZE,
2010 "parentFileNameHint=\"%s\"", backing_file);
2013 /* Create extents */
2014 filesize = total_size;
2015 while (filesize > 0) {
2016 int64_t size = filesize;
2018 if (split && size > split_size) {
2019 size = split_size;
2021 if (split) {
2022 snprintf(desc_filename, PATH_MAX, "%s-%c%03d%s",
2023 prefix, flat ? 'f' : 's', ++idx, postfix);
2024 } else if (flat) {
2025 snprintf(desc_filename, PATH_MAX, "%s-flat%s", prefix, postfix);
2026 } else {
2027 snprintf(desc_filename, PATH_MAX, "%s%s", prefix, postfix);
2029 snprintf(ext_filename, PATH_MAX, "%s%s", path, desc_filename);
2031 if (vmdk_create_extent(ext_filename, size,
2032 flat, compress, zeroed_grain, opts, errp)) {
2033 ret = -EINVAL;
2034 goto exit;
2036 filesize -= size;
2038 /* Format description line */
2039 snprintf(desc_line, BUF_SIZE,
2040 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
2041 g_string_append(ext_desc_lines, desc_line);
2043 /* generate descriptor file */
2044 desc = g_strdup_printf(desc_template,
2045 g_random_int(),
2046 parent_cid,
2047 fmt,
2048 parent_desc_line,
2049 ext_desc_lines->str,
2050 hw_version,
2051 total_size /
2052 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
2053 number_heads,
2054 adapter_type);
2055 desc_len = strlen(desc);
2056 /* the descriptor offset = 0x200 */
2057 if (!split && !flat) {
2058 desc_offset = 0x200;
2059 } else {
2060 ret = bdrv_create_file(filename, opts, &local_err);
2061 if (ret < 0) {
2062 error_propagate(errp, local_err);
2063 goto exit;
2067 new_blk = blk_new_open(filename, NULL, NULL,
2068 BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
2069 if (new_blk == NULL) {
2070 error_propagate(errp, local_err);
2071 ret = -EIO;
2072 goto exit;
2075 blk_set_allow_write_beyond_eof(new_blk, true);
2077 ret = blk_pwrite(new_blk, desc_offset, desc, desc_len, 0);
2078 if (ret < 0) {
2079 error_setg_errno(errp, -ret, "Could not write description");
2080 goto exit;
2082 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2083 * for description file */
2084 if (desc_offset == 0) {
2085 ret = blk_truncate(new_blk, desc_len);
2086 if (ret < 0) {
2087 error_setg_errno(errp, -ret, "Could not truncate file");
2090 exit:
2091 if (new_blk) {
2092 blk_unref(new_blk);
2094 g_free(adapter_type);
2095 g_free(backing_file);
2096 g_free(hw_version);
2097 g_free(fmt);
2098 g_free(desc);
2099 g_free(path);
2100 g_free(prefix);
2101 g_free(postfix);
2102 g_free(desc_line);
2103 g_free(ext_filename);
2104 g_free(desc_filename);
2105 g_free(parent_desc_line);
2106 g_string_free(ext_desc_lines, true);
2107 return ret;
2110 static void vmdk_close(BlockDriverState *bs)
2112 BDRVVmdkState *s = bs->opaque;
2114 vmdk_free_extents(bs);
2115 g_free(s->create_type);
2117 migrate_del_blocker(s->migration_blocker);
2118 error_free(s->migration_blocker);
2121 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
2123 BDRVVmdkState *s = bs->opaque;
2124 int i, err;
2125 int ret = 0;
2127 for (i = 0; i < s->num_extents; i++) {
2128 err = bdrv_co_flush(s->extents[i].file->bs);
2129 if (err < 0) {
2130 ret = err;
2133 return ret;
2136 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2138 int i;
2139 int64_t ret = 0;
2140 int64_t r;
2141 BDRVVmdkState *s = bs->opaque;
2143 ret = bdrv_get_allocated_file_size(bs->file->bs);
2144 if (ret < 0) {
2145 return ret;
2147 for (i = 0; i < s->num_extents; i++) {
2148 if (s->extents[i].file == bs->file) {
2149 continue;
2151 r = bdrv_get_allocated_file_size(s->extents[i].file->bs);
2152 if (r < 0) {
2153 return r;
2155 ret += r;
2157 return ret;
2160 static int vmdk_has_zero_init(BlockDriverState *bs)
2162 int i;
2163 BDRVVmdkState *s = bs->opaque;
2165 /* If has a flat extent and its underlying storage doesn't have zero init,
2166 * return 0. */
2167 for (i = 0; i < s->num_extents; i++) {
2168 if (s->extents[i].flat) {
2169 if (!bdrv_has_zero_init(s->extents[i].file->bs)) {
2170 return 0;
2174 return 1;
2177 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2179 ImageInfo *info = g_new0(ImageInfo, 1);
2181 *info = (ImageInfo){
2182 .filename = g_strdup(extent->file->bs->filename),
2183 .format = g_strdup(extent->type),
2184 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2185 .compressed = extent->compressed,
2186 .has_compressed = extent->compressed,
2187 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2188 .has_cluster_size = !extent->flat,
2191 return info;
2194 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2195 BdrvCheckMode fix)
2197 BDRVVmdkState *s = bs->opaque;
2198 VmdkExtent *extent = NULL;
2199 int64_t sector_num = 0;
2200 int64_t total_sectors = bdrv_nb_sectors(bs);
2201 int ret;
2202 uint64_t cluster_offset;
2204 if (fix) {
2205 return -ENOTSUP;
2208 for (;;) {
2209 if (sector_num >= total_sectors) {
2210 return 0;
2212 extent = find_extent(s, sector_num, extent);
2213 if (!extent) {
2214 fprintf(stderr,
2215 "ERROR: could not find extent for sector %" PRId64 "\n",
2216 sector_num);
2217 break;
2219 ret = get_cluster_offset(bs, extent, NULL,
2220 sector_num << BDRV_SECTOR_BITS,
2221 false, &cluster_offset, 0, 0);
2222 if (ret == VMDK_ERROR) {
2223 fprintf(stderr,
2224 "ERROR: could not get cluster_offset for sector %"
2225 PRId64 "\n", sector_num);
2226 break;
2228 if (ret == VMDK_OK &&
2229 cluster_offset >= bdrv_getlength(extent->file->bs))
2231 fprintf(stderr,
2232 "ERROR: cluster offset for sector %"
2233 PRId64 " points after EOF\n", sector_num);
2234 break;
2236 sector_num += extent->cluster_sectors;
2239 result->corruptions++;
2240 return 0;
2243 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2245 int i;
2246 BDRVVmdkState *s = bs->opaque;
2247 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2248 ImageInfoList **next;
2250 *spec_info = (ImageInfoSpecific){
2251 .type = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2252 .u = {
2253 .vmdk.data = g_new0(ImageInfoSpecificVmdk, 1),
2257 *spec_info->u.vmdk.data = (ImageInfoSpecificVmdk) {
2258 .create_type = g_strdup(s->create_type),
2259 .cid = s->cid,
2260 .parent_cid = s->parent_cid,
2263 next = &spec_info->u.vmdk.data->extents;
2264 for (i = 0; i < s->num_extents; i++) {
2265 *next = g_new0(ImageInfoList, 1);
2266 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2267 (*next)->next = NULL;
2268 next = &(*next)->next;
2271 return spec_info;
2274 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2276 return a->flat == b->flat &&
2277 a->compressed == b->compressed &&
2278 (a->flat || a->cluster_sectors == b->cluster_sectors);
2281 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2283 int i;
2284 BDRVVmdkState *s = bs->opaque;
2285 assert(s->num_extents);
2287 /* See if we have multiple extents but they have different cases */
2288 for (i = 1; i < s->num_extents; i++) {
2289 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2290 return -ENOTSUP;
2293 bdi->needs_compressed_writes = s->extents[0].compressed;
2294 if (!s->extents[0].flat) {
2295 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2297 return 0;
2300 static QemuOptsList vmdk_create_opts = {
2301 .name = "vmdk-create-opts",
2302 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2303 .desc = {
2305 .name = BLOCK_OPT_SIZE,
2306 .type = QEMU_OPT_SIZE,
2307 .help = "Virtual disk size"
2310 .name = BLOCK_OPT_ADAPTER_TYPE,
2311 .type = QEMU_OPT_STRING,
2312 .help = "Virtual adapter type, can be one of "
2313 "ide (default), lsilogic, buslogic or legacyESX"
2316 .name = BLOCK_OPT_BACKING_FILE,
2317 .type = QEMU_OPT_STRING,
2318 .help = "File name of a base image"
2321 .name = BLOCK_OPT_COMPAT6,
2322 .type = QEMU_OPT_BOOL,
2323 .help = "VMDK version 6 image",
2324 .def_value_str = "off"
2327 .name = BLOCK_OPT_HWVERSION,
2328 .type = QEMU_OPT_STRING,
2329 .help = "VMDK hardware version",
2330 .def_value_str = "undefined"
2333 .name = BLOCK_OPT_SUBFMT,
2334 .type = QEMU_OPT_STRING,
2335 .help =
2336 "VMDK flat extent format, can be one of "
2337 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2340 .name = BLOCK_OPT_ZEROED_GRAIN,
2341 .type = QEMU_OPT_BOOL,
2342 .help = "Enable efficient zero writes "
2343 "using the zeroed-grain GTE feature"
2345 { /* end of list */ }
2349 static BlockDriver bdrv_vmdk = {
2350 .format_name = "vmdk",
2351 .instance_size = sizeof(BDRVVmdkState),
2352 .bdrv_probe = vmdk_probe,
2353 .bdrv_open = vmdk_open,
2354 .bdrv_check = vmdk_check,
2355 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2356 .bdrv_co_preadv = vmdk_co_preadv,
2357 .bdrv_co_pwritev = vmdk_co_pwritev,
2358 .bdrv_co_pwritev_compressed = vmdk_co_pwritev_compressed,
2359 .bdrv_co_pwrite_zeroes = vmdk_co_pwrite_zeroes,
2360 .bdrv_close = vmdk_close,
2361 .bdrv_create = vmdk_create,
2362 .bdrv_co_flush_to_disk = vmdk_co_flush,
2363 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2364 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2365 .bdrv_has_zero_init = vmdk_has_zero_init,
2366 .bdrv_get_specific_info = vmdk_get_specific_info,
2367 .bdrv_refresh_limits = vmdk_refresh_limits,
2368 .bdrv_get_info = vmdk_get_info,
2370 .supports_backing = true,
2371 .create_opts = &vmdk_create_opts,
2374 static void bdrv_vmdk_init(void)
2376 bdrv_register(&bdrv_vmdk);
2379 block_init(bdrv_vmdk_init);