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