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