linux-user/sh4: fix incorrect memory write
[qemu/kevin.git] / block / vmdk.c
blob0fc97391a6cc53473a1eae4bc4d8aa130c89c33f
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/blocker.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 /* Return -ve errno, or 0 on success and write CID into *pcid. */
246 static int vmdk_read_cid(BlockDriverState *bs, int parent, uint32_t *pcid)
248 char *desc;
249 uint32_t cid;
250 const char *p_name, *cid_str;
251 size_t cid_str_size;
252 BDRVVmdkState *s = bs->opaque;
253 int ret;
255 desc = g_malloc0(DESC_SIZE);
256 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
257 if (ret < 0) {
258 goto out;
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 ret = -EINVAL;
273 goto out;
275 p_name += cid_str_size;
276 if (sscanf(p_name, "%" SCNx32, &cid) != 1) {
277 ret = -EINVAL;
278 goto out;
280 *pcid = cid;
281 ret = 0;
283 out:
284 g_free(desc);
285 return ret;
288 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
290 char *desc, *tmp_desc;
291 char *p_name, *tmp_str;
292 BDRVVmdkState *s = bs->opaque;
293 int ret = 0;
295 desc = g_malloc0(DESC_SIZE);
296 tmp_desc = g_malloc0(DESC_SIZE);
297 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
298 if (ret < 0) {
299 goto out;
302 desc[DESC_SIZE - 1] = '\0';
303 tmp_str = strstr(desc, "parentCID");
304 if (tmp_str == NULL) {
305 ret = -EINVAL;
306 goto out;
309 pstrcpy(tmp_desc, DESC_SIZE, tmp_str);
310 p_name = strstr(desc, "CID");
311 if (p_name != NULL) {
312 p_name += sizeof("CID");
313 snprintf(p_name, DESC_SIZE - (p_name - desc), "%" PRIx32 "\n", cid);
314 pstrcat(desc, DESC_SIZE, tmp_desc);
317 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
319 out:
320 g_free(desc);
321 g_free(tmp_desc);
322 return ret;
325 static int vmdk_is_cid_valid(BlockDriverState *bs)
327 BDRVVmdkState *s = bs->opaque;
328 uint32_t cur_pcid;
330 if (!s->cid_checked && bs->backing) {
331 BlockDriverState *p_bs = bs->backing->bs;
333 if (vmdk_read_cid(p_bs, 0, &cur_pcid) != 0) {
334 /* read failure: report as not valid */
335 return 0;
337 if (s->parent_cid != cur_pcid) {
338 /* CID not valid */
339 return 0;
342 s->cid_checked = true;
343 /* CID valid */
344 return 1;
347 /* We have nothing to do for VMDK reopen, stubs just return success */
348 static int vmdk_reopen_prepare(BDRVReopenState *state,
349 BlockReopenQueue *queue, Error **errp)
351 assert(state != NULL);
352 assert(state->bs != NULL);
353 return 0;
356 static int vmdk_parent_open(BlockDriverState *bs)
358 char *p_name;
359 char *desc;
360 BDRVVmdkState *s = bs->opaque;
361 int ret;
363 desc = g_malloc0(DESC_SIZE + 1);
364 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
365 if (ret < 0) {
366 goto out;
368 ret = 0;
370 p_name = strstr(desc, "parentFileNameHint");
371 if (p_name != NULL) {
372 char *end_name;
374 p_name += sizeof("parentFileNameHint") + 1;
375 end_name = strchr(p_name, '\"');
376 if (end_name == NULL) {
377 ret = -EINVAL;
378 goto out;
380 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
381 ret = -EINVAL;
382 goto out;
385 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
388 out:
389 g_free(desc);
390 return ret;
393 /* Create and append extent to the extent array. Return the added VmdkExtent
394 * address. return NULL if allocation failed. */
395 static int vmdk_add_extent(BlockDriverState *bs,
396 BdrvChild *file, bool flat, int64_t sectors,
397 int64_t l1_offset, int64_t l1_backup_offset,
398 uint32_t l1_size,
399 int l2_size, uint64_t cluster_sectors,
400 VmdkExtent **new_extent,
401 Error **errp)
403 VmdkExtent *extent;
404 BDRVVmdkState *s = bs->opaque;
405 int64_t nb_sectors;
407 if (cluster_sectors > 0x200000) {
408 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
409 error_setg(errp, "Invalid granularity, image may be corrupt");
410 return -EFBIG;
412 if (l1_size > 512 * 1024 * 1024) {
413 /* Although with big capacity and small l1_entry_sectors, we can get a
414 * big l1_size, we don't want unbounded value to allocate the table.
415 * Limit it to 512M, which is 16PB for default cluster and L2 table
416 * size */
417 error_setg(errp, "L1 size too big");
418 return -EFBIG;
421 nb_sectors = bdrv_nb_sectors(file->bs);
422 if (nb_sectors < 0) {
423 return nb_sectors;
426 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
427 extent = &s->extents[s->num_extents];
428 s->num_extents++;
430 memset(extent, 0, sizeof(VmdkExtent));
431 extent->file = file;
432 extent->flat = flat;
433 extent->sectors = sectors;
434 extent->l1_table_offset = l1_offset;
435 extent->l1_backup_table_offset = l1_backup_offset;
436 extent->l1_size = l1_size;
437 extent->l1_entry_sectors = l2_size * cluster_sectors;
438 extent->l2_size = l2_size;
439 extent->cluster_sectors = flat ? sectors : cluster_sectors;
440 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
442 if (s->num_extents > 1) {
443 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
444 } else {
445 extent->end_sector = extent->sectors;
447 bs->total_sectors = extent->end_sector;
448 if (new_extent) {
449 *new_extent = extent;
451 return 0;
454 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
455 Error **errp)
457 int ret;
458 size_t l1_size;
459 int i;
461 /* read the L1 table */
462 l1_size = extent->l1_size * sizeof(uint32_t);
463 extent->l1_table = g_try_malloc(l1_size);
464 if (l1_size && extent->l1_table == NULL) {
465 return -ENOMEM;
468 ret = bdrv_pread(extent->file,
469 extent->l1_table_offset,
470 extent->l1_table,
471 l1_size);
472 if (ret < 0) {
473 error_setg_errno(errp, -ret,
474 "Could not read l1 table from extent '%s'",
475 extent->file->bs->filename);
476 goto fail_l1;
478 for (i = 0; i < extent->l1_size; i++) {
479 le32_to_cpus(&extent->l1_table[i]);
482 if (extent->l1_backup_table_offset) {
483 extent->l1_backup_table = g_try_malloc(l1_size);
484 if (l1_size && extent->l1_backup_table == NULL) {
485 ret = -ENOMEM;
486 goto fail_l1;
488 ret = bdrv_pread(extent->file,
489 extent->l1_backup_table_offset,
490 extent->l1_backup_table,
491 l1_size);
492 if (ret < 0) {
493 error_setg_errno(errp, -ret,
494 "Could not read l1 backup table from extent '%s'",
495 extent->file->bs->filename);
496 goto fail_l1b;
498 for (i = 0; i < extent->l1_size; i++) {
499 le32_to_cpus(&extent->l1_backup_table[i]);
503 extent->l2_cache =
504 g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
505 return 0;
506 fail_l1b:
507 g_free(extent->l1_backup_table);
508 fail_l1:
509 g_free(extent->l1_table);
510 return ret;
513 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
514 BdrvChild *file,
515 int flags, Error **errp)
517 int ret;
518 uint32_t magic;
519 VMDK3Header header;
520 VmdkExtent *extent;
522 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
523 if (ret < 0) {
524 error_setg_errno(errp, -ret,
525 "Could not read header from file '%s'",
526 file->bs->filename);
527 return ret;
529 ret = vmdk_add_extent(bs, file, false,
530 le32_to_cpu(header.disk_sectors),
531 (int64_t)le32_to_cpu(header.l1dir_offset) << 9,
533 le32_to_cpu(header.l1dir_size),
534 4096,
535 le32_to_cpu(header.granularity),
536 &extent,
537 errp);
538 if (ret < 0) {
539 return ret;
541 ret = vmdk_init_tables(bs, extent, errp);
542 if (ret) {
543 /* free extent allocated by vmdk_add_extent */
544 vmdk_free_last_extent(bs);
546 return ret;
549 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
550 QDict *options, Error **errp);
552 static char *vmdk_read_desc(BdrvChild *file, uint64_t desc_offset, Error **errp)
554 int64_t size;
555 char *buf;
556 int ret;
558 size = bdrv_getlength(file->bs);
559 if (size < 0) {
560 error_setg_errno(errp, -size, "Could not access file");
561 return NULL;
564 if (size < 4) {
565 /* Both descriptor file and sparse image must be much larger than 4
566 * bytes, also callers of vmdk_read_desc want to compare the first 4
567 * bytes with VMDK4_MAGIC, let's error out if less is read. */
568 error_setg(errp, "File is too small, not a valid image");
569 return NULL;
572 size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */
573 buf = g_malloc(size + 1);
575 ret = bdrv_pread(file, desc_offset, buf, size);
576 if (ret < 0) {
577 error_setg_errno(errp, -ret, "Could not read from file");
578 g_free(buf);
579 return NULL;
581 buf[ret] = 0;
583 return buf;
586 static int vmdk_open_vmdk4(BlockDriverState *bs,
587 BdrvChild *file,
588 int flags, QDict *options, Error **errp)
590 int ret;
591 uint32_t magic;
592 uint32_t l1_size, l1_entry_sectors;
593 VMDK4Header header;
594 VmdkExtent *extent;
595 BDRVVmdkState *s = bs->opaque;
596 int64_t l1_backup_offset = 0;
597 bool compressed;
599 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
600 if (ret < 0) {
601 error_setg_errno(errp, -ret,
602 "Could not read header from file '%s'",
603 file->bs->filename);
604 return -EINVAL;
606 if (header.capacity == 0) {
607 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
608 if (desc_offset) {
609 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
610 if (!buf) {
611 return -EINVAL;
613 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
614 g_free(buf);
615 return ret;
619 if (!s->create_type) {
620 s->create_type = g_strdup("monolithicSparse");
623 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
625 * The footer takes precedence over the header, so read it in. The
626 * footer starts at offset -1024 from the end: One sector for the
627 * footer, and another one for the end-of-stream marker.
629 struct {
630 struct {
631 uint64_t val;
632 uint32_t size;
633 uint32_t type;
634 uint8_t pad[512 - 16];
635 } QEMU_PACKED footer_marker;
637 uint32_t magic;
638 VMDK4Header header;
639 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
641 struct {
642 uint64_t val;
643 uint32_t size;
644 uint32_t type;
645 uint8_t pad[512 - 16];
646 } QEMU_PACKED eos_marker;
647 } QEMU_PACKED footer;
649 ret = bdrv_pread(file,
650 bs->file->bs->total_sectors * 512 - 1536,
651 &footer, sizeof(footer));
652 if (ret < 0) {
653 error_setg_errno(errp, -ret, "Failed to read footer");
654 return ret;
657 /* Some sanity checks for the footer */
658 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
659 le32_to_cpu(footer.footer_marker.size) != 0 ||
660 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
661 le64_to_cpu(footer.eos_marker.val) != 0 ||
662 le32_to_cpu(footer.eos_marker.size) != 0 ||
663 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
665 error_setg(errp, "Invalid footer");
666 return -EINVAL;
669 header = footer.header;
672 compressed =
673 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
674 if (le32_to_cpu(header.version) > 3) {
675 error_setg(errp, "Unsupported VMDK version %" PRIu32,
676 le32_to_cpu(header.version));
677 return -ENOTSUP;
678 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR) &&
679 !compressed) {
680 /* VMware KB 2064959 explains that version 3 added support for
681 * persistent changed block tracking (CBT), and backup software can
682 * read it as version=1 if it doesn't care about the changed area
683 * information. So we are safe to enable read only. */
684 error_setg(errp, "VMDK version 3 must be read only");
685 return -EINVAL;
688 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
689 error_setg(errp, "L2 table size too big");
690 return -EINVAL;
693 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
694 * le64_to_cpu(header.granularity);
695 if (l1_entry_sectors == 0) {
696 error_setg(errp, "L1 entry size is invalid");
697 return -EINVAL;
699 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
700 / l1_entry_sectors;
701 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
702 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
704 if (bdrv_nb_sectors(file->bs) < le64_to_cpu(header.grain_offset)) {
705 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
706 (int64_t)(le64_to_cpu(header.grain_offset)
707 * BDRV_SECTOR_SIZE));
708 return -EINVAL;
711 ret = vmdk_add_extent(bs, file, false,
712 le64_to_cpu(header.capacity),
713 le64_to_cpu(header.gd_offset) << 9,
714 l1_backup_offset,
715 l1_size,
716 le32_to_cpu(header.num_gtes_per_gt),
717 le64_to_cpu(header.granularity),
718 &extent,
719 errp);
720 if (ret < 0) {
721 return ret;
723 extent->compressed =
724 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
725 if (extent->compressed) {
726 g_free(s->create_type);
727 s->create_type = g_strdup("streamOptimized");
729 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
730 extent->version = le32_to_cpu(header.version);
731 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
732 ret = vmdk_init_tables(bs, extent, errp);
733 if (ret) {
734 /* free extent allocated by vmdk_add_extent */
735 vmdk_free_last_extent(bs);
737 return ret;
740 /* find an option value out of descriptor file */
741 static int vmdk_parse_description(const char *desc, const char *opt_name,
742 char *buf, int buf_size)
744 char *opt_pos, *opt_end;
745 const char *end = desc + strlen(desc);
747 opt_pos = strstr(desc, opt_name);
748 if (!opt_pos) {
749 return VMDK_ERROR;
751 /* Skip "=\"" following opt_name */
752 opt_pos += strlen(opt_name) + 2;
753 if (opt_pos >= end) {
754 return VMDK_ERROR;
756 opt_end = opt_pos;
757 while (opt_end < end && *opt_end != '"') {
758 opt_end++;
760 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
761 return VMDK_ERROR;
763 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
764 return VMDK_OK;
767 /* Open an extent file and append to bs array */
768 static int vmdk_open_sparse(BlockDriverState *bs, BdrvChild *file, int flags,
769 char *buf, QDict *options, Error **errp)
771 uint32_t magic;
773 magic = ldl_be_p(buf);
774 switch (magic) {
775 case VMDK3_MAGIC:
776 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
777 break;
778 case VMDK4_MAGIC:
779 return vmdk_open_vmdk4(bs, file, flags, options, errp);
780 break;
781 default:
782 error_setg(errp, "Image not in VMDK format");
783 return -EINVAL;
784 break;
788 static const char *next_line(const char *s)
790 while (*s) {
791 if (*s == '\n') {
792 return s + 1;
794 s++;
796 return s;
799 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
800 const char *desc_file_path, QDict *options,
801 Error **errp)
803 int ret;
804 int matches;
805 char access[11];
806 char type[11];
807 char fname[512];
808 const char *p, *np;
809 int64_t sectors = 0;
810 int64_t flat_offset;
811 char *extent_path;
812 BdrvChild *extent_file;
813 BDRVVmdkState *s = bs->opaque;
814 VmdkExtent *extent;
815 char extent_opt_prefix[32];
816 Error *local_err = NULL;
818 for (p = desc; *p; p = next_line(p)) {
819 /* parse extent line in one of below formats:
821 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
822 * RW [size in sectors] SPARSE "file-name.vmdk"
823 * RW [size in sectors] VMFS "file-name.vmdk"
824 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
826 flat_offset = -1;
827 matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
828 access, &sectors, type, fname, &flat_offset);
829 if (matches < 4 || strcmp(access, "RW")) {
830 continue;
831 } else if (!strcmp(type, "FLAT")) {
832 if (matches != 5 || flat_offset < 0) {
833 goto invalid;
835 } else if (!strcmp(type, "VMFS")) {
836 if (matches == 4) {
837 flat_offset = 0;
838 } else {
839 goto invalid;
841 } else if (matches != 4) {
842 goto invalid;
845 if (sectors <= 0 ||
846 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
847 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
848 (strcmp(access, "RW"))) {
849 continue;
852 if (!path_is_absolute(fname) && !path_has_protocol(fname) &&
853 !desc_file_path[0])
855 error_setg(errp, "Cannot use relative extent paths with VMDK "
856 "descriptor file '%s'", bs->file->bs->filename);
857 return -EINVAL;
860 extent_path = g_malloc0(PATH_MAX);
861 path_combine(extent_path, PATH_MAX, desc_file_path, fname);
863 ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents);
864 assert(ret < 32);
866 extent_file = bdrv_open_child(extent_path, options, extent_opt_prefix,
867 bs, &child_file, false, &local_err);
868 g_free(extent_path);
869 if (local_err) {
870 error_propagate(errp, local_err);
871 return -EINVAL;
874 /* save to extents array */
875 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
876 /* FLAT extent */
878 ret = vmdk_add_extent(bs, extent_file, true, sectors,
879 0, 0, 0, 0, 0, &extent, errp);
880 if (ret < 0) {
881 bdrv_unref_child(bs, extent_file);
882 return ret;
884 extent->flat_start_offset = flat_offset << 9;
885 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
886 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
887 char *buf = vmdk_read_desc(extent_file, 0, errp);
888 if (!buf) {
889 ret = -EINVAL;
890 } else {
891 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf,
892 options, errp);
894 g_free(buf);
895 if (ret) {
896 bdrv_unref_child(bs, extent_file);
897 return ret;
899 extent = &s->extents[s->num_extents - 1];
900 } else {
901 error_setg(errp, "Unsupported extent type '%s'", type);
902 bdrv_unref_child(bs, extent_file);
903 return -ENOTSUP;
905 extent->type = g_strdup(type);
907 return 0;
909 invalid:
910 np = next_line(p);
911 assert(np != p);
912 if (np[-1] == '\n') {
913 np--;
915 error_setg(errp, "Invalid extent line: %.*s", (int)(np - p), p);
916 return -EINVAL;
919 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
920 QDict *options, Error **errp)
922 int ret;
923 char ct[128];
924 BDRVVmdkState *s = bs->opaque;
926 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
927 error_setg(errp, "invalid VMDK image descriptor");
928 ret = -EINVAL;
929 goto exit;
931 if (strcmp(ct, "monolithicFlat") &&
932 strcmp(ct, "vmfs") &&
933 strcmp(ct, "vmfsSparse") &&
934 strcmp(ct, "twoGbMaxExtentSparse") &&
935 strcmp(ct, "twoGbMaxExtentFlat")) {
936 error_setg(errp, "Unsupported image type '%s'", ct);
937 ret = -ENOTSUP;
938 goto exit;
940 s->create_type = g_strdup(ct);
941 s->desc_offset = 0;
942 ret = vmdk_parse_extents(buf, bs, bs->file->bs->exact_filename, options,
943 errp);
944 exit:
945 return ret;
948 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
949 Error **errp)
951 char *buf;
952 int ret;
953 BDRVVmdkState *s = bs->opaque;
954 uint32_t magic;
955 Error *local_err = NULL;
957 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
958 false, errp);
959 if (!bs->file) {
960 return -EINVAL;
963 buf = vmdk_read_desc(bs->file, 0, errp);
964 if (!buf) {
965 return -EINVAL;
968 magic = ldl_be_p(buf);
969 switch (magic) {
970 case VMDK3_MAGIC:
971 case VMDK4_MAGIC:
972 ret = vmdk_open_sparse(bs, bs->file, flags, buf, options,
973 errp);
974 s->desc_offset = 0x200;
975 break;
976 default:
977 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
978 break;
980 if (ret) {
981 goto fail;
984 /* try to open parent images, if exist */
985 ret = vmdk_parent_open(bs);
986 if (ret) {
987 goto fail;
989 ret = vmdk_read_cid(bs, 0, &s->cid);
990 if (ret) {
991 goto fail;
993 ret = vmdk_read_cid(bs, 1, &s->parent_cid);
994 if (ret) {
995 goto fail;
997 qemu_co_mutex_init(&s->lock);
999 /* Disable migration when VMDK images are used */
1000 error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "
1001 "does not support live migration",
1002 bdrv_get_device_or_node_name(bs));
1003 ret = migrate_add_blocker(s->migration_blocker, &local_err);
1004 if (local_err) {
1005 error_propagate(errp, local_err);
1006 error_free(s->migration_blocker);
1007 goto fail;
1010 g_free(buf);
1011 return 0;
1013 fail:
1014 g_free(buf);
1015 g_free(s->create_type);
1016 s->create_type = NULL;
1017 vmdk_free_extents(bs);
1018 return ret;
1022 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
1024 BDRVVmdkState *s = bs->opaque;
1025 int i;
1027 for (i = 0; i < s->num_extents; i++) {
1028 if (!s->extents[i].flat) {
1029 bs->bl.pwrite_zeroes_alignment =
1030 MAX(bs->bl.pwrite_zeroes_alignment,
1031 s->extents[i].cluster_sectors << BDRV_SECTOR_BITS);
1037 * get_whole_cluster
1039 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1040 * to the cluster at @cluster_sector_num.
1042 * If @skip_start_sector < @skip_end_sector, the relative range
1043 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1044 * it for call to write user data in the request.
1046 static int get_whole_cluster(BlockDriverState *bs,
1047 VmdkExtent *extent,
1048 uint64_t cluster_offset,
1049 uint64_t offset,
1050 uint64_t skip_start_bytes,
1051 uint64_t skip_end_bytes)
1053 int ret = VMDK_OK;
1054 int64_t cluster_bytes;
1055 uint8_t *whole_grain;
1057 /* For COW, align request sector_num to cluster start */
1058 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
1059 offset = QEMU_ALIGN_DOWN(offset, cluster_bytes);
1060 whole_grain = qemu_blockalign(bs, cluster_bytes);
1062 if (!bs->backing) {
1063 memset(whole_grain, 0, skip_start_bytes);
1064 memset(whole_grain + skip_end_bytes, 0, cluster_bytes - skip_end_bytes);
1067 assert(skip_end_bytes <= cluster_bytes);
1068 /* we will be here if it's first write on non-exist grain(cluster).
1069 * try to read from parent image, if exist */
1070 if (bs->backing && !vmdk_is_cid_valid(bs)) {
1071 ret = VMDK_ERROR;
1072 goto exit;
1075 /* Read backing data before skip range */
1076 if (skip_start_bytes > 0) {
1077 if (bs->backing) {
1078 ret = bdrv_pread(bs->backing, offset, whole_grain,
1079 skip_start_bytes);
1080 if (ret < 0) {
1081 ret = VMDK_ERROR;
1082 goto exit;
1085 ret = bdrv_pwrite(extent->file, cluster_offset, whole_grain,
1086 skip_start_bytes);
1087 if (ret < 0) {
1088 ret = VMDK_ERROR;
1089 goto exit;
1092 /* Read backing data after skip range */
1093 if (skip_end_bytes < cluster_bytes) {
1094 if (bs->backing) {
1095 ret = bdrv_pread(bs->backing, offset + skip_end_bytes,
1096 whole_grain + skip_end_bytes,
1097 cluster_bytes - skip_end_bytes);
1098 if (ret < 0) {
1099 ret = VMDK_ERROR;
1100 goto exit;
1103 ret = bdrv_pwrite(extent->file, cluster_offset + skip_end_bytes,
1104 whole_grain + skip_end_bytes,
1105 cluster_bytes - skip_end_bytes);
1106 if (ret < 0) {
1107 ret = VMDK_ERROR;
1108 goto exit;
1112 ret = VMDK_OK;
1113 exit:
1114 qemu_vfree(whole_grain);
1115 return ret;
1118 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1119 uint32_t offset)
1121 offset = cpu_to_le32(offset);
1122 /* update L2 table */
1123 if (bdrv_pwrite_sync(extent->file,
1124 ((int64_t)m_data->l2_offset * 512)
1125 + (m_data->l2_index * sizeof(offset)),
1126 &offset, sizeof(offset)) < 0) {
1127 return VMDK_ERROR;
1129 /* update backup L2 table */
1130 if (extent->l1_backup_table_offset != 0) {
1131 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1132 if (bdrv_pwrite_sync(extent->file,
1133 ((int64_t)m_data->l2_offset * 512)
1134 + (m_data->l2_index * sizeof(offset)),
1135 &offset, sizeof(offset)) < 0) {
1136 return VMDK_ERROR;
1139 if (m_data->l2_cache_entry) {
1140 *m_data->l2_cache_entry = offset;
1143 return VMDK_OK;
1147 * get_cluster_offset
1149 * Look up cluster offset in extent file by sector number, and store in
1150 * @cluster_offset.
1152 * For flat extents, the start offset as parsed from the description file is
1153 * returned.
1155 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1156 * offset for a new cluster and update L2 cache. If there is a backing file,
1157 * COW is done before returning; otherwise, zeroes are written to the allocated
1158 * cluster. Both COW and zero writing skips the sector range
1159 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1160 * has new data to write there.
1162 * Returns: VMDK_OK if cluster exists and mapped in the image.
1163 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1164 * VMDK_ERROR if failed.
1166 static int get_cluster_offset(BlockDriverState *bs,
1167 VmdkExtent *extent,
1168 VmdkMetaData *m_data,
1169 uint64_t offset,
1170 bool allocate,
1171 uint64_t *cluster_offset,
1172 uint64_t skip_start_bytes,
1173 uint64_t skip_end_bytes)
1175 unsigned int l1_index, l2_offset, l2_index;
1176 int min_index, i, j;
1177 uint32_t min_count, *l2_table;
1178 bool zeroed = false;
1179 int64_t ret;
1180 int64_t cluster_sector;
1182 if (m_data) {
1183 m_data->valid = 0;
1185 if (extent->flat) {
1186 *cluster_offset = extent->flat_start_offset;
1187 return VMDK_OK;
1190 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1191 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1192 if (l1_index >= extent->l1_size) {
1193 return VMDK_ERROR;
1195 l2_offset = extent->l1_table[l1_index];
1196 if (!l2_offset) {
1197 return VMDK_UNALLOC;
1199 for (i = 0; i < L2_CACHE_SIZE; i++) {
1200 if (l2_offset == extent->l2_cache_offsets[i]) {
1201 /* increment the hit count */
1202 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1203 for (j = 0; j < L2_CACHE_SIZE; j++) {
1204 extent->l2_cache_counts[j] >>= 1;
1207 l2_table = extent->l2_cache + (i * extent->l2_size);
1208 goto found;
1211 /* not found: load a new entry in the least used one */
1212 min_index = 0;
1213 min_count = 0xffffffff;
1214 for (i = 0; i < L2_CACHE_SIZE; i++) {
1215 if (extent->l2_cache_counts[i] < min_count) {
1216 min_count = extent->l2_cache_counts[i];
1217 min_index = i;
1220 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1221 if (bdrv_pread(extent->file,
1222 (int64_t)l2_offset * 512,
1223 l2_table,
1224 extent->l2_size * sizeof(uint32_t)
1225 ) != extent->l2_size * sizeof(uint32_t)) {
1226 return VMDK_ERROR;
1229 extent->l2_cache_offsets[min_index] = l2_offset;
1230 extent->l2_cache_counts[min_index] = 1;
1231 found:
1232 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1233 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1235 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1236 zeroed = true;
1239 if (!cluster_sector || zeroed) {
1240 if (!allocate) {
1241 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1244 cluster_sector = extent->next_cluster_sector;
1245 extent->next_cluster_sector += extent->cluster_sectors;
1247 /* First of all we write grain itself, to avoid race condition
1248 * that may to corrupt the image.
1249 * This problem may occur because of insufficient space on host disk
1250 * or inappropriate VM shutdown.
1252 ret = get_whole_cluster(bs, extent, cluster_sector * BDRV_SECTOR_SIZE,
1253 offset, skip_start_bytes, skip_end_bytes);
1254 if (ret) {
1255 return ret;
1257 if (m_data) {
1258 m_data->valid = 1;
1259 m_data->l1_index = l1_index;
1260 m_data->l2_index = l2_index;
1261 m_data->l2_offset = l2_offset;
1262 m_data->l2_cache_entry = &l2_table[l2_index];
1265 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1266 return VMDK_OK;
1269 static VmdkExtent *find_extent(BDRVVmdkState *s,
1270 int64_t sector_num, VmdkExtent *start_hint)
1272 VmdkExtent *extent = start_hint;
1274 if (!extent) {
1275 extent = &s->extents[0];
1277 while (extent < &s->extents[s->num_extents]) {
1278 if (sector_num < extent->end_sector) {
1279 return extent;
1281 extent++;
1283 return NULL;
1286 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent *extent,
1287 int64_t offset)
1289 uint64_t extent_begin_offset, extent_relative_offset;
1290 uint64_t cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1292 extent_begin_offset =
1293 (extent->end_sector - extent->sectors) * BDRV_SECTOR_SIZE;
1294 extent_relative_offset = offset - extent_begin_offset;
1295 return extent_relative_offset % cluster_size;
1298 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent *extent,
1299 int64_t sector_num)
1301 uint64_t offset;
1302 offset = vmdk_find_offset_in_cluster(extent, sector_num * BDRV_SECTOR_SIZE);
1303 return offset / BDRV_SECTOR_SIZE;
1306 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1307 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1309 BDRVVmdkState *s = bs->opaque;
1310 int64_t index_in_cluster, n, ret;
1311 uint64_t offset;
1312 VmdkExtent *extent;
1314 extent = find_extent(s, sector_num, NULL);
1315 if (!extent) {
1316 return 0;
1318 qemu_co_mutex_lock(&s->lock);
1319 ret = get_cluster_offset(bs, extent, NULL,
1320 sector_num * 512, false, &offset,
1321 0, 0);
1322 qemu_co_mutex_unlock(&s->lock);
1324 index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1325 switch (ret) {
1326 case VMDK_ERROR:
1327 ret = -EIO;
1328 break;
1329 case VMDK_UNALLOC:
1330 ret = 0;
1331 break;
1332 case VMDK_ZEROED:
1333 ret = BDRV_BLOCK_ZERO;
1334 break;
1335 case VMDK_OK:
1336 ret = BDRV_BLOCK_DATA;
1337 if (!extent->compressed) {
1338 ret |= BDRV_BLOCK_OFFSET_VALID;
1339 ret |= (offset + (index_in_cluster << BDRV_SECTOR_BITS))
1340 & BDRV_BLOCK_OFFSET_MASK;
1342 *file = extent->file->bs;
1343 break;
1346 n = extent->cluster_sectors - index_in_cluster;
1347 if (n > nb_sectors) {
1348 n = nb_sectors;
1350 *pnum = n;
1351 return ret;
1354 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1355 int64_t offset_in_cluster, QEMUIOVector *qiov,
1356 uint64_t qiov_offset, uint64_t n_bytes,
1357 uint64_t offset)
1359 int ret;
1360 VmdkGrainMarker *data = NULL;
1361 uLongf buf_len;
1362 QEMUIOVector local_qiov;
1363 struct iovec iov;
1364 int64_t write_offset;
1365 int64_t write_end_sector;
1367 if (extent->compressed) {
1368 void *compressed_data;
1370 if (!extent->has_marker) {
1371 ret = -EINVAL;
1372 goto out;
1374 buf_len = (extent->cluster_sectors << 9) * 2;
1375 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1377 compressed_data = g_malloc(n_bytes);
1378 qemu_iovec_to_buf(qiov, qiov_offset, compressed_data, n_bytes);
1379 ret = compress(data->data, &buf_len, compressed_data, n_bytes);
1380 g_free(compressed_data);
1382 if (ret != Z_OK || buf_len == 0) {
1383 ret = -EINVAL;
1384 goto out;
1387 data->lba = cpu_to_le64(offset >> BDRV_SECTOR_BITS);
1388 data->size = cpu_to_le32(buf_len);
1390 n_bytes = buf_len + sizeof(VmdkGrainMarker);
1391 iov = (struct iovec) {
1392 .iov_base = data,
1393 .iov_len = n_bytes,
1395 qemu_iovec_init_external(&local_qiov, &iov, 1);
1396 } else {
1397 qemu_iovec_init(&local_qiov, qiov->niov);
1398 qemu_iovec_concat(&local_qiov, qiov, qiov_offset, n_bytes);
1401 write_offset = cluster_offset + offset_in_cluster,
1402 ret = bdrv_co_pwritev(extent->file, write_offset, n_bytes,
1403 &local_qiov, 0);
1405 write_end_sector = DIV_ROUND_UP(write_offset + n_bytes, BDRV_SECTOR_SIZE);
1407 if (extent->compressed) {
1408 extent->next_cluster_sector = write_end_sector;
1409 } else {
1410 extent->next_cluster_sector = MAX(extent->next_cluster_sector,
1411 write_end_sector);
1414 if (ret < 0) {
1415 goto out;
1417 ret = 0;
1418 out:
1419 g_free(data);
1420 if (!extent->compressed) {
1421 qemu_iovec_destroy(&local_qiov);
1423 return ret;
1426 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1427 int64_t offset_in_cluster, QEMUIOVector *qiov,
1428 int bytes)
1430 int ret;
1431 int cluster_bytes, buf_bytes;
1432 uint8_t *cluster_buf, *compressed_data;
1433 uint8_t *uncomp_buf;
1434 uint32_t data_len;
1435 VmdkGrainMarker *marker;
1436 uLongf buf_len;
1439 if (!extent->compressed) {
1440 ret = bdrv_co_preadv(extent->file,
1441 cluster_offset + offset_in_cluster, bytes,
1442 qiov, 0);
1443 if (ret < 0) {
1444 return ret;
1446 return 0;
1448 cluster_bytes = extent->cluster_sectors * 512;
1449 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1450 buf_bytes = cluster_bytes * 2;
1451 cluster_buf = g_malloc(buf_bytes);
1452 uncomp_buf = g_malloc(cluster_bytes);
1453 ret = bdrv_pread(extent->file,
1454 cluster_offset,
1455 cluster_buf, buf_bytes);
1456 if (ret < 0) {
1457 goto out;
1459 compressed_data = cluster_buf;
1460 buf_len = cluster_bytes;
1461 data_len = cluster_bytes;
1462 if (extent->has_marker) {
1463 marker = (VmdkGrainMarker *)cluster_buf;
1464 compressed_data = marker->data;
1465 data_len = le32_to_cpu(marker->size);
1467 if (!data_len || data_len > buf_bytes) {
1468 ret = -EINVAL;
1469 goto out;
1471 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1472 if (ret != Z_OK) {
1473 ret = -EINVAL;
1474 goto out;
1477 if (offset_in_cluster < 0 ||
1478 offset_in_cluster + bytes > buf_len) {
1479 ret = -EINVAL;
1480 goto out;
1482 qemu_iovec_from_buf(qiov, 0, uncomp_buf + offset_in_cluster, bytes);
1483 ret = 0;
1485 out:
1486 g_free(uncomp_buf);
1487 g_free(cluster_buf);
1488 return ret;
1491 static int coroutine_fn
1492 vmdk_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1493 QEMUIOVector *qiov, int flags)
1495 BDRVVmdkState *s = bs->opaque;
1496 int ret;
1497 uint64_t n_bytes, offset_in_cluster;
1498 VmdkExtent *extent = NULL;
1499 QEMUIOVector local_qiov;
1500 uint64_t cluster_offset;
1501 uint64_t bytes_done = 0;
1503 qemu_iovec_init(&local_qiov, qiov->niov);
1504 qemu_co_mutex_lock(&s->lock);
1506 while (bytes > 0) {
1507 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1508 if (!extent) {
1509 ret = -EIO;
1510 goto fail;
1512 ret = get_cluster_offset(bs, extent, NULL,
1513 offset, false, &cluster_offset, 0, 0);
1514 offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1516 n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1517 - offset_in_cluster);
1519 if (ret != VMDK_OK) {
1520 /* if not allocated, try to read from parent image, if exist */
1521 if (bs->backing && ret != VMDK_ZEROED) {
1522 if (!vmdk_is_cid_valid(bs)) {
1523 ret = -EINVAL;
1524 goto fail;
1527 qemu_iovec_reset(&local_qiov);
1528 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1530 ret = bdrv_co_preadv(bs->backing, offset, n_bytes,
1531 &local_qiov, 0);
1532 if (ret < 0) {
1533 goto fail;
1535 } else {
1536 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
1538 } else {
1539 qemu_iovec_reset(&local_qiov);
1540 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1542 ret = vmdk_read_extent(extent, cluster_offset, offset_in_cluster,
1543 &local_qiov, n_bytes);
1544 if (ret) {
1545 goto fail;
1548 bytes -= n_bytes;
1549 offset += n_bytes;
1550 bytes_done += n_bytes;
1553 ret = 0;
1554 fail:
1555 qemu_co_mutex_unlock(&s->lock);
1556 qemu_iovec_destroy(&local_qiov);
1558 return ret;
1562 * vmdk_write:
1563 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1564 * if possible, otherwise return -ENOTSUP.
1565 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1566 * with each cluster. By dry run we can find if the zero write
1567 * is possible without modifying image data.
1569 * Returns: error code with 0 for success.
1571 static int vmdk_pwritev(BlockDriverState *bs, uint64_t offset,
1572 uint64_t bytes, QEMUIOVector *qiov,
1573 bool zeroed, bool zero_dry_run)
1575 BDRVVmdkState *s = bs->opaque;
1576 VmdkExtent *extent = NULL;
1577 int ret;
1578 int64_t offset_in_cluster, n_bytes;
1579 uint64_t cluster_offset;
1580 uint64_t bytes_done = 0;
1581 VmdkMetaData m_data;
1583 if (DIV_ROUND_UP(offset, BDRV_SECTOR_SIZE) > bs->total_sectors) {
1584 error_report("Wrong offset: offset=0x%" PRIx64
1585 " total_sectors=0x%" PRIx64,
1586 offset, bs->total_sectors);
1587 return -EIO;
1590 while (bytes > 0) {
1591 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1592 if (!extent) {
1593 return -EIO;
1595 offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1596 n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1597 - offset_in_cluster);
1599 ret = get_cluster_offset(bs, extent, &m_data, offset,
1600 !(extent->compressed || zeroed),
1601 &cluster_offset, offset_in_cluster,
1602 offset_in_cluster + n_bytes);
1603 if (extent->compressed) {
1604 if (ret == VMDK_OK) {
1605 /* Refuse write to allocated cluster for streamOptimized */
1606 error_report("Could not write to allocated cluster"
1607 " for streamOptimized");
1608 return -EIO;
1609 } else {
1610 /* allocate */
1611 ret = get_cluster_offset(bs, extent, &m_data, offset,
1612 true, &cluster_offset, 0, 0);
1615 if (ret == VMDK_ERROR) {
1616 return -EINVAL;
1618 if (zeroed) {
1619 /* Do zeroed write, buf is ignored */
1620 if (extent->has_zero_grain &&
1621 offset_in_cluster == 0 &&
1622 n_bytes >= extent->cluster_sectors * BDRV_SECTOR_SIZE) {
1623 n_bytes = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1624 if (!zero_dry_run) {
1625 /* update L2 tables */
1626 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1627 != VMDK_OK) {
1628 return -EIO;
1631 } else {
1632 return -ENOTSUP;
1634 } else {
1635 ret = vmdk_write_extent(extent, cluster_offset, offset_in_cluster,
1636 qiov, bytes_done, n_bytes, offset);
1637 if (ret) {
1638 return ret;
1640 if (m_data.valid) {
1641 /* update L2 tables */
1642 if (vmdk_L2update(extent, &m_data,
1643 cluster_offset >> BDRV_SECTOR_BITS)
1644 != VMDK_OK) {
1645 return -EIO;
1649 bytes -= n_bytes;
1650 offset += n_bytes;
1651 bytes_done += n_bytes;
1653 /* update CID on the first write every time the virtual disk is
1654 * opened */
1655 if (!s->cid_updated) {
1656 ret = vmdk_write_cid(bs, g_random_int());
1657 if (ret < 0) {
1658 return ret;
1660 s->cid_updated = true;
1663 return 0;
1666 static int coroutine_fn
1667 vmdk_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1668 QEMUIOVector *qiov, int flags)
1670 int ret;
1671 BDRVVmdkState *s = bs->opaque;
1672 qemu_co_mutex_lock(&s->lock);
1673 ret = vmdk_pwritev(bs, offset, bytes, qiov, false, false);
1674 qemu_co_mutex_unlock(&s->lock);
1675 return ret;
1678 static int coroutine_fn
1679 vmdk_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1680 uint64_t bytes, QEMUIOVector *qiov)
1682 return vmdk_co_pwritev(bs, offset, bytes, qiov, 0);
1685 static int coroutine_fn vmdk_co_pwrite_zeroes(BlockDriverState *bs,
1686 int64_t offset,
1687 int bytes,
1688 BdrvRequestFlags flags)
1690 int ret;
1691 BDRVVmdkState *s = bs->opaque;
1693 qemu_co_mutex_lock(&s->lock);
1694 /* write zeroes could fail if sectors not aligned to cluster, test it with
1695 * dry_run == true before really updating image */
1696 ret = vmdk_pwritev(bs, offset, bytes, NULL, true, true);
1697 if (!ret) {
1698 ret = vmdk_pwritev(bs, offset, bytes, NULL, true, false);
1700 qemu_co_mutex_unlock(&s->lock);
1701 return ret;
1704 static int vmdk_create_extent(const char *filename, int64_t filesize,
1705 bool flat, bool compress, bool zeroed_grain,
1706 QemuOpts *opts, Error **errp)
1708 int ret, i;
1709 BlockBackend *blk = NULL;
1710 VMDK4Header header;
1711 Error *local_err = NULL;
1712 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1713 uint32_t *gd_buf = NULL;
1714 int gd_buf_size;
1716 ret = bdrv_create_file(filename, opts, &local_err);
1717 if (ret < 0) {
1718 error_propagate(errp, local_err);
1719 goto exit;
1722 blk = blk_new_open(filename, NULL, NULL,
1723 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
1724 &local_err);
1725 if (blk == NULL) {
1726 error_propagate(errp, local_err);
1727 ret = -EIO;
1728 goto exit;
1731 blk_set_allow_write_beyond_eof(blk, true);
1733 if (flat) {
1734 ret = blk_truncate(blk, filesize, PREALLOC_MODE_OFF, errp);
1735 goto exit;
1737 magic = cpu_to_be32(VMDK4_MAGIC);
1738 memset(&header, 0, sizeof(header));
1739 if (compress) {
1740 header.version = 3;
1741 } else if (zeroed_grain) {
1742 header.version = 2;
1743 } else {
1744 header.version = 1;
1746 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1747 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1748 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1749 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1750 header.capacity = filesize / BDRV_SECTOR_SIZE;
1751 header.granularity = 128;
1752 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1754 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1755 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1756 BDRV_SECTOR_SIZE);
1757 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1758 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1760 header.desc_offset = 1;
1761 header.desc_size = 20;
1762 header.rgd_offset = header.desc_offset + header.desc_size;
1763 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1764 header.grain_offset =
1765 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1766 header.granularity);
1767 /* swap endianness for all header fields */
1768 header.version = cpu_to_le32(header.version);
1769 header.flags = cpu_to_le32(header.flags);
1770 header.capacity = cpu_to_le64(header.capacity);
1771 header.granularity = cpu_to_le64(header.granularity);
1772 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1773 header.desc_offset = cpu_to_le64(header.desc_offset);
1774 header.desc_size = cpu_to_le64(header.desc_size);
1775 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1776 header.gd_offset = cpu_to_le64(header.gd_offset);
1777 header.grain_offset = cpu_to_le64(header.grain_offset);
1778 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1780 header.check_bytes[0] = 0xa;
1781 header.check_bytes[1] = 0x20;
1782 header.check_bytes[2] = 0xd;
1783 header.check_bytes[3] = 0xa;
1785 /* write all the data */
1786 ret = blk_pwrite(blk, 0, &magic, sizeof(magic), 0);
1787 if (ret < 0) {
1788 error_setg(errp, QERR_IO_ERROR);
1789 goto exit;
1791 ret = blk_pwrite(blk, sizeof(magic), &header, sizeof(header), 0);
1792 if (ret < 0) {
1793 error_setg(errp, QERR_IO_ERROR);
1794 goto exit;
1797 ret = blk_truncate(blk, le64_to_cpu(header.grain_offset) << 9,
1798 PREALLOC_MODE_OFF, errp);
1799 if (ret < 0) {
1800 goto exit;
1803 /* write grain directory */
1804 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1805 gd_buf = g_malloc0(gd_buf_size);
1806 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1807 i < gt_count; i++, tmp += gt_size) {
1808 gd_buf[i] = cpu_to_le32(tmp);
1810 ret = blk_pwrite(blk, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1811 gd_buf, gd_buf_size, 0);
1812 if (ret < 0) {
1813 error_setg(errp, QERR_IO_ERROR);
1814 goto exit;
1817 /* write backup grain directory */
1818 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1819 i < gt_count; i++, tmp += gt_size) {
1820 gd_buf[i] = cpu_to_le32(tmp);
1822 ret = blk_pwrite(blk, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1823 gd_buf, gd_buf_size, 0);
1824 if (ret < 0) {
1825 error_setg(errp, QERR_IO_ERROR);
1826 goto exit;
1829 ret = 0;
1830 exit:
1831 if (blk) {
1832 blk_unref(blk);
1834 g_free(gd_buf);
1835 return ret;
1838 static int filename_decompose(const char *filename, char *path, char *prefix,
1839 char *postfix, size_t buf_len, Error **errp)
1841 const char *p, *q;
1843 if (filename == NULL || !strlen(filename)) {
1844 error_setg(errp, "No filename provided");
1845 return VMDK_ERROR;
1847 p = strrchr(filename, '/');
1848 if (p == NULL) {
1849 p = strrchr(filename, '\\');
1851 if (p == NULL) {
1852 p = strrchr(filename, ':');
1854 if (p != NULL) {
1855 p++;
1856 if (p - filename >= buf_len) {
1857 return VMDK_ERROR;
1859 pstrcpy(path, p - filename + 1, filename);
1860 } else {
1861 p = filename;
1862 path[0] = '\0';
1864 q = strrchr(p, '.');
1865 if (q == NULL) {
1866 pstrcpy(prefix, buf_len, p);
1867 postfix[0] = '\0';
1868 } else {
1869 if (q - p >= buf_len) {
1870 return VMDK_ERROR;
1872 pstrcpy(prefix, q - p + 1, p);
1873 pstrcpy(postfix, buf_len, q);
1875 return VMDK_OK;
1878 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1880 int idx = 0;
1881 BlockBackend *new_blk = NULL;
1882 Error *local_err = NULL;
1883 char *desc = NULL;
1884 int64_t total_size = 0, filesize;
1885 char *adapter_type = NULL;
1886 char *backing_file = NULL;
1887 char *hw_version = NULL;
1888 char *fmt = NULL;
1889 int ret = 0;
1890 bool flat, split, compress;
1891 GString *ext_desc_lines;
1892 char *path = g_malloc0(PATH_MAX);
1893 char *prefix = g_malloc0(PATH_MAX);
1894 char *postfix = g_malloc0(PATH_MAX);
1895 char *desc_line = g_malloc0(BUF_SIZE);
1896 char *ext_filename = g_malloc0(PATH_MAX);
1897 char *desc_filename = g_malloc0(PATH_MAX);
1898 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1899 const char *desc_extent_line;
1900 char *parent_desc_line = g_malloc0(BUF_SIZE);
1901 uint32_t parent_cid = 0xffffffff;
1902 uint32_t number_heads = 16;
1903 bool zeroed_grain = false;
1904 uint32_t desc_offset = 0, desc_len;
1905 const char desc_template[] =
1906 "# Disk DescriptorFile\n"
1907 "version=1\n"
1908 "CID=%" PRIx32 "\n"
1909 "parentCID=%" PRIx32 "\n"
1910 "createType=\"%s\"\n"
1911 "%s"
1912 "\n"
1913 "# Extent description\n"
1914 "%s"
1915 "\n"
1916 "# The Disk Data Base\n"
1917 "#DDB\n"
1918 "\n"
1919 "ddb.virtualHWVersion = \"%s\"\n"
1920 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1921 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1922 "ddb.geometry.sectors = \"63\"\n"
1923 "ddb.adapterType = \"%s\"\n";
1925 ext_desc_lines = g_string_new(NULL);
1927 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1928 ret = -EINVAL;
1929 goto exit;
1931 /* Read out options */
1932 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1933 BDRV_SECTOR_SIZE);
1934 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1935 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1936 hw_version = qemu_opt_get_del(opts, BLOCK_OPT_HWVERSION);
1937 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1938 if (strcmp(hw_version, "undefined")) {
1939 error_setg(errp,
1940 "compat6 cannot be enabled with hwversion set");
1941 ret = -EINVAL;
1942 goto exit;
1944 g_free(hw_version);
1945 hw_version = g_strdup("6");
1947 if (strcmp(hw_version, "undefined") == 0) {
1948 g_free(hw_version);
1949 hw_version = g_strdup("4");
1951 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1952 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1953 zeroed_grain = true;
1956 if (!adapter_type) {
1957 adapter_type = g_strdup("ide");
1958 } else if (strcmp(adapter_type, "ide") &&
1959 strcmp(adapter_type, "buslogic") &&
1960 strcmp(adapter_type, "lsilogic") &&
1961 strcmp(adapter_type, "legacyESX")) {
1962 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1963 ret = -EINVAL;
1964 goto exit;
1966 if (strcmp(adapter_type, "ide") != 0) {
1967 /* that's the number of heads with which vmware operates when
1968 creating, exporting, etc. vmdk files with a non-ide adapter type */
1969 number_heads = 255;
1971 if (!fmt) {
1972 /* Default format to monolithicSparse */
1973 fmt = g_strdup("monolithicSparse");
1974 } else if (strcmp(fmt, "monolithicFlat") &&
1975 strcmp(fmt, "monolithicSparse") &&
1976 strcmp(fmt, "twoGbMaxExtentSparse") &&
1977 strcmp(fmt, "twoGbMaxExtentFlat") &&
1978 strcmp(fmt, "streamOptimized")) {
1979 error_setg(errp, "Unknown subformat: '%s'", fmt);
1980 ret = -EINVAL;
1981 goto exit;
1983 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1984 strcmp(fmt, "twoGbMaxExtentSparse"));
1985 flat = !(strcmp(fmt, "monolithicFlat") &&
1986 strcmp(fmt, "twoGbMaxExtentFlat"));
1987 compress = !strcmp(fmt, "streamOptimized");
1988 if (flat) {
1989 desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1990 } else {
1991 desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1993 if (flat && backing_file) {
1994 error_setg(errp, "Flat image can't have backing file");
1995 ret = -ENOTSUP;
1996 goto exit;
1998 if (flat && zeroed_grain) {
1999 error_setg(errp, "Flat image can't enable zeroed grain");
2000 ret = -ENOTSUP;
2001 goto exit;
2003 if (backing_file) {
2004 BlockBackend *blk;
2005 char *full_backing = g_new0(char, PATH_MAX);
2006 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
2007 full_backing, PATH_MAX,
2008 &local_err);
2009 if (local_err) {
2010 g_free(full_backing);
2011 error_propagate(errp, local_err);
2012 ret = -ENOENT;
2013 goto exit;
2016 blk = blk_new_open(full_backing, NULL, NULL,
2017 BDRV_O_NO_BACKING, errp);
2018 g_free(full_backing);
2019 if (blk == NULL) {
2020 ret = -EIO;
2021 goto exit;
2023 if (strcmp(blk_bs(blk)->drv->format_name, "vmdk")) {
2024 blk_unref(blk);
2025 ret = -EINVAL;
2026 goto exit;
2028 ret = vmdk_read_cid(blk_bs(blk), 0, &parent_cid);
2029 blk_unref(blk);
2030 if (ret) {
2031 goto exit;
2033 snprintf(parent_desc_line, BUF_SIZE,
2034 "parentFileNameHint=\"%s\"", backing_file);
2037 /* Create extents */
2038 filesize = total_size;
2039 while (filesize > 0) {
2040 int64_t size = filesize;
2042 if (split && size > split_size) {
2043 size = split_size;
2045 if (split) {
2046 snprintf(desc_filename, PATH_MAX, "%s-%c%03d%s",
2047 prefix, flat ? 'f' : 's', ++idx, postfix);
2048 } else if (flat) {
2049 snprintf(desc_filename, PATH_MAX, "%s-flat%s", prefix, postfix);
2050 } else {
2051 snprintf(desc_filename, PATH_MAX, "%s%s", prefix, postfix);
2053 snprintf(ext_filename, PATH_MAX, "%s%s", path, desc_filename);
2055 if (vmdk_create_extent(ext_filename, size,
2056 flat, compress, zeroed_grain, opts, errp)) {
2057 ret = -EINVAL;
2058 goto exit;
2060 filesize -= size;
2062 /* Format description line */
2063 snprintf(desc_line, BUF_SIZE,
2064 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
2065 g_string_append(ext_desc_lines, desc_line);
2067 /* generate descriptor file */
2068 desc = g_strdup_printf(desc_template,
2069 g_random_int(),
2070 parent_cid,
2071 fmt,
2072 parent_desc_line,
2073 ext_desc_lines->str,
2074 hw_version,
2075 total_size /
2076 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
2077 number_heads,
2078 adapter_type);
2079 desc_len = strlen(desc);
2080 /* the descriptor offset = 0x200 */
2081 if (!split && !flat) {
2082 desc_offset = 0x200;
2083 } else {
2084 ret = bdrv_create_file(filename, opts, &local_err);
2085 if (ret < 0) {
2086 error_propagate(errp, local_err);
2087 goto exit;
2091 new_blk = blk_new_open(filename, NULL, NULL,
2092 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
2093 &local_err);
2094 if (new_blk == NULL) {
2095 error_propagate(errp, local_err);
2096 ret = -EIO;
2097 goto exit;
2100 blk_set_allow_write_beyond_eof(new_blk, true);
2102 ret = blk_pwrite(new_blk, desc_offset, desc, desc_len, 0);
2103 if (ret < 0) {
2104 error_setg_errno(errp, -ret, "Could not write description");
2105 goto exit;
2107 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2108 * for description file */
2109 if (desc_offset == 0) {
2110 ret = blk_truncate(new_blk, desc_len, PREALLOC_MODE_OFF, errp);
2112 exit:
2113 if (new_blk) {
2114 blk_unref(new_blk);
2116 g_free(adapter_type);
2117 g_free(backing_file);
2118 g_free(hw_version);
2119 g_free(fmt);
2120 g_free(desc);
2121 g_free(path);
2122 g_free(prefix);
2123 g_free(postfix);
2124 g_free(desc_line);
2125 g_free(ext_filename);
2126 g_free(desc_filename);
2127 g_free(parent_desc_line);
2128 g_string_free(ext_desc_lines, true);
2129 return ret;
2132 static void vmdk_close(BlockDriverState *bs)
2134 BDRVVmdkState *s = bs->opaque;
2136 vmdk_free_extents(bs);
2137 g_free(s->create_type);
2139 migrate_del_blocker(s->migration_blocker);
2140 error_free(s->migration_blocker);
2143 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
2145 BDRVVmdkState *s = bs->opaque;
2146 int i, err;
2147 int ret = 0;
2149 for (i = 0; i < s->num_extents; i++) {
2150 err = bdrv_co_flush(s->extents[i].file->bs);
2151 if (err < 0) {
2152 ret = err;
2155 return ret;
2158 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2160 int i;
2161 int64_t ret = 0;
2162 int64_t r;
2163 BDRVVmdkState *s = bs->opaque;
2165 ret = bdrv_get_allocated_file_size(bs->file->bs);
2166 if (ret < 0) {
2167 return ret;
2169 for (i = 0; i < s->num_extents; i++) {
2170 if (s->extents[i].file == bs->file) {
2171 continue;
2173 r = bdrv_get_allocated_file_size(s->extents[i].file->bs);
2174 if (r < 0) {
2175 return r;
2177 ret += r;
2179 return ret;
2182 static int vmdk_has_zero_init(BlockDriverState *bs)
2184 int i;
2185 BDRVVmdkState *s = bs->opaque;
2187 /* If has a flat extent and its underlying storage doesn't have zero init,
2188 * return 0. */
2189 for (i = 0; i < s->num_extents; i++) {
2190 if (s->extents[i].flat) {
2191 if (!bdrv_has_zero_init(s->extents[i].file->bs)) {
2192 return 0;
2196 return 1;
2199 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2201 ImageInfo *info = g_new0(ImageInfo, 1);
2203 *info = (ImageInfo){
2204 .filename = g_strdup(extent->file->bs->filename),
2205 .format = g_strdup(extent->type),
2206 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2207 .compressed = extent->compressed,
2208 .has_compressed = extent->compressed,
2209 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2210 .has_cluster_size = !extent->flat,
2213 return info;
2216 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2217 BdrvCheckMode fix)
2219 BDRVVmdkState *s = bs->opaque;
2220 VmdkExtent *extent = NULL;
2221 int64_t sector_num = 0;
2222 int64_t total_sectors = bdrv_nb_sectors(bs);
2223 int ret;
2224 uint64_t cluster_offset;
2226 if (fix) {
2227 return -ENOTSUP;
2230 for (;;) {
2231 if (sector_num >= total_sectors) {
2232 return 0;
2234 extent = find_extent(s, sector_num, extent);
2235 if (!extent) {
2236 fprintf(stderr,
2237 "ERROR: could not find extent for sector %" PRId64 "\n",
2238 sector_num);
2239 break;
2241 ret = get_cluster_offset(bs, extent, NULL,
2242 sector_num << BDRV_SECTOR_BITS,
2243 false, &cluster_offset, 0, 0);
2244 if (ret == VMDK_ERROR) {
2245 fprintf(stderr,
2246 "ERROR: could not get cluster_offset for sector %"
2247 PRId64 "\n", sector_num);
2248 break;
2250 if (ret == VMDK_OK &&
2251 cluster_offset >= bdrv_getlength(extent->file->bs))
2253 fprintf(stderr,
2254 "ERROR: cluster offset for sector %"
2255 PRId64 " points after EOF\n", sector_num);
2256 break;
2258 sector_num += extent->cluster_sectors;
2261 result->corruptions++;
2262 return 0;
2265 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2267 int i;
2268 BDRVVmdkState *s = bs->opaque;
2269 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2270 ImageInfoList **next;
2272 *spec_info = (ImageInfoSpecific){
2273 .type = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2274 .u = {
2275 .vmdk.data = g_new0(ImageInfoSpecificVmdk, 1),
2279 *spec_info->u.vmdk.data = (ImageInfoSpecificVmdk) {
2280 .create_type = g_strdup(s->create_type),
2281 .cid = s->cid,
2282 .parent_cid = s->parent_cid,
2285 next = &spec_info->u.vmdk.data->extents;
2286 for (i = 0; i < s->num_extents; i++) {
2287 *next = g_new0(ImageInfoList, 1);
2288 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2289 (*next)->next = NULL;
2290 next = &(*next)->next;
2293 return spec_info;
2296 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2298 return a->flat == b->flat &&
2299 a->compressed == b->compressed &&
2300 (a->flat || a->cluster_sectors == b->cluster_sectors);
2303 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2305 int i;
2306 BDRVVmdkState *s = bs->opaque;
2307 assert(s->num_extents);
2309 /* See if we have multiple extents but they have different cases */
2310 for (i = 1; i < s->num_extents; i++) {
2311 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2312 return -ENOTSUP;
2315 bdi->needs_compressed_writes = s->extents[0].compressed;
2316 if (!s->extents[0].flat) {
2317 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2319 return 0;
2322 static QemuOptsList vmdk_create_opts = {
2323 .name = "vmdk-create-opts",
2324 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2325 .desc = {
2327 .name = BLOCK_OPT_SIZE,
2328 .type = QEMU_OPT_SIZE,
2329 .help = "Virtual disk size"
2332 .name = BLOCK_OPT_ADAPTER_TYPE,
2333 .type = QEMU_OPT_STRING,
2334 .help = "Virtual adapter type, can be one of "
2335 "ide (default), lsilogic, buslogic or legacyESX"
2338 .name = BLOCK_OPT_BACKING_FILE,
2339 .type = QEMU_OPT_STRING,
2340 .help = "File name of a base image"
2343 .name = BLOCK_OPT_COMPAT6,
2344 .type = QEMU_OPT_BOOL,
2345 .help = "VMDK version 6 image",
2346 .def_value_str = "off"
2349 .name = BLOCK_OPT_HWVERSION,
2350 .type = QEMU_OPT_STRING,
2351 .help = "VMDK hardware version",
2352 .def_value_str = "undefined"
2355 .name = BLOCK_OPT_SUBFMT,
2356 .type = QEMU_OPT_STRING,
2357 .help =
2358 "VMDK flat extent format, can be one of "
2359 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2362 .name = BLOCK_OPT_ZEROED_GRAIN,
2363 .type = QEMU_OPT_BOOL,
2364 .help = "Enable efficient zero writes "
2365 "using the zeroed-grain GTE feature"
2367 { /* end of list */ }
2371 static BlockDriver bdrv_vmdk = {
2372 .format_name = "vmdk",
2373 .instance_size = sizeof(BDRVVmdkState),
2374 .bdrv_probe = vmdk_probe,
2375 .bdrv_open = vmdk_open,
2376 .bdrv_check = vmdk_check,
2377 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2378 .bdrv_child_perm = bdrv_format_default_perms,
2379 .bdrv_co_preadv = vmdk_co_preadv,
2380 .bdrv_co_pwritev = vmdk_co_pwritev,
2381 .bdrv_co_pwritev_compressed = vmdk_co_pwritev_compressed,
2382 .bdrv_co_pwrite_zeroes = vmdk_co_pwrite_zeroes,
2383 .bdrv_close = vmdk_close,
2384 .bdrv_create = vmdk_create,
2385 .bdrv_co_flush_to_disk = vmdk_co_flush,
2386 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2387 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2388 .bdrv_has_zero_init = vmdk_has_zero_init,
2389 .bdrv_get_specific_info = vmdk_get_specific_info,
2390 .bdrv_refresh_limits = vmdk_refresh_limits,
2391 .bdrv_get_info = vmdk_get_info,
2393 .supports_backing = true,
2394 .create_opts = &vmdk_create_opts,
2397 static void bdrv_vmdk_init(void)
2399 bdrv_register(&bdrv_vmdk);
2402 block_init(bdrv_vmdk_init);