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