xref: /qemu/block/vmdk.c (revision b3dd1b8c)
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_realloc(s->extents, s->num_extents * sizeof(VmdkExtent));
237 }
238 
239 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
240 {
241     char desc[DESC_SIZE];
242     uint32_t cid = 0xffffffff;
243     const char *p_name, *cid_str;
244     size_t cid_str_size;
245     BDRVVmdkState *s = bs->opaque;
246     int ret;
247 
248     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
249     if (ret < 0) {
250         return 0;
251     }
252 
253     if (parent) {
254         cid_str = "parentCID";
255         cid_str_size = sizeof("parentCID");
256     } else {
257         cid_str = "CID";
258         cid_str_size = sizeof("CID");
259     }
260 
261     desc[DESC_SIZE - 1] = '\0';
262     p_name = strstr(desc, cid_str);
263     if (p_name != NULL) {
264         p_name += cid_str_size;
265         sscanf(p_name, "%" SCNx32, &cid);
266     }
267 
268     return cid;
269 }
270 
271 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
272 {
273     char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
274     char *p_name, *tmp_str;
275     BDRVVmdkState *s = bs->opaque;
276     int ret;
277 
278     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
279     if (ret < 0) {
280         return ret;
281     }
282 
283     desc[DESC_SIZE - 1] = '\0';
284     tmp_str = strstr(desc, "parentCID");
285     if (tmp_str == NULL) {
286         return -EINVAL;
287     }
288 
289     pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
290     p_name = strstr(desc, "CID");
291     if (p_name != NULL) {
292         p_name += sizeof("CID");
293         snprintf(p_name, sizeof(desc) - (p_name - desc), "%" PRIx32 "\n", cid);
294         pstrcat(desc, sizeof(desc), tmp_desc);
295     }
296 
297     ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
298     if (ret < 0) {
299         return ret;
300     }
301 
302     return 0;
303 }
304 
305 static int vmdk_is_cid_valid(BlockDriverState *bs)
306 {
307     BDRVVmdkState *s = bs->opaque;
308     BlockDriverState *p_bs = bs->backing_hd;
309     uint32_t cur_pcid;
310 
311     if (!s->cid_checked && p_bs) {
312         cur_pcid = vmdk_read_cid(p_bs, 0);
313         if (s->parent_cid != cur_pcid) {
314             /* CID not valid */
315             return 0;
316         }
317     }
318     s->cid_checked = true;
319     /* CID valid */
320     return 1;
321 }
322 
323 /* Queue extents, if any, for reopen() */
324 static int vmdk_reopen_prepare(BDRVReopenState *state,
325                                BlockReopenQueue *queue, Error **errp)
326 {
327     BDRVVmdkState *s;
328     int ret = -1;
329     int i;
330     VmdkExtent *e;
331 
332     assert(state != NULL);
333     assert(state->bs != NULL);
334 
335     if (queue == NULL) {
336         error_setg(errp, "No reopen queue for VMDK extents");
337         goto exit;
338     }
339 
340     s = state->bs->opaque;
341 
342     assert(s != NULL);
343 
344     for (i = 0; i < s->num_extents; i++) {
345         e = &s->extents[i];
346         if (e->file != state->bs->file) {
347             bdrv_reopen_queue(queue, e->file, state->flags);
348         }
349     }
350     ret = 0;
351 
352 exit:
353     return ret;
354 }
355 
356 static int vmdk_parent_open(BlockDriverState *bs)
357 {
358     char *p_name;
359     char desc[DESC_SIZE + 1];
360     BDRVVmdkState *s = bs->opaque;
361     int ret;
362 
363     desc[DESC_SIZE] = '\0';
364     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
365     if (ret < 0) {
366         return ret;
367     }
368 
369     p_name = strstr(desc, "parentFileNameHint");
370     if (p_name != NULL) {
371         char *end_name;
372 
373         p_name += sizeof("parentFileNameHint") + 1;
374         end_name = strchr(p_name, '\"');
375         if (end_name == NULL) {
376             return -EINVAL;
377         }
378         if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
379             return -EINVAL;
380         }
381 
382         pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
383     }
384 
385     return 0;
386 }
387 
388 /* Create and append extent to the extent array. Return the added VmdkExtent
389  * address. return NULL if allocation failed. */
390 static int vmdk_add_extent(BlockDriverState *bs,
391                            BlockDriverState *file, bool flat, int64_t sectors,
392                            int64_t l1_offset, int64_t l1_backup_offset,
393                            uint32_t l1_size,
394                            int l2_size, uint64_t cluster_sectors,
395                            VmdkExtent **new_extent,
396                            Error **errp)
397 {
398     VmdkExtent *extent;
399     BDRVVmdkState *s = bs->opaque;
400     int64_t length;
401 
402     if (cluster_sectors > 0x200000) {
403         /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
404         error_setg(errp, "Invalid granularity, image may be corrupt");
405         return -EFBIG;
406     }
407     if (l1_size > 512 * 1024 * 1024) {
408         /* Although with big capacity and small l1_entry_sectors, we can get a
409          * big l1_size, we don't want unbounded value to allocate the table.
410          * Limit it to 512M, which is 16PB for default cluster and L2 table
411          * size */
412         error_setg(errp, "L1 size too big");
413         return -EFBIG;
414     }
415 
416     length = bdrv_getlength(file);
417     if (length < 0) {
418         return length;
419     }
420 
421     s->extents = g_realloc(s->extents,
422                               (s->num_extents + 1) * sizeof(VmdkExtent));
423     extent = &s->extents[s->num_extents];
424     s->num_extents++;
425 
426     memset(extent, 0, sizeof(VmdkExtent));
427     extent->file = file;
428     extent->flat = flat;
429     extent->sectors = sectors;
430     extent->l1_table_offset = l1_offset;
431     extent->l1_backup_table_offset = l1_backup_offset;
432     extent->l1_size = l1_size;
433     extent->l1_entry_sectors = l2_size * cluster_sectors;
434     extent->l2_size = l2_size;
435     extent->cluster_sectors = flat ? sectors : cluster_sectors;
436     extent->next_cluster_sector =
437         ROUND_UP(DIV_ROUND_UP(length, BDRV_SECTOR_SIZE), cluster_sectors);
438 
439     if (s->num_extents > 1) {
440         extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
441     } else {
442         extent->end_sector = extent->sectors;
443     }
444     bs->total_sectors = extent->end_sector;
445     if (new_extent) {
446         *new_extent = extent;
447     }
448     return 0;
449 }
450 
451 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
452                             Error **errp)
453 {
454     int ret;
455     int l1_size, i;
456 
457     /* read the L1 table */
458     l1_size = extent->l1_size * sizeof(uint32_t);
459     extent->l1_table = g_try_malloc(l1_size);
460     if (l1_size && extent->l1_table == NULL) {
461         return -ENOMEM;
462     }
463 
464     ret = bdrv_pread(extent->file,
465                      extent->l1_table_offset,
466                      extent->l1_table,
467                      l1_size);
468     if (ret < 0) {
469         error_setg_errno(errp, -ret,
470                          "Could not read l1 table from extent '%s'",
471                          extent->file->filename);
472         goto fail_l1;
473     }
474     for (i = 0; i < extent->l1_size; i++) {
475         le32_to_cpus(&extent->l1_table[i]);
476     }
477 
478     if (extent->l1_backup_table_offset) {
479         extent->l1_backup_table = g_try_malloc(l1_size);
480         if (l1_size && extent->l1_backup_table == NULL) {
481             ret = -ENOMEM;
482             goto fail_l1;
483         }
484         ret = bdrv_pread(extent->file,
485                          extent->l1_backup_table_offset,
486                          extent->l1_backup_table,
487                          l1_size);
488         if (ret < 0) {
489             error_setg_errno(errp, -ret,
490                              "Could not read l1 backup table from extent '%s'",
491                              extent->file->filename);
492             goto fail_l1b;
493         }
494         for (i = 0; i < extent->l1_size; i++) {
495             le32_to_cpus(&extent->l1_backup_table[i]);
496         }
497     }
498 
499     extent->l2_cache =
500         g_malloc(extent->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
501     return 0;
502  fail_l1b:
503     g_free(extent->l1_backup_table);
504  fail_l1:
505     g_free(extent->l1_table);
506     return ret;
507 }
508 
509 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
510                                  BlockDriverState *file,
511                                  int flags, Error **errp)
512 {
513     int ret;
514     uint32_t magic;
515     VMDK3Header header;
516     VmdkExtent *extent;
517 
518     ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
519     if (ret < 0) {
520         error_setg_errno(errp, -ret,
521                          "Could not read header from file '%s'",
522                          file->filename);
523         return ret;
524     }
525     ret = vmdk_add_extent(bs, file, false,
526                           le32_to_cpu(header.disk_sectors),
527                           le32_to_cpu(header.l1dir_offset) << 9,
528                           0,
529                           le32_to_cpu(header.l1dir_size),
530                           4096,
531                           le32_to_cpu(header.granularity),
532                           &extent,
533                           errp);
534     if (ret < 0) {
535         return ret;
536     }
537     ret = vmdk_init_tables(bs, extent, errp);
538     if (ret) {
539         /* free extent allocated by vmdk_add_extent */
540         vmdk_free_last_extent(bs);
541     }
542     return ret;
543 }
544 
545 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
546                                Error **errp);
547 
548 static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset,
549                             Error **errp)
550 {
551     int64_t size;
552     char *buf;
553     int ret;
554 
555     size = bdrv_getlength(file);
556     if (size < 0) {
557         error_setg_errno(errp, -size, "Could not access file");
558         return NULL;
559     }
560 
561     size = MIN(size, 1 << 20);  /* avoid unbounded allocation */
562     buf = g_malloc0(size + 1);
563 
564     ret = bdrv_pread(file, desc_offset, buf, size);
565     if (ret < 0) {
566         error_setg_errno(errp, -ret, "Could not read from file");
567         g_free(buf);
568         return NULL;
569     }
570 
571     return buf;
572 }
573 
574 static int vmdk_open_vmdk4(BlockDriverState *bs,
575                            BlockDriverState *file,
576                            int flags, Error **errp)
577 {
578     int ret;
579     uint32_t magic;
580     uint32_t l1_size, l1_entry_sectors;
581     VMDK4Header header;
582     VmdkExtent *extent;
583     BDRVVmdkState *s = bs->opaque;
584     int64_t l1_backup_offset = 0;
585 
586     ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
587     if (ret < 0) {
588         error_setg_errno(errp, -ret,
589                          "Could not read header from file '%s'",
590                          file->filename);
591         return -EINVAL;
592     }
593     if (header.capacity == 0) {
594         uint64_t desc_offset = le64_to_cpu(header.desc_offset);
595         if (desc_offset) {
596             char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
597             if (!buf) {
598                 return -EINVAL;
599             }
600             ret = vmdk_open_desc_file(bs, flags, buf, errp);
601             g_free(buf);
602             return ret;
603         }
604     }
605 
606     if (!s->create_type) {
607         s->create_type = g_strdup("monolithicSparse");
608     }
609 
610     if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
611         /*
612          * The footer takes precedence over the header, so read it in. The
613          * footer starts at offset -1024 from the end: One sector for the
614          * footer, and another one for the end-of-stream marker.
615          */
616         struct {
617             struct {
618                 uint64_t val;
619                 uint32_t size;
620                 uint32_t type;
621                 uint8_t pad[512 - 16];
622             } QEMU_PACKED footer_marker;
623 
624             uint32_t magic;
625             VMDK4Header header;
626             uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
627 
628             struct {
629                 uint64_t val;
630                 uint32_t size;
631                 uint32_t type;
632                 uint8_t pad[512 - 16];
633             } QEMU_PACKED eos_marker;
634         } QEMU_PACKED footer;
635 
636         ret = bdrv_pread(file,
637             bs->file->total_sectors * 512 - 1536,
638             &footer, sizeof(footer));
639         if (ret < 0) {
640             return ret;
641         }
642 
643         /* Some sanity checks for the footer */
644         if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
645             le32_to_cpu(footer.footer_marker.size) != 0  ||
646             le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
647             le64_to_cpu(footer.eos_marker.val) != 0  ||
648             le32_to_cpu(footer.eos_marker.size) != 0  ||
649             le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
650         {
651             return -EINVAL;
652         }
653 
654         header = footer.header;
655     }
656 
657     if (le32_to_cpu(header.version) > 3) {
658         char buf[64];
659         snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
660                  le32_to_cpu(header.version));
661         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
662                   bs->device_name, "vmdk", buf);
663         return -ENOTSUP;
664     } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
665         /* VMware KB 2064959 explains that version 3 added support for
666          * persistent changed block tracking (CBT), and backup software can
667          * read it as version=1 if it doesn't care about the changed area
668          * information. So we are safe to enable read only. */
669         error_setg(errp, "VMDK version 3 must be read only");
670         return -EINVAL;
671     }
672 
673     if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
674         error_setg(errp, "L2 table size too big");
675         return -EINVAL;
676     }
677 
678     l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
679                         * le64_to_cpu(header.granularity);
680     if (l1_entry_sectors == 0) {
681         return -EINVAL;
682     }
683     l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
684                 / l1_entry_sectors;
685     if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
686         l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
687     }
688     if (bdrv_nb_sectors(file) < le64_to_cpu(header.grain_offset)) {
689         error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
690                    (int64_t)(le64_to_cpu(header.grain_offset)
691                              * BDRV_SECTOR_SIZE));
692         return -EINVAL;
693     }
694 
695     ret = vmdk_add_extent(bs, file, false,
696                           le64_to_cpu(header.capacity),
697                           le64_to_cpu(header.gd_offset) << 9,
698                           l1_backup_offset,
699                           l1_size,
700                           le32_to_cpu(header.num_gtes_per_gt),
701                           le64_to_cpu(header.granularity),
702                           &extent,
703                           errp);
704     if (ret < 0) {
705         return ret;
706     }
707     extent->compressed =
708         le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
709     if (extent->compressed) {
710         g_free(s->create_type);
711         s->create_type = g_strdup("streamOptimized");
712     }
713     extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
714     extent->version = le32_to_cpu(header.version);
715     extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
716     ret = vmdk_init_tables(bs, extent, errp);
717     if (ret) {
718         /* free extent allocated by vmdk_add_extent */
719         vmdk_free_last_extent(bs);
720     }
721     return ret;
722 }
723 
724 /* find an option value out of descriptor file */
725 static int vmdk_parse_description(const char *desc, const char *opt_name,
726         char *buf, int buf_size)
727 {
728     char *opt_pos, *opt_end;
729     const char *end = desc + strlen(desc);
730 
731     opt_pos = strstr(desc, opt_name);
732     if (!opt_pos) {
733         return VMDK_ERROR;
734     }
735     /* Skip "=\"" following opt_name */
736     opt_pos += strlen(opt_name) + 2;
737     if (opt_pos >= end) {
738         return VMDK_ERROR;
739     }
740     opt_end = opt_pos;
741     while (opt_end < end && *opt_end != '"') {
742         opt_end++;
743     }
744     if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
745         return VMDK_ERROR;
746     }
747     pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
748     return VMDK_OK;
749 }
750 
751 /* Open an extent file and append to bs array */
752 static int vmdk_open_sparse(BlockDriverState *bs,
753                             BlockDriverState *file, int flags,
754                             char *buf, Error **errp)
755 {
756     uint32_t magic;
757 
758     magic = ldl_be_p(buf);
759     switch (magic) {
760         case VMDK3_MAGIC:
761             return vmdk_open_vmfs_sparse(bs, file, flags, errp);
762             break;
763         case VMDK4_MAGIC:
764             return vmdk_open_vmdk4(bs, file, flags, errp);
765             break;
766         default:
767             error_setg(errp, "Image not in VMDK format");
768             return -EINVAL;
769             break;
770     }
771 }
772 
773 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
774                               const char *desc_file_path, Error **errp)
775 {
776     int ret;
777     char access[11];
778     char type[11];
779     char fname[512];
780     const char *p = desc;
781     int64_t sectors = 0;
782     int64_t flat_offset;
783     char extent_path[PATH_MAX];
784     BlockDriverState *extent_file;
785     BDRVVmdkState *s = bs->opaque;
786     VmdkExtent *extent;
787 
788     while (*p) {
789         /* parse extent line:
790          * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
791          * or
792          * RW [size in sectors] SPARSE "file-name.vmdk"
793          */
794         flat_offset = -1;
795         ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
796                 access, &sectors, type, fname, &flat_offset);
797         if (ret < 4 || strcmp(access, "RW")) {
798             goto next_line;
799         } else if (!strcmp(type, "FLAT")) {
800             if (ret != 5 || flat_offset < 0) {
801                 error_setg(errp, "Invalid extent lines: \n%s", p);
802                 return -EINVAL;
803             }
804         } else if (!strcmp(type, "VMFS")) {
805             if (ret == 4) {
806                 flat_offset = 0;
807             } else {
808                 error_setg(errp, "Invalid extent lines:\n%s", p);
809                 return -EINVAL;
810             }
811         } else if (ret != 4) {
812             error_setg(errp, "Invalid extent lines:\n%s", p);
813             return -EINVAL;
814         }
815 
816         if (sectors <= 0 ||
817             (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
818              strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
819             (strcmp(access, "RW"))) {
820             goto next_line;
821         }
822 
823         path_combine(extent_path, sizeof(extent_path),
824                 desc_file_path, fname);
825         extent_file = NULL;
826         ret = bdrv_open(&extent_file, extent_path, NULL, NULL,
827                         bs->open_flags | BDRV_O_PROTOCOL, NULL, errp);
828         if (ret) {
829             return ret;
830         }
831 
832         /* save to extents array */
833         if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
834             /* FLAT extent */
835 
836             ret = vmdk_add_extent(bs, extent_file, true, sectors,
837                             0, 0, 0, 0, 0, &extent, errp);
838             if (ret < 0) {
839                 return ret;
840             }
841             extent->flat_start_offset = flat_offset << 9;
842         } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
843             /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
844             char *buf = vmdk_read_desc(extent_file, 0, errp);
845             if (!buf) {
846                 ret = -EINVAL;
847             } else {
848                 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf, errp);
849             }
850             if (ret) {
851                 g_free(buf);
852                 bdrv_unref(extent_file);
853                 return ret;
854             }
855             extent = &s->extents[s->num_extents - 1];
856         } else {
857             error_setg(errp, "Unsupported extent type '%s'", type);
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     int32_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 = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
1811     adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1812     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1813     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1814         flags |= BLOCK_FLAG_COMPAT6;
1815     }
1816     fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1817     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1818         zeroed_grain = true;
1819     }
1820 
1821     if (!adapter_type) {
1822         adapter_type = g_strdup("ide");
1823     } else if (strcmp(adapter_type, "ide") &&
1824                strcmp(adapter_type, "buslogic") &&
1825                strcmp(adapter_type, "lsilogic") &&
1826                strcmp(adapter_type, "legacyESX")) {
1827         error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1828         ret = -EINVAL;
1829         goto exit;
1830     }
1831     if (strcmp(adapter_type, "ide") != 0) {
1832         /* that's the number of heads with which vmware operates when
1833            creating, exporting, etc. vmdk files with a non-ide adapter type */
1834         number_heads = 255;
1835     }
1836     if (!fmt) {
1837         /* Default format to monolithicSparse */
1838         fmt = g_strdup("monolithicSparse");
1839     } else if (strcmp(fmt, "monolithicFlat") &&
1840                strcmp(fmt, "monolithicSparse") &&
1841                strcmp(fmt, "twoGbMaxExtentSparse") &&
1842                strcmp(fmt, "twoGbMaxExtentFlat") &&
1843                strcmp(fmt, "streamOptimized")) {
1844         error_setg(errp, "Unknown subformat: '%s'", fmt);
1845         ret = -EINVAL;
1846         goto exit;
1847     }
1848     split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1849               strcmp(fmt, "twoGbMaxExtentSparse"));
1850     flat = !(strcmp(fmt, "monolithicFlat") &&
1851              strcmp(fmt, "twoGbMaxExtentFlat"));
1852     compress = !strcmp(fmt, "streamOptimized");
1853     if (flat) {
1854         desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1855     } else {
1856         desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1857     }
1858     if (flat && backing_file) {
1859         error_setg(errp, "Flat image can't have backing file");
1860         ret = -ENOTSUP;
1861         goto exit;
1862     }
1863     if (flat && zeroed_grain) {
1864         error_setg(errp, "Flat image can't enable zeroed grain");
1865         ret = -ENOTSUP;
1866         goto exit;
1867     }
1868     if (backing_file) {
1869         BlockDriverState *bs = NULL;
1870         ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_NO_BACKING, NULL,
1871                         errp);
1872         if (ret != 0) {
1873             goto exit;
1874         }
1875         if (strcmp(bs->drv->format_name, "vmdk")) {
1876             bdrv_unref(bs);
1877             ret = -EINVAL;
1878             goto exit;
1879         }
1880         parent_cid = vmdk_read_cid(bs, 0);
1881         bdrv_unref(bs);
1882         snprintf(parent_desc_line, sizeof(parent_desc_line),
1883                 "parentFileNameHint=\"%s\"", backing_file);
1884     }
1885 
1886     /* Create extents */
1887     filesize = total_size;
1888     while (filesize > 0) {
1889         char desc_line[BUF_SIZE];
1890         char ext_filename[PATH_MAX];
1891         char desc_filename[PATH_MAX];
1892         int64_t size = filesize;
1893 
1894         if (split && size > split_size) {
1895             size = split_size;
1896         }
1897         if (split) {
1898             snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1899                     prefix, flat ? 'f' : 's', ++idx, postfix);
1900         } else if (flat) {
1901             snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1902                     prefix, postfix);
1903         } else {
1904             snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1905                     prefix, postfix);
1906         }
1907         snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1908                 path, desc_filename);
1909 
1910         if (vmdk_create_extent(ext_filename, size,
1911                                flat, compress, zeroed_grain, opts, errp)) {
1912             ret = -EINVAL;
1913             goto exit;
1914         }
1915         filesize -= size;
1916 
1917         /* Format description line */
1918         snprintf(desc_line, sizeof(desc_line),
1919                     desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1920         g_string_append(ext_desc_lines, desc_line);
1921     }
1922     /* generate descriptor file */
1923     desc = g_strdup_printf(desc_template,
1924                            (uint32_t)time(NULL),
1925                            parent_cid,
1926                            fmt,
1927                            parent_desc_line,
1928                            ext_desc_lines->str,
1929                            (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1930                            total_size /
1931                                (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1932                            number_heads,
1933                            adapter_type);
1934     desc_len = strlen(desc);
1935     /* the descriptor offset = 0x200 */
1936     if (!split && !flat) {
1937         desc_offset = 0x200;
1938     } else {
1939         ret = bdrv_create_file(filename, opts, &local_err);
1940         if (ret < 0) {
1941             error_propagate(errp, local_err);
1942             goto exit;
1943         }
1944     }
1945     assert(new_bs == NULL);
1946     ret = bdrv_open(&new_bs, filename, NULL, NULL,
1947                     BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
1948     if (ret < 0) {
1949         error_propagate(errp, local_err);
1950         goto exit;
1951     }
1952     ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
1953     if (ret < 0) {
1954         error_setg_errno(errp, -ret, "Could not write description");
1955         goto exit;
1956     }
1957     /* bdrv_pwrite write padding zeros to align to sector, we don't need that
1958      * for description file */
1959     if (desc_offset == 0) {
1960         ret = bdrv_truncate(new_bs, desc_len);
1961         if (ret < 0) {
1962             error_setg_errno(errp, -ret, "Could not truncate file");
1963         }
1964     }
1965 exit:
1966     if (new_bs) {
1967         bdrv_unref(new_bs);
1968     }
1969     g_free(adapter_type);
1970     g_free(backing_file);
1971     g_free(fmt);
1972     g_free(desc);
1973     g_string_free(ext_desc_lines, true);
1974     return ret;
1975 }
1976 
1977 static void vmdk_close(BlockDriverState *bs)
1978 {
1979     BDRVVmdkState *s = bs->opaque;
1980 
1981     vmdk_free_extents(bs);
1982     g_free(s->create_type);
1983 
1984     migrate_del_blocker(s->migration_blocker);
1985     error_free(s->migration_blocker);
1986 }
1987 
1988 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1989 {
1990     BDRVVmdkState *s = bs->opaque;
1991     int i, err;
1992     int ret = 0;
1993 
1994     for (i = 0; i < s->num_extents; i++) {
1995         err = bdrv_co_flush(s->extents[i].file);
1996         if (err < 0) {
1997             ret = err;
1998         }
1999     }
2000     return ret;
2001 }
2002 
2003 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2004 {
2005     int i;
2006     int64_t ret = 0;
2007     int64_t r;
2008     BDRVVmdkState *s = bs->opaque;
2009 
2010     ret = bdrv_get_allocated_file_size(bs->file);
2011     if (ret < 0) {
2012         return ret;
2013     }
2014     for (i = 0; i < s->num_extents; i++) {
2015         if (s->extents[i].file == bs->file) {
2016             continue;
2017         }
2018         r = bdrv_get_allocated_file_size(s->extents[i].file);
2019         if (r < 0) {
2020             return r;
2021         }
2022         ret += r;
2023     }
2024     return ret;
2025 }
2026 
2027 static int vmdk_has_zero_init(BlockDriverState *bs)
2028 {
2029     int i;
2030     BDRVVmdkState *s = bs->opaque;
2031 
2032     /* If has a flat extent and its underlying storage doesn't have zero init,
2033      * return 0. */
2034     for (i = 0; i < s->num_extents; i++) {
2035         if (s->extents[i].flat) {
2036             if (!bdrv_has_zero_init(s->extents[i].file)) {
2037                 return 0;
2038             }
2039         }
2040     }
2041     return 1;
2042 }
2043 
2044 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2045 {
2046     ImageInfo *info = g_new0(ImageInfo, 1);
2047 
2048     *info = (ImageInfo){
2049         .filename         = g_strdup(extent->file->filename),
2050         .format           = g_strdup(extent->type),
2051         .virtual_size     = extent->sectors * BDRV_SECTOR_SIZE,
2052         .compressed       = extent->compressed,
2053         .has_compressed   = extent->compressed,
2054         .cluster_size     = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2055         .has_cluster_size = !extent->flat,
2056     };
2057 
2058     return info;
2059 }
2060 
2061 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2062                       BdrvCheckMode fix)
2063 {
2064     BDRVVmdkState *s = bs->opaque;
2065     VmdkExtent *extent = NULL;
2066     int64_t sector_num = 0;
2067     int64_t total_sectors = bdrv_nb_sectors(bs);
2068     int ret;
2069     uint64_t cluster_offset;
2070 
2071     if (fix) {
2072         return -ENOTSUP;
2073     }
2074 
2075     for (;;) {
2076         if (sector_num >= total_sectors) {
2077             return 0;
2078         }
2079         extent = find_extent(s, sector_num, extent);
2080         if (!extent) {
2081             fprintf(stderr,
2082                     "ERROR: could not find extent for sector %" PRId64 "\n",
2083                     sector_num);
2084             break;
2085         }
2086         ret = get_cluster_offset(bs, extent, NULL,
2087                                  sector_num << BDRV_SECTOR_BITS,
2088                                  false, &cluster_offset, 0, 0);
2089         if (ret == VMDK_ERROR) {
2090             fprintf(stderr,
2091                     "ERROR: could not get cluster_offset for sector %"
2092                     PRId64 "\n", sector_num);
2093             break;
2094         }
2095         if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2096             fprintf(stderr,
2097                     "ERROR: cluster offset for sector %"
2098                     PRId64 " points after EOF\n", sector_num);
2099             break;
2100         }
2101         sector_num += extent->cluster_sectors;
2102     }
2103 
2104     result->corruptions++;
2105     return 0;
2106 }
2107 
2108 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2109 {
2110     int i;
2111     BDRVVmdkState *s = bs->opaque;
2112     ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2113     ImageInfoList **next;
2114 
2115     *spec_info = (ImageInfoSpecific){
2116         .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2117         {
2118             .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2119         },
2120     };
2121 
2122     *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2123         .create_type = g_strdup(s->create_type),
2124         .cid = s->cid,
2125         .parent_cid = s->parent_cid,
2126     };
2127 
2128     next = &spec_info->vmdk->extents;
2129     for (i = 0; i < s->num_extents; i++) {
2130         *next = g_new0(ImageInfoList, 1);
2131         (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2132         (*next)->next = NULL;
2133         next = &(*next)->next;
2134     }
2135 
2136     return spec_info;
2137 }
2138 
2139 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2140 {
2141     int i;
2142     BDRVVmdkState *s = bs->opaque;
2143     assert(s->num_extents);
2144     bdi->needs_compressed_writes = s->extents[0].compressed;
2145     if (!s->extents[0].flat) {
2146         bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2147     }
2148     /* See if we have multiple extents but they have different cases */
2149     for (i = 1; i < s->num_extents; i++) {
2150         if (bdi->needs_compressed_writes != s->extents[i].compressed ||
2151             (bdi->cluster_size && bdi->cluster_size !=
2152                 s->extents[i].cluster_sectors << BDRV_SECTOR_BITS)) {
2153             return -ENOTSUP;
2154         }
2155     }
2156     return 0;
2157 }
2158 
2159 static void vmdk_detach_aio_context(BlockDriverState *bs)
2160 {
2161     BDRVVmdkState *s = bs->opaque;
2162     int i;
2163 
2164     for (i = 0; i < s->num_extents; i++) {
2165         bdrv_detach_aio_context(s->extents[i].file);
2166     }
2167 }
2168 
2169 static void vmdk_attach_aio_context(BlockDriverState *bs,
2170                                     AioContext *new_context)
2171 {
2172     BDRVVmdkState *s = bs->opaque;
2173     int i;
2174 
2175     for (i = 0; i < s->num_extents; i++) {
2176         bdrv_attach_aio_context(s->extents[i].file, new_context);
2177     }
2178 }
2179 
2180 static QemuOptsList vmdk_create_opts = {
2181     .name = "vmdk-create-opts",
2182     .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2183     .desc = {
2184         {
2185             .name = BLOCK_OPT_SIZE,
2186             .type = QEMU_OPT_SIZE,
2187             .help = "Virtual disk size"
2188         },
2189         {
2190             .name = BLOCK_OPT_ADAPTER_TYPE,
2191             .type = QEMU_OPT_STRING,
2192             .help = "Virtual adapter type, can be one of "
2193                     "ide (default), lsilogic, buslogic or legacyESX"
2194         },
2195         {
2196             .name = BLOCK_OPT_BACKING_FILE,
2197             .type = QEMU_OPT_STRING,
2198             .help = "File name of a base image"
2199         },
2200         {
2201             .name = BLOCK_OPT_COMPAT6,
2202             .type = QEMU_OPT_BOOL,
2203             .help = "VMDK version 6 image",
2204             .def_value_str = "off"
2205         },
2206         {
2207             .name = BLOCK_OPT_SUBFMT,
2208             .type = QEMU_OPT_STRING,
2209             .help =
2210                 "VMDK flat extent format, can be one of "
2211                 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2212         },
2213         {
2214             .name = BLOCK_OPT_ZEROED_GRAIN,
2215             .type = QEMU_OPT_BOOL,
2216             .help = "Enable efficient zero writes "
2217                     "using the zeroed-grain GTE feature"
2218         },
2219         { /* end of list */ }
2220     }
2221 };
2222 
2223 static BlockDriver bdrv_vmdk = {
2224     .format_name                  = "vmdk",
2225     .instance_size                = sizeof(BDRVVmdkState),
2226     .bdrv_probe                   = vmdk_probe,
2227     .bdrv_open                    = vmdk_open,
2228     .bdrv_check                   = vmdk_check,
2229     .bdrv_reopen_prepare          = vmdk_reopen_prepare,
2230     .bdrv_read                    = vmdk_co_read,
2231     .bdrv_write                   = vmdk_co_write,
2232     .bdrv_write_compressed        = vmdk_write_compressed,
2233     .bdrv_co_write_zeroes         = vmdk_co_write_zeroes,
2234     .bdrv_close                   = vmdk_close,
2235     .bdrv_create                  = vmdk_create,
2236     .bdrv_co_flush_to_disk        = vmdk_co_flush,
2237     .bdrv_co_get_block_status     = vmdk_co_get_block_status,
2238     .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2239     .bdrv_has_zero_init           = vmdk_has_zero_init,
2240     .bdrv_get_specific_info       = vmdk_get_specific_info,
2241     .bdrv_refresh_limits          = vmdk_refresh_limits,
2242     .bdrv_get_info                = vmdk_get_info,
2243     .bdrv_detach_aio_context      = vmdk_detach_aio_context,
2244     .bdrv_attach_aio_context      = vmdk_attach_aio_context,
2245 
2246     .supports_backing             = true,
2247     .create_opts                  = &vmdk_create_opts,
2248 };
2249 
2250 static void bdrv_vmdk_init(void)
2251 {
2252     bdrv_register(&bdrv_vmdk);
2253 }
2254 
2255 block_init(bdrv_vmdk_init);
2256