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