vmdk: check granularity field in opening
[qemu-kvm.git] / block / vmdk.c
blob015cbd4e6037b8d5868ea86475e9b36547c287b6
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 uint32_t num_gtes_per_gte;
75 uint64_t rgd_offset;
76 uint64_t gd_offset;
77 uint64_t grain_offset;
78 char filler[1];
79 char check_bytes[4];
80 uint16_t compressAlgorithm;
81 } QEMU_PACKED VMDK4Header;
83 #define L2_CACHE_SIZE 16
85 typedef struct VmdkExtent {
86 BlockDriverState *file;
87 bool flat;
88 bool compressed;
89 bool has_marker;
90 bool has_zero_grain;
91 int version;
92 int64_t sectors;
93 int64_t end_sector;
94 int64_t flat_start_offset;
95 int64_t l1_table_offset;
96 int64_t l1_backup_table_offset;
97 uint32_t *l1_table;
98 uint32_t *l1_backup_table;
99 unsigned int l1_size;
100 uint32_t l1_entry_sectors;
102 unsigned int l2_size;
103 uint32_t *l2_cache;
104 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
105 uint32_t l2_cache_counts[L2_CACHE_SIZE];
107 unsigned int cluster_sectors;
108 } VmdkExtent;
110 typedef struct BDRVVmdkState {
111 CoMutex lock;
112 uint64_t desc_offset;
113 bool cid_updated;
114 uint32_t parent_cid;
115 int num_extents;
116 /* Extent array with num_extents entries, ascend ordered by address */
117 VmdkExtent *extents;
118 Error *migration_blocker;
119 } BDRVVmdkState;
121 typedef struct VmdkMetaData {
122 uint32_t offset;
123 unsigned int l1_index;
124 unsigned int l2_index;
125 unsigned int l2_offset;
126 int valid;
127 uint32_t *l2_cache_entry;
128 } VmdkMetaData;
130 typedef struct VmdkGrainMarker {
131 uint64_t lba;
132 uint32_t size;
133 uint8_t data[0];
134 } QEMU_PACKED VmdkGrainMarker;
136 enum {
137 MARKER_END_OF_STREAM = 0,
138 MARKER_GRAIN_TABLE = 1,
139 MARKER_GRAIN_DIRECTORY = 2,
140 MARKER_FOOTER = 3,
143 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
145 uint32_t magic;
147 if (buf_size < 4) {
148 return 0;
150 magic = be32_to_cpu(*(uint32_t *)buf);
151 if (magic == VMDK3_MAGIC ||
152 magic == VMDK4_MAGIC) {
153 return 100;
154 } else {
155 const char *p = (const char *)buf;
156 const char *end = p + buf_size;
157 while (p < end) {
158 if (*p == '#') {
159 /* skip comment line */
160 while (p < end && *p != '\n') {
161 p++;
163 p++;
164 continue;
166 if (*p == ' ') {
167 while (p < end && *p == ' ') {
168 p++;
170 /* skip '\r' if windows line endings used. */
171 if (p < end && *p == '\r') {
172 p++;
174 /* only accept blank lines before 'version=' line */
175 if (p == end || *p != '\n') {
176 return 0;
178 p++;
179 continue;
181 if (end - p >= strlen("version=X\n")) {
182 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
183 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
184 return 100;
187 if (end - p >= strlen("version=X\r\n")) {
188 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
189 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
190 return 100;
193 return 0;
195 return 0;
199 #define CHECK_CID 1
201 #define SECTOR_SIZE 512
202 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
203 #define BUF_SIZE 4096
204 #define HEADER_SIZE 512 /* first sector of 512 bytes */
206 static void vmdk_free_extents(BlockDriverState *bs)
208 int i;
209 BDRVVmdkState *s = bs->opaque;
210 VmdkExtent *e;
212 for (i = 0; i < s->num_extents; i++) {
213 e = &s->extents[i];
214 g_free(e->l1_table);
215 g_free(e->l2_cache);
216 g_free(e->l1_backup_table);
217 if (e->file != bs->file) {
218 bdrv_delete(e->file);
221 g_free(s->extents);
224 static void vmdk_free_last_extent(BlockDriverState *bs)
226 BDRVVmdkState *s = bs->opaque;
228 if (s->num_extents == 0) {
229 return;
231 s->num_extents--;
232 s->extents = g_realloc(s->extents, s->num_extents * sizeof(VmdkExtent));
235 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
237 char desc[DESC_SIZE];
238 uint32_t cid = 0xffffffff;
239 const char *p_name, *cid_str;
240 size_t cid_str_size;
241 BDRVVmdkState *s = bs->opaque;
242 int ret;
244 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
245 if (ret < 0) {
246 return 0;
249 if (parent) {
250 cid_str = "parentCID";
251 cid_str_size = sizeof("parentCID");
252 } else {
253 cid_str = "CID";
254 cid_str_size = sizeof("CID");
257 desc[DESC_SIZE - 1] = '\0';
258 p_name = strstr(desc, cid_str);
259 if (p_name != NULL) {
260 p_name += cid_str_size;
261 sscanf(p_name, "%x", &cid);
264 return cid;
267 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
269 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
270 char *p_name, *tmp_str;
271 BDRVVmdkState *s = bs->opaque;
272 int ret;
274 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
275 if (ret < 0) {
276 return ret;
279 desc[DESC_SIZE - 1] = '\0';
280 tmp_str = strstr(desc, "parentCID");
281 if (tmp_str == NULL) {
282 return -EINVAL;
285 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
286 p_name = strstr(desc, "CID");
287 if (p_name != NULL) {
288 p_name += sizeof("CID");
289 snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);
290 pstrcat(desc, sizeof(desc), tmp_desc);
293 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
294 if (ret < 0) {
295 return ret;
298 return 0;
301 static int vmdk_is_cid_valid(BlockDriverState *bs)
303 #ifdef CHECK_CID
304 BDRVVmdkState *s = bs->opaque;
305 BlockDriverState *p_bs = bs->backing_hd;
306 uint32_t cur_pcid;
308 if (p_bs) {
309 cur_pcid = vmdk_read_cid(p_bs, 0);
310 if (s->parent_cid != cur_pcid) {
311 /* CID not valid */
312 return 0;
315 #endif
316 /* CID valid */
317 return 1;
320 /* Queue extents, if any, for reopen() */
321 static int vmdk_reopen_prepare(BDRVReopenState *state,
322 BlockReopenQueue *queue, Error **errp)
324 BDRVVmdkState *s;
325 int ret = -1;
326 int i;
327 VmdkExtent *e;
329 assert(state != NULL);
330 assert(state->bs != NULL);
332 if (queue == NULL) {
333 error_set(errp, ERROR_CLASS_GENERIC_ERROR,
334 "No reopen queue for VMDK extents");
335 goto exit;
338 s = state->bs->opaque;
340 assert(s != NULL);
342 for (i = 0; i < s->num_extents; i++) {
343 e = &s->extents[i];
344 if (e->file != state->bs->file) {
345 bdrv_reopen_queue(queue, e->file, state->flags);
348 ret = 0;
350 exit:
351 return ret;
354 static int vmdk_parent_open(BlockDriverState *bs)
356 char *p_name;
357 char desc[DESC_SIZE + 1];
358 BDRVVmdkState *s = bs->opaque;
359 int ret;
361 desc[DESC_SIZE] = '\0';
362 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
363 if (ret < 0) {
364 return ret;
367 p_name = strstr(desc, "parentFileNameHint");
368 if (p_name != NULL) {
369 char *end_name;
371 p_name += sizeof("parentFileNameHint") + 1;
372 end_name = strchr(p_name, '\"');
373 if (end_name == NULL) {
374 return -EINVAL;
376 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
377 return -EINVAL;
380 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
383 return 0;
386 /* Create and append extent to the extent array. Return the added VmdkExtent
387 * address. return NULL if allocation failed. */
388 static int vmdk_add_extent(BlockDriverState *bs,
389 BlockDriverState *file, bool flat, int64_t sectors,
390 int64_t l1_offset, int64_t l1_backup_offset,
391 uint32_t l1_size,
392 int l2_size, uint64_t cluster_sectors,
393 VmdkExtent **new_extent)
395 VmdkExtent *extent;
396 BDRVVmdkState *s = bs->opaque;
398 if (cluster_sectors > 0x200000) {
399 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
400 error_report("invalid granularity, image may be corrupt");
401 return -EINVAL;
404 s->extents = g_realloc(s->extents,
405 (s->num_extents + 1) * sizeof(VmdkExtent));
406 extent = &s->extents[s->num_extents];
407 s->num_extents++;
409 memset(extent, 0, sizeof(VmdkExtent));
410 extent->file = file;
411 extent->flat = flat;
412 extent->sectors = sectors;
413 extent->l1_table_offset = l1_offset;
414 extent->l1_backup_table_offset = l1_backup_offset;
415 extent->l1_size = l1_size;
416 extent->l1_entry_sectors = l2_size * cluster_sectors;
417 extent->l2_size = l2_size;
418 extent->cluster_sectors = cluster_sectors;
420 if (s->num_extents > 1) {
421 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
422 } else {
423 extent->end_sector = extent->sectors;
425 bs->total_sectors = extent->end_sector;
426 if (new_extent) {
427 *new_extent = extent;
429 return 0;
432 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent)
434 int ret;
435 int l1_size, i;
437 /* read the L1 table */
438 l1_size = extent->l1_size * sizeof(uint32_t);
439 extent->l1_table = g_malloc(l1_size);
440 ret = bdrv_pread(extent->file,
441 extent->l1_table_offset,
442 extent->l1_table,
443 l1_size);
444 if (ret < 0) {
445 goto fail_l1;
447 for (i = 0; i < extent->l1_size; i++) {
448 le32_to_cpus(&extent->l1_table[i]);
451 if (extent->l1_backup_table_offset) {
452 extent->l1_backup_table = g_malloc(l1_size);
453 ret = bdrv_pread(extent->file,
454 extent->l1_backup_table_offset,
455 extent->l1_backup_table,
456 l1_size);
457 if (ret < 0) {
458 goto fail_l1b;
460 for (i = 0; i < extent->l1_size; i++) {
461 le32_to_cpus(&extent->l1_backup_table[i]);
465 extent->l2_cache =
466 g_malloc(extent->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
467 return 0;
468 fail_l1b:
469 g_free(extent->l1_backup_table);
470 fail_l1:
471 g_free(extent->l1_table);
472 return ret;
475 static int vmdk_open_vmdk3(BlockDriverState *bs,
476 BlockDriverState *file,
477 int flags)
479 int ret;
480 uint32_t magic;
481 VMDK3Header header;
482 VmdkExtent *extent;
484 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
485 if (ret < 0) {
486 return ret;
489 ret = vmdk_add_extent(bs,
490 bs->file, false,
491 le32_to_cpu(header.disk_sectors),
492 le32_to_cpu(header.l1dir_offset) << 9,
493 0, 1 << 6, 1 << 9,
494 le32_to_cpu(header.granularity),
495 &extent);
496 if (ret < 0) {
497 return ret;
499 ret = vmdk_init_tables(bs, extent);
500 if (ret) {
501 /* free extent allocated by vmdk_add_extent */
502 vmdk_free_last_extent(bs);
504 return ret;
507 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
508 uint64_t desc_offset);
510 static int vmdk_open_vmdk4(BlockDriverState *bs,
511 BlockDriverState *file,
512 int flags)
514 int ret;
515 uint32_t magic;
516 uint32_t l1_size, l1_entry_sectors;
517 VMDK4Header header;
518 VmdkExtent *extent;
519 int64_t l1_backup_offset = 0;
521 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
522 if (ret < 0) {
523 return ret;
525 if (header.capacity == 0) {
526 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
527 if (desc_offset) {
528 return vmdk_open_desc_file(bs, flags, desc_offset << 9);
532 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
534 * The footer takes precedence over the header, so read it in. The
535 * footer starts at offset -1024 from the end: One sector for the
536 * footer, and another one for the end-of-stream marker.
538 struct {
539 struct {
540 uint64_t val;
541 uint32_t size;
542 uint32_t type;
543 uint8_t pad[512 - 16];
544 } QEMU_PACKED footer_marker;
546 uint32_t magic;
547 VMDK4Header header;
548 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
550 struct {
551 uint64_t val;
552 uint32_t size;
553 uint32_t type;
554 uint8_t pad[512 - 16];
555 } QEMU_PACKED eos_marker;
556 } QEMU_PACKED footer;
558 ret = bdrv_pread(file,
559 bs->file->total_sectors * 512 - 1536,
560 &footer, sizeof(footer));
561 if (ret < 0) {
562 return ret;
565 /* Some sanity checks for the footer */
566 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
567 le32_to_cpu(footer.footer_marker.size) != 0 ||
568 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
569 le64_to_cpu(footer.eos_marker.val) != 0 ||
570 le32_to_cpu(footer.eos_marker.size) != 0 ||
571 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
573 return -EINVAL;
576 header = footer.header;
579 if (le32_to_cpu(header.version) >= 3) {
580 char buf[64];
581 snprintf(buf, sizeof(buf), "VMDK version %d",
582 le32_to_cpu(header.version));
583 qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
584 bs->device_name, "vmdk", buf);
585 return -ENOTSUP;
588 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gte)
589 * le64_to_cpu(header.granularity);
590 if (l1_entry_sectors == 0) {
591 return -EINVAL;
593 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
594 / l1_entry_sectors;
595 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
596 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
598 ret = vmdk_add_extent(bs, file, false,
599 le64_to_cpu(header.capacity),
600 le64_to_cpu(header.gd_offset) << 9,
601 l1_backup_offset,
602 l1_size,
603 le32_to_cpu(header.num_gtes_per_gte),
604 le64_to_cpu(header.granularity),
605 &extent);
606 if (ret < 0) {
607 return ret;
609 extent->compressed =
610 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
611 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
612 extent->version = le32_to_cpu(header.version);
613 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
614 ret = vmdk_init_tables(bs, extent);
615 if (ret) {
616 /* free extent allocated by vmdk_add_extent */
617 vmdk_free_last_extent(bs);
619 return ret;
622 /* find an option value out of descriptor file */
623 static int vmdk_parse_description(const char *desc, const char *opt_name,
624 char *buf, int buf_size)
626 char *opt_pos, *opt_end;
627 const char *end = desc + strlen(desc);
629 opt_pos = strstr(desc, opt_name);
630 if (!opt_pos) {
631 return VMDK_ERROR;
633 /* Skip "=\"" following opt_name */
634 opt_pos += strlen(opt_name) + 2;
635 if (opt_pos >= end) {
636 return VMDK_ERROR;
638 opt_end = opt_pos;
639 while (opt_end < end && *opt_end != '"') {
640 opt_end++;
642 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
643 return VMDK_ERROR;
645 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
646 return VMDK_OK;
649 /* Open an extent file and append to bs array */
650 static int vmdk_open_sparse(BlockDriverState *bs,
651 BlockDriverState *file,
652 int flags)
654 uint32_t magic;
656 if (bdrv_pread(file, 0, &magic, sizeof(magic)) != sizeof(magic)) {
657 return -EIO;
660 magic = be32_to_cpu(magic);
661 switch (magic) {
662 case VMDK3_MAGIC:
663 return vmdk_open_vmdk3(bs, file, flags);
664 break;
665 case VMDK4_MAGIC:
666 return vmdk_open_vmdk4(bs, file, flags);
667 break;
668 default:
669 return -EMEDIUMTYPE;
670 break;
674 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
675 const char *desc_file_path)
677 int ret;
678 char access[11];
679 char type[11];
680 char fname[512];
681 const char *p = desc;
682 int64_t sectors = 0;
683 int64_t flat_offset;
684 char extent_path[PATH_MAX];
685 BlockDriverState *extent_file;
687 while (*p) {
688 /* parse extent line:
689 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
690 * or
691 * RW [size in sectors] SPARSE "file-name.vmdk"
693 flat_offset = -1;
694 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
695 access, &sectors, type, fname, &flat_offset);
696 if (ret < 4 || strcmp(access, "RW")) {
697 goto next_line;
698 } else if (!strcmp(type, "FLAT")) {
699 if (ret != 5 || flat_offset < 0) {
700 return -EINVAL;
702 } else if (ret != 4) {
703 return -EINVAL;
706 if (sectors <= 0 ||
707 (strcmp(type, "FLAT") && strcmp(type, "SPARSE")) ||
708 (strcmp(access, "RW"))) {
709 goto next_line;
712 path_combine(extent_path, sizeof(extent_path),
713 desc_file_path, fname);
714 ret = bdrv_file_open(&extent_file, extent_path, NULL, bs->open_flags);
715 if (ret) {
716 return ret;
719 /* save to extents array */
720 if (!strcmp(type, "FLAT")) {
721 /* FLAT extent */
722 VmdkExtent *extent;
724 ret = vmdk_add_extent(bs, extent_file, true, sectors,
725 0, 0, 0, 0, sectors, &extent);
726 if (ret < 0) {
727 return ret;
729 extent->flat_start_offset = flat_offset << 9;
730 } else if (!strcmp(type, "SPARSE")) {
731 /* SPARSE extent */
732 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags);
733 if (ret) {
734 bdrv_delete(extent_file);
735 return ret;
737 } else {
738 fprintf(stderr,
739 "VMDK: Not supported extent type \"%s\""".\n", type);
740 return -ENOTSUP;
742 next_line:
743 /* move to next line */
744 while (*p && *p != '\n') {
745 p++;
747 p++;
749 return 0;
752 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
753 uint64_t desc_offset)
755 int ret;
756 char *buf = NULL;
757 char ct[128];
758 BDRVVmdkState *s = bs->opaque;
759 int64_t size;
761 size = bdrv_getlength(bs->file);
762 if (size < 0) {
763 return -EINVAL;
766 size = MIN(size, 1 << 20); /* avoid unbounded allocation */
767 buf = g_malloc0(size + 1);
769 ret = bdrv_pread(bs->file, desc_offset, buf, size);
770 if (ret < 0) {
771 goto exit;
773 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
774 ret = -EMEDIUMTYPE;
775 goto exit;
777 if (strcmp(ct, "monolithicFlat") &&
778 strcmp(ct, "twoGbMaxExtentSparse") &&
779 strcmp(ct, "twoGbMaxExtentFlat")) {
780 fprintf(stderr,
781 "VMDK: Not supported image type \"%s\""".\n", ct);
782 ret = -ENOTSUP;
783 goto exit;
785 s->desc_offset = 0;
786 ret = vmdk_parse_extents(buf, bs, bs->file->filename);
787 exit:
788 g_free(buf);
789 return ret;
792 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags)
794 int ret;
795 BDRVVmdkState *s = bs->opaque;
797 if (vmdk_open_sparse(bs, bs->file, flags) == 0) {
798 s->desc_offset = 0x200;
799 } else {
800 ret = vmdk_open_desc_file(bs, flags, 0);
801 if (ret) {
802 goto fail;
805 /* try to open parent images, if exist */
806 ret = vmdk_parent_open(bs);
807 if (ret) {
808 goto fail;
810 s->parent_cid = vmdk_read_cid(bs, 1);
811 qemu_co_mutex_init(&s->lock);
813 /* Disable migration when VMDK images are used */
814 error_set(&s->migration_blocker,
815 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
816 "vmdk", bs->device_name, "live migration");
817 migrate_add_blocker(s->migration_blocker);
819 return 0;
821 fail:
822 vmdk_free_extents(bs);
823 return ret;
826 static int get_whole_cluster(BlockDriverState *bs,
827 VmdkExtent *extent,
828 uint64_t cluster_offset,
829 uint64_t offset,
830 bool allocate)
832 /* 128 sectors * 512 bytes each = grain size 64KB */
833 uint8_t whole_grain[extent->cluster_sectors * 512];
835 /* we will be here if it's first write on non-exist grain(cluster).
836 * try to read from parent image, if exist */
837 if (bs->backing_hd) {
838 int ret;
840 if (!vmdk_is_cid_valid(bs)) {
841 return VMDK_ERROR;
844 /* floor offset to cluster */
845 offset -= offset % (extent->cluster_sectors * 512);
846 ret = bdrv_read(bs->backing_hd, offset >> 9, whole_grain,
847 extent->cluster_sectors);
848 if (ret < 0) {
849 return VMDK_ERROR;
852 /* Write grain only into the active image */
853 ret = bdrv_write(extent->file, cluster_offset, whole_grain,
854 extent->cluster_sectors);
855 if (ret < 0) {
856 return VMDK_ERROR;
859 return VMDK_OK;
862 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data)
864 uint32_t offset;
865 QEMU_BUILD_BUG_ON(sizeof(offset) != sizeof(m_data->offset));
866 offset = cpu_to_le32(m_data->offset);
867 /* update L2 table */
868 if (bdrv_pwrite_sync(
869 extent->file,
870 ((int64_t)m_data->l2_offset * 512)
871 + (m_data->l2_index * sizeof(m_data->offset)),
872 &offset, sizeof(offset)) < 0) {
873 return VMDK_ERROR;
875 /* update backup L2 table */
876 if (extent->l1_backup_table_offset != 0) {
877 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
878 if (bdrv_pwrite_sync(
879 extent->file,
880 ((int64_t)m_data->l2_offset * 512)
881 + (m_data->l2_index * sizeof(m_data->offset)),
882 &offset, sizeof(offset)) < 0) {
883 return VMDK_ERROR;
886 if (m_data->l2_cache_entry) {
887 *m_data->l2_cache_entry = offset;
890 return VMDK_OK;
893 static int get_cluster_offset(BlockDriverState *bs,
894 VmdkExtent *extent,
895 VmdkMetaData *m_data,
896 uint64_t offset,
897 int allocate,
898 uint64_t *cluster_offset)
900 unsigned int l1_index, l2_offset, l2_index;
901 int min_index, i, j;
902 uint32_t min_count, *l2_table;
903 bool zeroed = false;
905 if (m_data) {
906 m_data->valid = 0;
908 if (extent->flat) {
909 *cluster_offset = extent->flat_start_offset;
910 return VMDK_OK;
913 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
914 l1_index = (offset >> 9) / extent->l1_entry_sectors;
915 if (l1_index >= extent->l1_size) {
916 return VMDK_ERROR;
918 l2_offset = extent->l1_table[l1_index];
919 if (!l2_offset) {
920 return VMDK_UNALLOC;
922 for (i = 0; i < L2_CACHE_SIZE; i++) {
923 if (l2_offset == extent->l2_cache_offsets[i]) {
924 /* increment the hit count */
925 if (++extent->l2_cache_counts[i] == 0xffffffff) {
926 for (j = 0; j < L2_CACHE_SIZE; j++) {
927 extent->l2_cache_counts[j] >>= 1;
930 l2_table = extent->l2_cache + (i * extent->l2_size);
931 goto found;
934 /* not found: load a new entry in the least used one */
935 min_index = 0;
936 min_count = 0xffffffff;
937 for (i = 0; i < L2_CACHE_SIZE; i++) {
938 if (extent->l2_cache_counts[i] < min_count) {
939 min_count = extent->l2_cache_counts[i];
940 min_index = i;
943 l2_table = extent->l2_cache + (min_index * extent->l2_size);
944 if (bdrv_pread(
945 extent->file,
946 (int64_t)l2_offset * 512,
947 l2_table,
948 extent->l2_size * sizeof(uint32_t)
949 ) != extent->l2_size * sizeof(uint32_t)) {
950 return VMDK_ERROR;
953 extent->l2_cache_offsets[min_index] = l2_offset;
954 extent->l2_cache_counts[min_index] = 1;
955 found:
956 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
957 *cluster_offset = le32_to_cpu(l2_table[l2_index]);
959 if (m_data) {
960 m_data->valid = 1;
961 m_data->l1_index = l1_index;
962 m_data->l2_index = l2_index;
963 m_data->offset = *cluster_offset;
964 m_data->l2_offset = l2_offset;
965 m_data->l2_cache_entry = &l2_table[l2_index];
967 if (extent->has_zero_grain && *cluster_offset == VMDK_GTE_ZEROED) {
968 zeroed = true;
971 if (!*cluster_offset || zeroed) {
972 if (!allocate) {
973 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
976 /* Avoid the L2 tables update for the images that have snapshots. */
977 *cluster_offset = bdrv_getlength(extent->file);
978 if (!extent->compressed) {
979 bdrv_truncate(
980 extent->file,
981 *cluster_offset + (extent->cluster_sectors << 9)
985 *cluster_offset >>= 9;
986 l2_table[l2_index] = cpu_to_le32(*cluster_offset);
988 /* First of all we write grain itself, to avoid race condition
989 * that may to corrupt the image.
990 * This problem may occur because of insufficient space on host disk
991 * or inappropriate VM shutdown.
993 if (get_whole_cluster(
994 bs, extent, *cluster_offset, offset, allocate) == -1) {
995 return VMDK_ERROR;
998 if (m_data) {
999 m_data->offset = *cluster_offset;
1002 *cluster_offset <<= 9;
1003 return VMDK_OK;
1006 static VmdkExtent *find_extent(BDRVVmdkState *s,
1007 int64_t sector_num, VmdkExtent *start_hint)
1009 VmdkExtent *extent = start_hint;
1011 if (!extent) {
1012 extent = &s->extents[0];
1014 while (extent < &s->extents[s->num_extents]) {
1015 if (sector_num < extent->end_sector) {
1016 return extent;
1018 extent++;
1020 return NULL;
1023 static int coroutine_fn vmdk_co_is_allocated(BlockDriverState *bs,
1024 int64_t sector_num, int nb_sectors, int *pnum)
1026 BDRVVmdkState *s = bs->opaque;
1027 int64_t index_in_cluster, n, ret;
1028 uint64_t offset;
1029 VmdkExtent *extent;
1031 extent = find_extent(s, sector_num, NULL);
1032 if (!extent) {
1033 return 0;
1035 qemu_co_mutex_lock(&s->lock);
1036 ret = get_cluster_offset(bs, extent, NULL,
1037 sector_num * 512, 0, &offset);
1038 qemu_co_mutex_unlock(&s->lock);
1040 ret = (ret == VMDK_OK || ret == VMDK_ZEROED);
1042 index_in_cluster = sector_num % extent->cluster_sectors;
1043 n = extent->cluster_sectors - index_in_cluster;
1044 if (n > nb_sectors) {
1045 n = nb_sectors;
1047 *pnum = n;
1048 return ret;
1051 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1052 int64_t offset_in_cluster, const uint8_t *buf,
1053 int nb_sectors, int64_t sector_num)
1055 int ret;
1056 VmdkGrainMarker *data = NULL;
1057 uLongf buf_len;
1058 const uint8_t *write_buf = buf;
1059 int write_len = nb_sectors * 512;
1061 if (extent->compressed) {
1062 if (!extent->has_marker) {
1063 ret = -EINVAL;
1064 goto out;
1066 buf_len = (extent->cluster_sectors << 9) * 2;
1067 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1068 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1069 buf_len == 0) {
1070 ret = -EINVAL;
1071 goto out;
1073 data->lba = sector_num;
1074 data->size = buf_len;
1075 write_buf = (uint8_t *)data;
1076 write_len = buf_len + sizeof(VmdkGrainMarker);
1078 ret = bdrv_pwrite(extent->file,
1079 cluster_offset + offset_in_cluster,
1080 write_buf,
1081 write_len);
1082 if (ret != write_len) {
1083 ret = ret < 0 ? ret : -EIO;
1084 goto out;
1086 ret = 0;
1087 out:
1088 g_free(data);
1089 return ret;
1092 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1093 int64_t offset_in_cluster, uint8_t *buf,
1094 int nb_sectors)
1096 int ret;
1097 int cluster_bytes, buf_bytes;
1098 uint8_t *cluster_buf, *compressed_data;
1099 uint8_t *uncomp_buf;
1100 uint32_t data_len;
1101 VmdkGrainMarker *marker;
1102 uLongf buf_len;
1105 if (!extent->compressed) {
1106 ret = bdrv_pread(extent->file,
1107 cluster_offset + offset_in_cluster,
1108 buf, nb_sectors * 512);
1109 if (ret == nb_sectors * 512) {
1110 return 0;
1111 } else {
1112 return -EIO;
1115 cluster_bytes = extent->cluster_sectors * 512;
1116 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1117 buf_bytes = cluster_bytes * 2;
1118 cluster_buf = g_malloc(buf_bytes);
1119 uncomp_buf = g_malloc(cluster_bytes);
1120 ret = bdrv_pread(extent->file,
1121 cluster_offset,
1122 cluster_buf, buf_bytes);
1123 if (ret < 0) {
1124 goto out;
1126 compressed_data = cluster_buf;
1127 buf_len = cluster_bytes;
1128 data_len = cluster_bytes;
1129 if (extent->has_marker) {
1130 marker = (VmdkGrainMarker *)cluster_buf;
1131 compressed_data = marker->data;
1132 data_len = le32_to_cpu(marker->size);
1134 if (!data_len || data_len > buf_bytes) {
1135 ret = -EINVAL;
1136 goto out;
1138 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1139 if (ret != Z_OK) {
1140 ret = -EINVAL;
1141 goto out;
1144 if (offset_in_cluster < 0 ||
1145 offset_in_cluster + nb_sectors * 512 > buf_len) {
1146 ret = -EINVAL;
1147 goto out;
1149 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1150 ret = 0;
1152 out:
1153 g_free(uncomp_buf);
1154 g_free(cluster_buf);
1155 return ret;
1158 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1159 uint8_t *buf, int nb_sectors)
1161 BDRVVmdkState *s = bs->opaque;
1162 int ret;
1163 uint64_t n, index_in_cluster;
1164 uint64_t extent_begin_sector, extent_relative_sector_num;
1165 VmdkExtent *extent = NULL;
1166 uint64_t cluster_offset;
1168 while (nb_sectors > 0) {
1169 extent = find_extent(s, sector_num, extent);
1170 if (!extent) {
1171 return -EIO;
1173 ret = get_cluster_offset(
1174 bs, extent, NULL,
1175 sector_num << 9, 0, &cluster_offset);
1176 extent_begin_sector = extent->end_sector - extent->sectors;
1177 extent_relative_sector_num = sector_num - extent_begin_sector;
1178 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1179 n = extent->cluster_sectors - index_in_cluster;
1180 if (n > nb_sectors) {
1181 n = nb_sectors;
1183 if (ret != VMDK_OK) {
1184 /* if not allocated, try to read from parent image, if exist */
1185 if (bs->backing_hd && ret != VMDK_ZEROED) {
1186 if (!vmdk_is_cid_valid(bs)) {
1187 return -EINVAL;
1189 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1190 if (ret < 0) {
1191 return ret;
1193 } else {
1194 memset(buf, 0, 512 * n);
1196 } else {
1197 ret = vmdk_read_extent(extent,
1198 cluster_offset, index_in_cluster * 512,
1199 buf, n);
1200 if (ret) {
1201 return ret;
1204 nb_sectors -= n;
1205 sector_num += n;
1206 buf += n * 512;
1208 return 0;
1211 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1212 uint8_t *buf, int nb_sectors)
1214 int ret;
1215 BDRVVmdkState *s = bs->opaque;
1216 qemu_co_mutex_lock(&s->lock);
1217 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1218 qemu_co_mutex_unlock(&s->lock);
1219 return ret;
1223 * vmdk_write:
1224 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1225 * if possible, otherwise return -ENOTSUP.
1226 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1227 * with each cluster. By dry run we can find if the zero write
1228 * is possible without modifying image data.
1230 * Returns: error code with 0 for success.
1232 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1233 const uint8_t *buf, int nb_sectors,
1234 bool zeroed, bool zero_dry_run)
1236 BDRVVmdkState *s = bs->opaque;
1237 VmdkExtent *extent = NULL;
1238 int n, ret;
1239 int64_t index_in_cluster;
1240 uint64_t extent_begin_sector, extent_relative_sector_num;
1241 uint64_t cluster_offset;
1242 VmdkMetaData m_data;
1244 if (sector_num > bs->total_sectors) {
1245 fprintf(stderr,
1246 "(VMDK) Wrong offset: sector_num=0x%" PRIx64
1247 " total_sectors=0x%" PRIx64 "\n",
1248 sector_num, bs->total_sectors);
1249 return -EIO;
1252 while (nb_sectors > 0) {
1253 extent = find_extent(s, sector_num, extent);
1254 if (!extent) {
1255 return -EIO;
1257 ret = get_cluster_offset(
1259 extent,
1260 &m_data,
1261 sector_num << 9, !extent->compressed,
1262 &cluster_offset);
1263 if (extent->compressed) {
1264 if (ret == VMDK_OK) {
1265 /* Refuse write to allocated cluster for streamOptimized */
1266 fprintf(stderr,
1267 "VMDK: can't write to allocated cluster"
1268 " for streamOptimized\n");
1269 return -EIO;
1270 } else {
1271 /* allocate */
1272 ret = get_cluster_offset(
1274 extent,
1275 &m_data,
1276 sector_num << 9, 1,
1277 &cluster_offset);
1280 if (ret == VMDK_ERROR) {
1281 return -EINVAL;
1283 extent_begin_sector = extent->end_sector - extent->sectors;
1284 extent_relative_sector_num = sector_num - extent_begin_sector;
1285 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1286 n = extent->cluster_sectors - index_in_cluster;
1287 if (n > nb_sectors) {
1288 n = nb_sectors;
1290 if (zeroed) {
1291 /* Do zeroed write, buf is ignored */
1292 if (extent->has_zero_grain &&
1293 index_in_cluster == 0 &&
1294 n >= extent->cluster_sectors) {
1295 n = extent->cluster_sectors;
1296 if (!zero_dry_run) {
1297 m_data.offset = VMDK_GTE_ZEROED;
1298 /* update L2 tables */
1299 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1300 return -EIO;
1303 } else {
1304 return -ENOTSUP;
1306 } else {
1307 ret = vmdk_write_extent(extent,
1308 cluster_offset, index_in_cluster * 512,
1309 buf, n, sector_num);
1310 if (ret) {
1311 return ret;
1313 if (m_data.valid) {
1314 /* update L2 tables */
1315 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1316 return -EIO;
1320 nb_sectors -= n;
1321 sector_num += n;
1322 buf += n * 512;
1324 /* update CID on the first write every time the virtual disk is
1325 * opened */
1326 if (!s->cid_updated) {
1327 ret = vmdk_write_cid(bs, time(NULL));
1328 if (ret < 0) {
1329 return ret;
1331 s->cid_updated = true;
1334 return 0;
1337 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1338 const uint8_t *buf, int nb_sectors)
1340 int ret;
1341 BDRVVmdkState *s = bs->opaque;
1342 qemu_co_mutex_lock(&s->lock);
1343 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1344 qemu_co_mutex_unlock(&s->lock);
1345 return ret;
1348 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1349 int64_t sector_num,
1350 int nb_sectors)
1352 int ret;
1353 BDRVVmdkState *s = bs->opaque;
1354 qemu_co_mutex_lock(&s->lock);
1355 /* write zeroes could fail if sectors not aligned to cluster, test it with
1356 * dry_run == true before really updating image */
1357 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1358 if (!ret) {
1359 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1361 qemu_co_mutex_unlock(&s->lock);
1362 return ret;
1366 static int vmdk_create_extent(const char *filename, int64_t filesize,
1367 bool flat, bool compress, bool zeroed_grain)
1369 int ret, i;
1370 int fd = 0;
1371 VMDK4Header header;
1372 uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
1374 fd = qemu_open(filename,
1375 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1376 0644);
1377 if (fd < 0) {
1378 return -errno;
1380 if (flat) {
1381 ret = ftruncate(fd, filesize);
1382 if (ret < 0) {
1383 ret = -errno;
1385 goto exit;
1387 magic = cpu_to_be32(VMDK4_MAGIC);
1388 memset(&header, 0, sizeof(header));
1389 header.version = zeroed_grain ? 2 : 1;
1390 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1391 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1392 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1393 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1394 header.capacity = filesize / 512;
1395 header.granularity = 128;
1396 header.num_gtes_per_gte = 512;
1398 grains = (filesize / 512 + header.granularity - 1) / header.granularity;
1399 gt_size = ((header.num_gtes_per_gte * sizeof(uint32_t)) + 511) >> 9;
1400 gt_count =
1401 (grains + header.num_gtes_per_gte - 1) / header.num_gtes_per_gte;
1402 gd_size = (gt_count * sizeof(uint32_t) + 511) >> 9;
1404 header.desc_offset = 1;
1405 header.desc_size = 20;
1406 header.rgd_offset = header.desc_offset + header.desc_size;
1407 header.gd_offset = header.rgd_offset + gd_size + (gt_size * gt_count);
1408 header.grain_offset =
1409 ((header.gd_offset + gd_size + (gt_size * gt_count) +
1410 header.granularity - 1) / header.granularity) *
1411 header.granularity;
1412 /* swap endianness for all header fields */
1413 header.version = cpu_to_le32(header.version);
1414 header.flags = cpu_to_le32(header.flags);
1415 header.capacity = cpu_to_le64(header.capacity);
1416 header.granularity = cpu_to_le64(header.granularity);
1417 header.num_gtes_per_gte = cpu_to_le32(header.num_gtes_per_gte);
1418 header.desc_offset = cpu_to_le64(header.desc_offset);
1419 header.desc_size = cpu_to_le64(header.desc_size);
1420 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1421 header.gd_offset = cpu_to_le64(header.gd_offset);
1422 header.grain_offset = cpu_to_le64(header.grain_offset);
1423 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1425 header.check_bytes[0] = 0xa;
1426 header.check_bytes[1] = 0x20;
1427 header.check_bytes[2] = 0xd;
1428 header.check_bytes[3] = 0xa;
1430 /* write all the data */
1431 ret = qemu_write_full(fd, &magic, sizeof(magic));
1432 if (ret != sizeof(magic)) {
1433 ret = -errno;
1434 goto exit;
1436 ret = qemu_write_full(fd, &header, sizeof(header));
1437 if (ret != sizeof(header)) {
1438 ret = -errno;
1439 goto exit;
1442 ret = ftruncate(fd, le64_to_cpu(header.grain_offset) << 9);
1443 if (ret < 0) {
1444 ret = -errno;
1445 goto exit;
1448 /* write grain directory */
1449 lseek(fd, le64_to_cpu(header.rgd_offset) << 9, SEEK_SET);
1450 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_size;
1451 i < gt_count; i++, tmp += gt_size) {
1452 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1453 if (ret != sizeof(tmp)) {
1454 ret = -errno;
1455 goto exit;
1459 /* write backup grain directory */
1460 lseek(fd, le64_to_cpu(header.gd_offset) << 9, SEEK_SET);
1461 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_size;
1462 i < gt_count; i++, tmp += gt_size) {
1463 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1464 if (ret != sizeof(tmp)) {
1465 ret = -errno;
1466 goto exit;
1470 ret = 0;
1471 exit:
1472 qemu_close(fd);
1473 return ret;
1476 static int filename_decompose(const char *filename, char *path, char *prefix,
1477 char *postfix, size_t buf_len)
1479 const char *p, *q;
1481 if (filename == NULL || !strlen(filename)) {
1482 fprintf(stderr, "Vmdk: no filename provided.\n");
1483 return VMDK_ERROR;
1485 p = strrchr(filename, '/');
1486 if (p == NULL) {
1487 p = strrchr(filename, '\\');
1489 if (p == NULL) {
1490 p = strrchr(filename, ':');
1492 if (p != NULL) {
1493 p++;
1494 if (p - filename >= buf_len) {
1495 return VMDK_ERROR;
1497 pstrcpy(path, p - filename + 1, filename);
1498 } else {
1499 p = filename;
1500 path[0] = '\0';
1502 q = strrchr(p, '.');
1503 if (q == NULL) {
1504 pstrcpy(prefix, buf_len, p);
1505 postfix[0] = '\0';
1506 } else {
1507 if (q - p >= buf_len) {
1508 return VMDK_ERROR;
1510 pstrcpy(prefix, q - p + 1, p);
1511 pstrcpy(postfix, buf_len, q);
1513 return VMDK_OK;
1516 static int vmdk_create(const char *filename, QEMUOptionParameter *options)
1518 int fd, idx = 0;
1519 char desc[BUF_SIZE];
1520 int64_t total_size = 0, filesize;
1521 const char *adapter_type = NULL;
1522 const char *backing_file = NULL;
1523 const char *fmt = NULL;
1524 int flags = 0;
1525 int ret = 0;
1526 bool flat, split, compress;
1527 char ext_desc_lines[BUF_SIZE] = "";
1528 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1529 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1530 const char *desc_extent_line;
1531 char parent_desc_line[BUF_SIZE] = "";
1532 uint32_t parent_cid = 0xffffffff;
1533 uint32_t number_heads = 16;
1534 bool zeroed_grain = false;
1535 const char desc_template[] =
1536 "# Disk DescriptorFile\n"
1537 "version=1\n"
1538 "CID=%x\n"
1539 "parentCID=%x\n"
1540 "createType=\"%s\"\n"
1541 "%s"
1542 "\n"
1543 "# Extent description\n"
1544 "%s"
1545 "\n"
1546 "# The Disk Data Base\n"
1547 "#DDB\n"
1548 "\n"
1549 "ddb.virtualHWVersion = \"%d\"\n"
1550 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1551 "ddb.geometry.heads = \"%d\"\n"
1552 "ddb.geometry.sectors = \"63\"\n"
1553 "ddb.adapterType = \"%s\"\n";
1555 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX)) {
1556 return -EINVAL;
1558 /* Read out options */
1559 while (options && options->name) {
1560 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1561 total_size = options->value.n;
1562 } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {
1563 adapter_type = options->value.s;
1564 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1565 backing_file = options->value.s;
1566 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
1567 flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;
1568 } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {
1569 fmt = options->value.s;
1570 } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {
1571 zeroed_grain |= options->value.n;
1573 options++;
1575 if (!adapter_type) {
1576 adapter_type = "ide";
1577 } else if (strcmp(adapter_type, "ide") &&
1578 strcmp(adapter_type, "buslogic") &&
1579 strcmp(adapter_type, "lsilogic") &&
1580 strcmp(adapter_type, "legacyESX")) {
1581 fprintf(stderr, "VMDK: Unknown adapter type: '%s'.\n", adapter_type);
1582 return -EINVAL;
1584 if (strcmp(adapter_type, "ide") != 0) {
1585 /* that's the number of heads with which vmware operates when
1586 creating, exporting, etc. vmdk files with a non-ide adapter type */
1587 number_heads = 255;
1589 if (!fmt) {
1590 /* Default format to monolithicSparse */
1591 fmt = "monolithicSparse";
1592 } else if (strcmp(fmt, "monolithicFlat") &&
1593 strcmp(fmt, "monolithicSparse") &&
1594 strcmp(fmt, "twoGbMaxExtentSparse") &&
1595 strcmp(fmt, "twoGbMaxExtentFlat") &&
1596 strcmp(fmt, "streamOptimized")) {
1597 fprintf(stderr, "VMDK: Unknown subformat: %s\n", fmt);
1598 return -EINVAL;
1600 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1601 strcmp(fmt, "twoGbMaxExtentSparse"));
1602 flat = !(strcmp(fmt, "monolithicFlat") &&
1603 strcmp(fmt, "twoGbMaxExtentFlat"));
1604 compress = !strcmp(fmt, "streamOptimized");
1605 if (flat) {
1606 desc_extent_line = "RW %lld FLAT \"%s\" 0\n";
1607 } else {
1608 desc_extent_line = "RW %lld SPARSE \"%s\"\n";
1610 if (flat && backing_file) {
1611 /* not supporting backing file for flat image */
1612 return -ENOTSUP;
1614 if (backing_file) {
1615 BlockDriverState *bs = bdrv_new("");
1616 ret = bdrv_open(bs, backing_file, NULL, 0, NULL);
1617 if (ret != 0) {
1618 bdrv_delete(bs);
1619 return ret;
1621 if (strcmp(bs->drv->format_name, "vmdk")) {
1622 bdrv_delete(bs);
1623 return -EINVAL;
1625 parent_cid = vmdk_read_cid(bs, 0);
1626 bdrv_delete(bs);
1627 snprintf(parent_desc_line, sizeof(parent_desc_line),
1628 "parentFileNameHint=\"%s\"", backing_file);
1631 /* Create extents */
1632 filesize = total_size;
1633 while (filesize > 0) {
1634 char desc_line[BUF_SIZE];
1635 char ext_filename[PATH_MAX];
1636 char desc_filename[PATH_MAX];
1637 int64_t size = filesize;
1639 if (split && size > split_size) {
1640 size = split_size;
1642 if (split) {
1643 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1644 prefix, flat ? 'f' : 's', ++idx, postfix);
1645 } else if (flat) {
1646 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1647 prefix, postfix);
1648 } else {
1649 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1650 prefix, postfix);
1652 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1653 path, desc_filename);
1655 if (vmdk_create_extent(ext_filename, size,
1656 flat, compress, zeroed_grain)) {
1657 return -EINVAL;
1659 filesize -= size;
1661 /* Format description line */
1662 snprintf(desc_line, sizeof(desc_line),
1663 desc_extent_line, size / 512, desc_filename);
1664 pstrcat(ext_desc_lines, sizeof(ext_desc_lines), desc_line);
1666 /* generate descriptor file */
1667 snprintf(desc, sizeof(desc), desc_template,
1668 (unsigned int)time(NULL),
1669 parent_cid,
1670 fmt,
1671 parent_desc_line,
1672 ext_desc_lines,
1673 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1674 total_size / (int64_t)(63 * number_heads * 512), number_heads,
1675 adapter_type);
1676 if (split || flat) {
1677 fd = qemu_open(filename,
1678 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1679 0644);
1680 } else {
1681 fd = qemu_open(filename,
1682 O_WRONLY | O_BINARY | O_LARGEFILE,
1683 0644);
1685 if (fd < 0) {
1686 return -errno;
1688 /* the descriptor offset = 0x200 */
1689 if (!split && !flat && 0x200 != lseek(fd, 0x200, SEEK_SET)) {
1690 ret = -errno;
1691 goto exit;
1693 ret = qemu_write_full(fd, desc, strlen(desc));
1694 if (ret != strlen(desc)) {
1695 ret = -errno;
1696 goto exit;
1698 ret = 0;
1699 exit:
1700 qemu_close(fd);
1701 return ret;
1704 static void vmdk_close(BlockDriverState *bs)
1706 BDRVVmdkState *s = bs->opaque;
1708 vmdk_free_extents(bs);
1710 migrate_del_blocker(s->migration_blocker);
1711 error_free(s->migration_blocker);
1714 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1716 BDRVVmdkState *s = bs->opaque;
1717 int i, err;
1718 int ret = 0;
1720 for (i = 0; i < s->num_extents; i++) {
1721 err = bdrv_co_flush(s->extents[i].file);
1722 if (err < 0) {
1723 ret = err;
1726 return ret;
1729 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
1731 int i;
1732 int64_t ret = 0;
1733 int64_t r;
1734 BDRVVmdkState *s = bs->opaque;
1736 ret = bdrv_get_allocated_file_size(bs->file);
1737 if (ret < 0) {
1738 return ret;
1740 for (i = 0; i < s->num_extents; i++) {
1741 if (s->extents[i].file == bs->file) {
1742 continue;
1744 r = bdrv_get_allocated_file_size(s->extents[i].file);
1745 if (r < 0) {
1746 return r;
1748 ret += r;
1750 return ret;
1753 static int vmdk_has_zero_init(BlockDriverState *bs)
1755 int i;
1756 BDRVVmdkState *s = bs->opaque;
1758 /* If has a flat extent and its underlying storage doesn't have zero init,
1759 * return 0. */
1760 for (i = 0; i < s->num_extents; i++) {
1761 if (s->extents[i].flat) {
1762 if (!bdrv_has_zero_init(s->extents[i].file)) {
1763 return 0;
1767 return 1;
1770 static QEMUOptionParameter vmdk_create_options[] = {
1772 .name = BLOCK_OPT_SIZE,
1773 .type = OPT_SIZE,
1774 .help = "Virtual disk size"
1777 .name = BLOCK_OPT_ADAPTER_TYPE,
1778 .type = OPT_STRING,
1779 .help = "Virtual adapter type, can be one of "
1780 "ide (default), lsilogic, buslogic or legacyESX"
1783 .name = BLOCK_OPT_BACKING_FILE,
1784 .type = OPT_STRING,
1785 .help = "File name of a base image"
1788 .name = BLOCK_OPT_COMPAT6,
1789 .type = OPT_FLAG,
1790 .help = "VMDK version 6 image"
1793 .name = BLOCK_OPT_SUBFMT,
1794 .type = OPT_STRING,
1795 .help =
1796 "VMDK flat extent format, can be one of "
1797 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
1800 .name = BLOCK_OPT_ZEROED_GRAIN,
1801 .type = OPT_FLAG,
1802 .help = "Enable efficient zero writes using the zeroed-grain GTE feature"
1804 { NULL }
1807 static BlockDriver bdrv_vmdk = {
1808 .format_name = "vmdk",
1809 .instance_size = sizeof(BDRVVmdkState),
1810 .bdrv_probe = vmdk_probe,
1811 .bdrv_open = vmdk_open,
1812 .bdrv_reopen_prepare = vmdk_reopen_prepare,
1813 .bdrv_read = vmdk_co_read,
1814 .bdrv_write = vmdk_co_write,
1815 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
1816 .bdrv_close = vmdk_close,
1817 .bdrv_create = vmdk_create,
1818 .bdrv_co_flush_to_disk = vmdk_co_flush,
1819 .bdrv_co_is_allocated = vmdk_co_is_allocated,
1820 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
1821 .bdrv_has_zero_init = vmdk_has_zero_init,
1823 .create_options = vmdk_create_options,
1826 static void bdrv_vmdk_init(void)
1828 bdrv_register(&bdrv_vmdk);
1831 block_init(bdrv_vmdk_init);