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