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