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