xref: /qemu/block/vmdk.c (revision 8fb3c76c)
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                 bdrv_unref(extent_file);
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             g_free(buf);
850             if (ret) {
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             bdrv_unref(extent_file);
858             return -ENOTSUP;
859         }
860         extent->type = g_strdup(type);
861 next_line:
862         /* move to next line */
863         while (*p) {
864             if (*p == '\n') {
865                 p++;
866                 break;
867             }
868             p++;
869         }
870     }
871     return 0;
872 }
873 
874 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
875                                Error **errp)
876 {
877     int ret;
878     char ct[128];
879     BDRVVmdkState *s = bs->opaque;
880 
881     if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
882         error_setg(errp, "invalid VMDK image descriptor");
883         ret = -EINVAL;
884         goto exit;
885     }
886     if (strcmp(ct, "monolithicFlat") &&
887         strcmp(ct, "vmfs") &&
888         strcmp(ct, "vmfsSparse") &&
889         strcmp(ct, "twoGbMaxExtentSparse") &&
890         strcmp(ct, "twoGbMaxExtentFlat")) {
891         error_setg(errp, "Unsupported image type '%s'", ct);
892         ret = -ENOTSUP;
893         goto exit;
894     }
895     s->create_type = g_strdup(ct);
896     s->desc_offset = 0;
897     ret = vmdk_parse_extents(buf, bs, bs->file->filename, errp);
898 exit:
899     return ret;
900 }
901 
902 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
903                      Error **errp)
904 {
905     char *buf = NULL;
906     int ret;
907     BDRVVmdkState *s = bs->opaque;
908     uint32_t magic;
909 
910     buf = vmdk_read_desc(bs->file, 0, errp);
911     if (!buf) {
912         return -EINVAL;
913     }
914 
915     magic = ldl_be_p(buf);
916     switch (magic) {
917         case VMDK3_MAGIC:
918         case VMDK4_MAGIC:
919             ret = vmdk_open_sparse(bs, bs->file, flags, buf, errp);
920             s->desc_offset = 0x200;
921             break;
922         default:
923             ret = vmdk_open_desc_file(bs, flags, buf, errp);
924             break;
925     }
926     if (ret) {
927         goto fail;
928     }
929 
930     /* try to open parent images, if exist */
931     ret = vmdk_parent_open(bs);
932     if (ret) {
933         goto fail;
934     }
935     s->cid = vmdk_read_cid(bs, 0);
936     s->parent_cid = vmdk_read_cid(bs, 1);
937     qemu_co_mutex_init(&s->lock);
938 
939     /* Disable migration when VMDK images are used */
940     error_set(&s->migration_blocker,
941               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
942               "vmdk", bs->device_name, "live migration");
943     migrate_add_blocker(s->migration_blocker);
944     g_free(buf);
945     return 0;
946 
947 fail:
948     g_free(buf);
949     g_free(s->create_type);
950     s->create_type = NULL;
951     vmdk_free_extents(bs);
952     return ret;
953 }
954 
955 
956 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
957 {
958     BDRVVmdkState *s = bs->opaque;
959     int i;
960 
961     for (i = 0; i < s->num_extents; i++) {
962         if (!s->extents[i].flat) {
963             bs->bl.write_zeroes_alignment =
964                 MAX(bs->bl.write_zeroes_alignment,
965                     s->extents[i].cluster_sectors);
966         }
967     }
968 }
969 
970 /**
971  * get_whole_cluster
972  *
973  * Copy backing file's cluster that covers @sector_num, otherwise write zero,
974  * to the cluster at @cluster_sector_num.
975  *
976  * If @skip_start_sector < @skip_end_sector, the relative range
977  * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
978  * it for call to write user data in the request.
979  */
980 static int get_whole_cluster(BlockDriverState *bs,
981                              VmdkExtent *extent,
982                              uint64_t cluster_sector_num,
983                              uint64_t sector_num,
984                              uint64_t skip_start_sector,
985                              uint64_t skip_end_sector)
986 {
987     int ret = VMDK_OK;
988     int64_t cluster_bytes;
989     uint8_t *whole_grain;
990 
991     /* For COW, align request sector_num to cluster start */
992     sector_num = QEMU_ALIGN_DOWN(sector_num, extent->cluster_sectors);
993     cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
994     whole_grain = qemu_blockalign(bs, cluster_bytes);
995 
996     if (!bs->backing_hd) {
997         memset(whole_grain, 0,  skip_start_sector << BDRV_SECTOR_BITS);
998         memset(whole_grain + (skip_end_sector << BDRV_SECTOR_BITS), 0,
999                cluster_bytes - (skip_end_sector << BDRV_SECTOR_BITS));
1000     }
1001 
1002     assert(skip_end_sector <= extent->cluster_sectors);
1003     /* we will be here if it's first write on non-exist grain(cluster).
1004      * try to read from parent image, if exist */
1005     if (bs->backing_hd && !vmdk_is_cid_valid(bs)) {
1006         ret = VMDK_ERROR;
1007         goto exit;
1008     }
1009 
1010     /* Read backing data before skip range */
1011     if (skip_start_sector > 0) {
1012         if (bs->backing_hd) {
1013             ret = bdrv_read(bs->backing_hd, sector_num,
1014                             whole_grain, skip_start_sector);
1015             if (ret < 0) {
1016                 ret = VMDK_ERROR;
1017                 goto exit;
1018             }
1019         }
1020         ret = bdrv_write(extent->file, cluster_sector_num, whole_grain,
1021                          skip_start_sector);
1022         if (ret < 0) {
1023             ret = VMDK_ERROR;
1024             goto exit;
1025         }
1026     }
1027     /* Read backing data after skip range */
1028     if (skip_end_sector < extent->cluster_sectors) {
1029         if (bs->backing_hd) {
1030             ret = bdrv_read(bs->backing_hd, sector_num + skip_end_sector,
1031                             whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1032                             extent->cluster_sectors - skip_end_sector);
1033             if (ret < 0) {
1034                 ret = VMDK_ERROR;
1035                 goto exit;
1036             }
1037         }
1038         ret = bdrv_write(extent->file, cluster_sector_num + skip_end_sector,
1039                          whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1040                          extent->cluster_sectors - skip_end_sector);
1041         if (ret < 0) {
1042             ret = VMDK_ERROR;
1043             goto exit;
1044         }
1045     }
1046 
1047 exit:
1048     qemu_vfree(whole_grain);
1049     return ret;
1050 }
1051 
1052 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1053                          uint32_t offset)
1054 {
1055     offset = cpu_to_le32(offset);
1056     /* update L2 table */
1057     if (bdrv_pwrite_sync(
1058                 extent->file,
1059                 ((int64_t)m_data->l2_offset * 512)
1060                     + (m_data->l2_index * sizeof(offset)),
1061                 &offset, sizeof(offset)) < 0) {
1062         return VMDK_ERROR;
1063     }
1064     /* update backup L2 table */
1065     if (extent->l1_backup_table_offset != 0) {
1066         m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1067         if (bdrv_pwrite_sync(
1068                     extent->file,
1069                     ((int64_t)m_data->l2_offset * 512)
1070                         + (m_data->l2_index * sizeof(offset)),
1071                     &offset, sizeof(offset)) < 0) {
1072             return VMDK_ERROR;
1073         }
1074     }
1075     if (m_data->l2_cache_entry) {
1076         *m_data->l2_cache_entry = offset;
1077     }
1078 
1079     return VMDK_OK;
1080 }
1081 
1082 /**
1083  * get_cluster_offset
1084  *
1085  * Look up cluster offset in extent file by sector number, and store in
1086  * @cluster_offset.
1087  *
1088  * For flat extents, the start offset as parsed from the description file is
1089  * returned.
1090  *
1091  * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1092  * offset for a new cluster and update L2 cache. If there is a backing file,
1093  * COW is done before returning; otherwise, zeroes are written to the allocated
1094  * cluster. Both COW and zero writing skips the sector range
1095  * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1096  * has new data to write there.
1097  *
1098  * Returns: VMDK_OK if cluster exists and mapped in the image.
1099  *          VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1100  *          VMDK_ERROR if failed.
1101  */
1102 static int get_cluster_offset(BlockDriverState *bs,
1103                               VmdkExtent *extent,
1104                               VmdkMetaData *m_data,
1105                               uint64_t offset,
1106                               bool allocate,
1107                               uint64_t *cluster_offset,
1108                               uint64_t skip_start_sector,
1109                               uint64_t skip_end_sector)
1110 {
1111     unsigned int l1_index, l2_offset, l2_index;
1112     int min_index, i, j;
1113     uint32_t min_count, *l2_table;
1114     bool zeroed = false;
1115     int64_t ret;
1116     int64_t cluster_sector;
1117 
1118     if (m_data) {
1119         m_data->valid = 0;
1120     }
1121     if (extent->flat) {
1122         *cluster_offset = extent->flat_start_offset;
1123         return VMDK_OK;
1124     }
1125 
1126     offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1127     l1_index = (offset >> 9) / extent->l1_entry_sectors;
1128     if (l1_index >= extent->l1_size) {
1129         return VMDK_ERROR;
1130     }
1131     l2_offset = extent->l1_table[l1_index];
1132     if (!l2_offset) {
1133         return VMDK_UNALLOC;
1134     }
1135     for (i = 0; i < L2_CACHE_SIZE; i++) {
1136         if (l2_offset == extent->l2_cache_offsets[i]) {
1137             /* increment the hit count */
1138             if (++extent->l2_cache_counts[i] == 0xffffffff) {
1139                 for (j = 0; j < L2_CACHE_SIZE; j++) {
1140                     extent->l2_cache_counts[j] >>= 1;
1141                 }
1142             }
1143             l2_table = extent->l2_cache + (i * extent->l2_size);
1144             goto found;
1145         }
1146     }
1147     /* not found: load a new entry in the least used one */
1148     min_index = 0;
1149     min_count = 0xffffffff;
1150     for (i = 0; i < L2_CACHE_SIZE; i++) {
1151         if (extent->l2_cache_counts[i] < min_count) {
1152             min_count = extent->l2_cache_counts[i];
1153             min_index = i;
1154         }
1155     }
1156     l2_table = extent->l2_cache + (min_index * extent->l2_size);
1157     if (bdrv_pread(
1158                 extent->file,
1159                 (int64_t)l2_offset * 512,
1160                 l2_table,
1161                 extent->l2_size * sizeof(uint32_t)
1162             ) != extent->l2_size * sizeof(uint32_t)) {
1163         return VMDK_ERROR;
1164     }
1165 
1166     extent->l2_cache_offsets[min_index] = l2_offset;
1167     extent->l2_cache_counts[min_index] = 1;
1168  found:
1169     l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1170     cluster_sector = le32_to_cpu(l2_table[l2_index]);
1171 
1172     if (m_data) {
1173         m_data->valid = 1;
1174         m_data->l1_index = l1_index;
1175         m_data->l2_index = l2_index;
1176         m_data->l2_offset = l2_offset;
1177         m_data->l2_cache_entry = &l2_table[l2_index];
1178     }
1179     if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1180         zeroed = true;
1181     }
1182 
1183     if (!cluster_sector || zeroed) {
1184         if (!allocate) {
1185             return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1186         }
1187 
1188         cluster_sector = extent->next_cluster_sector;
1189         extent->next_cluster_sector += extent->cluster_sectors;
1190 
1191         /* First of all we write grain itself, to avoid race condition
1192          * that may to corrupt the image.
1193          * This problem may occur because of insufficient space on host disk
1194          * or inappropriate VM shutdown.
1195          */
1196         ret = get_whole_cluster(bs, extent,
1197                                 cluster_sector,
1198                                 offset >> BDRV_SECTOR_BITS,
1199                                 skip_start_sector, skip_end_sector);
1200         if (ret) {
1201             return ret;
1202         }
1203     }
1204     *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1205     return VMDK_OK;
1206 }
1207 
1208 static VmdkExtent *find_extent(BDRVVmdkState *s,
1209                                 int64_t sector_num, VmdkExtent *start_hint)
1210 {
1211     VmdkExtent *extent = start_hint;
1212 
1213     if (!extent) {
1214         extent = &s->extents[0];
1215     }
1216     while (extent < &s->extents[s->num_extents]) {
1217         if (sector_num < extent->end_sector) {
1218             return extent;
1219         }
1220         extent++;
1221     }
1222     return NULL;
1223 }
1224 
1225 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1226         int64_t sector_num, int nb_sectors, int *pnum)
1227 {
1228     BDRVVmdkState *s = bs->opaque;
1229     int64_t index_in_cluster, n, ret;
1230     uint64_t offset;
1231     VmdkExtent *extent;
1232 
1233     extent = find_extent(s, sector_num, NULL);
1234     if (!extent) {
1235         return 0;
1236     }
1237     qemu_co_mutex_lock(&s->lock);
1238     ret = get_cluster_offset(bs, extent, NULL,
1239                              sector_num * 512, false, &offset,
1240                              0, 0);
1241     qemu_co_mutex_unlock(&s->lock);
1242 
1243     switch (ret) {
1244     case VMDK_ERROR:
1245         ret = -EIO;
1246         break;
1247     case VMDK_UNALLOC:
1248         ret = 0;
1249         break;
1250     case VMDK_ZEROED:
1251         ret = BDRV_BLOCK_ZERO;
1252         break;
1253     case VMDK_OK:
1254         ret = BDRV_BLOCK_DATA;
1255         if (extent->file == bs->file && !extent->compressed) {
1256             ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1257         }
1258 
1259         break;
1260     }
1261 
1262     index_in_cluster = sector_num % extent->cluster_sectors;
1263     n = extent->cluster_sectors - index_in_cluster;
1264     if (n > nb_sectors) {
1265         n = nb_sectors;
1266     }
1267     *pnum = n;
1268     return ret;
1269 }
1270 
1271 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1272                             int64_t offset_in_cluster, const uint8_t *buf,
1273                             int nb_sectors, int64_t sector_num)
1274 {
1275     int ret;
1276     VmdkGrainMarker *data = NULL;
1277     uLongf buf_len;
1278     const uint8_t *write_buf = buf;
1279     int write_len = nb_sectors * 512;
1280 
1281     if (extent->compressed) {
1282         if (!extent->has_marker) {
1283             ret = -EINVAL;
1284             goto out;
1285         }
1286         buf_len = (extent->cluster_sectors << 9) * 2;
1287         data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1288         if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1289                 buf_len == 0) {
1290             ret = -EINVAL;
1291             goto out;
1292         }
1293         data->lba = sector_num;
1294         data->size = buf_len;
1295         write_buf = (uint8_t *)data;
1296         write_len = buf_len + sizeof(VmdkGrainMarker);
1297     }
1298     ret = bdrv_pwrite(extent->file,
1299                         cluster_offset + offset_in_cluster,
1300                         write_buf,
1301                         write_len);
1302     if (ret != write_len) {
1303         ret = ret < 0 ? ret : -EIO;
1304         goto out;
1305     }
1306     ret = 0;
1307  out:
1308     g_free(data);
1309     return ret;
1310 }
1311 
1312 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1313                             int64_t offset_in_cluster, uint8_t *buf,
1314                             int nb_sectors)
1315 {
1316     int ret;
1317     int cluster_bytes, buf_bytes;
1318     uint8_t *cluster_buf, *compressed_data;
1319     uint8_t *uncomp_buf;
1320     uint32_t data_len;
1321     VmdkGrainMarker *marker;
1322     uLongf buf_len;
1323 
1324 
1325     if (!extent->compressed) {
1326         ret = bdrv_pread(extent->file,
1327                           cluster_offset + offset_in_cluster,
1328                           buf, nb_sectors * 512);
1329         if (ret == nb_sectors * 512) {
1330             return 0;
1331         } else {
1332             return -EIO;
1333         }
1334     }
1335     cluster_bytes = extent->cluster_sectors * 512;
1336     /* Read two clusters in case GrainMarker + compressed data > one cluster */
1337     buf_bytes = cluster_bytes * 2;
1338     cluster_buf = g_malloc(buf_bytes);
1339     uncomp_buf = g_malloc(cluster_bytes);
1340     ret = bdrv_pread(extent->file,
1341                 cluster_offset,
1342                 cluster_buf, buf_bytes);
1343     if (ret < 0) {
1344         goto out;
1345     }
1346     compressed_data = cluster_buf;
1347     buf_len = cluster_bytes;
1348     data_len = cluster_bytes;
1349     if (extent->has_marker) {
1350         marker = (VmdkGrainMarker *)cluster_buf;
1351         compressed_data = marker->data;
1352         data_len = le32_to_cpu(marker->size);
1353     }
1354     if (!data_len || data_len > buf_bytes) {
1355         ret = -EINVAL;
1356         goto out;
1357     }
1358     ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1359     if (ret != Z_OK) {
1360         ret = -EINVAL;
1361         goto out;
1362 
1363     }
1364     if (offset_in_cluster < 0 ||
1365             offset_in_cluster + nb_sectors * 512 > buf_len) {
1366         ret = -EINVAL;
1367         goto out;
1368     }
1369     memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1370     ret = 0;
1371 
1372  out:
1373     g_free(uncomp_buf);
1374     g_free(cluster_buf);
1375     return ret;
1376 }
1377 
1378 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1379                     uint8_t *buf, int nb_sectors)
1380 {
1381     BDRVVmdkState *s = bs->opaque;
1382     int ret;
1383     uint64_t n, index_in_cluster;
1384     uint64_t extent_begin_sector, extent_relative_sector_num;
1385     VmdkExtent *extent = NULL;
1386     uint64_t cluster_offset;
1387 
1388     while (nb_sectors > 0) {
1389         extent = find_extent(s, sector_num, extent);
1390         if (!extent) {
1391             return -EIO;
1392         }
1393         ret = get_cluster_offset(bs, extent, NULL,
1394                                  sector_num << 9, false, &cluster_offset,
1395                                  0, 0);
1396         extent_begin_sector = extent->end_sector - extent->sectors;
1397         extent_relative_sector_num = sector_num - extent_begin_sector;
1398         index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1399         n = extent->cluster_sectors - index_in_cluster;
1400         if (n > nb_sectors) {
1401             n = nb_sectors;
1402         }
1403         if (ret != VMDK_OK) {
1404             /* if not allocated, try to read from parent image, if exist */
1405             if (bs->backing_hd && ret != VMDK_ZEROED) {
1406                 if (!vmdk_is_cid_valid(bs)) {
1407                     return -EINVAL;
1408                 }
1409                 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1410                 if (ret < 0) {
1411                     return ret;
1412                 }
1413             } else {
1414                 memset(buf, 0, 512 * n);
1415             }
1416         } else {
1417             ret = vmdk_read_extent(extent,
1418                             cluster_offset, index_in_cluster * 512,
1419                             buf, n);
1420             if (ret) {
1421                 return ret;
1422             }
1423         }
1424         nb_sectors -= n;
1425         sector_num += n;
1426         buf += n * 512;
1427     }
1428     return 0;
1429 }
1430 
1431 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1432                                      uint8_t *buf, int nb_sectors)
1433 {
1434     int ret;
1435     BDRVVmdkState *s = bs->opaque;
1436     qemu_co_mutex_lock(&s->lock);
1437     ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1438     qemu_co_mutex_unlock(&s->lock);
1439     return ret;
1440 }
1441 
1442 /**
1443  * vmdk_write:
1444  * @zeroed:       buf is ignored (data is zero), use zeroed_grain GTE feature
1445  *                if possible, otherwise return -ENOTSUP.
1446  * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1447  *                with each cluster. By dry run we can find if the zero write
1448  *                is possible without modifying image data.
1449  *
1450  * Returns: error code with 0 for success.
1451  */
1452 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1453                       const uint8_t *buf, int nb_sectors,
1454                       bool zeroed, bool zero_dry_run)
1455 {
1456     BDRVVmdkState *s = bs->opaque;
1457     VmdkExtent *extent = NULL;
1458     int ret;
1459     int64_t index_in_cluster, n;
1460     uint64_t extent_begin_sector, extent_relative_sector_num;
1461     uint64_t cluster_offset;
1462     VmdkMetaData m_data;
1463 
1464     if (sector_num > bs->total_sectors) {
1465         error_report("Wrong offset: sector_num=0x%" PRIx64
1466                 " total_sectors=0x%" PRIx64 "\n",
1467                 sector_num, bs->total_sectors);
1468         return -EIO;
1469     }
1470 
1471     while (nb_sectors > 0) {
1472         extent = find_extent(s, sector_num, extent);
1473         if (!extent) {
1474             return -EIO;
1475         }
1476         extent_begin_sector = extent->end_sector - extent->sectors;
1477         extent_relative_sector_num = sector_num - extent_begin_sector;
1478         index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1479         n = extent->cluster_sectors - index_in_cluster;
1480         if (n > nb_sectors) {
1481             n = nb_sectors;
1482         }
1483         ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1484                                  !(extent->compressed || zeroed),
1485                                  &cluster_offset,
1486                                  index_in_cluster, index_in_cluster + n);
1487         if (extent->compressed) {
1488             if (ret == VMDK_OK) {
1489                 /* Refuse write to allocated cluster for streamOptimized */
1490                 error_report("Could not write to allocated cluster"
1491                               " for streamOptimized");
1492                 return -EIO;
1493             } else {
1494                 /* allocate */
1495                 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1496                                          true, &cluster_offset, 0, 0);
1497             }
1498         }
1499         if (ret == VMDK_ERROR) {
1500             return -EINVAL;
1501         }
1502         if (zeroed) {
1503             /* Do zeroed write, buf is ignored */
1504             if (extent->has_zero_grain &&
1505                     index_in_cluster == 0 &&
1506                     n >= extent->cluster_sectors) {
1507                 n = extent->cluster_sectors;
1508                 if (!zero_dry_run) {
1509                     /* update L2 tables */
1510                     if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1511                             != VMDK_OK) {
1512                         return -EIO;
1513                     }
1514                 }
1515             } else {
1516                 return -ENOTSUP;
1517             }
1518         } else {
1519             ret = vmdk_write_extent(extent,
1520                             cluster_offset, index_in_cluster * 512,
1521                             buf, n, sector_num);
1522             if (ret) {
1523                 return ret;
1524             }
1525             if (m_data.valid) {
1526                 /* update L2 tables */
1527                 if (vmdk_L2update(extent, &m_data,
1528                                   cluster_offset >> BDRV_SECTOR_BITS)
1529                         != VMDK_OK) {
1530                     return -EIO;
1531                 }
1532             }
1533         }
1534         nb_sectors -= n;
1535         sector_num += n;
1536         buf += n * 512;
1537 
1538         /* update CID on the first write every time the virtual disk is
1539          * opened */
1540         if (!s->cid_updated) {
1541             ret = vmdk_write_cid(bs, time(NULL));
1542             if (ret < 0) {
1543                 return ret;
1544             }
1545             s->cid_updated = true;
1546         }
1547     }
1548     return 0;
1549 }
1550 
1551 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1552                                       const uint8_t *buf, int nb_sectors)
1553 {
1554     int ret;
1555     BDRVVmdkState *s = bs->opaque;
1556     qemu_co_mutex_lock(&s->lock);
1557     ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1558     qemu_co_mutex_unlock(&s->lock);
1559     return ret;
1560 }
1561 
1562 static int vmdk_write_compressed(BlockDriverState *bs,
1563                                  int64_t sector_num,
1564                                  const uint8_t *buf,
1565                                  int nb_sectors)
1566 {
1567     BDRVVmdkState *s = bs->opaque;
1568     if (s->num_extents == 1 && s->extents[0].compressed) {
1569         return vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1570     } else {
1571         return -ENOTSUP;
1572     }
1573 }
1574 
1575 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1576                                              int64_t sector_num,
1577                                              int nb_sectors,
1578                                              BdrvRequestFlags flags)
1579 {
1580     int ret;
1581     BDRVVmdkState *s = bs->opaque;
1582     qemu_co_mutex_lock(&s->lock);
1583     /* write zeroes could fail if sectors not aligned to cluster, test it with
1584      * dry_run == true before really updating image */
1585     ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1586     if (!ret) {
1587         ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1588     }
1589     qemu_co_mutex_unlock(&s->lock);
1590     return ret;
1591 }
1592 
1593 static int vmdk_create_extent(const char *filename, int64_t filesize,
1594                               bool flat, bool compress, bool zeroed_grain,
1595                               QemuOpts *opts, Error **errp)
1596 {
1597     int ret, i;
1598     BlockDriverState *bs = NULL;
1599     VMDK4Header header;
1600     Error *local_err = NULL;
1601     uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1602     uint32_t *gd_buf = NULL;
1603     int gd_buf_size;
1604 
1605     ret = bdrv_create_file(filename, opts, &local_err);
1606     if (ret < 0) {
1607         error_propagate(errp, local_err);
1608         goto exit;
1609     }
1610 
1611     assert(bs == NULL);
1612     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1613                     NULL, &local_err);
1614     if (ret < 0) {
1615         error_propagate(errp, local_err);
1616         goto exit;
1617     }
1618 
1619     if (flat) {
1620         ret = bdrv_truncate(bs, filesize);
1621         if (ret < 0) {
1622             error_setg_errno(errp, -ret, "Could not truncate file");
1623         }
1624         goto exit;
1625     }
1626     magic = cpu_to_be32(VMDK4_MAGIC);
1627     memset(&header, 0, sizeof(header));
1628     header.version = zeroed_grain ? 2 : 1;
1629     header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1630                    | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1631                    | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1632     header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1633     header.capacity = filesize / BDRV_SECTOR_SIZE;
1634     header.granularity = 128;
1635     header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1636 
1637     grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1638     gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1639                            BDRV_SECTOR_SIZE);
1640     gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1641     gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1642 
1643     header.desc_offset = 1;
1644     header.desc_size = 20;
1645     header.rgd_offset = header.desc_offset + header.desc_size;
1646     header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1647     header.grain_offset =
1648         ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1649                  header.granularity);
1650     /* swap endianness for all header fields */
1651     header.version = cpu_to_le32(header.version);
1652     header.flags = cpu_to_le32(header.flags);
1653     header.capacity = cpu_to_le64(header.capacity);
1654     header.granularity = cpu_to_le64(header.granularity);
1655     header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1656     header.desc_offset = cpu_to_le64(header.desc_offset);
1657     header.desc_size = cpu_to_le64(header.desc_size);
1658     header.rgd_offset = cpu_to_le64(header.rgd_offset);
1659     header.gd_offset = cpu_to_le64(header.gd_offset);
1660     header.grain_offset = cpu_to_le64(header.grain_offset);
1661     header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1662 
1663     header.check_bytes[0] = 0xa;
1664     header.check_bytes[1] = 0x20;
1665     header.check_bytes[2] = 0xd;
1666     header.check_bytes[3] = 0xa;
1667 
1668     /* write all the data */
1669     ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1670     if (ret < 0) {
1671         error_set(errp, QERR_IO_ERROR);
1672         goto exit;
1673     }
1674     ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1675     if (ret < 0) {
1676         error_set(errp, QERR_IO_ERROR);
1677         goto exit;
1678     }
1679 
1680     ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1681     if (ret < 0) {
1682         error_setg_errno(errp, -ret, "Could not truncate file");
1683         goto exit;
1684     }
1685 
1686     /* write grain directory */
1687     gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1688     gd_buf = g_malloc0(gd_buf_size);
1689     for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1690          i < gt_count; i++, tmp += gt_size) {
1691         gd_buf[i] = cpu_to_le32(tmp);
1692     }
1693     ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1694                       gd_buf, gd_buf_size);
1695     if (ret < 0) {
1696         error_set(errp, QERR_IO_ERROR);
1697         goto exit;
1698     }
1699 
1700     /* write backup grain directory */
1701     for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1702          i < gt_count; i++, tmp += gt_size) {
1703         gd_buf[i] = cpu_to_le32(tmp);
1704     }
1705     ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1706                       gd_buf, gd_buf_size);
1707     if (ret < 0) {
1708         error_set(errp, QERR_IO_ERROR);
1709         goto exit;
1710     }
1711 
1712     ret = 0;
1713 exit:
1714     if (bs) {
1715         bdrv_unref(bs);
1716     }
1717     g_free(gd_buf);
1718     return ret;
1719 }
1720 
1721 static int filename_decompose(const char *filename, char *path, char *prefix,
1722                               char *postfix, size_t buf_len, Error **errp)
1723 {
1724     const char *p, *q;
1725 
1726     if (filename == NULL || !strlen(filename)) {
1727         error_setg(errp, "No filename provided");
1728         return VMDK_ERROR;
1729     }
1730     p = strrchr(filename, '/');
1731     if (p == NULL) {
1732         p = strrchr(filename, '\\');
1733     }
1734     if (p == NULL) {
1735         p = strrchr(filename, ':');
1736     }
1737     if (p != NULL) {
1738         p++;
1739         if (p - filename >= buf_len) {
1740             return VMDK_ERROR;
1741         }
1742         pstrcpy(path, p - filename + 1, filename);
1743     } else {
1744         p = filename;
1745         path[0] = '\0';
1746     }
1747     q = strrchr(p, '.');
1748     if (q == NULL) {
1749         pstrcpy(prefix, buf_len, p);
1750         postfix[0] = '\0';
1751     } else {
1752         if (q - p >= buf_len) {
1753             return VMDK_ERROR;
1754         }
1755         pstrcpy(prefix, q - p + 1, p);
1756         pstrcpy(postfix, buf_len, q);
1757     }
1758     return VMDK_OK;
1759 }
1760 
1761 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1762 {
1763     int idx = 0;
1764     BlockDriverState *new_bs = NULL;
1765     Error *local_err = NULL;
1766     char *desc = NULL;
1767     int64_t total_size = 0, filesize;
1768     char *adapter_type = NULL;
1769     char *backing_file = NULL;
1770     char *fmt = NULL;
1771     int flags = 0;
1772     int ret = 0;
1773     bool flat, split, compress;
1774     GString *ext_desc_lines;
1775     char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1776     const int64_t split_size = 0x80000000;  /* VMDK has constant split size */
1777     const char *desc_extent_line;
1778     char parent_desc_line[BUF_SIZE] = "";
1779     uint32_t parent_cid = 0xffffffff;
1780     uint32_t number_heads = 16;
1781     bool zeroed_grain = false;
1782     uint32_t desc_offset = 0, desc_len;
1783     const char desc_template[] =
1784         "# Disk DescriptorFile\n"
1785         "version=1\n"
1786         "CID=%" PRIx32 "\n"
1787         "parentCID=%" PRIx32 "\n"
1788         "createType=\"%s\"\n"
1789         "%s"
1790         "\n"
1791         "# Extent description\n"
1792         "%s"
1793         "\n"
1794         "# The Disk Data Base\n"
1795         "#DDB\n"
1796         "\n"
1797         "ddb.virtualHWVersion = \"%d\"\n"
1798         "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1799         "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1800         "ddb.geometry.sectors = \"63\"\n"
1801         "ddb.adapterType = \"%s\"\n";
1802 
1803     ext_desc_lines = g_string_new(NULL);
1804 
1805     if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1806         ret = -EINVAL;
1807         goto exit;
1808     }
1809     /* Read out options */
1810     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1811                           BDRV_SECTOR_SIZE);
1812     adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1813     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1814     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1815         flags |= BLOCK_FLAG_COMPAT6;
1816     }
1817     fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1818     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1819         zeroed_grain = true;
1820     }
1821 
1822     if (!adapter_type) {
1823         adapter_type = g_strdup("ide");
1824     } else if (strcmp(adapter_type, "ide") &&
1825                strcmp(adapter_type, "buslogic") &&
1826                strcmp(adapter_type, "lsilogic") &&
1827                strcmp(adapter_type, "legacyESX")) {
1828         error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1829         ret = -EINVAL;
1830         goto exit;
1831     }
1832     if (strcmp(adapter_type, "ide") != 0) {
1833         /* that's the number of heads with which vmware operates when
1834            creating, exporting, etc. vmdk files with a non-ide adapter type */
1835         number_heads = 255;
1836     }
1837     if (!fmt) {
1838         /* Default format to monolithicSparse */
1839         fmt = g_strdup("monolithicSparse");
1840     } else if (strcmp(fmt, "monolithicFlat") &&
1841                strcmp(fmt, "monolithicSparse") &&
1842                strcmp(fmt, "twoGbMaxExtentSparse") &&
1843                strcmp(fmt, "twoGbMaxExtentFlat") &&
1844                strcmp(fmt, "streamOptimized")) {
1845         error_setg(errp, "Unknown subformat: '%s'", fmt);
1846         ret = -EINVAL;
1847         goto exit;
1848     }
1849     split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1850               strcmp(fmt, "twoGbMaxExtentSparse"));
1851     flat = !(strcmp(fmt, "monolithicFlat") &&
1852              strcmp(fmt, "twoGbMaxExtentFlat"));
1853     compress = !strcmp(fmt, "streamOptimized");
1854     if (flat) {
1855         desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1856     } else {
1857         desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1858     }
1859     if (flat && backing_file) {
1860         error_setg(errp, "Flat image can't have backing file");
1861         ret = -ENOTSUP;
1862         goto exit;
1863     }
1864     if (flat && zeroed_grain) {
1865         error_setg(errp, "Flat image can't enable zeroed grain");
1866         ret = -ENOTSUP;
1867         goto exit;
1868     }
1869     if (backing_file) {
1870         BlockDriverState *bs = NULL;
1871         ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_NO_BACKING, NULL,
1872                         errp);
1873         if (ret != 0) {
1874             goto exit;
1875         }
1876         if (strcmp(bs->drv->format_name, "vmdk")) {
1877             bdrv_unref(bs);
1878             ret = -EINVAL;
1879             goto exit;
1880         }
1881         parent_cid = vmdk_read_cid(bs, 0);
1882         bdrv_unref(bs);
1883         snprintf(parent_desc_line, sizeof(parent_desc_line),
1884                 "parentFileNameHint=\"%s\"", backing_file);
1885     }
1886 
1887     /* Create extents */
1888     filesize = total_size;
1889     while (filesize > 0) {
1890         char desc_line[BUF_SIZE];
1891         char ext_filename[PATH_MAX];
1892         char desc_filename[PATH_MAX];
1893         int64_t size = filesize;
1894 
1895         if (split && size > split_size) {
1896             size = split_size;
1897         }
1898         if (split) {
1899             snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1900                     prefix, flat ? 'f' : 's', ++idx, postfix);
1901         } else if (flat) {
1902             snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1903                     prefix, postfix);
1904         } else {
1905             snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1906                     prefix, postfix);
1907         }
1908         snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1909                 path, desc_filename);
1910 
1911         if (vmdk_create_extent(ext_filename, size,
1912                                flat, compress, zeroed_grain, opts, errp)) {
1913             ret = -EINVAL;
1914             goto exit;
1915         }
1916         filesize -= size;
1917 
1918         /* Format description line */
1919         snprintf(desc_line, sizeof(desc_line),
1920                     desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1921         g_string_append(ext_desc_lines, desc_line);
1922     }
1923     /* generate descriptor file */
1924     desc = g_strdup_printf(desc_template,
1925                            (uint32_t)time(NULL),
1926                            parent_cid,
1927                            fmt,
1928                            parent_desc_line,
1929                            ext_desc_lines->str,
1930                            (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1931                            total_size /
1932                                (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1933                            number_heads,
1934                            adapter_type);
1935     desc_len = strlen(desc);
1936     /* the descriptor offset = 0x200 */
1937     if (!split && !flat) {
1938         desc_offset = 0x200;
1939     } else {
1940         ret = bdrv_create_file(filename, opts, &local_err);
1941         if (ret < 0) {
1942             error_propagate(errp, local_err);
1943             goto exit;
1944         }
1945     }
1946     assert(new_bs == NULL);
1947     ret = bdrv_open(&new_bs, filename, NULL, NULL,
1948                     BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
1949     if (ret < 0) {
1950         error_propagate(errp, local_err);
1951         goto exit;
1952     }
1953     ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1954     if (ret < 0) {
1955         error_setg_errno(errp, -ret, "Could not write description");
1956         goto exit;
1957     }
1958     /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1959      * for description file */
1960     if (desc_offset == 0) {
1961         ret = bdrv_truncate(new_bs, desc_len);
1962         if (ret < 0) {
1963             error_setg_errno(errp, -ret, "Could not truncate file");
1964         }
1965     }
1966 exit:
1967     if (new_bs) {
1968         bdrv_unref(new_bs);
1969     }
1970     g_free(adapter_type);
1971     g_free(backing_file);
1972     g_free(fmt);
1973     g_free(desc);
1974     g_string_free(ext_desc_lines, true);
1975     return ret;
1976 }
1977 
1978 static void vmdk_close(BlockDriverState *bs)
1979 {
1980     BDRVVmdkState *s = bs->opaque;
1981 
1982     vmdk_free_extents(bs);
1983     g_free(s->create_type);
1984 
1985     migrate_del_blocker(s->migration_blocker);
1986     error_free(s->migration_blocker);
1987 }
1988 
1989 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1990 {
1991     BDRVVmdkState *s = bs->opaque;
1992     int i, err;
1993     int ret = 0;
1994 
1995     for (i = 0; i < s->num_extents; i++) {
1996         err = bdrv_co_flush(s->extents[i].file);
1997         if (err < 0) {
1998             ret = err;
1999         }
2000     }
2001     return ret;
2002 }
2003 
2004 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2005 {
2006     int i;
2007     int64_t ret = 0;
2008     int64_t r;
2009     BDRVVmdkState *s = bs->opaque;
2010 
2011     ret = bdrv_get_allocated_file_size(bs->file);
2012     if (ret < 0) {
2013         return ret;
2014     }
2015     for (i = 0; i < s->num_extents; i++) {
2016         if (s->extents[i].file == bs->file) {
2017             continue;
2018         }
2019         r = bdrv_get_allocated_file_size(s->extents[i].file);
2020         if (r < 0) {
2021             return r;
2022         }
2023         ret += r;
2024     }
2025     return ret;
2026 }
2027 
2028 static int vmdk_has_zero_init(BlockDriverState *bs)
2029 {
2030     int i;
2031     BDRVVmdkState *s = bs->opaque;
2032 
2033     /* If has a flat extent and its underlying storage doesn't have zero init,
2034      * return 0. */
2035     for (i = 0; i < s->num_extents; i++) {
2036         if (s->extents[i].flat) {
2037             if (!bdrv_has_zero_init(s->extents[i].file)) {
2038                 return 0;
2039             }
2040         }
2041     }
2042     return 1;
2043 }
2044 
2045 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2046 {
2047     ImageInfo *info = g_new0(ImageInfo, 1);
2048 
2049     *info = (ImageInfo){
2050         .filename         = g_strdup(extent->file->filename),
2051         .format           = g_strdup(extent->type),
2052         .virtual_size     = extent->sectors * BDRV_SECTOR_SIZE,
2053         .compressed       = extent->compressed,
2054         .has_compressed   = extent->compressed,
2055         .cluster_size     = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2056         .has_cluster_size = !extent->flat,
2057     };
2058 
2059     return info;
2060 }
2061 
2062 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2063                       BdrvCheckMode fix)
2064 {
2065     BDRVVmdkState *s = bs->opaque;
2066     VmdkExtent *extent = NULL;
2067     int64_t sector_num = 0;
2068     int64_t total_sectors = bdrv_nb_sectors(bs);
2069     int ret;
2070     uint64_t cluster_offset;
2071 
2072     if (fix) {
2073         return -ENOTSUP;
2074     }
2075 
2076     for (;;) {
2077         if (sector_num >= total_sectors) {
2078             return 0;
2079         }
2080         extent = find_extent(s, sector_num, extent);
2081         if (!extent) {
2082             fprintf(stderr,
2083                     "ERROR: could not find extent for sector %" PRId64 "\n",
2084                     sector_num);
2085             break;
2086         }
2087         ret = get_cluster_offset(bs, extent, NULL,
2088                                  sector_num << BDRV_SECTOR_BITS,
2089                                  false, &cluster_offset, 0, 0);
2090         if (ret == VMDK_ERROR) {
2091             fprintf(stderr,
2092                     "ERROR: could not get cluster_offset for sector %"
2093                     PRId64 "\n", sector_num);
2094             break;
2095         }
2096         if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2097             fprintf(stderr,
2098                     "ERROR: cluster offset for sector %"
2099                     PRId64 " points after EOF\n", sector_num);
2100             break;
2101         }
2102         sector_num += extent->cluster_sectors;
2103     }
2104 
2105     result->corruptions++;
2106     return 0;
2107 }
2108 
2109 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2110 {
2111     int i;
2112     BDRVVmdkState *s = bs->opaque;
2113     ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2114     ImageInfoList **next;
2115 
2116     *spec_info = (ImageInfoSpecific){
2117         .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2118         {
2119             .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2120         },
2121     };
2122 
2123     *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2124         .create_type = g_strdup(s->create_type),
2125         .cid = s->cid,
2126         .parent_cid = s->parent_cid,
2127     };
2128 
2129     next = &spec_info->vmdk->extents;
2130     for (i = 0; i < s->num_extents; i++) {
2131         *next = g_new0(ImageInfoList, 1);
2132         (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2133         (*next)->next = NULL;
2134         next = &(*next)->next;
2135     }
2136 
2137     return spec_info;
2138 }
2139 
2140 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2141 {
2142     int i;
2143     BDRVVmdkState *s = bs->opaque;
2144     assert(s->num_extents);
2145     bdi->needs_compressed_writes = s->extents[0].compressed;
2146     if (!s->extents[0].flat) {
2147         bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2148     }
2149     /* See if we have multiple extents but they have different cases */
2150     for (i = 1; i < s->num_extents; i++) {
2151         if (bdi->needs_compressed_writes != s->extents[i].compressed ||
2152             (bdi->cluster_size && bdi->cluster_size !=
2153                 s->extents[i].cluster_sectors << BDRV_SECTOR_BITS)) {
2154             return -ENOTSUP;
2155         }
2156     }
2157     return 0;
2158 }
2159 
2160 static void vmdk_detach_aio_context(BlockDriverState *bs)
2161 {
2162     BDRVVmdkState *s = bs->opaque;
2163     int i;
2164 
2165     for (i = 0; i < s->num_extents; i++) {
2166         bdrv_detach_aio_context(s->extents[i].file);
2167     }
2168 }
2169 
2170 static void vmdk_attach_aio_context(BlockDriverState *bs,
2171                                     AioContext *new_context)
2172 {
2173     BDRVVmdkState *s = bs->opaque;
2174     int i;
2175 
2176     for (i = 0; i < s->num_extents; i++) {
2177         bdrv_attach_aio_context(s->extents[i].file, new_context);
2178     }
2179 }
2180 
2181 static QemuOptsList vmdk_create_opts = {
2182     .name = "vmdk-create-opts",
2183     .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2184     .desc = {
2185         {
2186             .name = BLOCK_OPT_SIZE,
2187             .type = QEMU_OPT_SIZE,
2188             .help = "Virtual disk size"
2189         },
2190         {
2191             .name = BLOCK_OPT_ADAPTER_TYPE,
2192             .type = QEMU_OPT_STRING,
2193             .help = "Virtual adapter type, can be one of "
2194                     "ide (default), lsilogic, buslogic or legacyESX"
2195         },
2196         {
2197             .name = BLOCK_OPT_BACKING_FILE,
2198             .type = QEMU_OPT_STRING,
2199             .help = "File name of a base image"
2200         },
2201         {
2202             .name = BLOCK_OPT_COMPAT6,
2203             .type = QEMU_OPT_BOOL,
2204             .help = "VMDK version 6 image",
2205             .def_value_str = "off"
2206         },
2207         {
2208             .name = BLOCK_OPT_SUBFMT,
2209             .type = QEMU_OPT_STRING,
2210             .help =
2211                 "VMDK flat extent format, can be one of "
2212                 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2213         },
2214         {
2215             .name = BLOCK_OPT_ZEROED_GRAIN,
2216             .type = QEMU_OPT_BOOL,
2217             .help = "Enable efficient zero writes "
2218                     "using the zeroed-grain GTE feature"
2219         },
2220         { /* end of list */ }
2221     }
2222 };
2223 
2224 static BlockDriver bdrv_vmdk = {
2225     .format_name                  = "vmdk",
2226     .instance_size                = sizeof(BDRVVmdkState),
2227     .bdrv_probe                   = vmdk_probe,
2228     .bdrv_open                    = vmdk_open,
2229     .bdrv_check                   = vmdk_check,
2230     .bdrv_reopen_prepare          = vmdk_reopen_prepare,
2231     .bdrv_read                    = vmdk_co_read,
2232     .bdrv_write                   = vmdk_co_write,
2233     .bdrv_write_compressed        = vmdk_write_compressed,
2234     .bdrv_co_write_zeroes         = vmdk_co_write_zeroes,
2235     .bdrv_close                   = vmdk_close,
2236     .bdrv_create                  = vmdk_create,
2237     .bdrv_co_flush_to_disk        = vmdk_co_flush,
2238     .bdrv_co_get_block_status     = vmdk_co_get_block_status,
2239     .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2240     .bdrv_has_zero_init           = vmdk_has_zero_init,
2241     .bdrv_get_specific_info       = vmdk_get_specific_info,
2242     .bdrv_refresh_limits          = vmdk_refresh_limits,
2243     .bdrv_get_info                = vmdk_get_info,
2244     .bdrv_detach_aio_context      = vmdk_detach_aio_context,
2245     .bdrv_attach_aio_context      = vmdk_attach_aio_context,
2246 
2247     .supports_backing             = true,
2248     .create_opts                  = &vmdk_create_opts,
2249 };
2250 
2251 static void bdrv_vmdk_init(void)
2252 {
2253     bdrv_register(&bdrv_vmdk);
2254 }
2255 
2256 block_init(bdrv_vmdk_init);
2257