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