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