]> git.proxmox.com Git - mirror_qemu.git/blob - block/vmdk.c
vmdk: Clean up descriptor file reading
[mirror_qemu.git] / block / vmdk.c
1 /*
2 * Block driver for the VMDK format
3 *
4 * Copyright (c) 2004 Fabrice Bellard
5 * Copyright (c) 2005 Filip Navara
6 *
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:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
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.
24 */
25
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>
31 #include <glib.h>
32
33 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
34 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
35 #define VMDK4_COMPRESSION_DEFLATE 1
36 #define VMDK4_FLAG_NL_DETECT (1 << 0)
37 #define VMDK4_FLAG_RGD (1 << 1)
38 /* Zeroed-grain enable bit */
39 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
40 #define VMDK4_FLAG_COMPRESS (1 << 16)
41 #define VMDK4_FLAG_MARKER (1 << 17)
42 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
43
44 #define VMDK_GTE_ZEROED 0x1
45
46 /* VMDK internal error codes */
47 #define VMDK_OK 0
48 #define VMDK_ERROR (-1)
49 /* Cluster not allocated */
50 #define VMDK_UNALLOC (-2)
51 #define VMDK_ZEROED (-3)
52
53 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
54
55 typedef struct {
56 uint32_t version;
57 uint32_t flags;
58 uint32_t disk_sectors;
59 uint32_t granularity;
60 uint32_t l1dir_offset;
61 uint32_t l1dir_size;
62 uint32_t file_sectors;
63 uint32_t cylinders;
64 uint32_t heads;
65 uint32_t sectors_per_track;
66 } QEMU_PACKED VMDK3Header;
67
68 typedef struct {
69 uint32_t version;
70 uint32_t flags;
71 uint64_t capacity;
72 uint64_t granularity;
73 uint64_t desc_offset;
74 uint64_t desc_size;
75 /* Number of GrainTableEntries per GrainTable */
76 uint32_t num_gtes_per_gt;
77 uint64_t rgd_offset;
78 uint64_t gd_offset;
79 uint64_t grain_offset;
80 char filler[1];
81 char check_bytes[4];
82 uint16_t compressAlgorithm;
83 } QEMU_PACKED VMDK4Header;
84
85 #define L2_CACHE_SIZE 16
86
87 typedef struct VmdkExtent {
88 BlockDriverState *file;
89 bool flat;
90 bool compressed;
91 bool has_marker;
92 bool has_zero_grain;
93 int version;
94 int64_t sectors;
95 int64_t end_sector;
96 int64_t flat_start_offset;
97 int64_t l1_table_offset;
98 int64_t l1_backup_table_offset;
99 uint32_t *l1_table;
100 uint32_t *l1_backup_table;
101 unsigned int l1_size;
102 uint32_t l1_entry_sectors;
103
104 unsigned int l2_size;
105 uint32_t *l2_cache;
106 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
107 uint32_t l2_cache_counts[L2_CACHE_SIZE];
108
109 int64_t cluster_sectors;
110 int64_t next_cluster_sector;
111 char *type;
112 } VmdkExtent;
113
114 typedef struct BDRVVmdkState {
115 CoMutex lock;
116 uint64_t desc_offset;
117 bool cid_updated;
118 bool cid_checked;
119 uint32_t cid;
120 uint32_t parent_cid;
121 int num_extents;
122 /* Extent array with num_extents entries, ascend ordered by address */
123 VmdkExtent *extents;
124 Error *migration_blocker;
125 char *create_type;
126 } BDRVVmdkState;
127
128 typedef struct VmdkMetaData {
129 unsigned int l1_index;
130 unsigned int l2_index;
131 unsigned int l2_offset;
132 int valid;
133 uint32_t *l2_cache_entry;
134 } VmdkMetaData;
135
136 typedef struct VmdkGrainMarker {
137 uint64_t lba;
138 uint32_t size;
139 uint8_t data[0];
140 } QEMU_PACKED VmdkGrainMarker;
141
142 enum {
143 MARKER_END_OF_STREAM = 0,
144 MARKER_GRAIN_TABLE = 1,
145 MARKER_GRAIN_DIRECTORY = 2,
146 MARKER_FOOTER = 3,
147 };
148
149 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
150 {
151 uint32_t magic;
152
153 if (buf_size < 4) {
154 return 0;
155 }
156 magic = be32_to_cpu(*(uint32_t *)buf);
157 if (magic == VMDK3_MAGIC ||
158 magic == VMDK4_MAGIC) {
159 return 100;
160 } else {
161 const char *p = (const char *)buf;
162 const char *end = p + buf_size;
163 while (p < end) {
164 if (*p == '#') {
165 /* skip comment line */
166 while (p < end && *p != '\n') {
167 p++;
168 }
169 p++;
170 continue;
171 }
172 if (*p == ' ') {
173 while (p < end && *p == ' ') {
174 p++;
175 }
176 /* skip '\r' if windows line endings used. */
177 if (p < end && *p == '\r') {
178 p++;
179 }
180 /* only accept blank lines before 'version=' line */
181 if (p == end || *p != '\n') {
182 return 0;
183 }
184 p++;
185 continue;
186 }
187 if (end - p >= strlen("version=X\n")) {
188 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
189 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
190 return 100;
191 }
192 }
193 if (end - p >= strlen("version=X\r\n")) {
194 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
195 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
196 return 100;
197 }
198 }
199 return 0;
200 }
201 return 0;
202 }
203 }
204
205 #define SECTOR_SIZE 512
206 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
207 #define BUF_SIZE 4096
208 #define HEADER_SIZE 512 /* first sector of 512 bytes */
209
210 static void vmdk_free_extents(BlockDriverState *bs)
211 {
212 int i;
213 BDRVVmdkState *s = bs->opaque;
214 VmdkExtent *e;
215
216 for (i = 0; i < s->num_extents; i++) {
217 e = &s->extents[i];
218 g_free(e->l1_table);
219 g_free(e->l2_cache);
220 g_free(e->l1_backup_table);
221 g_free(e->type);
222 if (e->file != bs->file) {
223 bdrv_unref(e->file);
224 }
225 }
226 g_free(s->extents);
227 }
228
229 static void vmdk_free_last_extent(BlockDriverState *bs)
230 {
231 BDRVVmdkState *s = bs->opaque;
232
233 if (s->num_extents == 0) {
234 return;
235 }
236 s->num_extents--;
237 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
238 }
239
240 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
241 {
242 char desc[DESC_SIZE];
243 uint32_t cid = 0xffffffff;
244 const char *p_name, *cid_str;
245 size_t cid_str_size;
246 BDRVVmdkState *s = bs->opaque;
247 int ret;
248
249 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
250 if (ret < 0) {
251 return 0;
252 }
253
254 if (parent) {
255 cid_str = "parentCID";
256 cid_str_size = sizeof("parentCID");
257 } else {
258 cid_str = "CID";
259 cid_str_size = sizeof("CID");
260 }
261
262 desc[DESC_SIZE - 1] = '\0';
263 p_name = strstr(desc, cid_str);
264 if (p_name != NULL) {
265 p_name += cid_str_size;
266 sscanf(p_name, "%" SCNx32, &cid);
267 }
268
269 return cid;
270 }
271
272 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
273 {
274 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
275 char *p_name, *tmp_str;
276 BDRVVmdkState *s = bs->opaque;
277 int ret;
278
279 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
280 if (ret < 0) {
281 return ret;
282 }
283
284 desc[DESC_SIZE - 1] = '\0';
285 tmp_str = strstr(desc, "parentCID");
286 if (tmp_str == NULL) {
287 return -EINVAL;
288 }
289
290 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
291 p_name = strstr(desc, "CID");
292 if (p_name != NULL) {
293 p_name += sizeof("CID");
294 snprintf(p_name, sizeof(desc) - (p_name - desc), "%" PRIx32 "\n", cid);
295 pstrcat(desc, sizeof(desc), tmp_desc);
296 }
297
298 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
299 if (ret < 0) {
300 return ret;
301 }
302
303 return 0;
304 }
305
306 static int vmdk_is_cid_valid(BlockDriverState *bs)
307 {
308 BDRVVmdkState *s = bs->opaque;
309 BlockDriverState *p_bs = bs->backing_hd;
310 uint32_t cur_pcid;
311
312 if (!s->cid_checked && p_bs) {
313 cur_pcid = vmdk_read_cid(p_bs, 0);
314 if (s->parent_cid != cur_pcid) {
315 /* CID not valid */
316 return 0;
317 }
318 }
319 s->cid_checked = true;
320 /* CID valid */
321 return 1;
322 }
323
324 /* Queue extents, if any, for reopen() */
325 static int vmdk_reopen_prepare(BDRVReopenState *state,
326 BlockReopenQueue *queue, Error **errp)
327 {
328 BDRVVmdkState *s;
329 int ret = -1;
330 int i;
331 VmdkExtent *e;
332
333 assert(state != NULL);
334 assert(state->bs != NULL);
335
336 if (queue == NULL) {
337 error_setg(errp, "No reopen queue for VMDK extents");
338 goto exit;
339 }
340
341 s = state->bs->opaque;
342
343 assert(s != NULL);
344
345 for (i = 0; i < s->num_extents; i++) {
346 e = &s->extents[i];
347 if (e->file != state->bs->file) {
348 bdrv_reopen_queue(queue, e->file, state->flags);
349 }
350 }
351 ret = 0;
352
353 exit:
354 return ret;
355 }
356
357 static int vmdk_parent_open(BlockDriverState *bs)
358 {
359 char *p_name;
360 char desc[DESC_SIZE + 1];
361 BDRVVmdkState *s = bs->opaque;
362 int ret;
363
364 desc[DESC_SIZE] = '\0';
365 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
366 if (ret < 0) {
367 return ret;
368 }
369
370 p_name = strstr(desc, "parentFileNameHint");
371 if (p_name != NULL) {
372 char *end_name;
373
374 p_name += sizeof("parentFileNameHint") + 1;
375 end_name = strchr(p_name, '\"');
376 if (end_name == NULL) {
377 return -EINVAL;
378 }
379 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
380 return -EINVAL;
381 }
382
383 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
384 }
385
386 return 0;
387 }
388
389 /* Create and append extent to the extent array. Return the added VmdkExtent
390 * address. return NULL if allocation failed. */
391 static int vmdk_add_extent(BlockDriverState *bs,
392 BlockDriverState *file, bool flat, int64_t sectors,
393 int64_t l1_offset, int64_t l1_backup_offset,
394 uint32_t l1_size,
395 int l2_size, uint64_t cluster_sectors,
396 VmdkExtent **new_extent,
397 Error **errp)
398 {
399 VmdkExtent *extent;
400 BDRVVmdkState *s = bs->opaque;
401 int64_t nb_sectors;
402
403 if (cluster_sectors > 0x200000) {
404 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
405 error_setg(errp, "Invalid granularity, image may be corrupt");
406 return -EFBIG;
407 }
408 if (l1_size > 512 * 1024 * 1024) {
409 /* Although with big capacity and small l1_entry_sectors, we can get a
410 * big l1_size, we don't want unbounded value to allocate the table.
411 * Limit it to 512M, which is 16PB for default cluster and L2 table
412 * size */
413 error_setg(errp, "L1 size too big");
414 return -EFBIG;
415 }
416
417 nb_sectors = bdrv_nb_sectors(file);
418 if (nb_sectors < 0) {
419 return nb_sectors;
420 }
421
422 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
423 extent = &s->extents[s->num_extents];
424 s->num_extents++;
425
426 memset(extent, 0, sizeof(VmdkExtent));
427 extent->file = file;
428 extent->flat = flat;
429 extent->sectors = sectors;
430 extent->l1_table_offset = l1_offset;
431 extent->l1_backup_table_offset = l1_backup_offset;
432 extent->l1_size = l1_size;
433 extent->l1_entry_sectors = l2_size * cluster_sectors;
434 extent->l2_size = l2_size;
435 extent->cluster_sectors = flat ? sectors : cluster_sectors;
436 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
437
438 if (s->num_extents > 1) {
439 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
440 } else {
441 extent->end_sector = extent->sectors;
442 }
443 bs->total_sectors = extent->end_sector;
444 if (new_extent) {
445 *new_extent = extent;
446 }
447 return 0;
448 }
449
450 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
451 Error **errp)
452 {
453 int ret;
454 int l1_size, i;
455
456 /* read the L1 table */
457 l1_size = extent->l1_size * sizeof(uint32_t);
458 extent->l1_table = g_try_malloc(l1_size);
459 if (l1_size && extent->l1_table == NULL) {
460 return -ENOMEM;
461 }
462
463 ret = bdrv_pread(extent->file,
464 extent->l1_table_offset,
465 extent->l1_table,
466 l1_size);
467 if (ret < 0) {
468 error_setg_errno(errp, -ret,
469 "Could not read l1 table from extent '%s'",
470 extent->file->filename);
471 goto fail_l1;
472 }
473 for (i = 0; i < extent->l1_size; i++) {
474 le32_to_cpus(&extent->l1_table[i]);
475 }
476
477 if (extent->l1_backup_table_offset) {
478 extent->l1_backup_table = g_try_malloc(l1_size);
479 if (l1_size && extent->l1_backup_table == NULL) {
480 ret = -ENOMEM;
481 goto fail_l1;
482 }
483 ret = bdrv_pread(extent->file,
484 extent->l1_backup_table_offset,
485 extent->l1_backup_table,
486 l1_size);
487 if (ret < 0) {
488 error_setg_errno(errp, -ret,
489 "Could not read l1 backup table from extent '%s'",
490 extent->file->filename);
491 goto fail_l1b;
492 }
493 for (i = 0; i < extent->l1_size; i++) {
494 le32_to_cpus(&extent->l1_backup_table[i]);
495 }
496 }
497
498 extent->l2_cache =
499 g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
500 return 0;
501 fail_l1b:
502 g_free(extent->l1_backup_table);
503 fail_l1:
504 g_free(extent->l1_table);
505 return ret;
506 }
507
508 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
509 BlockDriverState *file,
510 int flags, Error **errp)
511 {
512 int ret;
513 uint32_t magic;
514 VMDK3Header header;
515 VmdkExtent *extent;
516
517 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
518 if (ret < 0) {
519 error_setg_errno(errp, -ret,
520 "Could not read header from file '%s'",
521 file->filename);
522 return ret;
523 }
524 ret = vmdk_add_extent(bs, file, false,
525 le32_to_cpu(header.disk_sectors),
526 le32_to_cpu(header.l1dir_offset) << 9,
527 0,
528 le32_to_cpu(header.l1dir_size),
529 4096,
530 le32_to_cpu(header.granularity),
531 &extent,
532 errp);
533 if (ret < 0) {
534 return ret;
535 }
536 ret = vmdk_init_tables(bs, extent, errp);
537 if (ret) {
538 /* free extent allocated by vmdk_add_extent */
539 vmdk_free_last_extent(bs);
540 }
541 return ret;
542 }
543
544 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
545 Error **errp);
546
547 static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset,
548 Error **errp)
549 {
550 int64_t size;
551 char *buf;
552 int ret;
553
554 size = bdrv_getlength(file);
555 if (size < 0) {
556 error_setg_errno(errp, -size, "Could not access file");
557 return NULL;
558 }
559
560 size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */
561 buf = g_malloc(size + 1);
562
563 ret = bdrv_pread(file, desc_offset, buf, size);
564 if (ret < 0) {
565 error_setg_errno(errp, -ret, "Could not read from file");
566 g_free(buf);
567 return NULL;
568 }
569 buf[ret] = 0;
570
571 return buf;
572 }
573
574 static int vmdk_open_vmdk4(BlockDriverState *bs,
575 BlockDriverState *file,
576 int flags, Error **errp)
577 {
578 int ret;
579 uint32_t magic;
580 uint32_t l1_size, l1_entry_sectors;
581 VMDK4Header header;
582 VmdkExtent *extent;
583 BDRVVmdkState *s = bs->opaque;
584 int64_t l1_backup_offset = 0;
585
586 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
587 if (ret < 0) {
588 error_setg_errno(errp, -ret,
589 "Could not read header from file '%s'",
590 file->filename);
591 return -EINVAL;
592 }
593 if (header.capacity == 0) {
594 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
595 if (desc_offset) {
596 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
597 if (!buf) {
598 return -EINVAL;
599 }
600 ret = vmdk_open_desc_file(bs, flags, buf, errp);
601 g_free(buf);
602 return ret;
603 }
604 }
605
606 if (!s->create_type) {
607 s->create_type = g_strdup("monolithicSparse");
608 }
609
610 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
611 /*
612 * The footer takes precedence over the header, so read it in. The
613 * footer starts at offset -1024 from the end: One sector for the
614 * footer, and another one for the end-of-stream marker.
615 */
616 struct {
617 struct {
618 uint64_t val;
619 uint32_t size;
620 uint32_t type;
621 uint8_t pad[512 - 16];
622 } QEMU_PACKED footer_marker;
623
624 uint32_t magic;
625 VMDK4Header header;
626 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
627
628 struct {
629 uint64_t val;
630 uint32_t size;
631 uint32_t type;
632 uint8_t pad[512 - 16];
633 } QEMU_PACKED eos_marker;
634 } QEMU_PACKED footer;
635
636 ret = bdrv_pread(file,
637 bs->file->total_sectors * 512 - 1536,
638 &footer, sizeof(footer));
639 if (ret < 0) {
640 return ret;
641 }
642
643 /* Some sanity checks for the footer */
644 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
645 le32_to_cpu(footer.footer_marker.size) != 0 ||
646 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
647 le64_to_cpu(footer.eos_marker.val) != 0 ||
648 le32_to_cpu(footer.eos_marker.size) != 0 ||
649 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
650 {
651 return -EINVAL;
652 }
653
654 header = footer.header;
655 }
656
657 if (le32_to_cpu(header.version) > 3) {
658 char buf[64];
659 snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
660 le32_to_cpu(header.version));
661 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
662 bdrv_get_device_name(bs), "vmdk", buf);
663 return -ENOTSUP;
664 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
665 /* VMware KB 2064959 explains that version 3 added support for
666 * persistent changed block tracking (CBT), and backup software can
667 * read it as version=1 if it doesn't care about the changed area
668 * information. So we are safe to enable read only. */
669 error_setg(errp, "VMDK version 3 must be read only");
670 return -EINVAL;
671 }
672
673 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
674 error_setg(errp, "L2 table size too big");
675 return -EINVAL;
676 }
677
678 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
679 * le64_to_cpu(header.granularity);
680 if (l1_entry_sectors == 0) {
681 return -EINVAL;
682 }
683 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
684 / l1_entry_sectors;
685 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
686 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
687 }
688 if (bdrv_nb_sectors(file) < le64_to_cpu(header.grain_offset)) {
689 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
690 (int64_t)(le64_to_cpu(header.grain_offset)
691 * BDRV_SECTOR_SIZE));
692 return -EINVAL;
693 }
694
695 ret = vmdk_add_extent(bs, file, false,
696 le64_to_cpu(header.capacity),
697 le64_to_cpu(header.gd_offset) << 9,
698 l1_backup_offset,
699 l1_size,
700 le32_to_cpu(header.num_gtes_per_gt),
701 le64_to_cpu(header.granularity),
702 &extent,
703 errp);
704 if (ret < 0) {
705 return ret;
706 }
707 extent->compressed =
708 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
709 if (extent->compressed) {
710 g_free(s->create_type);
711 s->create_type = g_strdup("streamOptimized");
712 }
713 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
714 extent->version = le32_to_cpu(header.version);
715 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
716 ret = vmdk_init_tables(bs, extent, errp);
717 if (ret) {
718 /* free extent allocated by vmdk_add_extent */
719 vmdk_free_last_extent(bs);
720 }
721 return ret;
722 }
723
724 /* find an option value out of descriptor file */
725 static int vmdk_parse_description(const char *desc, const char *opt_name,
726 char *buf, int buf_size)
727 {
728 char *opt_pos, *opt_end;
729 const char *end = desc + strlen(desc);
730
731 opt_pos = strstr(desc, opt_name);
732 if (!opt_pos) {
733 return VMDK_ERROR;
734 }
735 /* Skip "=\"" following opt_name */
736 opt_pos += strlen(opt_name) + 2;
737 if (opt_pos >= end) {
738 return VMDK_ERROR;
739 }
740 opt_end = opt_pos;
741 while (opt_end < end && *opt_end != '"') {
742 opt_end++;
743 }
744 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
745 return VMDK_ERROR;
746 }
747 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
748 return VMDK_OK;
749 }
750
751 /* Open an extent file and append to bs array */
752 static int vmdk_open_sparse(BlockDriverState *bs,
753 BlockDriverState *file, int flags,
754 char *buf, Error **errp)
755 {
756 uint32_t magic;
757
758 magic = ldl_be_p(buf);
759 switch (magic) {
760 case VMDK3_MAGIC:
761 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
762 break;
763 case VMDK4_MAGIC:
764 return vmdk_open_vmdk4(bs, file, flags, errp);
765 break;
766 default:
767 error_setg(errp, "Image not in VMDK format");
768 return -EINVAL;
769 break;
770 }
771 }
772
773 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
774 const char *desc_file_path, Error **errp)
775 {
776 int ret;
777 char access[11];
778 char type[11];
779 char fname[512];
780 const char *p = desc;
781 int64_t sectors = 0;
782 int64_t flat_offset;
783 char extent_path[PATH_MAX];
784 BlockDriverState *extent_file;
785 BDRVVmdkState *s = bs->opaque;
786 VmdkExtent *extent;
787
788 while (*p) {
789 /* parse extent line in one of below formats:
790 *
791 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
792 * RW [size in sectors] SPARSE "file-name.vmdk"
793 * RW [size in sectors] VMFS "file-name.vmdk"
794 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
795 */
796 flat_offset = -1;
797 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
798 access, &sectors, type, fname, &flat_offset);
799 if (ret < 4 || strcmp(access, "RW")) {
800 goto next_line;
801 } else if (!strcmp(type, "FLAT")) {
802 if (ret != 5 || flat_offset < 0) {
803 error_setg(errp, "Invalid extent lines: \n%s", p);
804 return -EINVAL;
805 }
806 } else if (!strcmp(type, "VMFS")) {
807 if (ret == 4) {
808 flat_offset = 0;
809 } else {
810 error_setg(errp, "Invalid extent lines:\n%s", p);
811 return -EINVAL;
812 }
813 } else if (ret != 4) {
814 error_setg(errp, "Invalid extent lines:\n%s", p);
815 return -EINVAL;
816 }
817
818 if (sectors <= 0 ||
819 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
820 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
821 (strcmp(access, "RW"))) {
822 goto next_line;
823 }
824
825 path_combine(extent_path, sizeof(extent_path),
826 desc_file_path, fname);
827 extent_file = NULL;
828 ret = bdrv_open(&extent_file, extent_path, NULL, NULL,
829 bs->open_flags | BDRV_O_PROTOCOL, NULL, errp);
830 if (ret) {
831 return ret;
832 }
833
834 /* save to extents array */
835 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
836 /* FLAT extent */
837
838 ret = vmdk_add_extent(bs, extent_file, true, sectors,
839 0, 0, 0, 0, 0, &extent, errp);
840 if (ret < 0) {
841 bdrv_unref(extent_file);
842 return ret;
843 }
844 extent->flat_start_offset = flat_offset << 9;
845 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
846 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
847 char *buf = vmdk_read_desc(extent_file, 0, errp);
848 if (!buf) {
849 ret = -EINVAL;
850 } else {
851 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf, errp);
852 }
853 g_free(buf);
854 if (ret) {
855 bdrv_unref(extent_file);
856 return ret;
857 }
858 extent = &s->extents[s->num_extents - 1];
859 } else {
860 error_setg(errp, "Unsupported extent type '%s'", type);
861 bdrv_unref(extent_file);
862 return -ENOTSUP;
863 }
864 extent->type = g_strdup(type);
865 next_line:
866 /* move to next line */
867 while (*p) {
868 if (*p == '\n') {
869 p++;
870 break;
871 }
872 p++;
873 }
874 }
875 return 0;
876 }
877
878 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
879 Error **errp)
880 {
881 int ret;
882 char ct[128];
883 BDRVVmdkState *s = bs->opaque;
884
885 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
886 error_setg(errp, "invalid VMDK image descriptor");
887 ret = -EINVAL;
888 goto exit;
889 }
890 if (strcmp(ct, "monolithicFlat") &&
891 strcmp(ct, "vmfs") &&
892 strcmp(ct, "vmfsSparse") &&
893 strcmp(ct, "twoGbMaxExtentSparse") &&
894 strcmp(ct, "twoGbMaxExtentFlat")) {
895 error_setg(errp, "Unsupported image type '%s'", ct);
896 ret = -ENOTSUP;
897 goto exit;
898 }
899 s->create_type = g_strdup(ct);
900 s->desc_offset = 0;
901 ret = vmdk_parse_extents(buf, bs, bs->file->filename, errp);
902 exit:
903 return ret;
904 }
905
906 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
907 Error **errp)
908 {
909 char *buf = NULL;
910 int ret;
911 BDRVVmdkState *s = bs->opaque;
912 uint32_t magic;
913
914 buf = vmdk_read_desc(bs->file, 0, errp);
915 if (!buf) {
916 return -EINVAL;
917 }
918
919 magic = ldl_be_p(buf);
920 switch (magic) {
921 case VMDK3_MAGIC:
922 case VMDK4_MAGIC:
923 ret = vmdk_open_sparse(bs, bs->file, flags, buf, errp);
924 s->desc_offset = 0x200;
925 break;
926 default:
927 ret = vmdk_open_desc_file(bs, flags, buf, errp);
928 break;
929 }
930 if (ret) {
931 goto fail;
932 }
933
934 /* try to open parent images, if exist */
935 ret = vmdk_parent_open(bs);
936 if (ret) {
937 goto fail;
938 }
939 s->cid = vmdk_read_cid(bs, 0);
940 s->parent_cid = vmdk_read_cid(bs, 1);
941 qemu_co_mutex_init(&s->lock);
942
943 /* Disable migration when VMDK images are used */
944 error_set(&s->migration_blocker,
945 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
946 "vmdk", bdrv_get_device_name(bs), "live migration");
947 migrate_add_blocker(s->migration_blocker);
948 g_free(buf);
949 return 0;
950
951 fail:
952 g_free(buf);
953 g_free(s->create_type);
954 s->create_type = NULL;
955 vmdk_free_extents(bs);
956 return ret;
957 }
958
959
960 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
961 {
962 BDRVVmdkState *s = bs->opaque;
963 int i;
964
965 for (i = 0; i < s->num_extents; i++) {
966 if (!s->extents[i].flat) {
967 bs->bl.write_zeroes_alignment =
968 MAX(bs->bl.write_zeroes_alignment,
969 s->extents[i].cluster_sectors);
970 }
971 }
972 }
973
974 /**
975 * get_whole_cluster
976 *
977 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
978 * to the cluster at @cluster_sector_num.
979 *
980 * If @skip_start_sector < @skip_end_sector, the relative range
981 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
982 * it for call to write user data in the request.
983 */
984 static int get_whole_cluster(BlockDriverState *bs,
985 VmdkExtent *extent,
986 uint64_t cluster_sector_num,
987 uint64_t sector_num,
988 uint64_t skip_start_sector,
989 uint64_t skip_end_sector)
990 {
991 int ret = VMDK_OK;
992 int64_t cluster_bytes;
993 uint8_t *whole_grain;
994
995 /* For COW, align request sector_num to cluster start */
996 sector_num = QEMU_ALIGN_DOWN(sector_num, extent->cluster_sectors);
997 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
998 whole_grain = qemu_blockalign(bs, cluster_bytes);
999
1000 if (!bs->backing_hd) {
1001 memset(whole_grain, 0, skip_start_sector << BDRV_SECTOR_BITS);
1002 memset(whole_grain + (skip_end_sector << BDRV_SECTOR_BITS), 0,
1003 cluster_bytes - (skip_end_sector << BDRV_SECTOR_BITS));
1004 }
1005
1006 assert(skip_end_sector <= extent->cluster_sectors);
1007 /* we will be here if it's first write on non-exist grain(cluster).
1008 * try to read from parent image, if exist */
1009 if (bs->backing_hd && !vmdk_is_cid_valid(bs)) {
1010 ret = VMDK_ERROR;
1011 goto exit;
1012 }
1013
1014 /* Read backing data before skip range */
1015 if (skip_start_sector > 0) {
1016 if (bs->backing_hd) {
1017 ret = bdrv_read(bs->backing_hd, sector_num,
1018 whole_grain, skip_start_sector);
1019 if (ret < 0) {
1020 ret = VMDK_ERROR;
1021 goto exit;
1022 }
1023 }
1024 ret = bdrv_write(extent->file, cluster_sector_num, whole_grain,
1025 skip_start_sector);
1026 if (ret < 0) {
1027 ret = VMDK_ERROR;
1028 goto exit;
1029 }
1030 }
1031 /* Read backing data after skip range */
1032 if (skip_end_sector < extent->cluster_sectors) {
1033 if (bs->backing_hd) {
1034 ret = bdrv_read(bs->backing_hd, sector_num + skip_end_sector,
1035 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1036 extent->cluster_sectors - skip_end_sector);
1037 if (ret < 0) {
1038 ret = VMDK_ERROR;
1039 goto exit;
1040 }
1041 }
1042 ret = bdrv_write(extent->file, cluster_sector_num + skip_end_sector,
1043 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1044 extent->cluster_sectors - skip_end_sector);
1045 if (ret < 0) {
1046 ret = VMDK_ERROR;
1047 goto exit;
1048 }
1049 }
1050
1051 exit:
1052 qemu_vfree(whole_grain);
1053 return ret;
1054 }
1055
1056 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1057 uint32_t offset)
1058 {
1059 offset = cpu_to_le32(offset);
1060 /* update L2 table */
1061 if (bdrv_pwrite_sync(
1062 extent->file,
1063 ((int64_t)m_data->l2_offset * 512)
1064 + (m_data->l2_index * sizeof(offset)),
1065 &offset, sizeof(offset)) < 0) {
1066 return VMDK_ERROR;
1067 }
1068 /* update backup L2 table */
1069 if (extent->l1_backup_table_offset != 0) {
1070 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1071 if (bdrv_pwrite_sync(
1072 extent->file,
1073 ((int64_t)m_data->l2_offset * 512)
1074 + (m_data->l2_index * sizeof(offset)),
1075 &offset, sizeof(offset)) < 0) {
1076 return VMDK_ERROR;
1077 }
1078 }
1079 if (m_data->l2_cache_entry) {
1080 *m_data->l2_cache_entry = offset;
1081 }
1082
1083 return VMDK_OK;
1084 }
1085
1086 /**
1087 * get_cluster_offset
1088 *
1089 * Look up cluster offset in extent file by sector number, and store in
1090 * @cluster_offset.
1091 *
1092 * For flat extents, the start offset as parsed from the description file is
1093 * returned.
1094 *
1095 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1096 * offset for a new cluster and update L2 cache. If there is a backing file,
1097 * COW is done before returning; otherwise, zeroes are written to the allocated
1098 * cluster. Both COW and zero writing skips the sector range
1099 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1100 * has new data to write there.
1101 *
1102 * Returns: VMDK_OK if cluster exists and mapped in the image.
1103 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1104 * VMDK_ERROR if failed.
1105 */
1106 static int get_cluster_offset(BlockDriverState *bs,
1107 VmdkExtent *extent,
1108 VmdkMetaData *m_data,
1109 uint64_t offset,
1110 bool allocate,
1111 uint64_t *cluster_offset,
1112 uint64_t skip_start_sector,
1113 uint64_t skip_end_sector)
1114 {
1115 unsigned int l1_index, l2_offset, l2_index;
1116 int min_index, i, j;
1117 uint32_t min_count, *l2_table;
1118 bool zeroed = false;
1119 int64_t ret;
1120 int64_t cluster_sector;
1121
1122 if (m_data) {
1123 m_data->valid = 0;
1124 }
1125 if (extent->flat) {
1126 *cluster_offset = extent->flat_start_offset;
1127 return VMDK_OK;
1128 }
1129
1130 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1131 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1132 if (l1_index >= extent->l1_size) {
1133 return VMDK_ERROR;
1134 }
1135 l2_offset = extent->l1_table[l1_index];
1136 if (!l2_offset) {
1137 return VMDK_UNALLOC;
1138 }
1139 for (i = 0; i < L2_CACHE_SIZE; i++) {
1140 if (l2_offset == extent->l2_cache_offsets[i]) {
1141 /* increment the hit count */
1142 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1143 for (j = 0; j < L2_CACHE_SIZE; j++) {
1144 extent->l2_cache_counts[j] >>= 1;
1145 }
1146 }
1147 l2_table = extent->l2_cache + (i * extent->l2_size);
1148 goto found;
1149 }
1150 }
1151 /* not found: load a new entry in the least used one */
1152 min_index = 0;
1153 min_count = 0xffffffff;
1154 for (i = 0; i < L2_CACHE_SIZE; i++) {
1155 if (extent->l2_cache_counts[i] < min_count) {
1156 min_count = extent->l2_cache_counts[i];
1157 min_index = i;
1158 }
1159 }
1160 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1161 if (bdrv_pread(
1162 extent->file,
1163 (int64_t)l2_offset * 512,
1164 l2_table,
1165 extent->l2_size * sizeof(uint32_t)
1166 ) != extent->l2_size * sizeof(uint32_t)) {
1167 return VMDK_ERROR;
1168 }
1169
1170 extent->l2_cache_offsets[min_index] = l2_offset;
1171 extent->l2_cache_counts[min_index] = 1;
1172 found:
1173 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1174 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1175
1176 if (m_data) {
1177 m_data->valid = 1;
1178 m_data->l1_index = l1_index;
1179 m_data->l2_index = l2_index;
1180 m_data->l2_offset = l2_offset;
1181 m_data->l2_cache_entry = &l2_table[l2_index];
1182 }
1183 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1184 zeroed = true;
1185 }
1186
1187 if (!cluster_sector || zeroed) {
1188 if (!allocate) {
1189 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1190 }
1191
1192 cluster_sector = extent->next_cluster_sector;
1193 extent->next_cluster_sector += extent->cluster_sectors;
1194
1195 /* First of all we write grain itself, to avoid race condition
1196 * that may to corrupt the image.
1197 * This problem may occur because of insufficient space on host disk
1198 * or inappropriate VM shutdown.
1199 */
1200 ret = get_whole_cluster(bs, extent,
1201 cluster_sector,
1202 offset >> BDRV_SECTOR_BITS,
1203 skip_start_sector, skip_end_sector);
1204 if (ret) {
1205 return ret;
1206 }
1207 }
1208 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1209 return VMDK_OK;
1210 }
1211
1212 static VmdkExtent *find_extent(BDRVVmdkState *s,
1213 int64_t sector_num, VmdkExtent *start_hint)
1214 {
1215 VmdkExtent *extent = start_hint;
1216
1217 if (!extent) {
1218 extent = &s->extents[0];
1219 }
1220 while (extent < &s->extents[s->num_extents]) {
1221 if (sector_num < extent->end_sector) {
1222 return extent;
1223 }
1224 extent++;
1225 }
1226 return NULL;
1227 }
1228
1229 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1230 int64_t sector_num, int nb_sectors, int *pnum)
1231 {
1232 BDRVVmdkState *s = bs->opaque;
1233 int64_t index_in_cluster, n, ret;
1234 uint64_t offset;
1235 VmdkExtent *extent;
1236
1237 extent = find_extent(s, sector_num, NULL);
1238 if (!extent) {
1239 return 0;
1240 }
1241 qemu_co_mutex_lock(&s->lock);
1242 ret = get_cluster_offset(bs, extent, NULL,
1243 sector_num * 512, false, &offset,
1244 0, 0);
1245 qemu_co_mutex_unlock(&s->lock);
1246
1247 switch (ret) {
1248 case VMDK_ERROR:
1249 ret = -EIO;
1250 break;
1251 case VMDK_UNALLOC:
1252 ret = 0;
1253 break;
1254 case VMDK_ZEROED:
1255 ret = BDRV_BLOCK_ZERO;
1256 break;
1257 case VMDK_OK:
1258 ret = BDRV_BLOCK_DATA;
1259 if (extent->file == bs->file && !extent->compressed) {
1260 ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1261 }
1262
1263 break;
1264 }
1265
1266 index_in_cluster = sector_num % extent->cluster_sectors;
1267 n = extent->cluster_sectors - index_in_cluster;
1268 if (n > nb_sectors) {
1269 n = nb_sectors;
1270 }
1271 *pnum = n;
1272 return ret;
1273 }
1274
1275 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1276 int64_t offset_in_cluster, const uint8_t *buf,
1277 int nb_sectors, int64_t sector_num)
1278 {
1279 int ret;
1280 VmdkGrainMarker *data = NULL;
1281 uLongf buf_len;
1282 const uint8_t *write_buf = buf;
1283 int write_len = nb_sectors * 512;
1284
1285 if (extent->compressed) {
1286 if (!extent->has_marker) {
1287 ret = -EINVAL;
1288 goto out;
1289 }
1290 buf_len = (extent->cluster_sectors << 9) * 2;
1291 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1292 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1293 buf_len == 0) {
1294 ret = -EINVAL;
1295 goto out;
1296 }
1297 data->lba = sector_num;
1298 data->size = buf_len;
1299 write_buf = (uint8_t *)data;
1300 write_len = buf_len + sizeof(VmdkGrainMarker);
1301 }
1302 ret = bdrv_pwrite(extent->file,
1303 cluster_offset + offset_in_cluster,
1304 write_buf,
1305 write_len);
1306 if (ret != write_len) {
1307 ret = ret < 0 ? ret : -EIO;
1308 goto out;
1309 }
1310 ret = 0;
1311 out:
1312 g_free(data);
1313 return ret;
1314 }
1315
1316 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1317 int64_t offset_in_cluster, uint8_t *buf,
1318 int nb_sectors)
1319 {
1320 int ret;
1321 int cluster_bytes, buf_bytes;
1322 uint8_t *cluster_buf, *compressed_data;
1323 uint8_t *uncomp_buf;
1324 uint32_t data_len;
1325 VmdkGrainMarker *marker;
1326 uLongf buf_len;
1327
1328
1329 if (!extent->compressed) {
1330 ret = bdrv_pread(extent->file,
1331 cluster_offset + offset_in_cluster,
1332 buf, nb_sectors * 512);
1333 if (ret == nb_sectors * 512) {
1334 return 0;
1335 } else {
1336 return -EIO;
1337 }
1338 }
1339 cluster_bytes = extent->cluster_sectors * 512;
1340 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1341 buf_bytes = cluster_bytes * 2;
1342 cluster_buf = g_malloc(buf_bytes);
1343 uncomp_buf = g_malloc(cluster_bytes);
1344 ret = bdrv_pread(extent->file,
1345 cluster_offset,
1346 cluster_buf, buf_bytes);
1347 if (ret < 0) {
1348 goto out;
1349 }
1350 compressed_data = cluster_buf;
1351 buf_len = cluster_bytes;
1352 data_len = cluster_bytes;
1353 if (extent->has_marker) {
1354 marker = (VmdkGrainMarker *)cluster_buf;
1355 compressed_data = marker->data;
1356 data_len = le32_to_cpu(marker->size);
1357 }
1358 if (!data_len || data_len > buf_bytes) {
1359 ret = -EINVAL;
1360 goto out;
1361 }
1362 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1363 if (ret != Z_OK) {
1364 ret = -EINVAL;
1365 goto out;
1366
1367 }
1368 if (offset_in_cluster < 0 ||
1369 offset_in_cluster + nb_sectors * 512 > buf_len) {
1370 ret = -EINVAL;
1371 goto out;
1372 }
1373 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1374 ret = 0;
1375
1376 out:
1377 g_free(uncomp_buf);
1378 g_free(cluster_buf);
1379 return ret;
1380 }
1381
1382 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1383 uint8_t *buf, int nb_sectors)
1384 {
1385 BDRVVmdkState *s = bs->opaque;
1386 int ret;
1387 uint64_t n, index_in_cluster;
1388 uint64_t extent_begin_sector, extent_relative_sector_num;
1389 VmdkExtent *extent = NULL;
1390 uint64_t cluster_offset;
1391
1392 while (nb_sectors > 0) {
1393 extent = find_extent(s, sector_num, extent);
1394 if (!extent) {
1395 return -EIO;
1396 }
1397 ret = get_cluster_offset(bs, extent, NULL,
1398 sector_num << 9, false, &cluster_offset,
1399 0, 0);
1400 extent_begin_sector = extent->end_sector - extent->sectors;
1401 extent_relative_sector_num = sector_num - extent_begin_sector;
1402 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1403 n = extent->cluster_sectors - index_in_cluster;
1404 if (n > nb_sectors) {
1405 n = nb_sectors;
1406 }
1407 if (ret != VMDK_OK) {
1408 /* if not allocated, try to read from parent image, if exist */
1409 if (bs->backing_hd && ret != VMDK_ZEROED) {
1410 if (!vmdk_is_cid_valid(bs)) {
1411 return -EINVAL;
1412 }
1413 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1414 if (ret < 0) {
1415 return ret;
1416 }
1417 } else {
1418 memset(buf, 0, 512 * n);
1419 }
1420 } else {
1421 ret = vmdk_read_extent(extent,
1422 cluster_offset, index_in_cluster * 512,
1423 buf, n);
1424 if (ret) {
1425 return ret;
1426 }
1427 }
1428 nb_sectors -= n;
1429 sector_num += n;
1430 buf += n * 512;
1431 }
1432 return 0;
1433 }
1434
1435 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1436 uint8_t *buf, int nb_sectors)
1437 {
1438 int ret;
1439 BDRVVmdkState *s = bs->opaque;
1440 qemu_co_mutex_lock(&s->lock);
1441 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1442 qemu_co_mutex_unlock(&s->lock);
1443 return ret;
1444 }
1445
1446 /**
1447 * vmdk_write:
1448 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1449 * if possible, otherwise return -ENOTSUP.
1450 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1451 * with each cluster. By dry run we can find if the zero write
1452 * is possible without modifying image data.
1453 *
1454 * Returns: error code with 0 for success.
1455 */
1456 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1457 const uint8_t *buf, int nb_sectors,
1458 bool zeroed, bool zero_dry_run)
1459 {
1460 BDRVVmdkState *s = bs->opaque;
1461 VmdkExtent *extent = NULL;
1462 int ret;
1463 int64_t index_in_cluster, n;
1464 uint64_t extent_begin_sector, extent_relative_sector_num;
1465 uint64_t cluster_offset;
1466 VmdkMetaData m_data;
1467
1468 if (sector_num > bs->total_sectors) {
1469 error_report("Wrong offset: sector_num=0x%" PRIx64
1470 " total_sectors=0x%" PRIx64 "\n",
1471 sector_num, bs->total_sectors);
1472 return -EIO;
1473 }
1474
1475 while (nb_sectors > 0) {
1476 extent = find_extent(s, sector_num, extent);
1477 if (!extent) {
1478 return -EIO;
1479 }
1480 extent_begin_sector = extent->end_sector - extent->sectors;
1481 extent_relative_sector_num = sector_num - extent_begin_sector;
1482 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1483 n = extent->cluster_sectors - index_in_cluster;
1484 if (n > nb_sectors) {
1485 n = nb_sectors;
1486 }
1487 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1488 !(extent->compressed || zeroed),
1489 &cluster_offset,
1490 index_in_cluster, index_in_cluster + n);
1491 if (extent->compressed) {
1492 if (ret == VMDK_OK) {
1493 /* Refuse write to allocated cluster for streamOptimized */
1494 error_report("Could not write to allocated cluster"
1495 " for streamOptimized");
1496 return -EIO;
1497 } else {
1498 /* allocate */
1499 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1500 true, &cluster_offset, 0, 0);
1501 }
1502 }
1503 if (ret == VMDK_ERROR) {
1504 return -EINVAL;
1505 }
1506 if (zeroed) {
1507 /* Do zeroed write, buf is ignored */
1508 if (extent->has_zero_grain &&
1509 index_in_cluster == 0 &&
1510 n >= extent->cluster_sectors) {
1511 n = extent->cluster_sectors;
1512 if (!zero_dry_run) {
1513 /* update L2 tables */
1514 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1515 != VMDK_OK) {
1516 return -EIO;
1517 }
1518 }
1519 } else {
1520 return -ENOTSUP;
1521 }
1522 } else {
1523 ret = vmdk_write_extent(extent,
1524 cluster_offset, index_in_cluster * 512,
1525 buf, n, sector_num);
1526 if (ret) {
1527 return ret;
1528 }
1529 if (m_data.valid) {
1530 /* update L2 tables */
1531 if (vmdk_L2update(extent, &m_data,
1532 cluster_offset >> BDRV_SECTOR_BITS)
1533 != VMDK_OK) {
1534 return -EIO;
1535 }
1536 }
1537 }
1538 nb_sectors -= n;
1539 sector_num += n;
1540 buf += n * 512;
1541
1542 /* update CID on the first write every time the virtual disk is
1543 * opened */
1544 if (!s->cid_updated) {
1545 ret = vmdk_write_cid(bs, g_random_int());
1546 if (ret < 0) {
1547 return ret;
1548 }
1549 s->cid_updated = true;
1550 }
1551 }
1552 return 0;
1553 }
1554
1555 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1556 const uint8_t *buf, int nb_sectors)
1557 {
1558 int ret;
1559 BDRVVmdkState *s = bs->opaque;
1560 qemu_co_mutex_lock(&s->lock);
1561 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1562 qemu_co_mutex_unlock(&s->lock);
1563 return ret;
1564 }
1565
1566 static int vmdk_write_compressed(BlockDriverState *bs,
1567 int64_t sector_num,
1568 const uint8_t *buf,
1569 int nb_sectors)
1570 {
1571 BDRVVmdkState *s = bs->opaque;
1572 if (s->num_extents == 1 && s->extents[0].compressed) {
1573 return vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1574 } else {
1575 return -ENOTSUP;
1576 }
1577 }
1578
1579 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1580 int64_t sector_num,
1581 int nb_sectors,
1582 BdrvRequestFlags flags)
1583 {
1584 int ret;
1585 BDRVVmdkState *s = bs->opaque;
1586 qemu_co_mutex_lock(&s->lock);
1587 /* write zeroes could fail if sectors not aligned to cluster, test it with
1588 * dry_run == true before really updating image */
1589 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1590 if (!ret) {
1591 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1592 }
1593 qemu_co_mutex_unlock(&s->lock);
1594 return ret;
1595 }
1596
1597 static int vmdk_create_extent(const char *filename, int64_t filesize,
1598 bool flat, bool compress, bool zeroed_grain,
1599 QemuOpts *opts, Error **errp)
1600 {
1601 int ret, i;
1602 BlockDriverState *bs = NULL;
1603 VMDK4Header header;
1604 Error *local_err = NULL;
1605 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1606 uint32_t *gd_buf = NULL;
1607 int gd_buf_size;
1608
1609 ret = bdrv_create_file(filename, opts, &local_err);
1610 if (ret < 0) {
1611 error_propagate(errp, local_err);
1612 goto exit;
1613 }
1614
1615 assert(bs == NULL);
1616 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1617 NULL, &local_err);
1618 if (ret < 0) {
1619 error_propagate(errp, local_err);
1620 goto exit;
1621 }
1622
1623 if (flat) {
1624 ret = bdrv_truncate(bs, filesize);
1625 if (ret < 0) {
1626 error_setg_errno(errp, -ret, "Could not truncate file");
1627 }
1628 goto exit;
1629 }
1630 magic = cpu_to_be32(VMDK4_MAGIC);
1631 memset(&header, 0, sizeof(header));
1632 header.version = zeroed_grain ? 2 : 1;
1633 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1634 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1635 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1636 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1637 header.capacity = filesize / BDRV_SECTOR_SIZE;
1638 header.granularity = 128;
1639 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1640
1641 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1642 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1643 BDRV_SECTOR_SIZE);
1644 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1645 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1646
1647 header.desc_offset = 1;
1648 header.desc_size = 20;
1649 header.rgd_offset = header.desc_offset + header.desc_size;
1650 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1651 header.grain_offset =
1652 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1653 header.granularity);
1654 /* swap endianness for all header fields */
1655 header.version = cpu_to_le32(header.version);
1656 header.flags = cpu_to_le32(header.flags);
1657 header.capacity = cpu_to_le64(header.capacity);
1658 header.granularity = cpu_to_le64(header.granularity);
1659 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1660 header.desc_offset = cpu_to_le64(header.desc_offset);
1661 header.desc_size = cpu_to_le64(header.desc_size);
1662 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1663 header.gd_offset = cpu_to_le64(header.gd_offset);
1664 header.grain_offset = cpu_to_le64(header.grain_offset);
1665 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1666
1667 header.check_bytes[0] = 0xa;
1668 header.check_bytes[1] = 0x20;
1669 header.check_bytes[2] = 0xd;
1670 header.check_bytes[3] = 0xa;
1671
1672 /* write all the data */
1673 ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1674 if (ret < 0) {
1675 error_set(errp, QERR_IO_ERROR);
1676 goto exit;
1677 }
1678 ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1679 if (ret < 0) {
1680 error_set(errp, QERR_IO_ERROR);
1681 goto exit;
1682 }
1683
1684 ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1685 if (ret < 0) {
1686 error_setg_errno(errp, -ret, "Could not truncate file");
1687 goto exit;
1688 }
1689
1690 /* write grain directory */
1691 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1692 gd_buf = g_malloc0(gd_buf_size);
1693 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1694 i < gt_count; i++, tmp += gt_size) {
1695 gd_buf[i] = cpu_to_le32(tmp);
1696 }
1697 ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1698 gd_buf, gd_buf_size);
1699 if (ret < 0) {
1700 error_set(errp, QERR_IO_ERROR);
1701 goto exit;
1702 }
1703
1704 /* write backup grain directory */
1705 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1706 i < gt_count; i++, tmp += gt_size) {
1707 gd_buf[i] = cpu_to_le32(tmp);
1708 }
1709 ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1710 gd_buf, gd_buf_size);
1711 if (ret < 0) {
1712 error_set(errp, QERR_IO_ERROR);
1713 goto exit;
1714 }
1715
1716 ret = 0;
1717 exit:
1718 if (bs) {
1719 bdrv_unref(bs);
1720 }
1721 g_free(gd_buf);
1722 return ret;
1723 }
1724
1725 static int filename_decompose(const char *filename, char *path, char *prefix,
1726 char *postfix, size_t buf_len, Error **errp)
1727 {
1728 const char *p, *q;
1729
1730 if (filename == NULL || !strlen(filename)) {
1731 error_setg(errp, "No filename provided");
1732 return VMDK_ERROR;
1733 }
1734 p = strrchr(filename, '/');
1735 if (p == NULL) {
1736 p = strrchr(filename, '\\');
1737 }
1738 if (p == NULL) {
1739 p = strrchr(filename, ':');
1740 }
1741 if (p != NULL) {
1742 p++;
1743 if (p - filename >= buf_len) {
1744 return VMDK_ERROR;
1745 }
1746 pstrcpy(path, p - filename + 1, filename);
1747 } else {
1748 p = filename;
1749 path[0] = '\0';
1750 }
1751 q = strrchr(p, '.');
1752 if (q == NULL) {
1753 pstrcpy(prefix, buf_len, p);
1754 postfix[0] = '\0';
1755 } else {
1756 if (q - p >= buf_len) {
1757 return VMDK_ERROR;
1758 }
1759 pstrcpy(prefix, q - p + 1, p);
1760 pstrcpy(postfix, buf_len, q);
1761 }
1762 return VMDK_OK;
1763 }
1764
1765 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1766 {
1767 int idx = 0;
1768 BlockDriverState *new_bs = NULL;
1769 Error *local_err = NULL;
1770 char *desc = NULL;
1771 int64_t total_size = 0, filesize;
1772 char *adapter_type = NULL;
1773 char *backing_file = NULL;
1774 char *fmt = NULL;
1775 int flags = 0;
1776 int ret = 0;
1777 bool flat, split, compress;
1778 GString *ext_desc_lines;
1779 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1780 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1781 const char *desc_extent_line;
1782 char parent_desc_line[BUF_SIZE] = "";
1783 uint32_t parent_cid = 0xffffffff;
1784 uint32_t number_heads = 16;
1785 bool zeroed_grain = false;
1786 uint32_t desc_offset = 0, desc_len;
1787 const char desc_template[] =
1788 "# Disk DescriptorFile\n"
1789 "version=1\n"
1790 "CID=%" PRIx32 "\n"
1791 "parentCID=%" PRIx32 "\n"
1792 "createType=\"%s\"\n"
1793 "%s"
1794 "\n"
1795 "# Extent description\n"
1796 "%s"
1797 "\n"
1798 "# The Disk Data Base\n"
1799 "#DDB\n"
1800 "\n"
1801 "ddb.virtualHWVersion = \"%d\"\n"
1802 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1803 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1804 "ddb.geometry.sectors = \"63\"\n"
1805 "ddb.adapterType = \"%s\"\n";
1806
1807 ext_desc_lines = g_string_new(NULL);
1808
1809 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1810 ret = -EINVAL;
1811 goto exit;
1812 }
1813 /* Read out options */
1814 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1815 BDRV_SECTOR_SIZE);
1816 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1817 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1818 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1819 flags |= BLOCK_FLAG_COMPAT6;
1820 }
1821 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1822 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1823 zeroed_grain = true;
1824 }
1825
1826 if (!adapter_type) {
1827 adapter_type = g_strdup("ide");
1828 } else if (strcmp(adapter_type, "ide") &&
1829 strcmp(adapter_type, "buslogic") &&
1830 strcmp(adapter_type, "lsilogic") &&
1831 strcmp(adapter_type, "legacyESX")) {
1832 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1833 ret = -EINVAL;
1834 goto exit;
1835 }
1836 if (strcmp(adapter_type, "ide") != 0) {
1837 /* that's the number of heads with which vmware operates when
1838 creating, exporting, etc. vmdk files with a non-ide adapter type */
1839 number_heads = 255;
1840 }
1841 if (!fmt) {
1842 /* Default format to monolithicSparse */
1843 fmt = g_strdup("monolithicSparse");
1844 } else if (strcmp(fmt, "monolithicFlat") &&
1845 strcmp(fmt, "monolithicSparse") &&
1846 strcmp(fmt, "twoGbMaxExtentSparse") &&
1847 strcmp(fmt, "twoGbMaxExtentFlat") &&
1848 strcmp(fmt, "streamOptimized")) {
1849 error_setg(errp, "Unknown subformat: '%s'", fmt);
1850 ret = -EINVAL;
1851 goto exit;
1852 }
1853 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1854 strcmp(fmt, "twoGbMaxExtentSparse"));
1855 flat = !(strcmp(fmt, "monolithicFlat") &&
1856 strcmp(fmt, "twoGbMaxExtentFlat"));
1857 compress = !strcmp(fmt, "streamOptimized");
1858 if (flat) {
1859 desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1860 } else {
1861 desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1862 }
1863 if (flat && backing_file) {
1864 error_setg(errp, "Flat image can't have backing file");
1865 ret = -ENOTSUP;
1866 goto exit;
1867 }
1868 if (flat && zeroed_grain) {
1869 error_setg(errp, "Flat image can't enable zeroed grain");
1870 ret = -ENOTSUP;
1871 goto exit;
1872 }
1873 if (backing_file) {
1874 BlockDriverState *bs = NULL;
1875 ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_NO_BACKING, NULL,
1876 errp);
1877 if (ret != 0) {
1878 goto exit;
1879 }
1880 if (strcmp(bs->drv->format_name, "vmdk")) {
1881 bdrv_unref(bs);
1882 ret = -EINVAL;
1883 goto exit;
1884 }
1885 parent_cid = vmdk_read_cid(bs, 0);
1886 bdrv_unref(bs);
1887 snprintf(parent_desc_line, sizeof(parent_desc_line),
1888 "parentFileNameHint=\"%s\"", backing_file);
1889 }
1890
1891 /* Create extents */
1892 filesize = total_size;
1893 while (filesize > 0) {
1894 char desc_line[BUF_SIZE];
1895 char ext_filename[PATH_MAX];
1896 char desc_filename[PATH_MAX];
1897 int64_t size = filesize;
1898
1899 if (split && size > split_size) {
1900 size = split_size;
1901 }
1902 if (split) {
1903 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1904 prefix, flat ? 'f' : 's', ++idx, postfix);
1905 } else if (flat) {
1906 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1907 prefix, postfix);
1908 } else {
1909 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1910 prefix, postfix);
1911 }
1912 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1913 path, desc_filename);
1914
1915 if (vmdk_create_extent(ext_filename, size,
1916 flat, compress, zeroed_grain, opts, errp)) {
1917 ret = -EINVAL;
1918 goto exit;
1919 }
1920 filesize -= size;
1921
1922 /* Format description line */
1923 snprintf(desc_line, sizeof(desc_line),
1924 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1925 g_string_append(ext_desc_lines, desc_line);
1926 }
1927 /* generate descriptor file */
1928 desc = g_strdup_printf(desc_template,
1929 g_random_int(),
1930 parent_cid,
1931 fmt,
1932 parent_desc_line,
1933 ext_desc_lines->str,
1934 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1935 total_size /
1936 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1937 number_heads,
1938 adapter_type);
1939 desc_len = strlen(desc);
1940 /* the descriptor offset = 0x200 */
1941 if (!split && !flat) {
1942 desc_offset = 0x200;
1943 } else {
1944 ret = bdrv_create_file(filename, opts, &local_err);
1945 if (ret < 0) {
1946 error_propagate(errp, local_err);
1947 goto exit;
1948 }
1949 }
1950 assert(new_bs == NULL);
1951 ret = bdrv_open(&new_bs, filename, NULL, NULL,
1952 BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
1953 if (ret < 0) {
1954 error_propagate(errp, local_err);
1955 goto exit;
1956 }
1957 ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1958 if (ret < 0) {
1959 error_setg_errno(errp, -ret, "Could not write description");
1960 goto exit;
1961 }
1962 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1963 * for description file */
1964 if (desc_offset == 0) {
1965 ret = bdrv_truncate(new_bs, desc_len);
1966 if (ret < 0) {
1967 error_setg_errno(errp, -ret, "Could not truncate file");
1968 }
1969 }
1970 exit:
1971 if (new_bs) {
1972 bdrv_unref(new_bs);
1973 }
1974 g_free(adapter_type);
1975 g_free(backing_file);
1976 g_free(fmt);
1977 g_free(desc);
1978 g_string_free(ext_desc_lines, true);
1979 return ret;
1980 }
1981
1982 static void vmdk_close(BlockDriverState *bs)
1983 {
1984 BDRVVmdkState *s = bs->opaque;
1985
1986 vmdk_free_extents(bs);
1987 g_free(s->create_type);
1988
1989 migrate_del_blocker(s->migration_blocker);
1990 error_free(s->migration_blocker);
1991 }
1992
1993 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1994 {
1995 BDRVVmdkState *s = bs->opaque;
1996 int i, err;
1997 int ret = 0;
1998
1999 for (i = 0; i < s->num_extents; i++) {
2000 err = bdrv_co_flush(s->extents[i].file);
2001 if (err < 0) {
2002 ret = err;
2003 }
2004 }
2005 return ret;
2006 }
2007
2008 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2009 {
2010 int i;
2011 int64_t ret = 0;
2012 int64_t r;
2013 BDRVVmdkState *s = bs->opaque;
2014
2015 ret = bdrv_get_allocated_file_size(bs->file);
2016 if (ret < 0) {
2017 return ret;
2018 }
2019 for (i = 0; i < s->num_extents; i++) {
2020 if (s->extents[i].file == bs->file) {
2021 continue;
2022 }
2023 r = bdrv_get_allocated_file_size(s->extents[i].file);
2024 if (r < 0) {
2025 return r;
2026 }
2027 ret += r;
2028 }
2029 return ret;
2030 }
2031
2032 static int vmdk_has_zero_init(BlockDriverState *bs)
2033 {
2034 int i;
2035 BDRVVmdkState *s = bs->opaque;
2036
2037 /* If has a flat extent and its underlying storage doesn't have zero init,
2038 * return 0. */
2039 for (i = 0; i < s->num_extents; i++) {
2040 if (s->extents[i].flat) {
2041 if (!bdrv_has_zero_init(s->extents[i].file)) {
2042 return 0;
2043 }
2044 }
2045 }
2046 return 1;
2047 }
2048
2049 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2050 {
2051 ImageInfo *info = g_new0(ImageInfo, 1);
2052
2053 *info = (ImageInfo){
2054 .filename = g_strdup(extent->file->filename),
2055 .format = g_strdup(extent->type),
2056 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2057 .compressed = extent->compressed,
2058 .has_compressed = extent->compressed,
2059 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2060 .has_cluster_size = !extent->flat,
2061 };
2062
2063 return info;
2064 }
2065
2066 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2067 BdrvCheckMode fix)
2068 {
2069 BDRVVmdkState *s = bs->opaque;
2070 VmdkExtent *extent = NULL;
2071 int64_t sector_num = 0;
2072 int64_t total_sectors = bdrv_nb_sectors(bs);
2073 int ret;
2074 uint64_t cluster_offset;
2075
2076 if (fix) {
2077 return -ENOTSUP;
2078 }
2079
2080 for (;;) {
2081 if (sector_num >= total_sectors) {
2082 return 0;
2083 }
2084 extent = find_extent(s, sector_num, extent);
2085 if (!extent) {
2086 fprintf(stderr,
2087 "ERROR: could not find extent for sector %" PRId64 "\n",
2088 sector_num);
2089 break;
2090 }
2091 ret = get_cluster_offset(bs, extent, NULL,
2092 sector_num << BDRV_SECTOR_BITS,
2093 false, &cluster_offset, 0, 0);
2094 if (ret == VMDK_ERROR) {
2095 fprintf(stderr,
2096 "ERROR: could not get cluster_offset for sector %"
2097 PRId64 "\n", sector_num);
2098 break;
2099 }
2100 if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2101 fprintf(stderr,
2102 "ERROR: cluster offset for sector %"
2103 PRId64 " points after EOF\n", sector_num);
2104 break;
2105 }
2106 sector_num += extent->cluster_sectors;
2107 }
2108
2109 result->corruptions++;
2110 return 0;
2111 }
2112
2113 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2114 {
2115 int i;
2116 BDRVVmdkState *s = bs->opaque;
2117 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2118 ImageInfoList **next;
2119
2120 *spec_info = (ImageInfoSpecific){
2121 .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2122 {
2123 .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2124 },
2125 };
2126
2127 *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2128 .create_type = g_strdup(s->create_type),
2129 .cid = s->cid,
2130 .parent_cid = s->parent_cid,
2131 };
2132
2133 next = &spec_info->vmdk->extents;
2134 for (i = 0; i < s->num_extents; i++) {
2135 *next = g_new0(ImageInfoList, 1);
2136 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2137 (*next)->next = NULL;
2138 next = &(*next)->next;
2139 }
2140
2141 return spec_info;
2142 }
2143
2144 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2145 {
2146 return a->flat == b->flat &&
2147 a->compressed == b->compressed &&
2148 (a->flat || a->cluster_sectors == b->cluster_sectors);
2149 }
2150
2151 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2152 {
2153 int i;
2154 BDRVVmdkState *s = bs->opaque;
2155 assert(s->num_extents);
2156
2157 /* See if we have multiple extents but they have different cases */
2158 for (i = 1; i < s->num_extents; i++) {
2159 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2160 return -ENOTSUP;
2161 }
2162 }
2163 bdi->needs_compressed_writes = s->extents[0].compressed;
2164 if (!s->extents[0].flat) {
2165 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2166 }
2167 return 0;
2168 }
2169
2170 static void vmdk_detach_aio_context(BlockDriverState *bs)
2171 {
2172 BDRVVmdkState *s = bs->opaque;
2173 int i;
2174
2175 for (i = 0; i < s->num_extents; i++) {
2176 bdrv_detach_aio_context(s->extents[i].file);
2177 }
2178 }
2179
2180 static void vmdk_attach_aio_context(BlockDriverState *bs,
2181 AioContext *new_context)
2182 {
2183 BDRVVmdkState *s = bs->opaque;
2184 int i;
2185
2186 for (i = 0; i < s->num_extents; i++) {
2187 bdrv_attach_aio_context(s->extents[i].file, new_context);
2188 }
2189 }
2190
2191 static QemuOptsList vmdk_create_opts = {
2192 .name = "vmdk-create-opts",
2193 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2194 .desc = {
2195 {
2196 .name = BLOCK_OPT_SIZE,
2197 .type = QEMU_OPT_SIZE,
2198 .help = "Virtual disk size"
2199 },
2200 {
2201 .name = BLOCK_OPT_ADAPTER_TYPE,
2202 .type = QEMU_OPT_STRING,
2203 .help = "Virtual adapter type, can be one of "
2204 "ide (default), lsilogic, buslogic or legacyESX"
2205 },
2206 {
2207 .name = BLOCK_OPT_BACKING_FILE,
2208 .type = QEMU_OPT_STRING,
2209 .help = "File name of a base image"
2210 },
2211 {
2212 .name = BLOCK_OPT_COMPAT6,
2213 .type = QEMU_OPT_BOOL,
2214 .help = "VMDK version 6 image",
2215 .def_value_str = "off"
2216 },
2217 {
2218 .name = BLOCK_OPT_SUBFMT,
2219 .type = QEMU_OPT_STRING,
2220 .help =
2221 "VMDK flat extent format, can be one of "
2222 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2223 },
2224 {
2225 .name = BLOCK_OPT_ZEROED_GRAIN,
2226 .type = QEMU_OPT_BOOL,
2227 .help = "Enable efficient zero writes "
2228 "using the zeroed-grain GTE feature"
2229 },
2230 { /* end of list */ }
2231 }
2232 };
2233
2234 static BlockDriver bdrv_vmdk = {
2235 .format_name = "vmdk",
2236 .instance_size = sizeof(BDRVVmdkState),
2237 .bdrv_probe = vmdk_probe,
2238 .bdrv_open = vmdk_open,
2239 .bdrv_check = vmdk_check,
2240 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2241 .bdrv_read = vmdk_co_read,
2242 .bdrv_write = vmdk_co_write,
2243 .bdrv_write_compressed = vmdk_write_compressed,
2244 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
2245 .bdrv_close = vmdk_close,
2246 .bdrv_create = vmdk_create,
2247 .bdrv_co_flush_to_disk = vmdk_co_flush,
2248 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2249 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2250 .bdrv_has_zero_init = vmdk_has_zero_init,
2251 .bdrv_get_specific_info = vmdk_get_specific_info,
2252 .bdrv_refresh_limits = vmdk_refresh_limits,
2253 .bdrv_get_info = vmdk_get_info,
2254 .bdrv_detach_aio_context = vmdk_detach_aio_context,
2255 .bdrv_attach_aio_context = vmdk_attach_aio_context,
2256
2257 .supports_backing = true,
2258 .create_opts = &vmdk_create_opts,
2259 };
2260
2261 static void bdrv_vmdk_init(void)
2262 {
2263 bdrv_register(&bdrv_vmdk);
2264 }
2265
2266 block_init(bdrv_vmdk_init);