block: Allow the user to define "node-name" option both on command line and QMP.
[qemu/cris-port.git] / block / vmdk.c
blob67b5f96a192b0dd58c0f6785678f5aa8f9820a82
1 /*
2 * Block driver for the VMDK format
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
26 #include "qemu-common.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "migration/migration.h"
30 #include <zlib.h>
32 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
33 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
34 #define VMDK4_COMPRESSION_DEFLATE 1
35 #define VMDK4_FLAG_NL_DETECT (1 << 0)
36 #define VMDK4_FLAG_RGD (1 << 1)
37 /* Zeroed-grain enable bit */
38 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
39 #define VMDK4_FLAG_COMPRESS (1 << 16)
40 #define VMDK4_FLAG_MARKER (1 << 17)
41 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
43 #define VMDK_GTE_ZEROED 0x1
45 /* VMDK internal error codes */
46 #define VMDK_OK 0
47 #define VMDK_ERROR (-1)
48 /* Cluster not allocated */
49 #define VMDK_UNALLOC (-2)
50 #define VMDK_ZEROED (-3)
52 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
54 typedef struct {
55 uint32_t version;
56 uint32_t flags;
57 uint32_t disk_sectors;
58 uint32_t granularity;
59 uint32_t l1dir_offset;
60 uint32_t l1dir_size;
61 uint32_t file_sectors;
62 uint32_t cylinders;
63 uint32_t heads;
64 uint32_t sectors_per_track;
65 } QEMU_PACKED VMDK3Header;
67 typedef struct {
68 uint32_t version;
69 uint32_t flags;
70 uint64_t capacity;
71 uint64_t granularity;
72 uint64_t desc_offset;
73 uint64_t desc_size;
74 /* Number of GrainTableEntries per GrainTable */
75 uint32_t num_gtes_per_gt;
76 uint64_t rgd_offset;
77 uint64_t gd_offset;
78 uint64_t grain_offset;
79 char filler[1];
80 char check_bytes[4];
81 uint16_t compressAlgorithm;
82 } QEMU_PACKED VMDK4Header;
84 #define L2_CACHE_SIZE 16
86 typedef struct VmdkExtent {
87 BlockDriverState *file;
88 bool flat;
89 bool compressed;
90 bool has_marker;
91 bool has_zero_grain;
92 int version;
93 int64_t sectors;
94 int64_t end_sector;
95 int64_t flat_start_offset;
96 int64_t l1_table_offset;
97 int64_t l1_backup_table_offset;
98 uint32_t *l1_table;
99 uint32_t *l1_backup_table;
100 unsigned int l1_size;
101 uint32_t l1_entry_sectors;
103 unsigned int l2_size;
104 uint32_t *l2_cache;
105 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
106 uint32_t l2_cache_counts[L2_CACHE_SIZE];
108 int64_t cluster_sectors;
109 char *type;
110 } VmdkExtent;
112 typedef struct BDRVVmdkState {
113 CoMutex lock;
114 uint64_t desc_offset;
115 bool cid_updated;
116 bool cid_checked;
117 uint32_t cid;
118 uint32_t parent_cid;
119 int num_extents;
120 /* Extent array with num_extents entries, ascend ordered by address */
121 VmdkExtent *extents;
122 Error *migration_blocker;
123 char *create_type;
124 } BDRVVmdkState;
126 typedef struct VmdkMetaData {
127 uint32_t offset;
128 unsigned int l1_index;
129 unsigned int l2_index;
130 unsigned int l2_offset;
131 int valid;
132 uint32_t *l2_cache_entry;
133 } VmdkMetaData;
135 typedef struct VmdkGrainMarker {
136 uint64_t lba;
137 uint32_t size;
138 uint8_t data[0];
139 } QEMU_PACKED VmdkGrainMarker;
141 enum {
142 MARKER_END_OF_STREAM = 0,
143 MARKER_GRAIN_TABLE = 1,
144 MARKER_GRAIN_DIRECTORY = 2,
145 MARKER_FOOTER = 3,
148 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
150 uint32_t magic;
152 if (buf_size < 4) {
153 return 0;
155 magic = be32_to_cpu(*(uint32_t *)buf);
156 if (magic == VMDK3_MAGIC ||
157 magic == VMDK4_MAGIC) {
158 return 100;
159 } else {
160 const char *p = (const char *)buf;
161 const char *end = p + buf_size;
162 while (p < end) {
163 if (*p == '#') {
164 /* skip comment line */
165 while (p < end && *p != '\n') {
166 p++;
168 p++;
169 continue;
171 if (*p == ' ') {
172 while (p < end && *p == ' ') {
173 p++;
175 /* skip '\r' if windows line endings used. */
176 if (p < end && *p == '\r') {
177 p++;
179 /* only accept blank lines before 'version=' line */
180 if (p == end || *p != '\n') {
181 return 0;
183 p++;
184 continue;
186 if (end - p >= strlen("version=X\n")) {
187 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
188 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
189 return 100;
192 if (end - p >= strlen("version=X\r\n")) {
193 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
194 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
195 return 100;
198 return 0;
200 return 0;
204 #define SECTOR_SIZE 512
205 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
206 #define BUF_SIZE 4096
207 #define HEADER_SIZE 512 /* first sector of 512 bytes */
209 static void vmdk_free_extents(BlockDriverState *bs)
211 int i;
212 BDRVVmdkState *s = bs->opaque;
213 VmdkExtent *e;
215 for (i = 0; i < s->num_extents; i++) {
216 e = &s->extents[i];
217 g_free(e->l1_table);
218 g_free(e->l2_cache);
219 g_free(e->l1_backup_table);
220 g_free(e->type);
221 if (e->file != bs->file) {
222 bdrv_unref(e->file);
225 g_free(s->extents);
228 static void vmdk_free_last_extent(BlockDriverState *bs)
230 BDRVVmdkState *s = bs->opaque;
232 if (s->num_extents == 0) {
233 return;
235 s->num_extents--;
236 s->extents = g_realloc(s->extents, s->num_extents * sizeof(VmdkExtent));
239 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
241 char desc[DESC_SIZE];
242 uint32_t cid = 0xffffffff;
243 const char *p_name, *cid_str;
244 size_t cid_str_size;
245 BDRVVmdkState *s = bs->opaque;
246 int ret;
248 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
249 if (ret < 0) {
250 return 0;
253 if (parent) {
254 cid_str = "parentCID";
255 cid_str_size = sizeof("parentCID");
256 } else {
257 cid_str = "CID";
258 cid_str_size = sizeof("CID");
261 desc[DESC_SIZE - 1] = '\0';
262 p_name = strstr(desc, cid_str);
263 if (p_name != NULL) {
264 p_name += cid_str_size;
265 sscanf(p_name, "%x", &cid);
268 return cid;
271 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
273 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
274 char *p_name, *tmp_str;
275 BDRVVmdkState *s = bs->opaque;
276 int ret;
278 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
279 if (ret < 0) {
280 return ret;
283 desc[DESC_SIZE - 1] = '\0';
284 tmp_str = strstr(desc, "parentCID");
285 if (tmp_str == NULL) {
286 return -EINVAL;
289 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
290 p_name = strstr(desc, "CID");
291 if (p_name != NULL) {
292 p_name += sizeof("CID");
293 snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);
294 pstrcat(desc, sizeof(desc), tmp_desc);
297 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
298 if (ret < 0) {
299 return ret;
302 return 0;
305 static int vmdk_is_cid_valid(BlockDriverState *bs)
307 BDRVVmdkState *s = bs->opaque;
308 BlockDriverState *p_bs = bs->backing_hd;
309 uint32_t cur_pcid;
311 if (!s->cid_checked && p_bs) {
312 cur_pcid = vmdk_read_cid(p_bs, 0);
313 if (s->parent_cid != cur_pcid) {
314 /* CID not valid */
315 return 0;
318 s->cid_checked = true;
319 /* CID valid */
320 return 1;
323 /* Queue extents, if any, for reopen() */
324 static int vmdk_reopen_prepare(BDRVReopenState *state,
325 BlockReopenQueue *queue, Error **errp)
327 BDRVVmdkState *s;
328 int ret = -1;
329 int i;
330 VmdkExtent *e;
332 assert(state != NULL);
333 assert(state->bs != NULL);
335 if (queue == NULL) {
336 error_setg(errp, "No reopen queue for VMDK extents");
337 goto exit;
340 s = state->bs->opaque;
342 assert(s != NULL);
344 for (i = 0; i < s->num_extents; i++) {
345 e = &s->extents[i];
346 if (e->file != state->bs->file) {
347 bdrv_reopen_queue(queue, e->file, state->flags);
350 ret = 0;
352 exit:
353 return ret;
356 static int vmdk_parent_open(BlockDriverState *bs)
358 char *p_name;
359 char desc[DESC_SIZE + 1];
360 BDRVVmdkState *s = bs->opaque;
361 int ret;
363 desc[DESC_SIZE] = '\0';
364 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
365 if (ret < 0) {
366 return ret;
369 p_name = strstr(desc, "parentFileNameHint");
370 if (p_name != NULL) {
371 char *end_name;
373 p_name += sizeof("parentFileNameHint") + 1;
374 end_name = strchr(p_name, '\"');
375 if (end_name == NULL) {
376 return -EINVAL;
378 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
379 return -EINVAL;
382 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
385 return 0;
388 /* Create and append extent to the extent array. Return the added VmdkExtent
389 * address. return NULL if allocation failed. */
390 static int vmdk_add_extent(BlockDriverState *bs,
391 BlockDriverState *file, bool flat, int64_t sectors,
392 int64_t l1_offset, int64_t l1_backup_offset,
393 uint32_t l1_size,
394 int l2_size, uint64_t cluster_sectors,
395 VmdkExtent **new_extent,
396 Error **errp)
398 VmdkExtent *extent;
399 BDRVVmdkState *s = bs->opaque;
401 if (cluster_sectors > 0x200000) {
402 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
403 error_setg(errp, "Invalid granularity, image may be corrupt");
404 return -EFBIG;
406 if (l1_size > 512 * 1024 * 1024) {
407 /* Although with big capacity and small l1_entry_sectors, we can get a
408 * big l1_size, we don't want unbounded value to allocate the table.
409 * Limit it to 512M, which is 16PB for default cluster and L2 table
410 * size */
411 error_setg(errp, "L1 size too big");
412 return -EFBIG;
415 s->extents = g_realloc(s->extents,
416 (s->num_extents + 1) * sizeof(VmdkExtent));
417 extent = &s->extents[s->num_extents];
418 s->num_extents++;
420 memset(extent, 0, sizeof(VmdkExtent));
421 extent->file = file;
422 extent->flat = flat;
423 extent->sectors = sectors;
424 extent->l1_table_offset = l1_offset;
425 extent->l1_backup_table_offset = l1_backup_offset;
426 extent->l1_size = l1_size;
427 extent->l1_entry_sectors = l2_size * cluster_sectors;
428 extent->l2_size = l2_size;
429 extent->cluster_sectors = flat ? sectors : cluster_sectors;
431 if (!flat) {
432 bs->bl.write_zeroes_alignment =
433 MAX(bs->bl.write_zeroes_alignment, cluster_sectors);
435 if (s->num_extents > 1) {
436 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
437 } else {
438 extent->end_sector = extent->sectors;
440 bs->total_sectors = extent->end_sector;
441 if (new_extent) {
442 *new_extent = extent;
444 return 0;
447 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
448 Error **errp)
450 int ret;
451 int l1_size, i;
453 /* read the L1 table */
454 l1_size = extent->l1_size * sizeof(uint32_t);
455 extent->l1_table = g_malloc(l1_size);
456 ret = bdrv_pread(extent->file,
457 extent->l1_table_offset,
458 extent->l1_table,
459 l1_size);
460 if (ret < 0) {
461 error_setg_errno(errp, -ret,
462 "Could not read l1 table from extent '%s'",
463 extent->file->filename);
464 goto fail_l1;
466 for (i = 0; i < extent->l1_size; i++) {
467 le32_to_cpus(&extent->l1_table[i]);
470 if (extent->l1_backup_table_offset) {
471 extent->l1_backup_table = g_malloc(l1_size);
472 ret = bdrv_pread(extent->file,
473 extent->l1_backup_table_offset,
474 extent->l1_backup_table,
475 l1_size);
476 if (ret < 0) {
477 error_setg_errno(errp, -ret,
478 "Could not read l1 backup table from extent '%s'",
479 extent->file->filename);
480 goto fail_l1b;
482 for (i = 0; i < extent->l1_size; i++) {
483 le32_to_cpus(&extent->l1_backup_table[i]);
487 extent->l2_cache =
488 g_malloc(extent->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
489 return 0;
490 fail_l1b:
491 g_free(extent->l1_backup_table);
492 fail_l1:
493 g_free(extent->l1_table);
494 return ret;
497 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
498 BlockDriverState *file,
499 int flags, Error **errp)
501 int ret;
502 uint32_t magic;
503 VMDK3Header header;
504 VmdkExtent *extent;
506 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
507 if (ret < 0) {
508 error_setg_errno(errp, -ret,
509 "Could not read header from file '%s'",
510 file->filename);
511 return ret;
513 ret = vmdk_add_extent(bs, file, false,
514 le32_to_cpu(header.disk_sectors),
515 le32_to_cpu(header.l1dir_offset) << 9,
517 le32_to_cpu(header.l1dir_size),
518 4096,
519 le32_to_cpu(header.granularity),
520 &extent,
521 errp);
522 if (ret < 0) {
523 return ret;
525 ret = vmdk_init_tables(bs, extent, errp);
526 if (ret) {
527 /* free extent allocated by vmdk_add_extent */
528 vmdk_free_last_extent(bs);
530 return ret;
533 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
534 uint64_t desc_offset, Error **errp);
536 static int vmdk_open_vmdk4(BlockDriverState *bs,
537 BlockDriverState *file,
538 int flags, Error **errp)
540 int ret;
541 uint32_t magic;
542 uint32_t l1_size, l1_entry_sectors;
543 VMDK4Header header;
544 VmdkExtent *extent;
545 BDRVVmdkState *s = bs->opaque;
546 int64_t l1_backup_offset = 0;
548 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
549 if (ret < 0) {
550 error_setg_errno(errp, -ret,
551 "Could not read header from file '%s'",
552 file->filename);
554 if (header.capacity == 0) {
555 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
556 if (desc_offset) {
557 return vmdk_open_desc_file(bs, flags, desc_offset << 9, errp);
561 if (!s->create_type) {
562 s->create_type = g_strdup("monolithicSparse");
565 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
567 * The footer takes precedence over the header, so read it in. The
568 * footer starts at offset -1024 from the end: One sector for the
569 * footer, and another one for the end-of-stream marker.
571 struct {
572 struct {
573 uint64_t val;
574 uint32_t size;
575 uint32_t type;
576 uint8_t pad[512 - 16];
577 } QEMU_PACKED footer_marker;
579 uint32_t magic;
580 VMDK4Header header;
581 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
583 struct {
584 uint64_t val;
585 uint32_t size;
586 uint32_t type;
587 uint8_t pad[512 - 16];
588 } QEMU_PACKED eos_marker;
589 } QEMU_PACKED footer;
591 ret = bdrv_pread(file,
592 bs->file->total_sectors * 512 - 1536,
593 &footer, sizeof(footer));
594 if (ret < 0) {
595 return ret;
598 /* Some sanity checks for the footer */
599 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
600 le32_to_cpu(footer.footer_marker.size) != 0 ||
601 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
602 le64_to_cpu(footer.eos_marker.val) != 0 ||
603 le32_to_cpu(footer.eos_marker.size) != 0 ||
604 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
606 return -EINVAL;
609 header = footer.header;
612 if (le32_to_cpu(header.version) > 3) {
613 char buf[64];
614 snprintf(buf, sizeof(buf), "VMDK version %d",
615 le32_to_cpu(header.version));
616 qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
617 bs->device_name, "vmdk", buf);
618 return -ENOTSUP;
619 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
620 /* VMware KB 2064959 explains that version 3 added support for
621 * persistent changed block tracking (CBT), and backup software can
622 * read it as version=1 if it doesn't care about the changed area
623 * information. So we are safe to enable read only. */
624 error_setg(errp, "VMDK version 3 must be read only");
625 return -EINVAL;
628 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
629 error_report("L2 table size too big");
630 return -EINVAL;
633 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
634 * le64_to_cpu(header.granularity);
635 if (l1_entry_sectors == 0) {
636 return -EINVAL;
638 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
639 / l1_entry_sectors;
640 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
641 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
643 if (bdrv_getlength(file) <
644 le64_to_cpu(header.grain_offset) * BDRV_SECTOR_SIZE) {
645 error_report("File truncated, expecting at least %lld bytes",
646 le64_to_cpu(header.grain_offset) * BDRV_SECTOR_SIZE);
647 return -EINVAL;
650 ret = vmdk_add_extent(bs, file, false,
651 le64_to_cpu(header.capacity),
652 le64_to_cpu(header.gd_offset) << 9,
653 l1_backup_offset,
654 l1_size,
655 le32_to_cpu(header.num_gtes_per_gt),
656 le64_to_cpu(header.granularity),
657 &extent,
658 errp);
659 if (ret < 0) {
660 return ret;
662 extent->compressed =
663 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
664 if (extent->compressed) {
665 g_free(s->create_type);
666 s->create_type = g_strdup("streamOptimized");
668 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
669 extent->version = le32_to_cpu(header.version);
670 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
671 ret = vmdk_init_tables(bs, extent, errp);
672 if (ret) {
673 /* free extent allocated by vmdk_add_extent */
674 vmdk_free_last_extent(bs);
676 return ret;
679 /* find an option value out of descriptor file */
680 static int vmdk_parse_description(const char *desc, const char *opt_name,
681 char *buf, int buf_size)
683 char *opt_pos, *opt_end;
684 const char *end = desc + strlen(desc);
686 opt_pos = strstr(desc, opt_name);
687 if (!opt_pos) {
688 return VMDK_ERROR;
690 /* Skip "=\"" following opt_name */
691 opt_pos += strlen(opt_name) + 2;
692 if (opt_pos >= end) {
693 return VMDK_ERROR;
695 opt_end = opt_pos;
696 while (opt_end < end && *opt_end != '"') {
697 opt_end++;
699 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
700 return VMDK_ERROR;
702 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
703 return VMDK_OK;
706 /* Open an extent file and append to bs array */
707 static int vmdk_open_sparse(BlockDriverState *bs,
708 BlockDriverState *file,
709 int flags, Error **errp)
711 uint32_t magic;
713 if (bdrv_pread(file, 0, &magic, sizeof(magic)) != sizeof(magic)) {
714 return -EIO;
717 magic = be32_to_cpu(magic);
718 switch (magic) {
719 case VMDK3_MAGIC:
720 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
721 break;
722 case VMDK4_MAGIC:
723 return vmdk_open_vmdk4(bs, file, flags, errp);
724 break;
725 default:
726 return -EMEDIUMTYPE;
727 break;
731 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
732 const char *desc_file_path, Error **errp)
734 int ret;
735 char access[11];
736 char type[11];
737 char fname[512];
738 const char *p = desc;
739 int64_t sectors = 0;
740 int64_t flat_offset;
741 char extent_path[PATH_MAX];
742 BlockDriverState *extent_file;
743 BDRVVmdkState *s = bs->opaque;
744 VmdkExtent *extent;
746 while (*p) {
747 /* parse extent line:
748 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
749 * or
750 * RW [size in sectors] SPARSE "file-name.vmdk"
752 flat_offset = -1;
753 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
754 access, &sectors, type, fname, &flat_offset);
755 if (ret < 4 || strcmp(access, "RW")) {
756 goto next_line;
757 } else if (!strcmp(type, "FLAT")) {
758 if (ret != 5 || flat_offset < 0) {
759 error_setg(errp, "Invalid extent lines: \n%s", p);
760 return -EINVAL;
762 } else if (!strcmp(type, "VMFS")) {
763 if (ret == 4) {
764 flat_offset = 0;
765 } else {
766 error_setg(errp, "Invalid extent lines:\n%s", p);
767 return -EINVAL;
769 } else if (ret != 4) {
770 error_setg(errp, "Invalid extent lines:\n%s", p);
771 return -EINVAL;
774 if (sectors <= 0 ||
775 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
776 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
777 (strcmp(access, "RW"))) {
778 goto next_line;
781 path_combine(extent_path, sizeof(extent_path),
782 desc_file_path, fname);
783 ret = bdrv_file_open(&extent_file, extent_path, NULL, NULL,
784 bs->open_flags, errp);
785 if (ret) {
786 return ret;
789 /* save to extents array */
790 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
791 /* FLAT extent */
793 ret = vmdk_add_extent(bs, extent_file, true, sectors,
794 0, 0, 0, 0, 0, &extent, errp);
795 if (ret < 0) {
796 return ret;
798 extent->flat_start_offset = flat_offset << 9;
799 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
800 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
801 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, errp);
802 if (ret) {
803 bdrv_unref(extent_file);
804 return ret;
806 extent = &s->extents[s->num_extents - 1];
807 } else {
808 error_setg(errp, "Unsupported extent type '%s'", type);
809 return -ENOTSUP;
811 extent->type = g_strdup(type);
812 next_line:
813 /* move to next line */
814 while (*p) {
815 if (*p == '\n') {
816 p++;
817 break;
819 p++;
822 return 0;
825 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
826 uint64_t desc_offset, Error **errp)
828 int ret;
829 char *buf = NULL;
830 char ct[128];
831 BDRVVmdkState *s = bs->opaque;
832 int64_t size;
834 size = bdrv_getlength(bs->file);
835 if (size < 0) {
836 return -EINVAL;
839 size = MIN(size, 1 << 20); /* avoid unbounded allocation */
840 buf = g_malloc0(size + 1);
842 ret = bdrv_pread(bs->file, desc_offset, buf, size);
843 if (ret < 0) {
844 goto exit;
846 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
847 ret = -EMEDIUMTYPE;
848 goto exit;
850 if (strcmp(ct, "monolithicFlat") &&
851 strcmp(ct, "vmfs") &&
852 strcmp(ct, "vmfsSparse") &&
853 strcmp(ct, "twoGbMaxExtentSparse") &&
854 strcmp(ct, "twoGbMaxExtentFlat")) {
855 error_setg(errp, "Unsupported image type '%s'", ct);
856 ret = -ENOTSUP;
857 goto exit;
859 s->create_type = g_strdup(ct);
860 s->desc_offset = 0;
861 ret = vmdk_parse_extents(buf, bs, bs->file->filename, errp);
862 exit:
863 g_free(buf);
864 return ret;
867 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
868 Error **errp)
870 int ret;
871 BDRVVmdkState *s = bs->opaque;
873 if (vmdk_open_sparse(bs, bs->file, flags, errp) == 0) {
874 s->desc_offset = 0x200;
875 } else {
876 ret = vmdk_open_desc_file(bs, flags, 0, errp);
877 if (ret) {
878 goto fail;
881 /* try to open parent images, if exist */
882 ret = vmdk_parent_open(bs);
883 if (ret) {
884 goto fail;
886 s->cid = vmdk_read_cid(bs, 0);
887 s->parent_cid = vmdk_read_cid(bs, 1);
888 qemu_co_mutex_init(&s->lock);
890 /* Disable migration when VMDK images are used */
891 error_set(&s->migration_blocker,
892 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
893 "vmdk", bs->device_name, "live migration");
894 migrate_add_blocker(s->migration_blocker);
896 return 0;
898 fail:
899 g_free(s->create_type);
900 s->create_type = NULL;
901 vmdk_free_extents(bs);
902 return ret;
905 static int get_whole_cluster(BlockDriverState *bs,
906 VmdkExtent *extent,
907 uint64_t cluster_offset,
908 uint64_t offset,
909 bool allocate)
911 int ret = VMDK_OK;
912 uint8_t *whole_grain = NULL;
914 /* we will be here if it's first write on non-exist grain(cluster).
915 * try to read from parent image, if exist */
916 if (bs->backing_hd) {
917 whole_grain =
918 qemu_blockalign(bs, extent->cluster_sectors << BDRV_SECTOR_BITS);
919 if (!vmdk_is_cid_valid(bs)) {
920 ret = VMDK_ERROR;
921 goto exit;
924 /* floor offset to cluster */
925 offset -= offset % (extent->cluster_sectors * 512);
926 ret = bdrv_read(bs->backing_hd, offset >> 9, whole_grain,
927 extent->cluster_sectors);
928 if (ret < 0) {
929 ret = VMDK_ERROR;
930 goto exit;
933 /* Write grain only into the active image */
934 ret = bdrv_write(extent->file, cluster_offset, whole_grain,
935 extent->cluster_sectors);
936 if (ret < 0) {
937 ret = VMDK_ERROR;
938 goto exit;
941 exit:
942 qemu_vfree(whole_grain);
943 return ret;
946 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data)
948 uint32_t offset;
949 QEMU_BUILD_BUG_ON(sizeof(offset) != sizeof(m_data->offset));
950 offset = cpu_to_le32(m_data->offset);
951 /* update L2 table */
952 if (bdrv_pwrite_sync(
953 extent->file,
954 ((int64_t)m_data->l2_offset * 512)
955 + (m_data->l2_index * sizeof(m_data->offset)),
956 &offset, sizeof(offset)) < 0) {
957 return VMDK_ERROR;
959 /* update backup L2 table */
960 if (extent->l1_backup_table_offset != 0) {
961 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
962 if (bdrv_pwrite_sync(
963 extent->file,
964 ((int64_t)m_data->l2_offset * 512)
965 + (m_data->l2_index * sizeof(m_data->offset)),
966 &offset, sizeof(offset)) < 0) {
967 return VMDK_ERROR;
970 if (m_data->l2_cache_entry) {
971 *m_data->l2_cache_entry = offset;
974 return VMDK_OK;
977 static int get_cluster_offset(BlockDriverState *bs,
978 VmdkExtent *extent,
979 VmdkMetaData *m_data,
980 uint64_t offset,
981 int allocate,
982 uint64_t *cluster_offset)
984 unsigned int l1_index, l2_offset, l2_index;
985 int min_index, i, j;
986 uint32_t min_count, *l2_table;
987 bool zeroed = false;
989 if (m_data) {
990 m_data->valid = 0;
992 if (extent->flat) {
993 *cluster_offset = extent->flat_start_offset;
994 return VMDK_OK;
997 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
998 l1_index = (offset >> 9) / extent->l1_entry_sectors;
999 if (l1_index >= extent->l1_size) {
1000 return VMDK_ERROR;
1002 l2_offset = extent->l1_table[l1_index];
1003 if (!l2_offset) {
1004 return VMDK_UNALLOC;
1006 for (i = 0; i < L2_CACHE_SIZE; i++) {
1007 if (l2_offset == extent->l2_cache_offsets[i]) {
1008 /* increment the hit count */
1009 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1010 for (j = 0; j < L2_CACHE_SIZE; j++) {
1011 extent->l2_cache_counts[j] >>= 1;
1014 l2_table = extent->l2_cache + (i * extent->l2_size);
1015 goto found;
1018 /* not found: load a new entry in the least used one */
1019 min_index = 0;
1020 min_count = 0xffffffff;
1021 for (i = 0; i < L2_CACHE_SIZE; i++) {
1022 if (extent->l2_cache_counts[i] < min_count) {
1023 min_count = extent->l2_cache_counts[i];
1024 min_index = i;
1027 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1028 if (bdrv_pread(
1029 extent->file,
1030 (int64_t)l2_offset * 512,
1031 l2_table,
1032 extent->l2_size * sizeof(uint32_t)
1033 ) != extent->l2_size * sizeof(uint32_t)) {
1034 return VMDK_ERROR;
1037 extent->l2_cache_offsets[min_index] = l2_offset;
1038 extent->l2_cache_counts[min_index] = 1;
1039 found:
1040 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1041 *cluster_offset = le32_to_cpu(l2_table[l2_index]);
1043 if (m_data) {
1044 m_data->valid = 1;
1045 m_data->l1_index = l1_index;
1046 m_data->l2_index = l2_index;
1047 m_data->offset = *cluster_offset;
1048 m_data->l2_offset = l2_offset;
1049 m_data->l2_cache_entry = &l2_table[l2_index];
1051 if (extent->has_zero_grain && *cluster_offset == VMDK_GTE_ZEROED) {
1052 zeroed = true;
1055 if (!*cluster_offset || zeroed) {
1056 if (!allocate) {
1057 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1060 /* Avoid the L2 tables update for the images that have snapshots. */
1061 *cluster_offset = bdrv_getlength(extent->file);
1062 if (!extent->compressed) {
1063 bdrv_truncate(
1064 extent->file,
1065 *cluster_offset + (extent->cluster_sectors << 9)
1069 *cluster_offset >>= 9;
1070 l2_table[l2_index] = cpu_to_le32(*cluster_offset);
1072 /* First of all we write grain itself, to avoid race condition
1073 * that may to corrupt the image.
1074 * This problem may occur because of insufficient space on host disk
1075 * or inappropriate VM shutdown.
1077 if (get_whole_cluster(
1078 bs, extent, *cluster_offset, offset, allocate) == -1) {
1079 return VMDK_ERROR;
1082 if (m_data) {
1083 m_data->offset = *cluster_offset;
1086 *cluster_offset <<= 9;
1087 return VMDK_OK;
1090 static VmdkExtent *find_extent(BDRVVmdkState *s,
1091 int64_t sector_num, VmdkExtent *start_hint)
1093 VmdkExtent *extent = start_hint;
1095 if (!extent) {
1096 extent = &s->extents[0];
1098 while (extent < &s->extents[s->num_extents]) {
1099 if (sector_num < extent->end_sector) {
1100 return extent;
1102 extent++;
1104 return NULL;
1107 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1108 int64_t sector_num, int nb_sectors, int *pnum)
1110 BDRVVmdkState *s = bs->opaque;
1111 int64_t index_in_cluster, n, ret;
1112 uint64_t offset;
1113 VmdkExtent *extent;
1115 extent = find_extent(s, sector_num, NULL);
1116 if (!extent) {
1117 return 0;
1119 qemu_co_mutex_lock(&s->lock);
1120 ret = get_cluster_offset(bs, extent, NULL,
1121 sector_num * 512, 0, &offset);
1122 qemu_co_mutex_unlock(&s->lock);
1124 switch (ret) {
1125 case VMDK_ERROR:
1126 ret = -EIO;
1127 break;
1128 case VMDK_UNALLOC:
1129 ret = 0;
1130 break;
1131 case VMDK_ZEROED:
1132 ret = BDRV_BLOCK_ZERO;
1133 break;
1134 case VMDK_OK:
1135 ret = BDRV_BLOCK_DATA;
1136 if (extent->file == bs->file) {
1137 ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1140 break;
1143 index_in_cluster = sector_num % extent->cluster_sectors;
1144 n = extent->cluster_sectors - index_in_cluster;
1145 if (n > nb_sectors) {
1146 n = nb_sectors;
1148 *pnum = n;
1149 return ret;
1152 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1153 int64_t offset_in_cluster, const uint8_t *buf,
1154 int nb_sectors, int64_t sector_num)
1156 int ret;
1157 VmdkGrainMarker *data = NULL;
1158 uLongf buf_len;
1159 const uint8_t *write_buf = buf;
1160 int write_len = nb_sectors * 512;
1162 if (extent->compressed) {
1163 if (!extent->has_marker) {
1164 ret = -EINVAL;
1165 goto out;
1167 buf_len = (extent->cluster_sectors << 9) * 2;
1168 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1169 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1170 buf_len == 0) {
1171 ret = -EINVAL;
1172 goto out;
1174 data->lba = sector_num;
1175 data->size = buf_len;
1176 write_buf = (uint8_t *)data;
1177 write_len = buf_len + sizeof(VmdkGrainMarker);
1179 ret = bdrv_pwrite(extent->file,
1180 cluster_offset + offset_in_cluster,
1181 write_buf,
1182 write_len);
1183 if (ret != write_len) {
1184 ret = ret < 0 ? ret : -EIO;
1185 goto out;
1187 ret = 0;
1188 out:
1189 g_free(data);
1190 return ret;
1193 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1194 int64_t offset_in_cluster, uint8_t *buf,
1195 int nb_sectors)
1197 int ret;
1198 int cluster_bytes, buf_bytes;
1199 uint8_t *cluster_buf, *compressed_data;
1200 uint8_t *uncomp_buf;
1201 uint32_t data_len;
1202 VmdkGrainMarker *marker;
1203 uLongf buf_len;
1206 if (!extent->compressed) {
1207 ret = bdrv_pread(extent->file,
1208 cluster_offset + offset_in_cluster,
1209 buf, nb_sectors * 512);
1210 if (ret == nb_sectors * 512) {
1211 return 0;
1212 } else {
1213 return -EIO;
1216 cluster_bytes = extent->cluster_sectors * 512;
1217 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1218 buf_bytes = cluster_bytes * 2;
1219 cluster_buf = g_malloc(buf_bytes);
1220 uncomp_buf = g_malloc(cluster_bytes);
1221 ret = bdrv_pread(extent->file,
1222 cluster_offset,
1223 cluster_buf, buf_bytes);
1224 if (ret < 0) {
1225 goto out;
1227 compressed_data = cluster_buf;
1228 buf_len = cluster_bytes;
1229 data_len = cluster_bytes;
1230 if (extent->has_marker) {
1231 marker = (VmdkGrainMarker *)cluster_buf;
1232 compressed_data = marker->data;
1233 data_len = le32_to_cpu(marker->size);
1235 if (!data_len || data_len > buf_bytes) {
1236 ret = -EINVAL;
1237 goto out;
1239 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1240 if (ret != Z_OK) {
1241 ret = -EINVAL;
1242 goto out;
1245 if (offset_in_cluster < 0 ||
1246 offset_in_cluster + nb_sectors * 512 > buf_len) {
1247 ret = -EINVAL;
1248 goto out;
1250 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1251 ret = 0;
1253 out:
1254 g_free(uncomp_buf);
1255 g_free(cluster_buf);
1256 return ret;
1259 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1260 uint8_t *buf, int nb_sectors)
1262 BDRVVmdkState *s = bs->opaque;
1263 int ret;
1264 uint64_t n, index_in_cluster;
1265 uint64_t extent_begin_sector, extent_relative_sector_num;
1266 VmdkExtent *extent = NULL;
1267 uint64_t cluster_offset;
1269 while (nb_sectors > 0) {
1270 extent = find_extent(s, sector_num, extent);
1271 if (!extent) {
1272 return -EIO;
1274 ret = get_cluster_offset(
1275 bs, extent, NULL,
1276 sector_num << 9, 0, &cluster_offset);
1277 extent_begin_sector = extent->end_sector - extent->sectors;
1278 extent_relative_sector_num = sector_num - extent_begin_sector;
1279 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1280 n = extent->cluster_sectors - index_in_cluster;
1281 if (n > nb_sectors) {
1282 n = nb_sectors;
1284 if (ret != VMDK_OK) {
1285 /* if not allocated, try to read from parent image, if exist */
1286 if (bs->backing_hd && ret != VMDK_ZEROED) {
1287 if (!vmdk_is_cid_valid(bs)) {
1288 return -EINVAL;
1290 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1291 if (ret < 0) {
1292 return ret;
1294 } else {
1295 memset(buf, 0, 512 * n);
1297 } else {
1298 ret = vmdk_read_extent(extent,
1299 cluster_offset, index_in_cluster * 512,
1300 buf, n);
1301 if (ret) {
1302 return ret;
1305 nb_sectors -= n;
1306 sector_num += n;
1307 buf += n * 512;
1309 return 0;
1312 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1313 uint8_t *buf, int nb_sectors)
1315 int ret;
1316 BDRVVmdkState *s = bs->opaque;
1317 qemu_co_mutex_lock(&s->lock);
1318 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1319 qemu_co_mutex_unlock(&s->lock);
1320 return ret;
1324 * vmdk_write:
1325 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1326 * if possible, otherwise return -ENOTSUP.
1327 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1328 * with each cluster. By dry run we can find if the zero write
1329 * is possible without modifying image data.
1331 * Returns: error code with 0 for success.
1333 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1334 const uint8_t *buf, int nb_sectors,
1335 bool zeroed, bool zero_dry_run)
1337 BDRVVmdkState *s = bs->opaque;
1338 VmdkExtent *extent = NULL;
1339 int ret;
1340 int64_t index_in_cluster, n;
1341 uint64_t extent_begin_sector, extent_relative_sector_num;
1342 uint64_t cluster_offset;
1343 VmdkMetaData m_data;
1345 if (sector_num > bs->total_sectors) {
1346 error_report("Wrong offset: sector_num=0x%" PRIx64
1347 " total_sectors=0x%" PRIx64 "\n",
1348 sector_num, bs->total_sectors);
1349 return -EIO;
1352 while (nb_sectors > 0) {
1353 extent = find_extent(s, sector_num, extent);
1354 if (!extent) {
1355 return -EIO;
1357 ret = get_cluster_offset(
1359 extent,
1360 &m_data,
1361 sector_num << 9, !extent->compressed,
1362 &cluster_offset);
1363 if (extent->compressed) {
1364 if (ret == VMDK_OK) {
1365 /* Refuse write to allocated cluster for streamOptimized */
1366 error_report("Could not write to allocated cluster"
1367 " for streamOptimized");
1368 return -EIO;
1369 } else {
1370 /* allocate */
1371 ret = get_cluster_offset(
1373 extent,
1374 &m_data,
1375 sector_num << 9, 1,
1376 &cluster_offset);
1379 if (ret == VMDK_ERROR) {
1380 return -EINVAL;
1382 extent_begin_sector = extent->end_sector - extent->sectors;
1383 extent_relative_sector_num = sector_num - extent_begin_sector;
1384 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1385 n = extent->cluster_sectors - index_in_cluster;
1386 if (n > nb_sectors) {
1387 n = nb_sectors;
1389 if (zeroed) {
1390 /* Do zeroed write, buf is ignored */
1391 if (extent->has_zero_grain &&
1392 index_in_cluster == 0 &&
1393 n >= extent->cluster_sectors) {
1394 n = extent->cluster_sectors;
1395 if (!zero_dry_run) {
1396 m_data.offset = VMDK_GTE_ZEROED;
1397 /* update L2 tables */
1398 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1399 return -EIO;
1402 } else {
1403 return -ENOTSUP;
1405 } else {
1406 ret = vmdk_write_extent(extent,
1407 cluster_offset, index_in_cluster * 512,
1408 buf, n, sector_num);
1409 if (ret) {
1410 return ret;
1412 if (m_data.valid) {
1413 /* update L2 tables */
1414 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1415 return -EIO;
1419 nb_sectors -= n;
1420 sector_num += n;
1421 buf += n * 512;
1423 /* update CID on the first write every time the virtual disk is
1424 * opened */
1425 if (!s->cid_updated) {
1426 ret = vmdk_write_cid(bs, time(NULL));
1427 if (ret < 0) {
1428 return ret;
1430 s->cid_updated = true;
1433 return 0;
1436 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1437 const uint8_t *buf, int nb_sectors)
1439 int ret;
1440 BDRVVmdkState *s = bs->opaque;
1441 qemu_co_mutex_lock(&s->lock);
1442 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1443 qemu_co_mutex_unlock(&s->lock);
1444 return ret;
1447 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1448 int64_t sector_num,
1449 int nb_sectors,
1450 BdrvRequestFlags flags)
1452 int ret;
1453 BDRVVmdkState *s = bs->opaque;
1454 qemu_co_mutex_lock(&s->lock);
1455 /* write zeroes could fail if sectors not aligned to cluster, test it with
1456 * dry_run == true before really updating image */
1457 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1458 if (!ret) {
1459 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1461 qemu_co_mutex_unlock(&s->lock);
1462 return ret;
1465 static int vmdk_create_extent(const char *filename, int64_t filesize,
1466 bool flat, bool compress, bool zeroed_grain,
1467 Error **errp)
1469 int ret, i;
1470 BlockDriverState *bs = NULL;
1471 VMDK4Header header;
1472 Error *local_err;
1473 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1474 uint32_t *gd_buf = NULL;
1475 int gd_buf_size;
1477 ret = bdrv_create_file(filename, NULL, &local_err);
1478 if (ret < 0) {
1479 error_propagate(errp, local_err);
1480 goto exit;
1483 ret = bdrv_file_open(&bs, filename, NULL, NULL, BDRV_O_RDWR, &local_err);
1484 if (ret < 0) {
1485 error_propagate(errp, local_err);
1486 goto exit;
1489 if (flat) {
1490 ret = bdrv_truncate(bs, filesize);
1491 if (ret < 0) {
1492 error_setg(errp, "Could not truncate file");
1494 goto exit;
1496 magic = cpu_to_be32(VMDK4_MAGIC);
1497 memset(&header, 0, sizeof(header));
1498 header.version = zeroed_grain ? 2 : 1;
1499 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1500 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1501 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1502 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1503 header.capacity = filesize / BDRV_SECTOR_SIZE;
1504 header.granularity = 128;
1505 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1507 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1508 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1509 BDRV_SECTOR_SIZE);
1510 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1511 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1513 header.desc_offset = 1;
1514 header.desc_size = 20;
1515 header.rgd_offset = header.desc_offset + header.desc_size;
1516 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1517 header.grain_offset =
1518 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1519 header.granularity);
1520 /* swap endianness for all header fields */
1521 header.version = cpu_to_le32(header.version);
1522 header.flags = cpu_to_le32(header.flags);
1523 header.capacity = cpu_to_le64(header.capacity);
1524 header.granularity = cpu_to_le64(header.granularity);
1525 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1526 header.desc_offset = cpu_to_le64(header.desc_offset);
1527 header.desc_size = cpu_to_le64(header.desc_size);
1528 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1529 header.gd_offset = cpu_to_le64(header.gd_offset);
1530 header.grain_offset = cpu_to_le64(header.grain_offset);
1531 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1533 header.check_bytes[0] = 0xa;
1534 header.check_bytes[1] = 0x20;
1535 header.check_bytes[2] = 0xd;
1536 header.check_bytes[3] = 0xa;
1538 /* write all the data */
1539 ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1540 if (ret < 0) {
1541 error_set(errp, QERR_IO_ERROR);
1542 goto exit;
1544 ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1545 if (ret < 0) {
1546 error_set(errp, QERR_IO_ERROR);
1547 goto exit;
1550 ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1551 if (ret < 0) {
1552 error_setg(errp, "Could not truncate file");
1553 goto exit;
1556 /* write grain directory */
1557 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1558 gd_buf = g_malloc0(gd_buf_size);
1559 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1560 i < gt_count; i++, tmp += gt_size) {
1561 gd_buf[i] = cpu_to_le32(tmp);
1563 ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1564 gd_buf, gd_buf_size);
1565 if (ret < 0) {
1566 error_set(errp, QERR_IO_ERROR);
1567 goto exit;
1570 /* write backup grain directory */
1571 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1572 i < gt_count; i++, tmp += gt_size) {
1573 gd_buf[i] = cpu_to_le32(tmp);
1575 ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1576 gd_buf, gd_buf_size);
1577 if (ret < 0) {
1578 error_set(errp, QERR_IO_ERROR);
1579 goto exit;
1582 ret = 0;
1583 exit:
1584 if (bs) {
1585 bdrv_unref(bs);
1587 g_free(gd_buf);
1588 return ret;
1591 static int filename_decompose(const char *filename, char *path, char *prefix,
1592 char *postfix, size_t buf_len, Error **errp)
1594 const char *p, *q;
1596 if (filename == NULL || !strlen(filename)) {
1597 error_setg(errp, "No filename provided");
1598 return VMDK_ERROR;
1600 p = strrchr(filename, '/');
1601 if (p == NULL) {
1602 p = strrchr(filename, '\\');
1604 if (p == NULL) {
1605 p = strrchr(filename, ':');
1607 if (p != NULL) {
1608 p++;
1609 if (p - filename >= buf_len) {
1610 return VMDK_ERROR;
1612 pstrcpy(path, p - filename + 1, filename);
1613 } else {
1614 p = filename;
1615 path[0] = '\0';
1617 q = strrchr(p, '.');
1618 if (q == NULL) {
1619 pstrcpy(prefix, buf_len, p);
1620 postfix[0] = '\0';
1621 } else {
1622 if (q - p >= buf_len) {
1623 return VMDK_ERROR;
1625 pstrcpy(prefix, q - p + 1, p);
1626 pstrcpy(postfix, buf_len, q);
1628 return VMDK_OK;
1631 static int vmdk_create(const char *filename, QEMUOptionParameter *options,
1632 Error **errp)
1634 int idx = 0;
1635 BlockDriverState *new_bs = NULL;
1636 Error *local_err;
1637 char *desc = NULL;
1638 int64_t total_size = 0, filesize;
1639 const char *adapter_type = NULL;
1640 const char *backing_file = NULL;
1641 const char *fmt = NULL;
1642 int flags = 0;
1643 int ret = 0;
1644 bool flat, split, compress;
1645 GString *ext_desc_lines;
1646 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1647 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1648 const char *desc_extent_line;
1649 char parent_desc_line[BUF_SIZE] = "";
1650 uint32_t parent_cid = 0xffffffff;
1651 uint32_t number_heads = 16;
1652 bool zeroed_grain = false;
1653 uint32_t desc_offset = 0, desc_len;
1654 const char desc_template[] =
1655 "# Disk DescriptorFile\n"
1656 "version=1\n"
1657 "CID=%x\n"
1658 "parentCID=%x\n"
1659 "createType=\"%s\"\n"
1660 "%s"
1661 "\n"
1662 "# Extent description\n"
1663 "%s"
1664 "\n"
1665 "# The Disk Data Base\n"
1666 "#DDB\n"
1667 "\n"
1668 "ddb.virtualHWVersion = \"%d\"\n"
1669 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1670 "ddb.geometry.heads = \"%d\"\n"
1671 "ddb.geometry.sectors = \"63\"\n"
1672 "ddb.adapterType = \"%s\"\n";
1674 ext_desc_lines = g_string_new(NULL);
1676 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1677 ret = -EINVAL;
1678 goto exit;
1680 /* Read out options */
1681 while (options && options->name) {
1682 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1683 total_size = options->value.n;
1684 } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {
1685 adapter_type = options->value.s;
1686 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1687 backing_file = options->value.s;
1688 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
1689 flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;
1690 } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {
1691 fmt = options->value.s;
1692 } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {
1693 zeroed_grain |= options->value.n;
1695 options++;
1697 if (!adapter_type) {
1698 adapter_type = "ide";
1699 } else if (strcmp(adapter_type, "ide") &&
1700 strcmp(adapter_type, "buslogic") &&
1701 strcmp(adapter_type, "lsilogic") &&
1702 strcmp(adapter_type, "legacyESX")) {
1703 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1704 ret = -EINVAL;
1705 goto exit;
1707 if (strcmp(adapter_type, "ide") != 0) {
1708 /* that's the number of heads with which vmware operates when
1709 creating, exporting, etc. vmdk files with a non-ide adapter type */
1710 number_heads = 255;
1712 if (!fmt) {
1713 /* Default format to monolithicSparse */
1714 fmt = "monolithicSparse";
1715 } else if (strcmp(fmt, "monolithicFlat") &&
1716 strcmp(fmt, "monolithicSparse") &&
1717 strcmp(fmt, "twoGbMaxExtentSparse") &&
1718 strcmp(fmt, "twoGbMaxExtentFlat") &&
1719 strcmp(fmt, "streamOptimized")) {
1720 error_setg(errp, "Unknown subformat: '%s'", fmt);
1721 ret = -EINVAL;
1722 goto exit;
1724 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1725 strcmp(fmt, "twoGbMaxExtentSparse"));
1726 flat = !(strcmp(fmt, "monolithicFlat") &&
1727 strcmp(fmt, "twoGbMaxExtentFlat"));
1728 compress = !strcmp(fmt, "streamOptimized");
1729 if (flat) {
1730 desc_extent_line = "RW %lld FLAT \"%s\" 0\n";
1731 } else {
1732 desc_extent_line = "RW %lld SPARSE \"%s\"\n";
1734 if (flat && backing_file) {
1735 error_setg(errp, "Flat image can't have backing file");
1736 ret = -ENOTSUP;
1737 goto exit;
1739 if (flat && zeroed_grain) {
1740 error_setg(errp, "Flat image can't enable zeroed grain");
1741 ret = -ENOTSUP;
1742 goto exit;
1744 if (backing_file) {
1745 BlockDriverState *bs = bdrv_new("");
1746 ret = bdrv_open(bs, backing_file, NULL, BDRV_O_NO_BACKING, NULL, errp);
1747 if (ret != 0) {
1748 bdrv_unref(bs);
1749 goto exit;
1751 if (strcmp(bs->drv->format_name, "vmdk")) {
1752 bdrv_unref(bs);
1753 ret = -EINVAL;
1754 goto exit;
1756 parent_cid = vmdk_read_cid(bs, 0);
1757 bdrv_unref(bs);
1758 snprintf(parent_desc_line, sizeof(parent_desc_line),
1759 "parentFileNameHint=\"%s\"", backing_file);
1762 /* Create extents */
1763 filesize = total_size;
1764 while (filesize > 0) {
1765 char desc_line[BUF_SIZE];
1766 char ext_filename[PATH_MAX];
1767 char desc_filename[PATH_MAX];
1768 int64_t size = filesize;
1770 if (split && size > split_size) {
1771 size = split_size;
1773 if (split) {
1774 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1775 prefix, flat ? 'f' : 's', ++idx, postfix);
1776 } else if (flat) {
1777 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1778 prefix, postfix);
1779 } else {
1780 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1781 prefix, postfix);
1783 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1784 path, desc_filename);
1786 if (vmdk_create_extent(ext_filename, size,
1787 flat, compress, zeroed_grain, errp)) {
1788 ret = -EINVAL;
1789 goto exit;
1791 filesize -= size;
1793 /* Format description line */
1794 snprintf(desc_line, sizeof(desc_line),
1795 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1796 g_string_append(ext_desc_lines, desc_line);
1798 /* generate descriptor file */
1799 desc = g_strdup_printf(desc_template,
1800 (unsigned int)time(NULL),
1801 parent_cid,
1802 fmt,
1803 parent_desc_line,
1804 ext_desc_lines->str,
1805 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1806 total_size /
1807 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1808 number_heads,
1809 adapter_type);
1810 desc_len = strlen(desc);
1811 /* the descriptor offset = 0x200 */
1812 if (!split && !flat) {
1813 desc_offset = 0x200;
1814 } else {
1815 ret = bdrv_create_file(filename, options, &local_err);
1816 if (ret < 0) {
1817 error_setg_errno(errp, -ret, "Could not create image file");
1818 goto exit;
1821 ret = bdrv_file_open(&new_bs, filename, NULL, NULL, BDRV_O_RDWR, &local_err);
1822 if (ret < 0) {
1823 error_setg_errno(errp, -ret, "Could not write description");
1824 goto exit;
1826 ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1827 if (ret < 0) {
1828 error_setg_errno(errp, -ret, "Could not write description");
1829 goto exit;
1831 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1832 * for description file */
1833 if (desc_offset == 0) {
1834 ret = bdrv_truncate(new_bs, desc_len);
1835 if (ret < 0) {
1836 error_setg(errp, "Could not truncate file");
1839 exit:
1840 if (new_bs) {
1841 bdrv_unref(new_bs);
1843 g_free(desc);
1844 g_string_free(ext_desc_lines, true);
1845 return ret;
1848 static void vmdk_close(BlockDriverState *bs)
1850 BDRVVmdkState *s = bs->opaque;
1852 vmdk_free_extents(bs);
1853 g_free(s->create_type);
1855 migrate_del_blocker(s->migration_blocker);
1856 error_free(s->migration_blocker);
1859 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1861 BDRVVmdkState *s = bs->opaque;
1862 int i, err;
1863 int ret = 0;
1865 for (i = 0; i < s->num_extents; i++) {
1866 err = bdrv_co_flush(s->extents[i].file);
1867 if (err < 0) {
1868 ret = err;
1871 return ret;
1874 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
1876 int i;
1877 int64_t ret = 0;
1878 int64_t r;
1879 BDRVVmdkState *s = bs->opaque;
1881 ret = bdrv_get_allocated_file_size(bs->file);
1882 if (ret < 0) {
1883 return ret;
1885 for (i = 0; i < s->num_extents; i++) {
1886 if (s->extents[i].file == bs->file) {
1887 continue;
1889 r = bdrv_get_allocated_file_size(s->extents[i].file);
1890 if (r < 0) {
1891 return r;
1893 ret += r;
1895 return ret;
1898 static int vmdk_has_zero_init(BlockDriverState *bs)
1900 int i;
1901 BDRVVmdkState *s = bs->opaque;
1903 /* If has a flat extent and its underlying storage doesn't have zero init,
1904 * return 0. */
1905 for (i = 0; i < s->num_extents; i++) {
1906 if (s->extents[i].flat) {
1907 if (!bdrv_has_zero_init(s->extents[i].file)) {
1908 return 0;
1912 return 1;
1915 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
1917 ImageInfo *info = g_new0(ImageInfo, 1);
1919 *info = (ImageInfo){
1920 .filename = g_strdup(extent->file->filename),
1921 .format = g_strdup(extent->type),
1922 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
1923 .compressed = extent->compressed,
1924 .has_compressed = extent->compressed,
1925 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
1926 .has_cluster_size = !extent->flat,
1929 return info;
1932 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
1934 int i;
1935 BDRVVmdkState *s = bs->opaque;
1936 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
1937 ImageInfoList **next;
1939 *spec_info = (ImageInfoSpecific){
1940 .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
1942 .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
1946 *spec_info->vmdk = (ImageInfoSpecificVmdk) {
1947 .create_type = g_strdup(s->create_type),
1948 .cid = s->cid,
1949 .parent_cid = s->parent_cid,
1952 next = &spec_info->vmdk->extents;
1953 for (i = 0; i < s->num_extents; i++) {
1954 *next = g_new0(ImageInfoList, 1);
1955 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
1956 (*next)->next = NULL;
1957 next = &(*next)->next;
1960 return spec_info;
1963 static QEMUOptionParameter vmdk_create_options[] = {
1965 .name = BLOCK_OPT_SIZE,
1966 .type = OPT_SIZE,
1967 .help = "Virtual disk size"
1970 .name = BLOCK_OPT_ADAPTER_TYPE,
1971 .type = OPT_STRING,
1972 .help = "Virtual adapter type, can be one of "
1973 "ide (default), lsilogic, buslogic or legacyESX"
1976 .name = BLOCK_OPT_BACKING_FILE,
1977 .type = OPT_STRING,
1978 .help = "File name of a base image"
1981 .name = BLOCK_OPT_COMPAT6,
1982 .type = OPT_FLAG,
1983 .help = "VMDK version 6 image"
1986 .name = BLOCK_OPT_SUBFMT,
1987 .type = OPT_STRING,
1988 .help =
1989 "VMDK flat extent format, can be one of "
1990 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
1993 .name = BLOCK_OPT_ZEROED_GRAIN,
1994 .type = OPT_FLAG,
1995 .help = "Enable efficient zero writes using the zeroed-grain GTE feature"
1997 { NULL }
2000 static BlockDriver bdrv_vmdk = {
2001 .format_name = "vmdk",
2002 .instance_size = sizeof(BDRVVmdkState),
2003 .bdrv_probe = vmdk_probe,
2004 .bdrv_open = vmdk_open,
2005 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2006 .bdrv_read = vmdk_co_read,
2007 .bdrv_write = vmdk_co_write,
2008 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
2009 .bdrv_close = vmdk_close,
2010 .bdrv_create = vmdk_create,
2011 .bdrv_co_flush_to_disk = vmdk_co_flush,
2012 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2013 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2014 .bdrv_has_zero_init = vmdk_has_zero_init,
2015 .bdrv_get_specific_info = vmdk_get_specific_info,
2017 .create_options = vmdk_create_options,
2020 static void bdrv_vmdk_init(void)
2022 bdrv_register(&bdrv_vmdk);
2025 block_init(bdrv_vmdk_init);