]> git.proxmox.com Git - mirror_qemu.git/blob - block/vmdk.c
vmdk: Use g_random_int to generate CID
[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); /* avoid unbounded allocation */
561 buf = g_malloc0(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
570 return buf;
571 }
572
573 static int vmdk_open_vmdk4(BlockDriverState *bs,
574 BlockDriverState *file,
575 int flags, Error **errp)
576 {
577 int ret;
578 uint32_t magic;
579 uint32_t l1_size, l1_entry_sectors;
580 VMDK4Header header;
581 VmdkExtent *extent;
582 BDRVVmdkState *s = bs->opaque;
583 int64_t l1_backup_offset = 0;
584
585 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
586 if (ret < 0) {
587 error_setg_errno(errp, -ret,
588 "Could not read header from file '%s'",
589 file->filename);
590 return -EINVAL;
591 }
592 if (header.capacity == 0) {
593 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
594 if (desc_offset) {
595 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
596 if (!buf) {
597 return -EINVAL;
598 }
599 ret = vmdk_open_desc_file(bs, flags, buf, errp);
600 g_free(buf);
601 return ret;
602 }
603 }
604
605 if (!s->create_type) {
606 s->create_type = g_strdup("monolithicSparse");
607 }
608
609 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
610 /*
611 * The footer takes precedence over the header, so read it in. The
612 * footer starts at offset -1024 from the end: One sector for the
613 * footer, and another one for the end-of-stream marker.
614 */
615 struct {
616 struct {
617 uint64_t val;
618 uint32_t size;
619 uint32_t type;
620 uint8_t pad[512 - 16];
621 } QEMU_PACKED footer_marker;
622
623 uint32_t magic;
624 VMDK4Header header;
625 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
626
627 struct {
628 uint64_t val;
629 uint32_t size;
630 uint32_t type;
631 uint8_t pad[512 - 16];
632 } QEMU_PACKED eos_marker;
633 } QEMU_PACKED footer;
634
635 ret = bdrv_pread(file,
636 bs->file->total_sectors * 512 - 1536,
637 &footer, sizeof(footer));
638 if (ret < 0) {
639 return ret;
640 }
641
642 /* Some sanity checks for the footer */
643 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
644 le32_to_cpu(footer.footer_marker.size) != 0 ||
645 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
646 le64_to_cpu(footer.eos_marker.val) != 0 ||
647 le32_to_cpu(footer.eos_marker.size) != 0 ||
648 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
649 {
650 return -EINVAL;
651 }
652
653 header = footer.header;
654 }
655
656 if (le32_to_cpu(header.version) > 3) {
657 char buf[64];
658 snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
659 le32_to_cpu(header.version));
660 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
661 bdrv_get_device_name(bs), "vmdk", buf);
662 return -ENOTSUP;
663 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
664 /* VMware KB 2064959 explains that version 3 added support for
665 * persistent changed block tracking (CBT), and backup software can
666 * read it as version=1 if it doesn't care about the changed area
667 * information. So we are safe to enable read only. */
668 error_setg(errp, "VMDK version 3 must be read only");
669 return -EINVAL;
670 }
671
672 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
673 error_setg(errp, "L2 table size too big");
674 return -EINVAL;
675 }
676
677 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
678 * le64_to_cpu(header.granularity);
679 if (l1_entry_sectors == 0) {
680 return -EINVAL;
681 }
682 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
683 / l1_entry_sectors;
684 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
685 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
686 }
687 if (bdrv_nb_sectors(file) < le64_to_cpu(header.grain_offset)) {
688 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
689 (int64_t)(le64_to_cpu(header.grain_offset)
690 * BDRV_SECTOR_SIZE));
691 return -EINVAL;
692 }
693
694 ret = vmdk_add_extent(bs, file, false,
695 le64_to_cpu(header.capacity),
696 le64_to_cpu(header.gd_offset) << 9,
697 l1_backup_offset,
698 l1_size,
699 le32_to_cpu(header.num_gtes_per_gt),
700 le64_to_cpu(header.granularity),
701 &extent,
702 errp);
703 if (ret < 0) {
704 return ret;
705 }
706 extent->compressed =
707 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
708 if (extent->compressed) {
709 g_free(s->create_type);
710 s->create_type = g_strdup("streamOptimized");
711 }
712 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
713 extent->version = le32_to_cpu(header.version);
714 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
715 ret = vmdk_init_tables(bs, extent, errp);
716 if (ret) {
717 /* free extent allocated by vmdk_add_extent */
718 vmdk_free_last_extent(bs);
719 }
720 return ret;
721 }
722
723 /* find an option value out of descriptor file */
724 static int vmdk_parse_description(const char *desc, const char *opt_name,
725 char *buf, int buf_size)
726 {
727 char *opt_pos, *opt_end;
728 const char *end = desc + strlen(desc);
729
730 opt_pos = strstr(desc, opt_name);
731 if (!opt_pos) {
732 return VMDK_ERROR;
733 }
734 /* Skip "=\"" following opt_name */
735 opt_pos += strlen(opt_name) + 2;
736 if (opt_pos >= end) {
737 return VMDK_ERROR;
738 }
739 opt_end = opt_pos;
740 while (opt_end < end && *opt_end != '"') {
741 opt_end++;
742 }
743 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
744 return VMDK_ERROR;
745 }
746 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
747 return VMDK_OK;
748 }
749
750 /* Open an extent file and append to bs array */
751 static int vmdk_open_sparse(BlockDriverState *bs,
752 BlockDriverState *file, int flags,
753 char *buf, Error **errp)
754 {
755 uint32_t magic;
756
757 magic = ldl_be_p(buf);
758 switch (magic) {
759 case VMDK3_MAGIC:
760 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
761 break;
762 case VMDK4_MAGIC:
763 return vmdk_open_vmdk4(bs, file, flags, errp);
764 break;
765 default:
766 error_setg(errp, "Image not in VMDK format");
767 return -EINVAL;
768 break;
769 }
770 }
771
772 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
773 const char *desc_file_path, Error **errp)
774 {
775 int ret;
776 char access[11];
777 char type[11];
778 char fname[512];
779 const char *p = desc;
780 int64_t sectors = 0;
781 int64_t flat_offset;
782 char extent_path[PATH_MAX];
783 BlockDriverState *extent_file;
784 BDRVVmdkState *s = bs->opaque;
785 VmdkExtent *extent;
786
787 while (*p) {
788 /* parse extent line:
789 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
790 * or
791 * RW [size in sectors] SPARSE "file-name.vmdk"
792 */
793 flat_offset = -1;
794 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
795 access, &sectors, type, fname, &flat_offset);
796 if (ret < 4 || strcmp(access, "RW")) {
797 goto next_line;
798 } else if (!strcmp(type, "FLAT")) {
799 if (ret != 5 || flat_offset < 0) {
800 error_setg(errp, "Invalid extent lines: \n%s", p);
801 return -EINVAL;
802 }
803 } else if (!strcmp(type, "VMFS")) {
804 if (ret == 4) {
805 flat_offset = 0;
806 } else {
807 error_setg(errp, "Invalid extent lines:\n%s", p);
808 return -EINVAL;
809 }
810 } else if (ret != 4) {
811 error_setg(errp, "Invalid extent lines:\n%s", p);
812 return -EINVAL;
813 }
814
815 if (sectors <= 0 ||
816 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
817 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
818 (strcmp(access, "RW"))) {
819 goto next_line;
820 }
821
822 path_combine(extent_path, sizeof(extent_path),
823 desc_file_path, fname);
824 extent_file = NULL;
825 ret = bdrv_open(&extent_file, extent_path, NULL, NULL,
826 bs->open_flags | BDRV_O_PROTOCOL, NULL, errp);
827 if (ret) {
828 return ret;
829 }
830
831 /* save to extents array */
832 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
833 /* FLAT extent */
834
835 ret = vmdk_add_extent(bs, extent_file, true, sectors,
836 0, 0, 0, 0, 0, &extent, errp);
837 if (ret < 0) {
838 bdrv_unref(extent_file);
839 return ret;
840 }
841 extent->flat_start_offset = flat_offset << 9;
842 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
843 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
844 char *buf = vmdk_read_desc(extent_file, 0, errp);
845 if (!buf) {
846 ret = -EINVAL;
847 } else {
848 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf, errp);
849 }
850 g_free(buf);
851 if (ret) {
852 bdrv_unref(extent_file);
853 return ret;
854 }
855 extent = &s->extents[s->num_extents - 1];
856 } else {
857 error_setg(errp, "Unsupported extent type '%s'", type);
858 bdrv_unref(extent_file);
859 return -ENOTSUP;
860 }
861 extent->type = g_strdup(type);
862 next_line:
863 /* move to next line */
864 while (*p) {
865 if (*p == '\n') {
866 p++;
867 break;
868 }
869 p++;
870 }
871 }
872 return 0;
873 }
874
875 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
876 Error **errp)
877 {
878 int ret;
879 char ct[128];
880 BDRVVmdkState *s = bs->opaque;
881
882 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
883 error_setg(errp, "invalid VMDK image descriptor");
884 ret = -EINVAL;
885 goto exit;
886 }
887 if (strcmp(ct, "monolithicFlat") &&
888 strcmp(ct, "vmfs") &&
889 strcmp(ct, "vmfsSparse") &&
890 strcmp(ct, "twoGbMaxExtentSparse") &&
891 strcmp(ct, "twoGbMaxExtentFlat")) {
892 error_setg(errp, "Unsupported image type '%s'", ct);
893 ret = -ENOTSUP;
894 goto exit;
895 }
896 s->create_type = g_strdup(ct);
897 s->desc_offset = 0;
898 ret = vmdk_parse_extents(buf, bs, bs->file->filename, errp);
899 exit:
900 return ret;
901 }
902
903 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
904 Error **errp)
905 {
906 char *buf = NULL;
907 int ret;
908 BDRVVmdkState *s = bs->opaque;
909 uint32_t magic;
910
911 buf = vmdk_read_desc(bs->file, 0, errp);
912 if (!buf) {
913 return -EINVAL;
914 }
915
916 magic = ldl_be_p(buf);
917 switch (magic) {
918 case VMDK3_MAGIC:
919 case VMDK4_MAGIC:
920 ret = vmdk_open_sparse(bs, bs->file, flags, buf, errp);
921 s->desc_offset = 0x200;
922 break;
923 default:
924 ret = vmdk_open_desc_file(bs, flags, buf, errp);
925 break;
926 }
927 if (ret) {
928 goto fail;
929 }
930
931 /* try to open parent images, if exist */
932 ret = vmdk_parent_open(bs);
933 if (ret) {
934 goto fail;
935 }
936 s->cid = vmdk_read_cid(bs, 0);
937 s->parent_cid = vmdk_read_cid(bs, 1);
938 qemu_co_mutex_init(&s->lock);
939
940 /* Disable migration when VMDK images are used */
941 error_set(&s->migration_blocker,
942 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
943 "vmdk", bdrv_get_device_name(bs), "live migration");
944 migrate_add_blocker(s->migration_blocker);
945 g_free(buf);
946 return 0;
947
948 fail:
949 g_free(buf);
950 g_free(s->create_type);
951 s->create_type = NULL;
952 vmdk_free_extents(bs);
953 return ret;
954 }
955
956
957 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
958 {
959 BDRVVmdkState *s = bs->opaque;
960 int i;
961
962 for (i = 0; i < s->num_extents; i++) {
963 if (!s->extents[i].flat) {
964 bs->bl.write_zeroes_alignment =
965 MAX(bs->bl.write_zeroes_alignment,
966 s->extents[i].cluster_sectors);
967 }
968 }
969 }
970
971 /**
972 * get_whole_cluster
973 *
974 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
975 * to the cluster at @cluster_sector_num.
976 *
977 * If @skip_start_sector < @skip_end_sector, the relative range
978 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
979 * it for call to write user data in the request.
980 */
981 static int get_whole_cluster(BlockDriverState *bs,
982 VmdkExtent *extent,
983 uint64_t cluster_sector_num,
984 uint64_t sector_num,
985 uint64_t skip_start_sector,
986 uint64_t skip_end_sector)
987 {
988 int ret = VMDK_OK;
989 int64_t cluster_bytes;
990 uint8_t *whole_grain;
991
992 /* For COW, align request sector_num to cluster start */
993 sector_num = QEMU_ALIGN_DOWN(sector_num, extent->cluster_sectors);
994 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
995 whole_grain = qemu_blockalign(bs, cluster_bytes);
996
997 if (!bs->backing_hd) {
998 memset(whole_grain, 0, skip_start_sector << BDRV_SECTOR_BITS);
999 memset(whole_grain + (skip_end_sector << BDRV_SECTOR_BITS), 0,
1000 cluster_bytes - (skip_end_sector << BDRV_SECTOR_BITS));
1001 }
1002
1003 assert(skip_end_sector <= extent->cluster_sectors);
1004 /* we will be here if it's first write on non-exist grain(cluster).
1005 * try to read from parent image, if exist */
1006 if (bs->backing_hd && !vmdk_is_cid_valid(bs)) {
1007 ret = VMDK_ERROR;
1008 goto exit;
1009 }
1010
1011 /* Read backing data before skip range */
1012 if (skip_start_sector > 0) {
1013 if (bs->backing_hd) {
1014 ret = bdrv_read(bs->backing_hd, sector_num,
1015 whole_grain, skip_start_sector);
1016 if (ret < 0) {
1017 ret = VMDK_ERROR;
1018 goto exit;
1019 }
1020 }
1021 ret = bdrv_write(extent->file, cluster_sector_num, whole_grain,
1022 skip_start_sector);
1023 if (ret < 0) {
1024 ret = VMDK_ERROR;
1025 goto exit;
1026 }
1027 }
1028 /* Read backing data after skip range */
1029 if (skip_end_sector < extent->cluster_sectors) {
1030 if (bs->backing_hd) {
1031 ret = bdrv_read(bs->backing_hd, sector_num + skip_end_sector,
1032 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1033 extent->cluster_sectors - skip_end_sector);
1034 if (ret < 0) {
1035 ret = VMDK_ERROR;
1036 goto exit;
1037 }
1038 }
1039 ret = bdrv_write(extent->file, cluster_sector_num + skip_end_sector,
1040 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1041 extent->cluster_sectors - skip_end_sector);
1042 if (ret < 0) {
1043 ret = VMDK_ERROR;
1044 goto exit;
1045 }
1046 }
1047
1048 exit:
1049 qemu_vfree(whole_grain);
1050 return ret;
1051 }
1052
1053 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1054 uint32_t offset)
1055 {
1056 offset = cpu_to_le32(offset);
1057 /* update L2 table */
1058 if (bdrv_pwrite_sync(
1059 extent->file,
1060 ((int64_t)m_data->l2_offset * 512)
1061 + (m_data->l2_index * sizeof(offset)),
1062 &offset, sizeof(offset)) < 0) {
1063 return VMDK_ERROR;
1064 }
1065 /* update backup L2 table */
1066 if (extent->l1_backup_table_offset != 0) {
1067 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1068 if (bdrv_pwrite_sync(
1069 extent->file,
1070 ((int64_t)m_data->l2_offset * 512)
1071 + (m_data->l2_index * sizeof(offset)),
1072 &offset, sizeof(offset)) < 0) {
1073 return VMDK_ERROR;
1074 }
1075 }
1076 if (m_data->l2_cache_entry) {
1077 *m_data->l2_cache_entry = offset;
1078 }
1079
1080 return VMDK_OK;
1081 }
1082
1083 /**
1084 * get_cluster_offset
1085 *
1086 * Look up cluster offset in extent file by sector number, and store in
1087 * @cluster_offset.
1088 *
1089 * For flat extents, the start offset as parsed from the description file is
1090 * returned.
1091 *
1092 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1093 * offset for a new cluster and update L2 cache. If there is a backing file,
1094 * COW is done before returning; otherwise, zeroes are written to the allocated
1095 * cluster. Both COW and zero writing skips the sector range
1096 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1097 * has new data to write there.
1098 *
1099 * Returns: VMDK_OK if cluster exists and mapped in the image.
1100 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1101 * VMDK_ERROR if failed.
1102 */
1103 static int get_cluster_offset(BlockDriverState *bs,
1104 VmdkExtent *extent,
1105 VmdkMetaData *m_data,
1106 uint64_t offset,
1107 bool allocate,
1108 uint64_t *cluster_offset,
1109 uint64_t skip_start_sector,
1110 uint64_t skip_end_sector)
1111 {
1112 unsigned int l1_index, l2_offset, l2_index;
1113 int min_index, i, j;
1114 uint32_t min_count, *l2_table;
1115 bool zeroed = false;
1116 int64_t ret;
1117 int64_t cluster_sector;
1118
1119 if (m_data) {
1120 m_data->valid = 0;
1121 }
1122 if (extent->flat) {
1123 *cluster_offset = extent->flat_start_offset;
1124 return VMDK_OK;
1125 }
1126
1127 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1128 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1129 if (l1_index >= extent->l1_size) {
1130 return VMDK_ERROR;
1131 }
1132 l2_offset = extent->l1_table[l1_index];
1133 if (!l2_offset) {
1134 return VMDK_UNALLOC;
1135 }
1136 for (i = 0; i < L2_CACHE_SIZE; i++) {
1137 if (l2_offset == extent->l2_cache_offsets[i]) {
1138 /* increment the hit count */
1139 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1140 for (j = 0; j < L2_CACHE_SIZE; j++) {
1141 extent->l2_cache_counts[j] >>= 1;
1142 }
1143 }
1144 l2_table = extent->l2_cache + (i * extent->l2_size);
1145 goto found;
1146 }
1147 }
1148 /* not found: load a new entry in the least used one */
1149 min_index = 0;
1150 min_count = 0xffffffff;
1151 for (i = 0; i < L2_CACHE_SIZE; i++) {
1152 if (extent->l2_cache_counts[i] < min_count) {
1153 min_count = extent->l2_cache_counts[i];
1154 min_index = i;
1155 }
1156 }
1157 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1158 if (bdrv_pread(
1159 extent->file,
1160 (int64_t)l2_offset * 512,
1161 l2_table,
1162 extent->l2_size * sizeof(uint32_t)
1163 ) != extent->l2_size * sizeof(uint32_t)) {
1164 return VMDK_ERROR;
1165 }
1166
1167 extent->l2_cache_offsets[min_index] = l2_offset;
1168 extent->l2_cache_counts[min_index] = 1;
1169 found:
1170 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1171 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1172
1173 if (m_data) {
1174 m_data->valid = 1;
1175 m_data->l1_index = l1_index;
1176 m_data->l2_index = l2_index;
1177 m_data->l2_offset = l2_offset;
1178 m_data->l2_cache_entry = &l2_table[l2_index];
1179 }
1180 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1181 zeroed = true;
1182 }
1183
1184 if (!cluster_sector || zeroed) {
1185 if (!allocate) {
1186 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1187 }
1188
1189 cluster_sector = extent->next_cluster_sector;
1190 extent->next_cluster_sector += extent->cluster_sectors;
1191
1192 /* First of all we write grain itself, to avoid race condition
1193 * that may to corrupt the image.
1194 * This problem may occur because of insufficient space on host disk
1195 * or inappropriate VM shutdown.
1196 */
1197 ret = get_whole_cluster(bs, extent,
1198 cluster_sector,
1199 offset >> BDRV_SECTOR_BITS,
1200 skip_start_sector, skip_end_sector);
1201 if (ret) {
1202 return ret;
1203 }
1204 }
1205 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1206 return VMDK_OK;
1207 }
1208
1209 static VmdkExtent *find_extent(BDRVVmdkState *s,
1210 int64_t sector_num, VmdkExtent *start_hint)
1211 {
1212 VmdkExtent *extent = start_hint;
1213
1214 if (!extent) {
1215 extent = &s->extents[0];
1216 }
1217 while (extent < &s->extents[s->num_extents]) {
1218 if (sector_num < extent->end_sector) {
1219 return extent;
1220 }
1221 extent++;
1222 }
1223 return NULL;
1224 }
1225
1226 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1227 int64_t sector_num, int nb_sectors, int *pnum)
1228 {
1229 BDRVVmdkState *s = bs->opaque;
1230 int64_t index_in_cluster, n, ret;
1231 uint64_t offset;
1232 VmdkExtent *extent;
1233
1234 extent = find_extent(s, sector_num, NULL);
1235 if (!extent) {
1236 return 0;
1237 }
1238 qemu_co_mutex_lock(&s->lock);
1239 ret = get_cluster_offset(bs, extent, NULL,
1240 sector_num * 512, false, &offset,
1241 0, 0);
1242 qemu_co_mutex_unlock(&s->lock);
1243
1244 switch (ret) {
1245 case VMDK_ERROR:
1246 ret = -EIO;
1247 break;
1248 case VMDK_UNALLOC:
1249 ret = 0;
1250 break;
1251 case VMDK_ZEROED:
1252 ret = BDRV_BLOCK_ZERO;
1253 break;
1254 case VMDK_OK:
1255 ret = BDRV_BLOCK_DATA;
1256 if (extent->file == bs->file && !extent->compressed) {
1257 ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1258 }
1259
1260 break;
1261 }
1262
1263 index_in_cluster = sector_num % extent->cluster_sectors;
1264 n = extent->cluster_sectors - index_in_cluster;
1265 if (n > nb_sectors) {
1266 n = nb_sectors;
1267 }
1268 *pnum = n;
1269 return ret;
1270 }
1271
1272 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1273 int64_t offset_in_cluster, const uint8_t *buf,
1274 int nb_sectors, int64_t sector_num)
1275 {
1276 int ret;
1277 VmdkGrainMarker *data = NULL;
1278 uLongf buf_len;
1279 const uint8_t *write_buf = buf;
1280 int write_len = nb_sectors * 512;
1281
1282 if (extent->compressed) {
1283 if (!extent->has_marker) {
1284 ret = -EINVAL;
1285 goto out;
1286 }
1287 buf_len = (extent->cluster_sectors << 9) * 2;
1288 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1289 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1290 buf_len == 0) {
1291 ret = -EINVAL;
1292 goto out;
1293 }
1294 data->lba = sector_num;
1295 data->size = buf_len;
1296 write_buf = (uint8_t *)data;
1297 write_len = buf_len + sizeof(VmdkGrainMarker);
1298 }
1299 ret = bdrv_pwrite(extent->file,
1300 cluster_offset + offset_in_cluster,
1301 write_buf,
1302 write_len);
1303 if (ret != write_len) {
1304 ret = ret < 0 ? ret : -EIO;
1305 goto out;
1306 }
1307 ret = 0;
1308 out:
1309 g_free(data);
1310 return ret;
1311 }
1312
1313 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1314 int64_t offset_in_cluster, uint8_t *buf,
1315 int nb_sectors)
1316 {
1317 int ret;
1318 int cluster_bytes, buf_bytes;
1319 uint8_t *cluster_buf, *compressed_data;
1320 uint8_t *uncomp_buf;
1321 uint32_t data_len;
1322 VmdkGrainMarker *marker;
1323 uLongf buf_len;
1324
1325
1326 if (!extent->compressed) {
1327 ret = bdrv_pread(extent->file,
1328 cluster_offset + offset_in_cluster,
1329 buf, nb_sectors * 512);
1330 if (ret == nb_sectors * 512) {
1331 return 0;
1332 } else {
1333 return -EIO;
1334 }
1335 }
1336 cluster_bytes = extent->cluster_sectors * 512;
1337 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1338 buf_bytes = cluster_bytes * 2;
1339 cluster_buf = g_malloc(buf_bytes);
1340 uncomp_buf = g_malloc(cluster_bytes);
1341 ret = bdrv_pread(extent->file,
1342 cluster_offset,
1343 cluster_buf, buf_bytes);
1344 if (ret < 0) {
1345 goto out;
1346 }
1347 compressed_data = cluster_buf;
1348 buf_len = cluster_bytes;
1349 data_len = cluster_bytes;
1350 if (extent->has_marker) {
1351 marker = (VmdkGrainMarker *)cluster_buf;
1352 compressed_data = marker->data;
1353 data_len = le32_to_cpu(marker->size);
1354 }
1355 if (!data_len || data_len > buf_bytes) {
1356 ret = -EINVAL;
1357 goto out;
1358 }
1359 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1360 if (ret != Z_OK) {
1361 ret = -EINVAL;
1362 goto out;
1363
1364 }
1365 if (offset_in_cluster < 0 ||
1366 offset_in_cluster + nb_sectors * 512 > buf_len) {
1367 ret = -EINVAL;
1368 goto out;
1369 }
1370 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1371 ret = 0;
1372
1373 out:
1374 g_free(uncomp_buf);
1375 g_free(cluster_buf);
1376 return ret;
1377 }
1378
1379 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1380 uint8_t *buf, int nb_sectors)
1381 {
1382 BDRVVmdkState *s = bs->opaque;
1383 int ret;
1384 uint64_t n, index_in_cluster;
1385 uint64_t extent_begin_sector, extent_relative_sector_num;
1386 VmdkExtent *extent = NULL;
1387 uint64_t cluster_offset;
1388
1389 while (nb_sectors > 0) {
1390 extent = find_extent(s, sector_num, extent);
1391 if (!extent) {
1392 return -EIO;
1393 }
1394 ret = get_cluster_offset(bs, extent, NULL,
1395 sector_num << 9, false, &cluster_offset,
1396 0, 0);
1397 extent_begin_sector = extent->end_sector - extent->sectors;
1398 extent_relative_sector_num = sector_num - extent_begin_sector;
1399 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1400 n = extent->cluster_sectors - index_in_cluster;
1401 if (n > nb_sectors) {
1402 n = nb_sectors;
1403 }
1404 if (ret != VMDK_OK) {
1405 /* if not allocated, try to read from parent image, if exist */
1406 if (bs->backing_hd && ret != VMDK_ZEROED) {
1407 if (!vmdk_is_cid_valid(bs)) {
1408 return -EINVAL;
1409 }
1410 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1411 if (ret < 0) {
1412 return ret;
1413 }
1414 } else {
1415 memset(buf, 0, 512 * n);
1416 }
1417 } else {
1418 ret = vmdk_read_extent(extent,
1419 cluster_offset, index_in_cluster * 512,
1420 buf, n);
1421 if (ret) {
1422 return ret;
1423 }
1424 }
1425 nb_sectors -= n;
1426 sector_num += n;
1427 buf += n * 512;
1428 }
1429 return 0;
1430 }
1431
1432 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1433 uint8_t *buf, int nb_sectors)
1434 {
1435 int ret;
1436 BDRVVmdkState *s = bs->opaque;
1437 qemu_co_mutex_lock(&s->lock);
1438 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1439 qemu_co_mutex_unlock(&s->lock);
1440 return ret;
1441 }
1442
1443 /**
1444 * vmdk_write:
1445 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1446 * if possible, otherwise return -ENOTSUP.
1447 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1448 * with each cluster. By dry run we can find if the zero write
1449 * is possible without modifying image data.
1450 *
1451 * Returns: error code with 0 for success.
1452 */
1453 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1454 const uint8_t *buf, int nb_sectors,
1455 bool zeroed, bool zero_dry_run)
1456 {
1457 BDRVVmdkState *s = bs->opaque;
1458 VmdkExtent *extent = NULL;
1459 int ret;
1460 int64_t index_in_cluster, n;
1461 uint64_t extent_begin_sector, extent_relative_sector_num;
1462 uint64_t cluster_offset;
1463 VmdkMetaData m_data;
1464
1465 if (sector_num > bs->total_sectors) {
1466 error_report("Wrong offset: sector_num=0x%" PRIx64
1467 " total_sectors=0x%" PRIx64 "\n",
1468 sector_num, bs->total_sectors);
1469 return -EIO;
1470 }
1471
1472 while (nb_sectors > 0) {
1473 extent = find_extent(s, sector_num, extent);
1474 if (!extent) {
1475 return -EIO;
1476 }
1477 extent_begin_sector = extent->end_sector - extent->sectors;
1478 extent_relative_sector_num = sector_num - extent_begin_sector;
1479 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1480 n = extent->cluster_sectors - index_in_cluster;
1481 if (n > nb_sectors) {
1482 n = nb_sectors;
1483 }
1484 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1485 !(extent->compressed || zeroed),
1486 &cluster_offset,
1487 index_in_cluster, index_in_cluster + n);
1488 if (extent->compressed) {
1489 if (ret == VMDK_OK) {
1490 /* Refuse write to allocated cluster for streamOptimized */
1491 error_report("Could not write to allocated cluster"
1492 " for streamOptimized");
1493 return -EIO;
1494 } else {
1495 /* allocate */
1496 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1497 true, &cluster_offset, 0, 0);
1498 }
1499 }
1500 if (ret == VMDK_ERROR) {
1501 return -EINVAL;
1502 }
1503 if (zeroed) {
1504 /* Do zeroed write, buf is ignored */
1505 if (extent->has_zero_grain &&
1506 index_in_cluster == 0 &&
1507 n >= extent->cluster_sectors) {
1508 n = extent->cluster_sectors;
1509 if (!zero_dry_run) {
1510 /* update L2 tables */
1511 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1512 != VMDK_OK) {
1513 return -EIO;
1514 }
1515 }
1516 } else {
1517 return -ENOTSUP;
1518 }
1519 } else {
1520 ret = vmdk_write_extent(extent,
1521 cluster_offset, index_in_cluster * 512,
1522 buf, n, sector_num);
1523 if (ret) {
1524 return ret;
1525 }
1526 if (m_data.valid) {
1527 /* update L2 tables */
1528 if (vmdk_L2update(extent, &m_data,
1529 cluster_offset >> BDRV_SECTOR_BITS)
1530 != VMDK_OK) {
1531 return -EIO;
1532 }
1533 }
1534 }
1535 nb_sectors -= n;
1536 sector_num += n;
1537 buf += n * 512;
1538
1539 /* update CID on the first write every time the virtual disk is
1540 * opened */
1541 if (!s->cid_updated) {
1542 ret = vmdk_write_cid(bs, g_random_int());
1543 if (ret < 0) {
1544 return ret;
1545 }
1546 s->cid_updated = true;
1547 }
1548 }
1549 return 0;
1550 }
1551
1552 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1553 const uint8_t *buf, int nb_sectors)
1554 {
1555 int ret;
1556 BDRVVmdkState *s = bs->opaque;
1557 qemu_co_mutex_lock(&s->lock);
1558 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1559 qemu_co_mutex_unlock(&s->lock);
1560 return ret;
1561 }
1562
1563 static int vmdk_write_compressed(BlockDriverState *bs,
1564 int64_t sector_num,
1565 const uint8_t *buf,
1566 int nb_sectors)
1567 {
1568 BDRVVmdkState *s = bs->opaque;
1569 if (s->num_extents == 1 && s->extents[0].compressed) {
1570 return vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1571 } else {
1572 return -ENOTSUP;
1573 }
1574 }
1575
1576 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1577 int64_t sector_num,
1578 int nb_sectors,
1579 BdrvRequestFlags flags)
1580 {
1581 int ret;
1582 BDRVVmdkState *s = bs->opaque;
1583 qemu_co_mutex_lock(&s->lock);
1584 /* write zeroes could fail if sectors not aligned to cluster, test it with
1585 * dry_run == true before really updating image */
1586 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1587 if (!ret) {
1588 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1589 }
1590 qemu_co_mutex_unlock(&s->lock);
1591 return ret;
1592 }
1593
1594 static int vmdk_create_extent(const char *filename, int64_t filesize,
1595 bool flat, bool compress, bool zeroed_grain,
1596 QemuOpts *opts, Error **errp)
1597 {
1598 int ret, i;
1599 BlockDriverState *bs = NULL;
1600 VMDK4Header header;
1601 Error *local_err = NULL;
1602 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1603 uint32_t *gd_buf = NULL;
1604 int gd_buf_size;
1605
1606 ret = bdrv_create_file(filename, opts, &local_err);
1607 if (ret < 0) {
1608 error_propagate(errp, local_err);
1609 goto exit;
1610 }
1611
1612 assert(bs == NULL);
1613 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1614 NULL, &local_err);
1615 if (ret < 0) {
1616 error_propagate(errp, local_err);
1617 goto exit;
1618 }
1619
1620 if (flat) {
1621 ret = bdrv_truncate(bs, filesize);
1622 if (ret < 0) {
1623 error_setg_errno(errp, -ret, "Could not truncate file");
1624 }
1625 goto exit;
1626 }
1627 magic = cpu_to_be32(VMDK4_MAGIC);
1628 memset(&header, 0, sizeof(header));
1629 header.version = zeroed_grain ? 2 : 1;
1630 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1631 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1632 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1633 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1634 header.capacity = filesize / BDRV_SECTOR_SIZE;
1635 header.granularity = 128;
1636 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1637
1638 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1639 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1640 BDRV_SECTOR_SIZE);
1641 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1642 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1643
1644 header.desc_offset = 1;
1645 header.desc_size = 20;
1646 header.rgd_offset = header.desc_offset + header.desc_size;
1647 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1648 header.grain_offset =
1649 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1650 header.granularity);
1651 /* swap endianness for all header fields */
1652 header.version = cpu_to_le32(header.version);
1653 header.flags = cpu_to_le32(header.flags);
1654 header.capacity = cpu_to_le64(header.capacity);
1655 header.granularity = cpu_to_le64(header.granularity);
1656 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1657 header.desc_offset = cpu_to_le64(header.desc_offset);
1658 header.desc_size = cpu_to_le64(header.desc_size);
1659 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1660 header.gd_offset = cpu_to_le64(header.gd_offset);
1661 header.grain_offset = cpu_to_le64(header.grain_offset);
1662 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1663
1664 header.check_bytes[0] = 0xa;
1665 header.check_bytes[1] = 0x20;
1666 header.check_bytes[2] = 0xd;
1667 header.check_bytes[3] = 0xa;
1668
1669 /* write all the data */
1670 ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1671 if (ret < 0) {
1672 error_set(errp, QERR_IO_ERROR);
1673 goto exit;
1674 }
1675 ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1676 if (ret < 0) {
1677 error_set(errp, QERR_IO_ERROR);
1678 goto exit;
1679 }
1680
1681 ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1682 if (ret < 0) {
1683 error_setg_errno(errp, -ret, "Could not truncate file");
1684 goto exit;
1685 }
1686
1687 /* write grain directory */
1688 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1689 gd_buf = g_malloc0(gd_buf_size);
1690 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1691 i < gt_count; i++, tmp += gt_size) {
1692 gd_buf[i] = cpu_to_le32(tmp);
1693 }
1694 ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1695 gd_buf, gd_buf_size);
1696 if (ret < 0) {
1697 error_set(errp, QERR_IO_ERROR);
1698 goto exit;
1699 }
1700
1701 /* write backup grain directory */
1702 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1703 i < gt_count; i++, tmp += gt_size) {
1704 gd_buf[i] = cpu_to_le32(tmp);
1705 }
1706 ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1707 gd_buf, gd_buf_size);
1708 if (ret < 0) {
1709 error_set(errp, QERR_IO_ERROR);
1710 goto exit;
1711 }
1712
1713 ret = 0;
1714 exit:
1715 if (bs) {
1716 bdrv_unref(bs);
1717 }
1718 g_free(gd_buf);
1719 return ret;
1720 }
1721
1722 static int filename_decompose(const char *filename, char *path, char *prefix,
1723 char *postfix, size_t buf_len, Error **errp)
1724 {
1725 const char *p, *q;
1726
1727 if (filename == NULL || !strlen(filename)) {
1728 error_setg(errp, "No filename provided");
1729 return VMDK_ERROR;
1730 }
1731 p = strrchr(filename, '/');
1732 if (p == NULL) {
1733 p = strrchr(filename, '\\');
1734 }
1735 if (p == NULL) {
1736 p = strrchr(filename, ':');
1737 }
1738 if (p != NULL) {
1739 p++;
1740 if (p - filename >= buf_len) {
1741 return VMDK_ERROR;
1742 }
1743 pstrcpy(path, p - filename + 1, filename);
1744 } else {
1745 p = filename;
1746 path[0] = '\0';
1747 }
1748 q = strrchr(p, '.');
1749 if (q == NULL) {
1750 pstrcpy(prefix, buf_len, p);
1751 postfix[0] = '\0';
1752 } else {
1753 if (q - p >= buf_len) {
1754 return VMDK_ERROR;
1755 }
1756 pstrcpy(prefix, q - p + 1, p);
1757 pstrcpy(postfix, buf_len, q);
1758 }
1759 return VMDK_OK;
1760 }
1761
1762 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1763 {
1764 int idx = 0;
1765 BlockDriverState *new_bs = NULL;
1766 Error *local_err = NULL;
1767 char *desc = NULL;
1768 int64_t total_size = 0, filesize;
1769 char *adapter_type = NULL;
1770 char *backing_file = NULL;
1771 char *fmt = NULL;
1772 int flags = 0;
1773 int ret = 0;
1774 bool flat, split, compress;
1775 GString *ext_desc_lines;
1776 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1777 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1778 const char *desc_extent_line;
1779 char parent_desc_line[BUF_SIZE] = "";
1780 uint32_t parent_cid = 0xffffffff;
1781 uint32_t number_heads = 16;
1782 bool zeroed_grain = false;
1783 uint32_t desc_offset = 0, desc_len;
1784 const char desc_template[] =
1785 "# Disk DescriptorFile\n"
1786 "version=1\n"
1787 "CID=%" PRIx32 "\n"
1788 "parentCID=%" PRIx32 "\n"
1789 "createType=\"%s\"\n"
1790 "%s"
1791 "\n"
1792 "# Extent description\n"
1793 "%s"
1794 "\n"
1795 "# The Disk Data Base\n"
1796 "#DDB\n"
1797 "\n"
1798 "ddb.virtualHWVersion = \"%d\"\n"
1799 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1800 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1801 "ddb.geometry.sectors = \"63\"\n"
1802 "ddb.adapterType = \"%s\"\n";
1803
1804 ext_desc_lines = g_string_new(NULL);
1805
1806 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1807 ret = -EINVAL;
1808 goto exit;
1809 }
1810 /* Read out options */
1811 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1812 BDRV_SECTOR_SIZE);
1813 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1814 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1815 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1816 flags |= BLOCK_FLAG_COMPAT6;
1817 }
1818 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1819 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1820 zeroed_grain = true;
1821 }
1822
1823 if (!adapter_type) {
1824 adapter_type = g_strdup("ide");
1825 } else if (strcmp(adapter_type, "ide") &&
1826 strcmp(adapter_type, "buslogic") &&
1827 strcmp(adapter_type, "lsilogic") &&
1828 strcmp(adapter_type, "legacyESX")) {
1829 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1830 ret = -EINVAL;
1831 goto exit;
1832 }
1833 if (strcmp(adapter_type, "ide") != 0) {
1834 /* that's the number of heads with which vmware operates when
1835 creating, exporting, etc. vmdk files with a non-ide adapter type */
1836 number_heads = 255;
1837 }
1838 if (!fmt) {
1839 /* Default format to monolithicSparse */
1840 fmt = g_strdup("monolithicSparse");
1841 } else if (strcmp(fmt, "monolithicFlat") &&
1842 strcmp(fmt, "monolithicSparse") &&
1843 strcmp(fmt, "twoGbMaxExtentSparse") &&
1844 strcmp(fmt, "twoGbMaxExtentFlat") &&
1845 strcmp(fmt, "streamOptimized")) {
1846 error_setg(errp, "Unknown subformat: '%s'", fmt);
1847 ret = -EINVAL;
1848 goto exit;
1849 }
1850 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1851 strcmp(fmt, "twoGbMaxExtentSparse"));
1852 flat = !(strcmp(fmt, "monolithicFlat") &&
1853 strcmp(fmt, "twoGbMaxExtentFlat"));
1854 compress = !strcmp(fmt, "streamOptimized");
1855 if (flat) {
1856 desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1857 } else {
1858 desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1859 }
1860 if (flat && backing_file) {
1861 error_setg(errp, "Flat image can't have backing file");
1862 ret = -ENOTSUP;
1863 goto exit;
1864 }
1865 if (flat && zeroed_grain) {
1866 error_setg(errp, "Flat image can't enable zeroed grain");
1867 ret = -ENOTSUP;
1868 goto exit;
1869 }
1870 if (backing_file) {
1871 BlockDriverState *bs = NULL;
1872 ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_NO_BACKING, NULL,
1873 errp);
1874 if (ret != 0) {
1875 goto exit;
1876 }
1877 if (strcmp(bs->drv->format_name, "vmdk")) {
1878 bdrv_unref(bs);
1879 ret = -EINVAL;
1880 goto exit;
1881 }
1882 parent_cid = vmdk_read_cid(bs, 0);
1883 bdrv_unref(bs);
1884 snprintf(parent_desc_line, sizeof(parent_desc_line),
1885 "parentFileNameHint=\"%s\"", backing_file);
1886 }
1887
1888 /* Create extents */
1889 filesize = total_size;
1890 while (filesize > 0) {
1891 char desc_line[BUF_SIZE];
1892 char ext_filename[PATH_MAX];
1893 char desc_filename[PATH_MAX];
1894 int64_t size = filesize;
1895
1896 if (split && size > split_size) {
1897 size = split_size;
1898 }
1899 if (split) {
1900 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1901 prefix, flat ? 'f' : 's', ++idx, postfix);
1902 } else if (flat) {
1903 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1904 prefix, postfix);
1905 } else {
1906 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1907 prefix, postfix);
1908 }
1909 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1910 path, desc_filename);
1911
1912 if (vmdk_create_extent(ext_filename, size,
1913 flat, compress, zeroed_grain, opts, errp)) {
1914 ret = -EINVAL;
1915 goto exit;
1916 }
1917 filesize -= size;
1918
1919 /* Format description line */
1920 snprintf(desc_line, sizeof(desc_line),
1921 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1922 g_string_append(ext_desc_lines, desc_line);
1923 }
1924 /* generate descriptor file */
1925 desc = g_strdup_printf(desc_template,
1926 g_random_int(),
1927 parent_cid,
1928 fmt,
1929 parent_desc_line,
1930 ext_desc_lines->str,
1931 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1932 total_size /
1933 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1934 number_heads,
1935 adapter_type);
1936 desc_len = strlen(desc);
1937 /* the descriptor offset = 0x200 */
1938 if (!split && !flat) {
1939 desc_offset = 0x200;
1940 } else {
1941 ret = bdrv_create_file(filename, opts, &local_err);
1942 if (ret < 0) {
1943 error_propagate(errp, local_err);
1944 goto exit;
1945 }
1946 }
1947 assert(new_bs == NULL);
1948 ret = bdrv_open(&new_bs, filename, NULL, NULL,
1949 BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
1950 if (ret < 0) {
1951 error_propagate(errp, local_err);
1952 goto exit;
1953 }
1954 ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1955 if (ret < 0) {
1956 error_setg_errno(errp, -ret, "Could not write description");
1957 goto exit;
1958 }
1959 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1960 * for description file */
1961 if (desc_offset == 0) {
1962 ret = bdrv_truncate(new_bs, desc_len);
1963 if (ret < 0) {
1964 error_setg_errno(errp, -ret, "Could not truncate file");
1965 }
1966 }
1967 exit:
1968 if (new_bs) {
1969 bdrv_unref(new_bs);
1970 }
1971 g_free(adapter_type);
1972 g_free(backing_file);
1973 g_free(fmt);
1974 g_free(desc);
1975 g_string_free(ext_desc_lines, true);
1976 return ret;
1977 }
1978
1979 static void vmdk_close(BlockDriverState *bs)
1980 {
1981 BDRVVmdkState *s = bs->opaque;
1982
1983 vmdk_free_extents(bs);
1984 g_free(s->create_type);
1985
1986 migrate_del_blocker(s->migration_blocker);
1987 error_free(s->migration_blocker);
1988 }
1989
1990 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1991 {
1992 BDRVVmdkState *s = bs->opaque;
1993 int i, err;
1994 int ret = 0;
1995
1996 for (i = 0; i < s->num_extents; i++) {
1997 err = bdrv_co_flush(s->extents[i].file);
1998 if (err < 0) {
1999 ret = err;
2000 }
2001 }
2002 return ret;
2003 }
2004
2005 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2006 {
2007 int i;
2008 int64_t ret = 0;
2009 int64_t r;
2010 BDRVVmdkState *s = bs->opaque;
2011
2012 ret = bdrv_get_allocated_file_size(bs->file);
2013 if (ret < 0) {
2014 return ret;
2015 }
2016 for (i = 0; i < s->num_extents; i++) {
2017 if (s->extents[i].file == bs->file) {
2018 continue;
2019 }
2020 r = bdrv_get_allocated_file_size(s->extents[i].file);
2021 if (r < 0) {
2022 return r;
2023 }
2024 ret += r;
2025 }
2026 return ret;
2027 }
2028
2029 static int vmdk_has_zero_init(BlockDriverState *bs)
2030 {
2031 int i;
2032 BDRVVmdkState *s = bs->opaque;
2033
2034 /* If has a flat extent and its underlying storage doesn't have zero init,
2035 * return 0. */
2036 for (i = 0; i < s->num_extents; i++) {
2037 if (s->extents[i].flat) {
2038 if (!bdrv_has_zero_init(s->extents[i].file)) {
2039 return 0;
2040 }
2041 }
2042 }
2043 return 1;
2044 }
2045
2046 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2047 {
2048 ImageInfo *info = g_new0(ImageInfo, 1);
2049
2050 *info = (ImageInfo){
2051 .filename = g_strdup(extent->file->filename),
2052 .format = g_strdup(extent->type),
2053 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2054 .compressed = extent->compressed,
2055 .has_compressed = extent->compressed,
2056 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2057 .has_cluster_size = !extent->flat,
2058 };
2059
2060 return info;
2061 }
2062
2063 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2064 BdrvCheckMode fix)
2065 {
2066 BDRVVmdkState *s = bs->opaque;
2067 VmdkExtent *extent = NULL;
2068 int64_t sector_num = 0;
2069 int64_t total_sectors = bdrv_nb_sectors(bs);
2070 int ret;
2071 uint64_t cluster_offset;
2072
2073 if (fix) {
2074 return -ENOTSUP;
2075 }
2076
2077 for (;;) {
2078 if (sector_num >= total_sectors) {
2079 return 0;
2080 }
2081 extent = find_extent(s, sector_num, extent);
2082 if (!extent) {
2083 fprintf(stderr,
2084 "ERROR: could not find extent for sector %" PRId64 "\n",
2085 sector_num);
2086 break;
2087 }
2088 ret = get_cluster_offset(bs, extent, NULL,
2089 sector_num << BDRV_SECTOR_BITS,
2090 false, &cluster_offset, 0, 0);
2091 if (ret == VMDK_ERROR) {
2092 fprintf(stderr,
2093 "ERROR: could not get cluster_offset for sector %"
2094 PRId64 "\n", sector_num);
2095 break;
2096 }
2097 if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2098 fprintf(stderr,
2099 "ERROR: cluster offset for sector %"
2100 PRId64 " points after EOF\n", sector_num);
2101 break;
2102 }
2103 sector_num += extent->cluster_sectors;
2104 }
2105
2106 result->corruptions++;
2107 return 0;
2108 }
2109
2110 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2111 {
2112 int i;
2113 BDRVVmdkState *s = bs->opaque;
2114 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2115 ImageInfoList **next;
2116
2117 *spec_info = (ImageInfoSpecific){
2118 .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2119 {
2120 .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2121 },
2122 };
2123
2124 *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2125 .create_type = g_strdup(s->create_type),
2126 .cid = s->cid,
2127 .parent_cid = s->parent_cid,
2128 };
2129
2130 next = &spec_info->vmdk->extents;
2131 for (i = 0; i < s->num_extents; i++) {
2132 *next = g_new0(ImageInfoList, 1);
2133 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2134 (*next)->next = NULL;
2135 next = &(*next)->next;
2136 }
2137
2138 return spec_info;
2139 }
2140
2141 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2142 {
2143 return a->flat == b->flat &&
2144 a->compressed == b->compressed &&
2145 (a->flat || a->cluster_sectors == b->cluster_sectors);
2146 }
2147
2148 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2149 {
2150 int i;
2151 BDRVVmdkState *s = bs->opaque;
2152 assert(s->num_extents);
2153
2154 /* See if we have multiple extents but they have different cases */
2155 for (i = 1; i < s->num_extents; i++) {
2156 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2157 return -ENOTSUP;
2158 }
2159 }
2160 bdi->needs_compressed_writes = s->extents[0].compressed;
2161 if (!s->extents[0].flat) {
2162 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2163 }
2164 return 0;
2165 }
2166
2167 static void vmdk_detach_aio_context(BlockDriverState *bs)
2168 {
2169 BDRVVmdkState *s = bs->opaque;
2170 int i;
2171
2172 for (i = 0; i < s->num_extents; i++) {
2173 bdrv_detach_aio_context(s->extents[i].file);
2174 }
2175 }
2176
2177 static void vmdk_attach_aio_context(BlockDriverState *bs,
2178 AioContext *new_context)
2179 {
2180 BDRVVmdkState *s = bs->opaque;
2181 int i;
2182
2183 for (i = 0; i < s->num_extents; i++) {
2184 bdrv_attach_aio_context(s->extents[i].file, new_context);
2185 }
2186 }
2187
2188 static QemuOptsList vmdk_create_opts = {
2189 .name = "vmdk-create-opts",
2190 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2191 .desc = {
2192 {
2193 .name = BLOCK_OPT_SIZE,
2194 .type = QEMU_OPT_SIZE,
2195 .help = "Virtual disk size"
2196 },
2197 {
2198 .name = BLOCK_OPT_ADAPTER_TYPE,
2199 .type = QEMU_OPT_STRING,
2200 .help = "Virtual adapter type, can be one of "
2201 "ide (default), lsilogic, buslogic or legacyESX"
2202 },
2203 {
2204 .name = BLOCK_OPT_BACKING_FILE,
2205 .type = QEMU_OPT_STRING,
2206 .help = "File name of a base image"
2207 },
2208 {
2209 .name = BLOCK_OPT_COMPAT6,
2210 .type = QEMU_OPT_BOOL,
2211 .help = "VMDK version 6 image",
2212 .def_value_str = "off"
2213 },
2214 {
2215 .name = BLOCK_OPT_SUBFMT,
2216 .type = QEMU_OPT_STRING,
2217 .help =
2218 "VMDK flat extent format, can be one of "
2219 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2220 },
2221 {
2222 .name = BLOCK_OPT_ZEROED_GRAIN,
2223 .type = QEMU_OPT_BOOL,
2224 .help = "Enable efficient zero writes "
2225 "using the zeroed-grain GTE feature"
2226 },
2227 { /* end of list */ }
2228 }
2229 };
2230
2231 static BlockDriver bdrv_vmdk = {
2232 .format_name = "vmdk",
2233 .instance_size = sizeof(BDRVVmdkState),
2234 .bdrv_probe = vmdk_probe,
2235 .bdrv_open = vmdk_open,
2236 .bdrv_check = vmdk_check,
2237 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2238 .bdrv_read = vmdk_co_read,
2239 .bdrv_write = vmdk_co_write,
2240 .bdrv_write_compressed = vmdk_write_compressed,
2241 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
2242 .bdrv_close = vmdk_close,
2243 .bdrv_create = vmdk_create,
2244 .bdrv_co_flush_to_disk = vmdk_co_flush,
2245 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2246 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2247 .bdrv_has_zero_init = vmdk_has_zero_init,
2248 .bdrv_get_specific_info = vmdk_get_specific_info,
2249 .bdrv_refresh_limits = vmdk_refresh_limits,
2250 .bdrv_get_info = vmdk_get_info,
2251 .bdrv_detach_aio_context = vmdk_detach_aio_context,
2252 .bdrv_attach_aio_context = vmdk_attach_aio_context,
2253
2254 .supports_backing = true,
2255 .create_opts = &vmdk_create_opts,
2256 };
2257
2258 static void bdrv_vmdk_init(void)
2259 {
2260 bdrv_register(&bdrv_vmdk);
2261 }
2262
2263 block_init(bdrv_vmdk_init);