xilinx: Inline usages of xilinx_axi*_init()
[qemu/rayw.git] / block / vmdk.c
blob83839f9b7a48b46a413e41d0b56c482eae1319d2
1 /*
2 * Block driver for the VMDK format
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
26 #include "qemu-common.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "migration/migration.h"
30 #include <zlib.h>
32 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
33 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
34 #define VMDK4_COMPRESSION_DEFLATE 1
35 #define VMDK4_FLAG_NL_DETECT (1 << 0)
36 #define VMDK4_FLAG_RGD (1 << 1)
37 /* Zeroed-grain enable bit */
38 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
39 #define VMDK4_FLAG_COMPRESS (1 << 16)
40 #define VMDK4_FLAG_MARKER (1 << 17)
41 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
43 #define VMDK_GTE_ZEROED 0x1
45 /* VMDK internal error codes */
46 #define VMDK_OK 0
47 #define VMDK_ERROR (-1)
48 /* Cluster not allocated */
49 #define VMDK_UNALLOC (-2)
50 #define VMDK_ZEROED (-3)
52 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
54 typedef struct {
55 uint32_t version;
56 uint32_t flags;
57 uint32_t disk_sectors;
58 uint32_t granularity;
59 uint32_t l1dir_offset;
60 uint32_t l1dir_size;
61 uint32_t file_sectors;
62 uint32_t cylinders;
63 uint32_t heads;
64 uint32_t sectors_per_track;
65 } QEMU_PACKED VMDK3Header;
67 typedef struct {
68 uint32_t version;
69 uint32_t flags;
70 uint64_t capacity;
71 uint64_t granularity;
72 uint64_t desc_offset;
73 uint64_t desc_size;
74 /* Number of GrainTableEntries per GrainTable */
75 uint32_t num_gtes_per_gt;
76 uint64_t rgd_offset;
77 uint64_t gd_offset;
78 uint64_t grain_offset;
79 char filler[1];
80 char check_bytes[4];
81 uint16_t compressAlgorithm;
82 } QEMU_PACKED VMDK4Header;
84 #define L2_CACHE_SIZE 16
86 typedef struct VmdkExtent {
87 BlockDriverState *file;
88 bool flat;
89 bool compressed;
90 bool has_marker;
91 bool has_zero_grain;
92 int version;
93 int64_t sectors;
94 int64_t end_sector;
95 int64_t flat_start_offset;
96 int64_t l1_table_offset;
97 int64_t l1_backup_table_offset;
98 uint32_t *l1_table;
99 uint32_t *l1_backup_table;
100 unsigned int l1_size;
101 uint32_t l1_entry_sectors;
103 unsigned int l2_size;
104 uint32_t *l2_cache;
105 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
106 uint32_t l2_cache_counts[L2_CACHE_SIZE];
108 int64_t cluster_sectors;
109 char *type;
110 } VmdkExtent;
112 typedef struct BDRVVmdkState {
113 CoMutex lock;
114 uint64_t desc_offset;
115 bool cid_updated;
116 bool cid_checked;
117 uint32_t cid;
118 uint32_t parent_cid;
119 int num_extents;
120 /* Extent array with num_extents entries, ascend ordered by address */
121 VmdkExtent *extents;
122 Error *migration_blocker;
123 char *create_type;
124 } BDRVVmdkState;
126 typedef struct VmdkMetaData {
127 uint32_t offset;
128 unsigned int l1_index;
129 unsigned int l2_index;
130 unsigned int l2_offset;
131 int valid;
132 uint32_t *l2_cache_entry;
133 } VmdkMetaData;
135 typedef struct VmdkGrainMarker {
136 uint64_t lba;
137 uint32_t size;
138 uint8_t data[0];
139 } QEMU_PACKED VmdkGrainMarker;
141 enum {
142 MARKER_END_OF_STREAM = 0,
143 MARKER_GRAIN_TABLE = 1,
144 MARKER_GRAIN_DIRECTORY = 2,
145 MARKER_FOOTER = 3,
148 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
150 uint32_t magic;
152 if (buf_size < 4) {
153 return 0;
155 magic = be32_to_cpu(*(uint32_t *)buf);
156 if (magic == VMDK3_MAGIC ||
157 magic == VMDK4_MAGIC) {
158 return 100;
159 } else {
160 const char *p = (const char *)buf;
161 const char *end = p + buf_size;
162 while (p < end) {
163 if (*p == '#') {
164 /* skip comment line */
165 while (p < end && *p != '\n') {
166 p++;
168 p++;
169 continue;
171 if (*p == ' ') {
172 while (p < end && *p == ' ') {
173 p++;
175 /* skip '\r' if windows line endings used. */
176 if (p < end && *p == '\r') {
177 p++;
179 /* only accept blank lines before 'version=' line */
180 if (p == end || *p != '\n') {
181 return 0;
183 p++;
184 continue;
186 if (end - p >= strlen("version=X\n")) {
187 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
188 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
189 return 100;
192 if (end - p >= strlen("version=X\r\n")) {
193 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
194 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
195 return 100;
198 return 0;
200 return 0;
204 #define SECTOR_SIZE 512
205 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
206 #define BUF_SIZE 4096
207 #define HEADER_SIZE 512 /* first sector of 512 bytes */
209 static void vmdk_free_extents(BlockDriverState *bs)
211 int i;
212 BDRVVmdkState *s = bs->opaque;
213 VmdkExtent *e;
215 for (i = 0; i < s->num_extents; i++) {
216 e = &s->extents[i];
217 g_free(e->l1_table);
218 g_free(e->l2_cache);
219 g_free(e->l1_backup_table);
220 g_free(e->type);
221 if (e->file != bs->file) {
222 bdrv_unref(e->file);
225 g_free(s->extents);
228 static void vmdk_free_last_extent(BlockDriverState *bs)
230 BDRVVmdkState *s = bs->opaque;
232 if (s->num_extents == 0) {
233 return;
235 s->num_extents--;
236 s->extents = g_realloc(s->extents, s->num_extents * sizeof(VmdkExtent));
239 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
241 char desc[DESC_SIZE];
242 uint32_t cid = 0xffffffff;
243 const char *p_name, *cid_str;
244 size_t cid_str_size;
245 BDRVVmdkState *s = bs->opaque;
246 int ret;
248 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
249 if (ret < 0) {
250 return 0;
253 if (parent) {
254 cid_str = "parentCID";
255 cid_str_size = sizeof("parentCID");
256 } else {
257 cid_str = "CID";
258 cid_str_size = sizeof("CID");
261 desc[DESC_SIZE - 1] = '\0';
262 p_name = strstr(desc, cid_str);
263 if (p_name != NULL) {
264 p_name += cid_str_size;
265 sscanf(p_name, "%x", &cid);
268 return cid;
271 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
273 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
274 char *p_name, *tmp_str;
275 BDRVVmdkState *s = bs->opaque;
276 int ret;
278 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
279 if (ret < 0) {
280 return ret;
283 desc[DESC_SIZE - 1] = '\0';
284 tmp_str = strstr(desc, "parentCID");
285 if (tmp_str == NULL) {
286 return -EINVAL;
289 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
290 p_name = strstr(desc, "CID");
291 if (p_name != NULL) {
292 p_name += sizeof("CID");
293 snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);
294 pstrcat(desc, sizeof(desc), tmp_desc);
297 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
298 if (ret < 0) {
299 return ret;
302 return 0;
305 static int vmdk_is_cid_valid(BlockDriverState *bs)
307 BDRVVmdkState *s = bs->opaque;
308 BlockDriverState *p_bs = bs->backing_hd;
309 uint32_t cur_pcid;
311 if (!s->cid_checked && p_bs) {
312 cur_pcid = vmdk_read_cid(p_bs, 0);
313 if (s->parent_cid != cur_pcid) {
314 /* CID not valid */
315 return 0;
318 s->cid_checked = true;
319 /* CID valid */
320 return 1;
323 /* Queue extents, if any, for reopen() */
324 static int vmdk_reopen_prepare(BDRVReopenState *state,
325 BlockReopenQueue *queue, Error **errp)
327 BDRVVmdkState *s;
328 int ret = -1;
329 int i;
330 VmdkExtent *e;
332 assert(state != NULL);
333 assert(state->bs != NULL);
335 if (queue == NULL) {
336 error_setg(errp, "No reopen queue for VMDK extents");
337 goto exit;
340 s = state->bs->opaque;
342 assert(s != NULL);
344 for (i = 0; i < s->num_extents; i++) {
345 e = &s->extents[i];
346 if (e->file != state->bs->file) {
347 bdrv_reopen_queue(queue, e->file, state->flags);
350 ret = 0;
352 exit:
353 return ret;
356 static int vmdk_parent_open(BlockDriverState *bs)
358 char *p_name;
359 char desc[DESC_SIZE + 1];
360 BDRVVmdkState *s = bs->opaque;
361 int ret;
363 desc[DESC_SIZE] = '\0';
364 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
365 if (ret < 0) {
366 return ret;
369 p_name = strstr(desc, "parentFileNameHint");
370 if (p_name != NULL) {
371 char *end_name;
373 p_name += sizeof("parentFileNameHint") + 1;
374 end_name = strchr(p_name, '\"');
375 if (end_name == NULL) {
376 return -EINVAL;
378 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
379 return -EINVAL;
382 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
385 return 0;
388 /* Create and append extent to the extent array. Return the added VmdkExtent
389 * address. return NULL if allocation failed. */
390 static int vmdk_add_extent(BlockDriverState *bs,
391 BlockDriverState *file, bool flat, int64_t sectors,
392 int64_t l1_offset, int64_t l1_backup_offset,
393 uint32_t l1_size,
394 int l2_size, uint64_t cluster_sectors,
395 VmdkExtent **new_extent,
396 Error **errp)
398 VmdkExtent *extent;
399 BDRVVmdkState *s = bs->opaque;
401 if (cluster_sectors > 0x200000) {
402 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
403 error_setg(errp, "Invalid granularity, image may be corrupt");
404 return -EFBIG;
406 if (l1_size > 512 * 1024 * 1024) {
407 /* Although with big capacity and small l1_entry_sectors, we can get a
408 * big l1_size, we don't want unbounded value to allocate the table.
409 * Limit it to 512M, which is 16PB for default cluster and L2 table
410 * size */
411 error_setg(errp, "L1 size too big");
412 return -EFBIG;
415 s->extents = g_realloc(s->extents,
416 (s->num_extents + 1) * sizeof(VmdkExtent));
417 extent = &s->extents[s->num_extents];
418 s->num_extents++;
420 memset(extent, 0, sizeof(VmdkExtent));
421 extent->file = file;
422 extent->flat = flat;
423 extent->sectors = sectors;
424 extent->l1_table_offset = l1_offset;
425 extent->l1_backup_table_offset = l1_backup_offset;
426 extent->l1_size = l1_size;
427 extent->l1_entry_sectors = l2_size * cluster_sectors;
428 extent->l2_size = l2_size;
429 extent->cluster_sectors = flat ? 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 int l1_size, i;
449 /* read the L1 table */
450 l1_size = extent->l1_size * sizeof(uint32_t);
451 extent->l1_table = g_malloc(l1_size);
452 ret = bdrv_pread(extent->file,
453 extent->l1_table_offset,
454 extent->l1_table,
455 l1_size);
456 if (ret < 0) {
457 error_setg_errno(errp, -ret,
458 "Could not read l1 table from extent '%s'",
459 extent->file->filename);
460 goto fail_l1;
462 for (i = 0; i < extent->l1_size; i++) {
463 le32_to_cpus(&extent->l1_table[i]);
466 if (extent->l1_backup_table_offset) {
467 extent->l1_backup_table = g_malloc(l1_size);
468 ret = bdrv_pread(extent->file,
469 extent->l1_backup_table_offset,
470 extent->l1_backup_table,
471 l1_size);
472 if (ret < 0) {
473 error_setg_errno(errp, -ret,
474 "Could not read l1 backup table from extent '%s'",
475 extent->file->filename);
476 goto fail_l1b;
478 for (i = 0; i < extent->l1_size; i++) {
479 le32_to_cpus(&extent->l1_backup_table[i]);
483 extent->l2_cache =
484 g_malloc(extent->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
485 return 0;
486 fail_l1b:
487 g_free(extent->l1_backup_table);
488 fail_l1:
489 g_free(extent->l1_table);
490 return ret;
493 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
494 BlockDriverState *file,
495 int flags, Error **errp)
497 int ret;
498 uint32_t magic;
499 VMDK3Header header;
500 VmdkExtent *extent;
502 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
503 if (ret < 0) {
504 error_setg_errno(errp, -ret,
505 "Could not read header from file '%s'",
506 file->filename);
507 return ret;
509 ret = vmdk_add_extent(bs, file, false,
510 le32_to_cpu(header.disk_sectors),
511 le32_to_cpu(header.l1dir_offset) << 9,
513 le32_to_cpu(header.l1dir_size),
514 4096,
515 le32_to_cpu(header.granularity),
516 &extent,
517 errp);
518 if (ret < 0) {
519 return ret;
521 ret = vmdk_init_tables(bs, extent, errp);
522 if (ret) {
523 /* free extent allocated by vmdk_add_extent */
524 vmdk_free_last_extent(bs);
526 return ret;
529 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
530 Error **errp);
532 static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset,
533 Error **errp)
535 int64_t size;
536 char *buf;
537 int ret;
539 size = bdrv_getlength(file);
540 if (size < 0) {
541 error_setg_errno(errp, -size, "Could not access file");
542 return NULL;
545 size = MIN(size, 1 << 20); /* avoid unbounded allocation */
546 buf = g_malloc0(size + 1);
548 ret = bdrv_pread(file, desc_offset, buf, size);
549 if (ret < 0) {
550 error_setg_errno(errp, -ret, "Could not read from file");
551 g_free(buf);
552 return NULL;
555 return buf;
558 static int vmdk_open_vmdk4(BlockDriverState *bs,
559 BlockDriverState *file,
560 int flags, Error **errp)
562 int ret;
563 uint32_t magic;
564 uint32_t l1_size, l1_entry_sectors;
565 VMDK4Header header;
566 VmdkExtent *extent;
567 BDRVVmdkState *s = bs->opaque;
568 int64_t l1_backup_offset = 0;
570 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
571 if (ret < 0) {
572 error_setg_errno(errp, -ret,
573 "Could not read header from file '%s'",
574 file->filename);
575 return -EINVAL;
577 if (header.capacity == 0) {
578 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
579 if (desc_offset) {
580 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
581 if (!buf) {
582 return -EINVAL;
584 ret = vmdk_open_desc_file(bs, flags, buf, errp);
585 g_free(buf);
586 return ret;
590 if (!s->create_type) {
591 s->create_type = g_strdup("monolithicSparse");
594 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
596 * The footer takes precedence over the header, so read it in. The
597 * footer starts at offset -1024 from the end: One sector for the
598 * footer, and another one for the end-of-stream marker.
600 struct {
601 struct {
602 uint64_t val;
603 uint32_t size;
604 uint32_t type;
605 uint8_t pad[512 - 16];
606 } QEMU_PACKED footer_marker;
608 uint32_t magic;
609 VMDK4Header header;
610 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
612 struct {
613 uint64_t val;
614 uint32_t size;
615 uint32_t type;
616 uint8_t pad[512 - 16];
617 } QEMU_PACKED eos_marker;
618 } QEMU_PACKED footer;
620 ret = bdrv_pread(file,
621 bs->file->total_sectors * 512 - 1536,
622 &footer, sizeof(footer));
623 if (ret < 0) {
624 return ret;
627 /* Some sanity checks for the footer */
628 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
629 le32_to_cpu(footer.footer_marker.size) != 0 ||
630 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
631 le64_to_cpu(footer.eos_marker.val) != 0 ||
632 le32_to_cpu(footer.eos_marker.size) != 0 ||
633 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
635 return -EINVAL;
638 header = footer.header;
641 if (le32_to_cpu(header.version) > 3) {
642 char buf[64];
643 snprintf(buf, sizeof(buf), "VMDK version %d",
644 le32_to_cpu(header.version));
645 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
646 bs->device_name, "vmdk", buf);
647 return -ENOTSUP;
648 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
649 /* VMware KB 2064959 explains that version 3 added support for
650 * persistent changed block tracking (CBT), and backup software can
651 * read it as version=1 if it doesn't care about the changed area
652 * information. So we are safe to enable read only. */
653 error_setg(errp, "VMDK version 3 must be read only");
654 return -EINVAL;
657 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
658 error_setg(errp, "L2 table size too big");
659 return -EINVAL;
662 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
663 * le64_to_cpu(header.granularity);
664 if (l1_entry_sectors == 0) {
665 return -EINVAL;
667 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
668 / l1_entry_sectors;
669 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
670 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
672 if (bdrv_getlength(file) <
673 le64_to_cpu(header.grain_offset) * BDRV_SECTOR_SIZE) {
674 error_setg(errp, "File truncated, expecting at least %lld bytes",
675 le64_to_cpu(header.grain_offset) * BDRV_SECTOR_SIZE);
676 return -EINVAL;
679 ret = vmdk_add_extent(bs, file, false,
680 le64_to_cpu(header.capacity),
681 le64_to_cpu(header.gd_offset) << 9,
682 l1_backup_offset,
683 l1_size,
684 le32_to_cpu(header.num_gtes_per_gt),
685 le64_to_cpu(header.granularity),
686 &extent,
687 errp);
688 if (ret < 0) {
689 return ret;
691 extent->compressed =
692 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
693 if (extent->compressed) {
694 g_free(s->create_type);
695 s->create_type = g_strdup("streamOptimized");
697 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
698 extent->version = le32_to_cpu(header.version);
699 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
700 ret = vmdk_init_tables(bs, extent, errp);
701 if (ret) {
702 /* free extent allocated by vmdk_add_extent */
703 vmdk_free_last_extent(bs);
705 return ret;
708 /* find an option value out of descriptor file */
709 static int vmdk_parse_description(const char *desc, const char *opt_name,
710 char *buf, int buf_size)
712 char *opt_pos, *opt_end;
713 const char *end = desc + strlen(desc);
715 opt_pos = strstr(desc, opt_name);
716 if (!opt_pos) {
717 return VMDK_ERROR;
719 /* Skip "=\"" following opt_name */
720 opt_pos += strlen(opt_name) + 2;
721 if (opt_pos >= end) {
722 return VMDK_ERROR;
724 opt_end = opt_pos;
725 while (opt_end < end && *opt_end != '"') {
726 opt_end++;
728 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
729 return VMDK_ERROR;
731 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
732 return VMDK_OK;
735 /* Open an extent file and append to bs array */
736 static int vmdk_open_sparse(BlockDriverState *bs,
737 BlockDriverState *file, int flags,
738 char *buf, Error **errp)
740 uint32_t magic;
742 magic = ldl_be_p(buf);
743 switch (magic) {
744 case VMDK3_MAGIC:
745 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
746 break;
747 case VMDK4_MAGIC:
748 return vmdk_open_vmdk4(bs, file, flags, errp);
749 break;
750 default:
751 error_setg(errp, "Image not in VMDK format");
752 return -EINVAL;
753 break;
757 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
758 const char *desc_file_path, Error **errp)
760 int ret;
761 char access[11];
762 char type[11];
763 char fname[512];
764 const char *p = desc;
765 int64_t sectors = 0;
766 int64_t flat_offset;
767 char extent_path[PATH_MAX];
768 BlockDriverState *extent_file;
769 BDRVVmdkState *s = bs->opaque;
770 VmdkExtent *extent;
772 while (*p) {
773 /* parse extent line:
774 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
775 * or
776 * RW [size in sectors] SPARSE "file-name.vmdk"
778 flat_offset = -1;
779 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
780 access, &sectors, type, fname, &flat_offset);
781 if (ret < 4 || strcmp(access, "RW")) {
782 goto next_line;
783 } else if (!strcmp(type, "FLAT")) {
784 if (ret != 5 || flat_offset < 0) {
785 error_setg(errp, "Invalid extent lines: \n%s", p);
786 return -EINVAL;
788 } else if (!strcmp(type, "VMFS")) {
789 if (ret == 4) {
790 flat_offset = 0;
791 } else {
792 error_setg(errp, "Invalid extent lines:\n%s", p);
793 return -EINVAL;
795 } else if (ret != 4) {
796 error_setg(errp, "Invalid extent lines:\n%s", p);
797 return -EINVAL;
800 if (sectors <= 0 ||
801 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
802 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
803 (strcmp(access, "RW"))) {
804 goto next_line;
807 path_combine(extent_path, sizeof(extent_path),
808 desc_file_path, fname);
809 extent_file = NULL;
810 ret = bdrv_open(&extent_file, extent_path, NULL, NULL,
811 bs->open_flags | BDRV_O_PROTOCOL, NULL, errp);
812 if (ret) {
813 return ret;
816 /* save to extents array */
817 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
818 /* FLAT extent */
820 ret = vmdk_add_extent(bs, extent_file, true, sectors,
821 0, 0, 0, 0, 0, &extent, errp);
822 if (ret < 0) {
823 return ret;
825 extent->flat_start_offset = flat_offset << 9;
826 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
827 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
828 char *buf = vmdk_read_desc(extent_file, 0, errp);
829 if (!buf) {
830 ret = -EINVAL;
831 } else {
832 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf, errp);
834 if (ret) {
835 g_free(buf);
836 bdrv_unref(extent_file);
837 return ret;
839 extent = &s->extents[s->num_extents - 1];
840 } else {
841 error_setg(errp, "Unsupported extent type '%s'", type);
842 return -ENOTSUP;
844 extent->type = g_strdup(type);
845 next_line:
846 /* move to next line */
847 while (*p) {
848 if (*p == '\n') {
849 p++;
850 break;
852 p++;
855 return 0;
858 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
859 Error **errp)
861 int ret;
862 char ct[128];
863 BDRVVmdkState *s = bs->opaque;
865 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
866 error_setg(errp, "invalid VMDK image descriptor");
867 ret = -EINVAL;
868 goto exit;
870 if (strcmp(ct, "monolithicFlat") &&
871 strcmp(ct, "vmfs") &&
872 strcmp(ct, "vmfsSparse") &&
873 strcmp(ct, "twoGbMaxExtentSparse") &&
874 strcmp(ct, "twoGbMaxExtentFlat")) {
875 error_setg(errp, "Unsupported image type '%s'", ct);
876 ret = -ENOTSUP;
877 goto exit;
879 s->create_type = g_strdup(ct);
880 s->desc_offset = 0;
881 ret = vmdk_parse_extents(buf, bs, bs->file->filename, errp);
882 exit:
883 return ret;
886 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
887 Error **errp)
889 char *buf = NULL;
890 int ret;
891 BDRVVmdkState *s = bs->opaque;
892 uint32_t magic;
894 buf = vmdk_read_desc(bs->file, 0, errp);
895 if (!buf) {
896 return -EINVAL;
899 magic = ldl_be_p(buf);
900 switch (magic) {
901 case VMDK3_MAGIC:
902 case VMDK4_MAGIC:
903 ret = vmdk_open_sparse(bs, bs->file, flags, buf, errp);
904 s->desc_offset = 0x200;
905 break;
906 default:
907 ret = vmdk_open_desc_file(bs, flags, buf, errp);
908 break;
910 if (ret) {
911 goto fail;
914 /* try to open parent images, if exist */
915 ret = vmdk_parent_open(bs);
916 if (ret) {
917 goto fail;
919 s->cid = vmdk_read_cid(bs, 0);
920 s->parent_cid = vmdk_read_cid(bs, 1);
921 qemu_co_mutex_init(&s->lock);
923 /* Disable migration when VMDK images are used */
924 error_set(&s->migration_blocker,
925 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
926 "vmdk", bs->device_name, "live migration");
927 migrate_add_blocker(s->migration_blocker);
928 g_free(buf);
929 return 0;
931 fail:
932 g_free(buf);
933 g_free(s->create_type);
934 s->create_type = NULL;
935 vmdk_free_extents(bs);
936 return ret;
940 static int vmdk_refresh_limits(BlockDriverState *bs)
942 BDRVVmdkState *s = bs->opaque;
943 int i;
945 for (i = 0; i < s->num_extents; i++) {
946 if (!s->extents[i].flat) {
947 bs->bl.write_zeroes_alignment =
948 MAX(bs->bl.write_zeroes_alignment,
949 s->extents[i].cluster_sectors);
953 return 0;
956 static int get_whole_cluster(BlockDriverState *bs,
957 VmdkExtent *extent,
958 uint64_t cluster_offset,
959 uint64_t offset,
960 bool allocate)
962 int ret = VMDK_OK;
963 uint8_t *whole_grain = NULL;
965 /* we will be here if it's first write on non-exist grain(cluster).
966 * try to read from parent image, if exist */
967 if (bs->backing_hd) {
968 whole_grain =
969 qemu_blockalign(bs, extent->cluster_sectors << BDRV_SECTOR_BITS);
970 if (!vmdk_is_cid_valid(bs)) {
971 ret = VMDK_ERROR;
972 goto exit;
975 /* floor offset to cluster */
976 offset -= offset % (extent->cluster_sectors * 512);
977 ret = bdrv_read(bs->backing_hd, offset >> 9, whole_grain,
978 extent->cluster_sectors);
979 if (ret < 0) {
980 ret = VMDK_ERROR;
981 goto exit;
984 /* Write grain only into the active image */
985 ret = bdrv_write(extent->file, cluster_offset, whole_grain,
986 extent->cluster_sectors);
987 if (ret < 0) {
988 ret = VMDK_ERROR;
989 goto exit;
992 exit:
993 qemu_vfree(whole_grain);
994 return ret;
997 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data)
999 uint32_t offset;
1000 QEMU_BUILD_BUG_ON(sizeof(offset) != sizeof(m_data->offset));
1001 offset = cpu_to_le32(m_data->offset);
1002 /* update L2 table */
1003 if (bdrv_pwrite_sync(
1004 extent->file,
1005 ((int64_t)m_data->l2_offset * 512)
1006 + (m_data->l2_index * sizeof(m_data->offset)),
1007 &offset, sizeof(offset)) < 0) {
1008 return VMDK_ERROR;
1010 /* update backup L2 table */
1011 if (extent->l1_backup_table_offset != 0) {
1012 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1013 if (bdrv_pwrite_sync(
1014 extent->file,
1015 ((int64_t)m_data->l2_offset * 512)
1016 + (m_data->l2_index * sizeof(m_data->offset)),
1017 &offset, sizeof(offset)) < 0) {
1018 return VMDK_ERROR;
1021 if (m_data->l2_cache_entry) {
1022 *m_data->l2_cache_entry = offset;
1025 return VMDK_OK;
1028 static int get_cluster_offset(BlockDriverState *bs,
1029 VmdkExtent *extent,
1030 VmdkMetaData *m_data,
1031 uint64_t offset,
1032 int allocate,
1033 uint64_t *cluster_offset)
1035 unsigned int l1_index, l2_offset, l2_index;
1036 int min_index, i, j;
1037 uint32_t min_count, *l2_table;
1038 bool zeroed = false;
1040 if (m_data) {
1041 m_data->valid = 0;
1043 if (extent->flat) {
1044 *cluster_offset = extent->flat_start_offset;
1045 return VMDK_OK;
1048 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1049 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1050 if (l1_index >= extent->l1_size) {
1051 return VMDK_ERROR;
1053 l2_offset = extent->l1_table[l1_index];
1054 if (!l2_offset) {
1055 return VMDK_UNALLOC;
1057 for (i = 0; i < L2_CACHE_SIZE; i++) {
1058 if (l2_offset == extent->l2_cache_offsets[i]) {
1059 /* increment the hit count */
1060 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1061 for (j = 0; j < L2_CACHE_SIZE; j++) {
1062 extent->l2_cache_counts[j] >>= 1;
1065 l2_table = extent->l2_cache + (i * extent->l2_size);
1066 goto found;
1069 /* not found: load a new entry in the least used one */
1070 min_index = 0;
1071 min_count = 0xffffffff;
1072 for (i = 0; i < L2_CACHE_SIZE; i++) {
1073 if (extent->l2_cache_counts[i] < min_count) {
1074 min_count = extent->l2_cache_counts[i];
1075 min_index = i;
1078 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1079 if (bdrv_pread(
1080 extent->file,
1081 (int64_t)l2_offset * 512,
1082 l2_table,
1083 extent->l2_size * sizeof(uint32_t)
1084 ) != extent->l2_size * sizeof(uint32_t)) {
1085 return VMDK_ERROR;
1088 extent->l2_cache_offsets[min_index] = l2_offset;
1089 extent->l2_cache_counts[min_index] = 1;
1090 found:
1091 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1092 *cluster_offset = le32_to_cpu(l2_table[l2_index]);
1094 if (m_data) {
1095 m_data->valid = 1;
1096 m_data->l1_index = l1_index;
1097 m_data->l2_index = l2_index;
1098 m_data->offset = *cluster_offset;
1099 m_data->l2_offset = l2_offset;
1100 m_data->l2_cache_entry = &l2_table[l2_index];
1102 if (extent->has_zero_grain && *cluster_offset == VMDK_GTE_ZEROED) {
1103 zeroed = true;
1106 if (!*cluster_offset || zeroed) {
1107 if (!allocate) {
1108 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1111 /* Avoid the L2 tables update for the images that have snapshots. */
1112 *cluster_offset = bdrv_getlength(extent->file);
1113 if (!extent->compressed) {
1114 bdrv_truncate(
1115 extent->file,
1116 *cluster_offset + (extent->cluster_sectors << 9)
1120 *cluster_offset >>= 9;
1121 l2_table[l2_index] = cpu_to_le32(*cluster_offset);
1123 /* First of all we write grain itself, to avoid race condition
1124 * that may to corrupt the image.
1125 * This problem may occur because of insufficient space on host disk
1126 * or inappropriate VM shutdown.
1128 if (get_whole_cluster(
1129 bs, extent, *cluster_offset, offset, allocate) == -1) {
1130 return VMDK_ERROR;
1133 if (m_data) {
1134 m_data->offset = *cluster_offset;
1137 *cluster_offset <<= 9;
1138 return VMDK_OK;
1141 static VmdkExtent *find_extent(BDRVVmdkState *s,
1142 int64_t sector_num, VmdkExtent *start_hint)
1144 VmdkExtent *extent = start_hint;
1146 if (!extent) {
1147 extent = &s->extents[0];
1149 while (extent < &s->extents[s->num_extents]) {
1150 if (sector_num < extent->end_sector) {
1151 return extent;
1153 extent++;
1155 return NULL;
1158 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1159 int64_t sector_num, int nb_sectors, int *pnum)
1161 BDRVVmdkState *s = bs->opaque;
1162 int64_t index_in_cluster, n, ret;
1163 uint64_t offset;
1164 VmdkExtent *extent;
1166 extent = find_extent(s, sector_num, NULL);
1167 if (!extent) {
1168 return 0;
1170 qemu_co_mutex_lock(&s->lock);
1171 ret = get_cluster_offset(bs, extent, NULL,
1172 sector_num * 512, 0, &offset);
1173 qemu_co_mutex_unlock(&s->lock);
1175 switch (ret) {
1176 case VMDK_ERROR:
1177 ret = -EIO;
1178 break;
1179 case VMDK_UNALLOC:
1180 ret = 0;
1181 break;
1182 case VMDK_ZEROED:
1183 ret = BDRV_BLOCK_ZERO;
1184 break;
1185 case VMDK_OK:
1186 ret = BDRV_BLOCK_DATA;
1187 if (extent->file == bs->file) {
1188 ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1191 break;
1194 index_in_cluster = sector_num % extent->cluster_sectors;
1195 n = extent->cluster_sectors - index_in_cluster;
1196 if (n > nb_sectors) {
1197 n = nb_sectors;
1199 *pnum = n;
1200 return ret;
1203 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1204 int64_t offset_in_cluster, const uint8_t *buf,
1205 int nb_sectors, int64_t sector_num)
1207 int ret;
1208 VmdkGrainMarker *data = NULL;
1209 uLongf buf_len;
1210 const uint8_t *write_buf = buf;
1211 int write_len = nb_sectors * 512;
1213 if (extent->compressed) {
1214 if (!extent->has_marker) {
1215 ret = -EINVAL;
1216 goto out;
1218 buf_len = (extent->cluster_sectors << 9) * 2;
1219 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1220 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1221 buf_len == 0) {
1222 ret = -EINVAL;
1223 goto out;
1225 data->lba = sector_num;
1226 data->size = buf_len;
1227 write_buf = (uint8_t *)data;
1228 write_len = buf_len + sizeof(VmdkGrainMarker);
1230 ret = bdrv_pwrite(extent->file,
1231 cluster_offset + offset_in_cluster,
1232 write_buf,
1233 write_len);
1234 if (ret != write_len) {
1235 ret = ret < 0 ? ret : -EIO;
1236 goto out;
1238 ret = 0;
1239 out:
1240 g_free(data);
1241 return ret;
1244 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1245 int64_t offset_in_cluster, uint8_t *buf,
1246 int nb_sectors)
1248 int ret;
1249 int cluster_bytes, buf_bytes;
1250 uint8_t *cluster_buf, *compressed_data;
1251 uint8_t *uncomp_buf;
1252 uint32_t data_len;
1253 VmdkGrainMarker *marker;
1254 uLongf buf_len;
1257 if (!extent->compressed) {
1258 ret = bdrv_pread(extent->file,
1259 cluster_offset + offset_in_cluster,
1260 buf, nb_sectors * 512);
1261 if (ret == nb_sectors * 512) {
1262 return 0;
1263 } else {
1264 return -EIO;
1267 cluster_bytes = extent->cluster_sectors * 512;
1268 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1269 buf_bytes = cluster_bytes * 2;
1270 cluster_buf = g_malloc(buf_bytes);
1271 uncomp_buf = g_malloc(cluster_bytes);
1272 ret = bdrv_pread(extent->file,
1273 cluster_offset,
1274 cluster_buf, buf_bytes);
1275 if (ret < 0) {
1276 goto out;
1278 compressed_data = cluster_buf;
1279 buf_len = cluster_bytes;
1280 data_len = cluster_bytes;
1281 if (extent->has_marker) {
1282 marker = (VmdkGrainMarker *)cluster_buf;
1283 compressed_data = marker->data;
1284 data_len = le32_to_cpu(marker->size);
1286 if (!data_len || data_len > buf_bytes) {
1287 ret = -EINVAL;
1288 goto out;
1290 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1291 if (ret != Z_OK) {
1292 ret = -EINVAL;
1293 goto out;
1296 if (offset_in_cluster < 0 ||
1297 offset_in_cluster + nb_sectors * 512 > buf_len) {
1298 ret = -EINVAL;
1299 goto out;
1301 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1302 ret = 0;
1304 out:
1305 g_free(uncomp_buf);
1306 g_free(cluster_buf);
1307 return ret;
1310 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1311 uint8_t *buf, int nb_sectors)
1313 BDRVVmdkState *s = bs->opaque;
1314 int ret;
1315 uint64_t n, index_in_cluster;
1316 uint64_t extent_begin_sector, extent_relative_sector_num;
1317 VmdkExtent *extent = NULL;
1318 uint64_t cluster_offset;
1320 while (nb_sectors > 0) {
1321 extent = find_extent(s, sector_num, extent);
1322 if (!extent) {
1323 return -EIO;
1325 ret = get_cluster_offset(
1326 bs, extent, NULL,
1327 sector_num << 9, 0, &cluster_offset);
1328 extent_begin_sector = extent->end_sector - extent->sectors;
1329 extent_relative_sector_num = sector_num - extent_begin_sector;
1330 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1331 n = extent->cluster_sectors - index_in_cluster;
1332 if (n > nb_sectors) {
1333 n = nb_sectors;
1335 if (ret != VMDK_OK) {
1336 /* if not allocated, try to read from parent image, if exist */
1337 if (bs->backing_hd && ret != VMDK_ZEROED) {
1338 if (!vmdk_is_cid_valid(bs)) {
1339 return -EINVAL;
1341 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1342 if (ret < 0) {
1343 return ret;
1345 } else {
1346 memset(buf, 0, 512 * n);
1348 } else {
1349 ret = vmdk_read_extent(extent,
1350 cluster_offset, index_in_cluster * 512,
1351 buf, n);
1352 if (ret) {
1353 return ret;
1356 nb_sectors -= n;
1357 sector_num += n;
1358 buf += n * 512;
1360 return 0;
1363 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1364 uint8_t *buf, int nb_sectors)
1366 int ret;
1367 BDRVVmdkState *s = bs->opaque;
1368 qemu_co_mutex_lock(&s->lock);
1369 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1370 qemu_co_mutex_unlock(&s->lock);
1371 return ret;
1375 * vmdk_write:
1376 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1377 * if possible, otherwise return -ENOTSUP.
1378 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1379 * with each cluster. By dry run we can find if the zero write
1380 * is possible without modifying image data.
1382 * Returns: error code with 0 for success.
1384 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1385 const uint8_t *buf, int nb_sectors,
1386 bool zeroed, bool zero_dry_run)
1388 BDRVVmdkState *s = bs->opaque;
1389 VmdkExtent *extent = NULL;
1390 int ret;
1391 int64_t index_in_cluster, n;
1392 uint64_t extent_begin_sector, extent_relative_sector_num;
1393 uint64_t cluster_offset;
1394 VmdkMetaData m_data;
1396 if (sector_num > bs->total_sectors) {
1397 error_report("Wrong offset: sector_num=0x%" PRIx64
1398 " total_sectors=0x%" PRIx64 "\n",
1399 sector_num, bs->total_sectors);
1400 return -EIO;
1403 while (nb_sectors > 0) {
1404 extent = find_extent(s, sector_num, extent);
1405 if (!extent) {
1406 return -EIO;
1408 ret = get_cluster_offset(
1410 extent,
1411 &m_data,
1412 sector_num << 9, !extent->compressed,
1413 &cluster_offset);
1414 if (extent->compressed) {
1415 if (ret == VMDK_OK) {
1416 /* Refuse write to allocated cluster for streamOptimized */
1417 error_report("Could not write to allocated cluster"
1418 " for streamOptimized");
1419 return -EIO;
1420 } else {
1421 /* allocate */
1422 ret = get_cluster_offset(
1424 extent,
1425 &m_data,
1426 sector_num << 9, 1,
1427 &cluster_offset);
1430 if (ret == VMDK_ERROR) {
1431 return -EINVAL;
1433 extent_begin_sector = extent->end_sector - extent->sectors;
1434 extent_relative_sector_num = sector_num - extent_begin_sector;
1435 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1436 n = extent->cluster_sectors - index_in_cluster;
1437 if (n > nb_sectors) {
1438 n = nb_sectors;
1440 if (zeroed) {
1441 /* Do zeroed write, buf is ignored */
1442 if (extent->has_zero_grain &&
1443 index_in_cluster == 0 &&
1444 n >= extent->cluster_sectors) {
1445 n = extent->cluster_sectors;
1446 if (!zero_dry_run) {
1447 m_data.offset = VMDK_GTE_ZEROED;
1448 /* update L2 tables */
1449 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1450 return -EIO;
1453 } else {
1454 return -ENOTSUP;
1456 } else {
1457 ret = vmdk_write_extent(extent,
1458 cluster_offset, index_in_cluster * 512,
1459 buf, n, sector_num);
1460 if (ret) {
1461 return ret;
1463 if (m_data.valid) {
1464 /* update L2 tables */
1465 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1466 return -EIO;
1470 nb_sectors -= n;
1471 sector_num += n;
1472 buf += n * 512;
1474 /* update CID on the first write every time the virtual disk is
1475 * opened */
1476 if (!s->cid_updated) {
1477 ret = vmdk_write_cid(bs, time(NULL));
1478 if (ret < 0) {
1479 return ret;
1481 s->cid_updated = true;
1484 return 0;
1487 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1488 const uint8_t *buf, int nb_sectors)
1490 int ret;
1491 BDRVVmdkState *s = bs->opaque;
1492 qemu_co_mutex_lock(&s->lock);
1493 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1494 qemu_co_mutex_unlock(&s->lock);
1495 return ret;
1498 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1499 int64_t sector_num,
1500 int nb_sectors,
1501 BdrvRequestFlags flags)
1503 int ret;
1504 BDRVVmdkState *s = bs->opaque;
1505 qemu_co_mutex_lock(&s->lock);
1506 /* write zeroes could fail if sectors not aligned to cluster, test it with
1507 * dry_run == true before really updating image */
1508 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1509 if (!ret) {
1510 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1512 qemu_co_mutex_unlock(&s->lock);
1513 return ret;
1516 static int vmdk_create_extent(const char *filename, int64_t filesize,
1517 bool flat, bool compress, bool zeroed_grain,
1518 Error **errp)
1520 int ret, i;
1521 BlockDriverState *bs = NULL;
1522 VMDK4Header header;
1523 Error *local_err;
1524 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1525 uint32_t *gd_buf = NULL;
1526 int gd_buf_size;
1528 ret = bdrv_create_file(filename, NULL, &local_err);
1529 if (ret < 0) {
1530 error_propagate(errp, local_err);
1531 goto exit;
1534 assert(bs == NULL);
1535 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1536 NULL, &local_err);
1537 if (ret < 0) {
1538 error_propagate(errp, local_err);
1539 goto exit;
1542 if (flat) {
1543 ret = bdrv_truncate(bs, filesize);
1544 if (ret < 0) {
1545 error_setg_errno(errp, -ret, "Could not truncate file");
1547 goto exit;
1549 magic = cpu_to_be32(VMDK4_MAGIC);
1550 memset(&header, 0, sizeof(header));
1551 header.version = zeroed_grain ? 2 : 1;
1552 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1553 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1554 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1555 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1556 header.capacity = filesize / BDRV_SECTOR_SIZE;
1557 header.granularity = 128;
1558 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1560 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1561 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1562 BDRV_SECTOR_SIZE);
1563 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1564 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1566 header.desc_offset = 1;
1567 header.desc_size = 20;
1568 header.rgd_offset = header.desc_offset + header.desc_size;
1569 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1570 header.grain_offset =
1571 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1572 header.granularity);
1573 /* swap endianness for all header fields */
1574 header.version = cpu_to_le32(header.version);
1575 header.flags = cpu_to_le32(header.flags);
1576 header.capacity = cpu_to_le64(header.capacity);
1577 header.granularity = cpu_to_le64(header.granularity);
1578 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1579 header.desc_offset = cpu_to_le64(header.desc_offset);
1580 header.desc_size = cpu_to_le64(header.desc_size);
1581 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1582 header.gd_offset = cpu_to_le64(header.gd_offset);
1583 header.grain_offset = cpu_to_le64(header.grain_offset);
1584 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1586 header.check_bytes[0] = 0xa;
1587 header.check_bytes[1] = 0x20;
1588 header.check_bytes[2] = 0xd;
1589 header.check_bytes[3] = 0xa;
1591 /* write all the data */
1592 ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1593 if (ret < 0) {
1594 error_set(errp, QERR_IO_ERROR);
1595 goto exit;
1597 ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1598 if (ret < 0) {
1599 error_set(errp, QERR_IO_ERROR);
1600 goto exit;
1603 ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1604 if (ret < 0) {
1605 error_setg_errno(errp, -ret, "Could not truncate file");
1606 goto exit;
1609 /* write grain directory */
1610 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1611 gd_buf = g_malloc0(gd_buf_size);
1612 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1613 i < gt_count; i++, tmp += gt_size) {
1614 gd_buf[i] = cpu_to_le32(tmp);
1616 ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1617 gd_buf, gd_buf_size);
1618 if (ret < 0) {
1619 error_set(errp, QERR_IO_ERROR);
1620 goto exit;
1623 /* write backup grain directory */
1624 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1625 i < gt_count; i++, tmp += gt_size) {
1626 gd_buf[i] = cpu_to_le32(tmp);
1628 ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1629 gd_buf, gd_buf_size);
1630 if (ret < 0) {
1631 error_set(errp, QERR_IO_ERROR);
1632 goto exit;
1635 ret = 0;
1636 exit:
1637 if (bs) {
1638 bdrv_unref(bs);
1640 g_free(gd_buf);
1641 return ret;
1644 static int filename_decompose(const char *filename, char *path, char *prefix,
1645 char *postfix, size_t buf_len, Error **errp)
1647 const char *p, *q;
1649 if (filename == NULL || !strlen(filename)) {
1650 error_setg(errp, "No filename provided");
1651 return VMDK_ERROR;
1653 p = strrchr(filename, '/');
1654 if (p == NULL) {
1655 p = strrchr(filename, '\\');
1657 if (p == NULL) {
1658 p = strrchr(filename, ':');
1660 if (p != NULL) {
1661 p++;
1662 if (p - filename >= buf_len) {
1663 return VMDK_ERROR;
1665 pstrcpy(path, p - filename + 1, filename);
1666 } else {
1667 p = filename;
1668 path[0] = '\0';
1670 q = strrchr(p, '.');
1671 if (q == NULL) {
1672 pstrcpy(prefix, buf_len, p);
1673 postfix[0] = '\0';
1674 } else {
1675 if (q - p >= buf_len) {
1676 return VMDK_ERROR;
1678 pstrcpy(prefix, q - p + 1, p);
1679 pstrcpy(postfix, buf_len, q);
1681 return VMDK_OK;
1684 static int vmdk_create(const char *filename, QEMUOptionParameter *options,
1685 Error **errp)
1687 int idx = 0;
1688 BlockDriverState *new_bs = NULL;
1689 Error *local_err;
1690 char *desc = NULL;
1691 int64_t total_size = 0, filesize;
1692 const char *adapter_type = NULL;
1693 const char *backing_file = NULL;
1694 const char *fmt = NULL;
1695 int flags = 0;
1696 int ret = 0;
1697 bool flat, split, compress;
1698 GString *ext_desc_lines;
1699 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1700 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1701 const char *desc_extent_line;
1702 char parent_desc_line[BUF_SIZE] = "";
1703 uint32_t parent_cid = 0xffffffff;
1704 uint32_t number_heads = 16;
1705 bool zeroed_grain = false;
1706 uint32_t desc_offset = 0, desc_len;
1707 const char desc_template[] =
1708 "# Disk DescriptorFile\n"
1709 "version=1\n"
1710 "CID=%x\n"
1711 "parentCID=%x\n"
1712 "createType=\"%s\"\n"
1713 "%s"
1714 "\n"
1715 "# Extent description\n"
1716 "%s"
1717 "\n"
1718 "# The Disk Data Base\n"
1719 "#DDB\n"
1720 "\n"
1721 "ddb.virtualHWVersion = \"%d\"\n"
1722 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1723 "ddb.geometry.heads = \"%d\"\n"
1724 "ddb.geometry.sectors = \"63\"\n"
1725 "ddb.adapterType = \"%s\"\n";
1727 ext_desc_lines = g_string_new(NULL);
1729 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1730 ret = -EINVAL;
1731 goto exit;
1733 /* Read out options */
1734 while (options && options->name) {
1735 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1736 total_size = options->value.n;
1737 } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {
1738 adapter_type = options->value.s;
1739 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1740 backing_file = options->value.s;
1741 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
1742 flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;
1743 } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {
1744 fmt = options->value.s;
1745 } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {
1746 zeroed_grain |= options->value.n;
1748 options++;
1750 if (!adapter_type) {
1751 adapter_type = "ide";
1752 } else if (strcmp(adapter_type, "ide") &&
1753 strcmp(adapter_type, "buslogic") &&
1754 strcmp(adapter_type, "lsilogic") &&
1755 strcmp(adapter_type, "legacyESX")) {
1756 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1757 ret = -EINVAL;
1758 goto exit;
1760 if (strcmp(adapter_type, "ide") != 0) {
1761 /* that's the number of heads with which vmware operates when
1762 creating, exporting, etc. vmdk files with a non-ide adapter type */
1763 number_heads = 255;
1765 if (!fmt) {
1766 /* Default format to monolithicSparse */
1767 fmt = "monolithicSparse";
1768 } else if (strcmp(fmt, "monolithicFlat") &&
1769 strcmp(fmt, "monolithicSparse") &&
1770 strcmp(fmt, "twoGbMaxExtentSparse") &&
1771 strcmp(fmt, "twoGbMaxExtentFlat") &&
1772 strcmp(fmt, "streamOptimized")) {
1773 error_setg(errp, "Unknown subformat: '%s'", fmt);
1774 ret = -EINVAL;
1775 goto exit;
1777 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1778 strcmp(fmt, "twoGbMaxExtentSparse"));
1779 flat = !(strcmp(fmt, "monolithicFlat") &&
1780 strcmp(fmt, "twoGbMaxExtentFlat"));
1781 compress = !strcmp(fmt, "streamOptimized");
1782 if (flat) {
1783 desc_extent_line = "RW %lld FLAT \"%s\" 0\n";
1784 } else {
1785 desc_extent_line = "RW %lld SPARSE \"%s\"\n";
1787 if (flat && backing_file) {
1788 error_setg(errp, "Flat image can't have backing file");
1789 ret = -ENOTSUP;
1790 goto exit;
1792 if (flat && zeroed_grain) {
1793 error_setg(errp, "Flat image can't enable zeroed grain");
1794 ret = -ENOTSUP;
1795 goto exit;
1797 if (backing_file) {
1798 BlockDriverState *bs = NULL;
1799 ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_NO_BACKING, NULL,
1800 errp);
1801 if (ret != 0) {
1802 goto exit;
1804 if (strcmp(bs->drv->format_name, "vmdk")) {
1805 bdrv_unref(bs);
1806 ret = -EINVAL;
1807 goto exit;
1809 parent_cid = vmdk_read_cid(bs, 0);
1810 bdrv_unref(bs);
1811 snprintf(parent_desc_line, sizeof(parent_desc_line),
1812 "parentFileNameHint=\"%s\"", backing_file);
1815 /* Create extents */
1816 filesize = total_size;
1817 while (filesize > 0) {
1818 char desc_line[BUF_SIZE];
1819 char ext_filename[PATH_MAX];
1820 char desc_filename[PATH_MAX];
1821 int64_t size = filesize;
1823 if (split && size > split_size) {
1824 size = split_size;
1826 if (split) {
1827 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1828 prefix, flat ? 'f' : 's', ++idx, postfix);
1829 } else if (flat) {
1830 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1831 prefix, postfix);
1832 } else {
1833 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1834 prefix, postfix);
1836 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1837 path, desc_filename);
1839 if (vmdk_create_extent(ext_filename, size,
1840 flat, compress, zeroed_grain, errp)) {
1841 ret = -EINVAL;
1842 goto exit;
1844 filesize -= size;
1846 /* Format description line */
1847 snprintf(desc_line, sizeof(desc_line),
1848 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1849 g_string_append(ext_desc_lines, desc_line);
1851 /* generate descriptor file */
1852 desc = g_strdup_printf(desc_template,
1853 (unsigned int)time(NULL),
1854 parent_cid,
1855 fmt,
1856 parent_desc_line,
1857 ext_desc_lines->str,
1858 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1859 total_size /
1860 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1861 number_heads,
1862 adapter_type);
1863 desc_len = strlen(desc);
1864 /* the descriptor offset = 0x200 */
1865 if (!split && !flat) {
1866 desc_offset = 0x200;
1867 } else {
1868 ret = bdrv_create_file(filename, options, &local_err);
1869 if (ret < 0) {
1870 error_setg_errno(errp, -ret, "Could not create image file");
1871 goto exit;
1874 assert(new_bs == NULL);
1875 ret = bdrv_open(&new_bs, filename, NULL, NULL,
1876 BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
1877 if (ret < 0) {
1878 error_setg_errno(errp, -ret, "Could not write description");
1879 goto exit;
1881 ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1882 if (ret < 0) {
1883 error_setg_errno(errp, -ret, "Could not write description");
1884 goto exit;
1886 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1887 * for description file */
1888 if (desc_offset == 0) {
1889 ret = bdrv_truncate(new_bs, desc_len);
1890 if (ret < 0) {
1891 error_setg_errno(errp, -ret, "Could not truncate file");
1894 exit:
1895 if (new_bs) {
1896 bdrv_unref(new_bs);
1898 g_free(desc);
1899 g_string_free(ext_desc_lines, true);
1900 return ret;
1903 static void vmdk_close(BlockDriverState *bs)
1905 BDRVVmdkState *s = bs->opaque;
1907 vmdk_free_extents(bs);
1908 g_free(s->create_type);
1910 migrate_del_blocker(s->migration_blocker);
1911 error_free(s->migration_blocker);
1914 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1916 BDRVVmdkState *s = bs->opaque;
1917 int i, err;
1918 int ret = 0;
1920 for (i = 0; i < s->num_extents; i++) {
1921 err = bdrv_co_flush(s->extents[i].file);
1922 if (err < 0) {
1923 ret = err;
1926 return ret;
1929 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
1931 int i;
1932 int64_t ret = 0;
1933 int64_t r;
1934 BDRVVmdkState *s = bs->opaque;
1936 ret = bdrv_get_allocated_file_size(bs->file);
1937 if (ret < 0) {
1938 return ret;
1940 for (i = 0; i < s->num_extents; i++) {
1941 if (s->extents[i].file == bs->file) {
1942 continue;
1944 r = bdrv_get_allocated_file_size(s->extents[i].file);
1945 if (r < 0) {
1946 return r;
1948 ret += r;
1950 return ret;
1953 static int vmdk_has_zero_init(BlockDriverState *bs)
1955 int i;
1956 BDRVVmdkState *s = bs->opaque;
1958 /* If has a flat extent and its underlying storage doesn't have zero init,
1959 * return 0. */
1960 for (i = 0; i < s->num_extents; i++) {
1961 if (s->extents[i].flat) {
1962 if (!bdrv_has_zero_init(s->extents[i].file)) {
1963 return 0;
1967 return 1;
1970 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
1972 ImageInfo *info = g_new0(ImageInfo, 1);
1974 *info = (ImageInfo){
1975 .filename = g_strdup(extent->file->filename),
1976 .format = g_strdup(extent->type),
1977 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
1978 .compressed = extent->compressed,
1979 .has_compressed = extent->compressed,
1980 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
1981 .has_cluster_size = !extent->flat,
1984 return info;
1987 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
1988 BdrvCheckMode fix)
1990 BDRVVmdkState *s = bs->opaque;
1991 VmdkExtent *extent = NULL;
1992 int64_t sector_num = 0;
1993 int64_t total_sectors = bdrv_getlength(bs) / BDRV_SECTOR_SIZE;
1994 int ret;
1995 uint64_t cluster_offset;
1997 if (fix) {
1998 return -ENOTSUP;
2001 for (;;) {
2002 if (sector_num >= total_sectors) {
2003 return 0;
2005 extent = find_extent(s, sector_num, extent);
2006 if (!extent) {
2007 fprintf(stderr,
2008 "ERROR: could not find extent for sector %" PRId64 "\n",
2009 sector_num);
2010 break;
2012 ret = get_cluster_offset(bs, extent, NULL,
2013 sector_num << BDRV_SECTOR_BITS,
2014 0, &cluster_offset);
2015 if (ret == VMDK_ERROR) {
2016 fprintf(stderr,
2017 "ERROR: could not get cluster_offset for sector %"
2018 PRId64 "\n", sector_num);
2019 break;
2021 if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2022 fprintf(stderr,
2023 "ERROR: cluster offset for sector %"
2024 PRId64 " points after EOF\n", sector_num);
2025 break;
2027 sector_num += extent->cluster_sectors;
2030 result->corruptions++;
2031 return 0;
2034 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2036 int i;
2037 BDRVVmdkState *s = bs->opaque;
2038 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2039 ImageInfoList **next;
2041 *spec_info = (ImageInfoSpecific){
2042 .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2044 .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2048 *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2049 .create_type = g_strdup(s->create_type),
2050 .cid = s->cid,
2051 .parent_cid = s->parent_cid,
2054 next = &spec_info->vmdk->extents;
2055 for (i = 0; i < s->num_extents; i++) {
2056 *next = g_new0(ImageInfoList, 1);
2057 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2058 (*next)->next = NULL;
2059 next = &(*next)->next;
2062 return spec_info;
2065 static QEMUOptionParameter vmdk_create_options[] = {
2067 .name = BLOCK_OPT_SIZE,
2068 .type = OPT_SIZE,
2069 .help = "Virtual disk size"
2072 .name = BLOCK_OPT_ADAPTER_TYPE,
2073 .type = OPT_STRING,
2074 .help = "Virtual adapter type, can be one of "
2075 "ide (default), lsilogic, buslogic or legacyESX"
2078 .name = BLOCK_OPT_BACKING_FILE,
2079 .type = OPT_STRING,
2080 .help = "File name of a base image"
2083 .name = BLOCK_OPT_COMPAT6,
2084 .type = OPT_FLAG,
2085 .help = "VMDK version 6 image"
2088 .name = BLOCK_OPT_SUBFMT,
2089 .type = OPT_STRING,
2090 .help =
2091 "VMDK flat extent format, can be one of "
2092 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2095 .name = BLOCK_OPT_ZEROED_GRAIN,
2096 .type = OPT_FLAG,
2097 .help = "Enable efficient zero writes using the zeroed-grain GTE feature"
2099 { NULL }
2102 static BlockDriver bdrv_vmdk = {
2103 .format_name = "vmdk",
2104 .instance_size = sizeof(BDRVVmdkState),
2105 .bdrv_probe = vmdk_probe,
2106 .bdrv_open = vmdk_open,
2107 .bdrv_check = vmdk_check,
2108 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2109 .bdrv_read = vmdk_co_read,
2110 .bdrv_write = vmdk_co_write,
2111 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
2112 .bdrv_close = vmdk_close,
2113 .bdrv_create = vmdk_create,
2114 .bdrv_co_flush_to_disk = vmdk_co_flush,
2115 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2116 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2117 .bdrv_has_zero_init = vmdk_has_zero_init,
2118 .bdrv_get_specific_info = vmdk_get_specific_info,
2119 .bdrv_refresh_limits = vmdk_refresh_limits,
2121 .create_options = vmdk_create_options,
2124 static void bdrv_vmdk_init(void)
2126 bdrv_register(&bdrv_vmdk);
2129 block_init(bdrv_vmdk_init);