xref: /qemu/block/vmdk.c (revision 8b7b9c5c)
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 "qapi/error.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "qapi/qmp/qdict.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qemu/error-report.h"
33 #include "qemu/module.h"
34 #include "qemu/option.h"
35 #include "qemu/bswap.h"
36 #include "qemu/memalign.h"
37 #include "migration/blocker.h"
38 #include "qemu/cutils.h"
39 #include <zlib.h>
40 
41 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
42 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
43 #define VMDK4_COMPRESSION_DEFLATE 1
44 #define VMDK4_FLAG_NL_DETECT (1 << 0)
45 #define VMDK4_FLAG_RGD (1 << 1)
46 /* Zeroed-grain enable bit */
47 #define VMDK4_FLAG_ZERO_GRAIN   (1 << 2)
48 #define VMDK4_FLAG_COMPRESS (1 << 16)
49 #define VMDK4_FLAG_MARKER (1 << 17)
50 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
51 
52 #define VMDK_EXTENT_MAX_SECTORS (1ULL << 32)
53 
54 #define VMDK_GTE_ZEROED 0x1
55 
56 /* VMDK internal error codes */
57 #define VMDK_OK      0
58 #define VMDK_ERROR   (-1)
59 /* Cluster not allocated */
60 #define VMDK_UNALLOC (-2)
61 #define VMDK_ZEROED  (-3)
62 
63 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
64 #define BLOCK_OPT_TOOLSVERSION "toolsversion"
65 
66 typedef struct {
67     uint32_t version;
68     uint32_t flags;
69     uint32_t disk_sectors;
70     uint32_t granularity;
71     uint32_t l1dir_offset;
72     uint32_t l1dir_size;
73     uint32_t file_sectors;
74     uint32_t cylinders;
75     uint32_t heads;
76     uint32_t sectors_per_track;
77 } QEMU_PACKED VMDK3Header;
78 
79 typedef struct {
80     uint32_t version;
81     uint32_t flags;
82     uint64_t capacity;
83     uint64_t granularity;
84     uint64_t desc_offset;
85     uint64_t desc_size;
86     /* Number of GrainTableEntries per GrainTable */
87     uint32_t num_gtes_per_gt;
88     uint64_t rgd_offset;
89     uint64_t gd_offset;
90     uint64_t grain_offset;
91     char filler[1];
92     char check_bytes[4];
93     uint16_t compressAlgorithm;
94 } QEMU_PACKED VMDK4Header;
95 
96 typedef struct VMDKSESparseConstHeader {
97     uint64_t magic;
98     uint64_t version;
99     uint64_t capacity;
100     uint64_t grain_size;
101     uint64_t grain_table_size;
102     uint64_t flags;
103     uint64_t reserved1;
104     uint64_t reserved2;
105     uint64_t reserved3;
106     uint64_t reserved4;
107     uint64_t volatile_header_offset;
108     uint64_t volatile_header_size;
109     uint64_t journal_header_offset;
110     uint64_t journal_header_size;
111     uint64_t journal_offset;
112     uint64_t journal_size;
113     uint64_t grain_dir_offset;
114     uint64_t grain_dir_size;
115     uint64_t grain_tables_offset;
116     uint64_t grain_tables_size;
117     uint64_t free_bitmap_offset;
118     uint64_t free_bitmap_size;
119     uint64_t backmap_offset;
120     uint64_t backmap_size;
121     uint64_t grains_offset;
122     uint64_t grains_size;
123     uint8_t pad[304];
124 } QEMU_PACKED VMDKSESparseConstHeader;
125 
126 typedef struct VMDKSESparseVolatileHeader {
127     uint64_t magic;
128     uint64_t free_gt_number;
129     uint64_t next_txn_seq_number;
130     uint64_t replay_journal;
131     uint8_t pad[480];
132 } QEMU_PACKED VMDKSESparseVolatileHeader;
133 
134 #define L2_CACHE_SIZE 16
135 
136 typedef struct VmdkExtent {
137     BdrvChild *file;
138     bool flat;
139     bool compressed;
140     bool has_marker;
141     bool has_zero_grain;
142     bool sesparse;
143     uint64_t sesparse_l2_tables_offset;
144     uint64_t sesparse_clusters_offset;
145     int32_t entry_size;
146     int version;
147     int64_t sectors;
148     int64_t end_sector;
149     int64_t flat_start_offset;
150     int64_t l1_table_offset;
151     int64_t l1_backup_table_offset;
152     void *l1_table;
153     uint32_t *l1_backup_table;
154     unsigned int l1_size;
155     uint32_t l1_entry_sectors;
156 
157     unsigned int l2_size;
158     void *l2_cache;
159     uint32_t l2_cache_offsets[L2_CACHE_SIZE];
160     uint32_t l2_cache_counts[L2_CACHE_SIZE];
161 
162     int64_t cluster_sectors;
163     int64_t next_cluster_sector;
164     char *type;
165 } VmdkExtent;
166 
167 typedef struct BDRVVmdkState {
168     CoMutex lock;
169     uint64_t desc_offset;
170     bool cid_updated;
171     bool cid_checked;
172     uint32_t cid;
173     uint32_t parent_cid;
174     int num_extents;
175     /* Extent array with num_extents entries, ascend ordered by address */
176     VmdkExtent *extents;
177     Error *migration_blocker;
178     char *create_type;
179 } BDRVVmdkState;
180 
181 typedef struct BDRVVmdkReopenState {
182     bool *extents_using_bs_file;
183 } BDRVVmdkReopenState;
184 
185 typedef struct VmdkMetaData {
186     unsigned int l1_index;
187     unsigned int l2_index;
188     unsigned int l2_offset;
189     bool new_allocation;
190     uint32_t *l2_cache_entry;
191 } VmdkMetaData;
192 
193 typedef struct VmdkGrainMarker {
194     uint64_t lba;
195     uint32_t size;
196     uint8_t  data[];
197 } QEMU_PACKED VmdkGrainMarker;
198 
199 enum {
200     MARKER_END_OF_STREAM    = 0,
201     MARKER_GRAIN_TABLE      = 1,
202     MARKER_GRAIN_DIRECTORY  = 2,
203     MARKER_FOOTER           = 3,
204 };
205 
206 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
207 {
208     uint32_t magic;
209 
210     if (buf_size < 4) {
211         return 0;
212     }
213     magic = be32_to_cpu(*(uint32_t *)buf);
214     if (magic == VMDK3_MAGIC ||
215         magic == VMDK4_MAGIC) {
216         return 100;
217     } else {
218         const char *p = (const char *)buf;
219         const char *end = p + buf_size;
220         while (p < end) {
221             if (*p == '#') {
222                 /* skip comment line */
223                 while (p < end && *p != '\n') {
224                     p++;
225                 }
226                 p++;
227                 continue;
228             }
229             if (*p == ' ') {
230                 while (p < end && *p == ' ') {
231                     p++;
232                 }
233                 /* skip '\r' if windows line endings used. */
234                 if (p < end && *p == '\r') {
235                     p++;
236                 }
237                 /* only accept blank lines before 'version=' line */
238                 if (p == end || *p != '\n') {
239                     return 0;
240                 }
241                 p++;
242                 continue;
243             }
244             if (end - p >= strlen("version=X\n")) {
245                 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
246                     strncmp("version=2\n", p, strlen("version=2\n")) == 0 ||
247                     strncmp("version=3\n", p, strlen("version=3\n")) == 0) {
248                     return 100;
249                 }
250             }
251             if (end - p >= strlen("version=X\r\n")) {
252                 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
253                     strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0 ||
254                     strncmp("version=3\r\n", p, strlen("version=3\r\n")) == 0) {
255                     return 100;
256                 }
257             }
258             return 0;
259         }
260         return 0;
261     }
262 }
263 
264 #define SECTOR_SIZE 512
265 #define DESC_SIZE (20 * SECTOR_SIZE)    /* 20 sectors of 512 bytes each */
266 #define BUF_SIZE 4096
267 #define HEADER_SIZE 512                 /* first sector of 512 bytes */
268 
269 static void vmdk_free_extents(BlockDriverState *bs)
270 {
271     int i;
272     BDRVVmdkState *s = bs->opaque;
273     VmdkExtent *e;
274 
275     bdrv_graph_wrlock(NULL);
276     for (i = 0; i < s->num_extents; i++) {
277         e = &s->extents[i];
278         g_free(e->l1_table);
279         g_free(e->l2_cache);
280         g_free(e->l1_backup_table);
281         g_free(e->type);
282         if (e->file != bs->file) {
283             bdrv_unref_child(bs, e->file);
284         }
285     }
286     bdrv_graph_wrunlock();
287 
288     g_free(s->extents);
289 }
290 
291 static void vmdk_free_last_extent(BlockDriverState *bs)
292 {
293     BDRVVmdkState *s = bs->opaque;
294 
295     if (s->num_extents == 0) {
296         return;
297     }
298     s->num_extents--;
299     s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
300 }
301 
302 /* Return -ve errno, or 0 on success and write CID into *pcid. */
303 static int vmdk_read_cid(BlockDriverState *bs, int parent, uint32_t *pcid)
304 {
305     char *desc;
306     uint32_t cid;
307     const char *p_name, *cid_str;
308     size_t cid_str_size;
309     BDRVVmdkState *s = bs->opaque;
310     int ret;
311 
312     desc = g_malloc0(DESC_SIZE);
313     ret = bdrv_pread(bs->file, s->desc_offset, DESC_SIZE, desc, 0);
314     if (ret < 0) {
315         goto out;
316     }
317 
318     if (parent) {
319         cid_str = "parentCID";
320         cid_str_size = sizeof("parentCID");
321     } else {
322         cid_str = "CID";
323         cid_str_size = sizeof("CID");
324     }
325 
326     desc[DESC_SIZE - 1] = '\0';
327     p_name = strstr(desc, cid_str);
328     if (p_name == NULL) {
329         ret = -EINVAL;
330         goto out;
331     }
332     p_name += cid_str_size;
333     if (sscanf(p_name, "%" SCNx32, &cid) != 1) {
334         ret = -EINVAL;
335         goto out;
336     }
337     *pcid = cid;
338     ret = 0;
339 
340 out:
341     g_free(desc);
342     return ret;
343 }
344 
345 static int coroutine_fn GRAPH_RDLOCK
346 vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
347 {
348     char *desc, *tmp_desc;
349     char *p_name, *tmp_str;
350     BDRVVmdkState *s = bs->opaque;
351     int ret = 0;
352 
353     desc = g_malloc0(DESC_SIZE);
354     tmp_desc = g_malloc0(DESC_SIZE);
355     ret = bdrv_co_pread(bs->file, s->desc_offset, DESC_SIZE, desc, 0);
356     if (ret < 0) {
357         goto out;
358     }
359 
360     desc[DESC_SIZE - 1] = '\0';
361     tmp_str = strstr(desc, "parentCID");
362     if (tmp_str == NULL) {
363         ret = -EINVAL;
364         goto out;
365     }
366 
367     pstrcpy(tmp_desc, DESC_SIZE, tmp_str);
368     p_name = strstr(desc, "CID");
369     if (p_name != NULL) {
370         p_name += sizeof("CID");
371         snprintf(p_name, DESC_SIZE - (p_name - desc), "%" PRIx32 "\n", cid);
372         pstrcat(desc, DESC_SIZE, tmp_desc);
373     }
374 
375     ret = bdrv_co_pwrite_sync(bs->file, s->desc_offset, DESC_SIZE, desc, 0);
376 
377 out:
378     g_free(desc);
379     g_free(tmp_desc);
380     return ret;
381 }
382 
383 static int coroutine_fn vmdk_is_cid_valid(BlockDriverState *bs)
384 {
385     BDRVVmdkState *s = bs->opaque;
386     uint32_t cur_pcid;
387 
388     if (!s->cid_checked && bs->backing) {
389         BlockDriverState *p_bs = bs->backing->bs;
390 
391         if (strcmp(p_bs->drv->format_name, "vmdk")) {
392             /* Backing file is not in vmdk format, so it does not have
393              * a CID, which makes the overlay's parent CID invalid */
394             return 0;
395         }
396 
397         if (vmdk_read_cid(p_bs, 0, &cur_pcid) != 0) {
398             /* read failure: report as not valid */
399             return 0;
400         }
401         if (s->parent_cid != cur_pcid) {
402             /* CID not valid */
403             return 0;
404         }
405     }
406     s->cid_checked = true;
407     /* CID valid */
408     return 1;
409 }
410 
411 static int vmdk_reopen_prepare(BDRVReopenState *state,
412                                BlockReopenQueue *queue, Error **errp)
413 {
414     BDRVVmdkState *s;
415     BDRVVmdkReopenState *rs;
416     int i;
417 
418     assert(state != NULL);
419     assert(state->bs != NULL);
420     assert(state->opaque == NULL);
421 
422     s = state->bs->opaque;
423 
424     rs = g_new0(BDRVVmdkReopenState, 1);
425     state->opaque = rs;
426 
427     /*
428      * Check whether there are any extents stored in bs->file; if bs->file
429      * changes, we will need to update their .file pointers to follow suit
430      */
431     rs->extents_using_bs_file = g_new(bool, s->num_extents);
432     for (i = 0; i < s->num_extents; i++) {
433         rs->extents_using_bs_file[i] = s->extents[i].file == state->bs->file;
434     }
435 
436     return 0;
437 }
438 
439 static void vmdk_reopen_clean(BDRVReopenState *state)
440 {
441     BDRVVmdkReopenState *rs = state->opaque;
442 
443     g_free(rs->extents_using_bs_file);
444     g_free(rs);
445     state->opaque = NULL;
446 }
447 
448 static void vmdk_reopen_commit(BDRVReopenState *state)
449 {
450     BDRVVmdkState *s = state->bs->opaque;
451     BDRVVmdkReopenState *rs = state->opaque;
452     int i;
453 
454     for (i = 0; i < s->num_extents; i++) {
455         if (rs->extents_using_bs_file[i]) {
456             s->extents[i].file = state->bs->file;
457         }
458     }
459 
460     vmdk_reopen_clean(state);
461 }
462 
463 static void vmdk_reopen_abort(BDRVReopenState *state)
464 {
465     vmdk_reopen_clean(state);
466 }
467 
468 static int vmdk_parent_open(BlockDriverState *bs)
469 {
470     char *p_name;
471     char *desc;
472     BDRVVmdkState *s = bs->opaque;
473     int ret;
474 
475     desc = g_malloc0(DESC_SIZE + 1);
476     ret = bdrv_pread(bs->file, s->desc_offset, DESC_SIZE, desc, 0);
477     if (ret < 0) {
478         goto out;
479     }
480 
481     p_name = strstr(desc, "parentFileNameHint");
482     if (p_name != NULL) {
483         char *end_name;
484 
485         p_name += sizeof("parentFileNameHint") + 1;
486         end_name = strchr(p_name, '\"');
487         if (end_name == NULL) {
488             ret = -EINVAL;
489             goto out;
490         }
491         if ((end_name - p_name) > sizeof(bs->auto_backing_file) - 1) {
492             ret = -EINVAL;
493             goto out;
494         }
495 
496         pstrcpy(bs->auto_backing_file, end_name - p_name + 1, p_name);
497         pstrcpy(bs->backing_file, sizeof(bs->backing_file),
498                 bs->auto_backing_file);
499         pstrcpy(bs->backing_format, sizeof(bs->backing_format),
500                 "vmdk");
501     }
502 
503 out:
504     g_free(desc);
505     return ret;
506 }
507 
508 /* Create and append extent to the extent array. Return the added VmdkExtent
509  * address. return NULL if allocation failed. */
510 static int vmdk_add_extent(BlockDriverState *bs,
511                            BdrvChild *file, bool flat, int64_t sectors,
512                            int64_t l1_offset, int64_t l1_backup_offset,
513                            uint32_t l1_size,
514                            int l2_size, uint64_t cluster_sectors,
515                            VmdkExtent **new_extent,
516                            Error **errp)
517 {
518     VmdkExtent *extent;
519     BDRVVmdkState *s = bs->opaque;
520     int64_t nb_sectors;
521 
522     if (cluster_sectors > 0x200000) {
523         /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
524         error_setg(errp, "Invalid granularity, image may be corrupt");
525         return -EFBIG;
526     }
527     if (l1_size > 32 * 1024 * 1024) {
528         /*
529          * Although with big capacity and small l1_entry_sectors, we can get a
530          * big l1_size, we don't want unbounded value to allocate the table.
531          * Limit it to 32M, which is enough to store:
532          *     8TB  - for both VMDK3 & VMDK4 with
533          *            minimal cluster size: 512B
534          *            minimal L2 table size: 512 entries
535          *            8 TB is still more than the maximal value supported for
536          *            VMDK3 & VMDK4 which is 2TB.
537          *     64TB - for "ESXi seSparse Extent"
538          *            minimal cluster size: 512B (default is 4KB)
539          *            L2 table size: 4096 entries (const).
540          *            64TB is more than the maximal value supported for
541          *            seSparse VMDKs (which is slightly less than 64TB)
542          */
543         error_setg(errp, "L1 size too big");
544         return -EFBIG;
545     }
546 
547     nb_sectors = bdrv_nb_sectors(file->bs);
548     if (nb_sectors < 0) {
549         return nb_sectors;
550     }
551 
552     s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
553     extent = &s->extents[s->num_extents];
554     s->num_extents++;
555 
556     memset(extent, 0, sizeof(VmdkExtent));
557     extent->file = file;
558     extent->flat = flat;
559     extent->sectors = sectors;
560     extent->l1_table_offset = l1_offset;
561     extent->l1_backup_table_offset = l1_backup_offset;
562     extent->l1_size = l1_size;
563     extent->l1_entry_sectors = l2_size * cluster_sectors;
564     extent->l2_size = l2_size;
565     extent->cluster_sectors = flat ? sectors : cluster_sectors;
566     extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
567     extent->entry_size = sizeof(uint32_t);
568 
569     if (s->num_extents > 1) {
570         extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
571     } else {
572         extent->end_sector = extent->sectors;
573     }
574     bs->total_sectors = extent->end_sector;
575     if (new_extent) {
576         *new_extent = extent;
577     }
578     return 0;
579 }
580 
581 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
582                             Error **errp)
583 {
584     int ret;
585     size_t l1_size;
586     int i;
587 
588     /* read the L1 table */
589     l1_size = extent->l1_size * extent->entry_size;
590     extent->l1_table = g_try_malloc(l1_size);
591     if (l1_size && extent->l1_table == NULL) {
592         return -ENOMEM;
593     }
594 
595     ret = bdrv_pread(extent->file, extent->l1_table_offset, l1_size,
596                      extent->l1_table, 0);
597     if (ret < 0) {
598         bdrv_refresh_filename(extent->file->bs);
599         error_setg_errno(errp, -ret,
600                          "Could not read l1 table from extent '%s'",
601                          extent->file->bs->filename);
602         goto fail_l1;
603     }
604     for (i = 0; i < extent->l1_size; i++) {
605         if (extent->entry_size == sizeof(uint64_t)) {
606             le64_to_cpus((uint64_t *)extent->l1_table + i);
607         } else {
608             assert(extent->entry_size == sizeof(uint32_t));
609             le32_to_cpus((uint32_t *)extent->l1_table + i);
610         }
611     }
612 
613     if (extent->l1_backup_table_offset) {
614         assert(!extent->sesparse);
615         extent->l1_backup_table = g_try_malloc(l1_size);
616         if (l1_size && extent->l1_backup_table == NULL) {
617             ret = -ENOMEM;
618             goto fail_l1;
619         }
620         ret = bdrv_pread(extent->file, extent->l1_backup_table_offset,
621                          l1_size, extent->l1_backup_table, 0);
622         if (ret < 0) {
623             bdrv_refresh_filename(extent->file->bs);
624             error_setg_errno(errp, -ret,
625                              "Could not read l1 backup table from extent '%s'",
626                              extent->file->bs->filename);
627             goto fail_l1b;
628         }
629         for (i = 0; i < extent->l1_size; i++) {
630             le32_to_cpus(&extent->l1_backup_table[i]);
631         }
632     }
633 
634     extent->l2_cache =
635         g_malloc(extent->entry_size * extent->l2_size * L2_CACHE_SIZE);
636     return 0;
637  fail_l1b:
638     g_free(extent->l1_backup_table);
639  fail_l1:
640     g_free(extent->l1_table);
641     return ret;
642 }
643 
644 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
645                                  BdrvChild *file,
646                                  int flags, Error **errp)
647 {
648     int ret;
649     uint32_t magic;
650     VMDK3Header header;
651     VmdkExtent *extent = NULL;
652 
653     ret = bdrv_pread(file, sizeof(magic), sizeof(header), &header, 0);
654     if (ret < 0) {
655         bdrv_refresh_filename(file->bs);
656         error_setg_errno(errp, -ret,
657                          "Could not read header from file '%s'",
658                          file->bs->filename);
659         return ret;
660     }
661     ret = vmdk_add_extent(bs, file, false,
662                           le32_to_cpu(header.disk_sectors),
663                           (int64_t)le32_to_cpu(header.l1dir_offset) << 9,
664                           0,
665                           le32_to_cpu(header.l1dir_size),
666                           4096,
667                           le32_to_cpu(header.granularity),
668                           &extent,
669                           errp);
670     if (ret < 0) {
671         return ret;
672     }
673     ret = vmdk_init_tables(bs, extent, errp);
674     if (ret) {
675         /* free extent allocated by vmdk_add_extent */
676         vmdk_free_last_extent(bs);
677     }
678     return ret;
679 }
680 
681 #define SESPARSE_CONST_HEADER_MAGIC UINT64_C(0x00000000cafebabe)
682 #define SESPARSE_VOLATILE_HEADER_MAGIC UINT64_C(0x00000000cafecafe)
683 
684 /* Strict checks - format not officially documented */
685 static int check_se_sparse_const_header(VMDKSESparseConstHeader *header,
686                                         Error **errp)
687 {
688     header->magic = le64_to_cpu(header->magic);
689     header->version = le64_to_cpu(header->version);
690     header->grain_size = le64_to_cpu(header->grain_size);
691     header->grain_table_size = le64_to_cpu(header->grain_table_size);
692     header->flags = le64_to_cpu(header->flags);
693     header->reserved1 = le64_to_cpu(header->reserved1);
694     header->reserved2 = le64_to_cpu(header->reserved2);
695     header->reserved3 = le64_to_cpu(header->reserved3);
696     header->reserved4 = le64_to_cpu(header->reserved4);
697 
698     header->volatile_header_offset =
699         le64_to_cpu(header->volatile_header_offset);
700     header->volatile_header_size = le64_to_cpu(header->volatile_header_size);
701 
702     header->journal_header_offset = le64_to_cpu(header->journal_header_offset);
703     header->journal_header_size = le64_to_cpu(header->journal_header_size);
704 
705     header->journal_offset = le64_to_cpu(header->journal_offset);
706     header->journal_size = le64_to_cpu(header->journal_size);
707 
708     header->grain_dir_offset = le64_to_cpu(header->grain_dir_offset);
709     header->grain_dir_size = le64_to_cpu(header->grain_dir_size);
710 
711     header->grain_tables_offset = le64_to_cpu(header->grain_tables_offset);
712     header->grain_tables_size = le64_to_cpu(header->grain_tables_size);
713 
714     header->free_bitmap_offset = le64_to_cpu(header->free_bitmap_offset);
715     header->free_bitmap_size = le64_to_cpu(header->free_bitmap_size);
716 
717     header->backmap_offset = le64_to_cpu(header->backmap_offset);
718     header->backmap_size = le64_to_cpu(header->backmap_size);
719 
720     header->grains_offset = le64_to_cpu(header->grains_offset);
721     header->grains_size = le64_to_cpu(header->grains_size);
722 
723     if (header->magic != SESPARSE_CONST_HEADER_MAGIC) {
724         error_setg(errp, "Bad const header magic: 0x%016" PRIx64,
725                    header->magic);
726         return -EINVAL;
727     }
728 
729     if (header->version != 0x0000000200000001) {
730         error_setg(errp, "Unsupported version: 0x%016" PRIx64,
731                    header->version);
732         return -ENOTSUP;
733     }
734 
735     if (header->grain_size != 8) {
736         error_setg(errp, "Unsupported grain size: %" PRIu64,
737                    header->grain_size);
738         return -ENOTSUP;
739     }
740 
741     if (header->grain_table_size != 64) {
742         error_setg(errp, "Unsupported grain table size: %" PRIu64,
743                    header->grain_table_size);
744         return -ENOTSUP;
745     }
746 
747     if (header->flags != 0) {
748         error_setg(errp, "Unsupported flags: 0x%016" PRIx64,
749                    header->flags);
750         return -ENOTSUP;
751     }
752 
753     if (header->reserved1 != 0 || header->reserved2 != 0 ||
754         header->reserved3 != 0 || header->reserved4 != 0) {
755         error_setg(errp, "Unsupported reserved bits:"
756                    " 0x%016" PRIx64 " 0x%016" PRIx64
757                    " 0x%016" PRIx64 " 0x%016" PRIx64,
758                    header->reserved1, header->reserved2,
759                    header->reserved3, header->reserved4);
760         return -ENOTSUP;
761     }
762 
763     /* check that padding is 0 */
764     if (!buffer_is_zero(header->pad, sizeof(header->pad))) {
765         error_setg(errp, "Unsupported non-zero const header padding");
766         return -ENOTSUP;
767     }
768 
769     return 0;
770 }
771 
772 static int check_se_sparse_volatile_header(VMDKSESparseVolatileHeader *header,
773                                            Error **errp)
774 {
775     header->magic = le64_to_cpu(header->magic);
776     header->free_gt_number = le64_to_cpu(header->free_gt_number);
777     header->next_txn_seq_number = le64_to_cpu(header->next_txn_seq_number);
778     header->replay_journal = le64_to_cpu(header->replay_journal);
779 
780     if (header->magic != SESPARSE_VOLATILE_HEADER_MAGIC) {
781         error_setg(errp, "Bad volatile header magic: 0x%016" PRIx64,
782                    header->magic);
783         return -EINVAL;
784     }
785 
786     if (header->replay_journal) {
787         error_setg(errp, "Image is dirty, Replaying journal not supported");
788         return -ENOTSUP;
789     }
790 
791     /* check that padding is 0 */
792     if (!buffer_is_zero(header->pad, sizeof(header->pad))) {
793         error_setg(errp, "Unsupported non-zero volatile header padding");
794         return -ENOTSUP;
795     }
796 
797     return 0;
798 }
799 
800 static int vmdk_open_se_sparse(BlockDriverState *bs,
801                                BdrvChild *file,
802                                int flags, Error **errp)
803 {
804     int ret;
805     VMDKSESparseConstHeader const_header;
806     VMDKSESparseVolatileHeader volatile_header;
807     VmdkExtent *extent = NULL;
808 
809     ret = bdrv_apply_auto_read_only(bs,
810             "No write support for seSparse images available", errp);
811     if (ret < 0) {
812         return ret;
813     }
814 
815     assert(sizeof(const_header) == SECTOR_SIZE);
816 
817     ret = bdrv_pread(file, 0, sizeof(const_header), &const_header, 0);
818     if (ret < 0) {
819         bdrv_refresh_filename(file->bs);
820         error_setg_errno(errp, -ret,
821                          "Could not read const header from file '%s'",
822                          file->bs->filename);
823         return ret;
824     }
825 
826     /* check const header */
827     ret = check_se_sparse_const_header(&const_header, errp);
828     if (ret < 0) {
829         return ret;
830     }
831 
832     assert(sizeof(volatile_header) == SECTOR_SIZE);
833 
834     ret = bdrv_pread(file, const_header.volatile_header_offset * SECTOR_SIZE,
835                      sizeof(volatile_header), &volatile_header, 0);
836     if (ret < 0) {
837         bdrv_refresh_filename(file->bs);
838         error_setg_errno(errp, -ret,
839                          "Could not read volatile header from file '%s'",
840                          file->bs->filename);
841         return ret;
842     }
843 
844     /* check volatile header */
845     ret = check_se_sparse_volatile_header(&volatile_header, errp);
846     if (ret < 0) {
847         return ret;
848     }
849 
850     ret = vmdk_add_extent(bs, file, false,
851                           const_header.capacity,
852                           const_header.grain_dir_offset * SECTOR_SIZE,
853                           0,
854                           const_header.grain_dir_size *
855                           SECTOR_SIZE / sizeof(uint64_t),
856                           const_header.grain_table_size *
857                           SECTOR_SIZE / sizeof(uint64_t),
858                           const_header.grain_size,
859                           &extent,
860                           errp);
861     if (ret < 0) {
862         return ret;
863     }
864 
865     extent->sesparse = true;
866     extent->sesparse_l2_tables_offset = const_header.grain_tables_offset;
867     extent->sesparse_clusters_offset = const_header.grains_offset;
868     extent->entry_size = sizeof(uint64_t);
869 
870     ret = vmdk_init_tables(bs, extent, errp);
871     if (ret) {
872         /* free extent allocated by vmdk_add_extent */
873         vmdk_free_last_extent(bs);
874     }
875 
876     return ret;
877 }
878 
879 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
880                                QDict *options, Error **errp);
881 
882 static char *vmdk_read_desc(BdrvChild *file, uint64_t desc_offset, Error **errp)
883 {
884     int64_t size;
885     char *buf;
886     int ret;
887 
888     size = bdrv_getlength(file->bs);
889     if (size < 0) {
890         error_setg_errno(errp, -size, "Could not access file");
891         return NULL;
892     }
893 
894     if (size < 4) {
895         /* Both descriptor file and sparse image must be much larger than 4
896          * bytes, also callers of vmdk_read_desc want to compare the first 4
897          * bytes with VMDK4_MAGIC, let's error out if less is read. */
898         error_setg(errp, "File is too small, not a valid image");
899         return NULL;
900     }
901 
902     size = MIN(size, (1 << 20) - 1);  /* avoid unbounded allocation */
903     buf = g_malloc(size + 1);
904 
905     ret = bdrv_pread(file, desc_offset, size, buf, 0);
906     if (ret < 0) {
907         error_setg_errno(errp, -ret, "Could not read from file");
908         g_free(buf);
909         return NULL;
910     }
911     buf[size] = 0;
912 
913     return buf;
914 }
915 
916 static int vmdk_open_vmdk4(BlockDriverState *bs,
917                            BdrvChild *file,
918                            int flags, QDict *options, Error **errp)
919 {
920     int ret;
921     uint32_t magic;
922     uint32_t l1_size, l1_entry_sectors;
923     VMDK4Header header;
924     VmdkExtent *extent = NULL;
925     BDRVVmdkState *s = bs->opaque;
926     int64_t l1_backup_offset = 0;
927     bool compressed;
928 
929     ret = bdrv_pread(file, sizeof(magic), sizeof(header), &header, 0);
930     if (ret < 0) {
931         bdrv_refresh_filename(file->bs);
932         error_setg_errno(errp, -ret,
933                          "Could not read header from file '%s'",
934                          file->bs->filename);
935         return -EINVAL;
936     }
937     if (header.capacity == 0) {
938         uint64_t desc_offset = le64_to_cpu(header.desc_offset);
939         if (desc_offset) {
940             char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
941             if (!buf) {
942                 return -EINVAL;
943             }
944             ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
945             g_free(buf);
946             return ret;
947         }
948     }
949 
950     if (!s->create_type) {
951         s->create_type = g_strdup("monolithicSparse");
952     }
953 
954     if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
955         /*
956          * The footer takes precedence over the header, so read it in. The
957          * footer starts at offset -1024 from the end: One sector for the
958          * footer, and another one for the end-of-stream marker.
959          */
960         struct {
961             struct {
962                 uint64_t val;
963                 uint32_t size;
964                 uint32_t type;
965                 uint8_t pad[512 - 16];
966             } QEMU_PACKED footer_marker;
967 
968             uint32_t magic;
969             VMDK4Header header;
970             uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
971 
972             struct {
973                 uint64_t val;
974                 uint32_t size;
975                 uint32_t type;
976                 uint8_t pad[512 - 16];
977             } QEMU_PACKED eos_marker;
978         } QEMU_PACKED footer;
979 
980         ret = bdrv_pread(file, bs->file->bs->total_sectors * 512 - 1536,
981                          sizeof(footer), &footer, 0);
982         if (ret < 0) {
983             error_setg_errno(errp, -ret, "Failed to read footer");
984             return ret;
985         }
986 
987         /* Some sanity checks for the footer */
988         if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
989             le32_to_cpu(footer.footer_marker.size) != 0  ||
990             le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
991             le64_to_cpu(footer.eos_marker.val) != 0  ||
992             le32_to_cpu(footer.eos_marker.size) != 0  ||
993             le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
994         {
995             error_setg(errp, "Invalid footer");
996             return -EINVAL;
997         }
998 
999         header = footer.header;
1000     }
1001 
1002     compressed =
1003         le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
1004     if (le32_to_cpu(header.version) > 3) {
1005         error_setg(errp, "Unsupported VMDK version %" PRIu32,
1006                    le32_to_cpu(header.version));
1007         return -ENOTSUP;
1008     } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR) &&
1009                !compressed) {
1010         /* VMware KB 2064959 explains that version 3 added support for
1011          * persistent changed block tracking (CBT), and backup software can
1012          * read it as version=1 if it doesn't care about the changed area
1013          * information. So we are safe to enable read only. */
1014         error_setg(errp, "VMDK version 3 must be read only");
1015         return -EINVAL;
1016     }
1017 
1018     if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
1019         error_setg(errp, "L2 table size too big");
1020         return -EINVAL;
1021     }
1022 
1023     l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
1024                         * le64_to_cpu(header.granularity);
1025     if (l1_entry_sectors == 0) {
1026         error_setg(errp, "L1 entry size is invalid");
1027         return -EINVAL;
1028     }
1029     l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
1030                 / l1_entry_sectors;
1031     if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
1032         l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
1033     }
1034     if (bdrv_nb_sectors(file->bs) < le64_to_cpu(header.grain_offset)) {
1035         error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
1036                    (int64_t)(le64_to_cpu(header.grain_offset)
1037                              * BDRV_SECTOR_SIZE));
1038         return -EINVAL;
1039     }
1040 
1041     ret = vmdk_add_extent(bs, file, false,
1042                           le64_to_cpu(header.capacity),
1043                           le64_to_cpu(header.gd_offset) << 9,
1044                           l1_backup_offset,
1045                           l1_size,
1046                           le32_to_cpu(header.num_gtes_per_gt),
1047                           le64_to_cpu(header.granularity),
1048                           &extent,
1049                           errp);
1050     if (ret < 0) {
1051         return ret;
1052     }
1053     extent->compressed =
1054         le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
1055     if (extent->compressed) {
1056         g_free(s->create_type);
1057         s->create_type = g_strdup("streamOptimized");
1058     }
1059     extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
1060     extent->version = le32_to_cpu(header.version);
1061     extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
1062     ret = vmdk_init_tables(bs, extent, errp);
1063     if (ret) {
1064         /* free extent allocated by vmdk_add_extent */
1065         vmdk_free_last_extent(bs);
1066     }
1067     return ret;
1068 }
1069 
1070 /* find an option value out of descriptor file */
1071 static int vmdk_parse_description(const char *desc, const char *opt_name,
1072         char *buf, int buf_size)
1073 {
1074     char *opt_pos, *opt_end;
1075     const char *end = desc + strlen(desc);
1076 
1077     opt_pos = strstr(desc, opt_name);
1078     if (!opt_pos) {
1079         return VMDK_ERROR;
1080     }
1081     /* Skip "=\"" following opt_name */
1082     opt_pos += strlen(opt_name) + 2;
1083     if (opt_pos >= end) {
1084         return VMDK_ERROR;
1085     }
1086     opt_end = opt_pos;
1087     while (opt_end < end && *opt_end != '"') {
1088         opt_end++;
1089     }
1090     if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
1091         return VMDK_ERROR;
1092     }
1093     pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
1094     return VMDK_OK;
1095 }
1096 
1097 /* Open an extent file and append to bs array */
1098 static int vmdk_open_sparse(BlockDriverState *bs, BdrvChild *file, int flags,
1099                             char *buf, QDict *options, Error **errp)
1100 {
1101     uint32_t magic;
1102 
1103     magic = ldl_be_p(buf);
1104     switch (magic) {
1105         case VMDK3_MAGIC:
1106             return vmdk_open_vmfs_sparse(bs, file, flags, errp);
1107         case VMDK4_MAGIC:
1108             return vmdk_open_vmdk4(bs, file, flags, options, errp);
1109         default:
1110             error_setg(errp, "Image not in VMDK format");
1111             return -EINVAL;
1112     }
1113 }
1114 
1115 static const char *next_line(const char *s)
1116 {
1117     while (*s) {
1118         if (*s == '\n') {
1119             return s + 1;
1120         }
1121         s++;
1122     }
1123     return s;
1124 }
1125 
1126 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
1127                               QDict *options, Error **errp)
1128 {
1129     int ret;
1130     int matches;
1131     char access[11];
1132     char type[11];
1133     char fname[512];
1134     const char *p, *np;
1135     int64_t sectors = 0;
1136     int64_t flat_offset;
1137     char *desc_file_dir = NULL;
1138     char *extent_path;
1139     BdrvChild *extent_file;
1140     BdrvChildRole extent_role;
1141     BDRVVmdkState *s = bs->opaque;
1142     VmdkExtent *extent = NULL;
1143     char extent_opt_prefix[32];
1144     Error *local_err = NULL;
1145 
1146     for (p = desc; *p; p = next_line(p)) {
1147         /* parse extent line in one of below formats:
1148          *
1149          * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
1150          * RW [size in sectors] SPARSE "file-name.vmdk"
1151          * RW [size in sectors] VMFS "file-name.vmdk"
1152          * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
1153          * RW [size in sectors] SESPARSE "file-name.vmdk"
1154          */
1155         flat_offset = -1;
1156         matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
1157                          access, &sectors, type, fname, &flat_offset);
1158         if (matches < 4 || strcmp(access, "RW")) {
1159             continue;
1160         } else if (!strcmp(type, "FLAT")) {
1161             if (matches != 5 || flat_offset < 0) {
1162                 goto invalid;
1163             }
1164         } else if (!strcmp(type, "VMFS")) {
1165             if (matches == 4) {
1166                 flat_offset = 0;
1167             } else {
1168                 goto invalid;
1169             }
1170         } else if (matches != 4) {
1171             goto invalid;
1172         }
1173 
1174         if (sectors <= 0 ||
1175             (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
1176              strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE") &&
1177              strcmp(type, "SESPARSE")) ||
1178             (strcmp(access, "RW"))) {
1179             continue;
1180         }
1181 
1182         if (path_is_absolute(fname)) {
1183             extent_path = g_strdup(fname);
1184         } else {
1185             if (!desc_file_dir) {
1186                 desc_file_dir = bdrv_dirname(bs->file->bs, errp);
1187                 if (!desc_file_dir) {
1188                     bdrv_refresh_filename(bs->file->bs);
1189                     error_prepend(errp, "Cannot use relative paths with VMDK "
1190                                   "descriptor file '%s': ",
1191                                   bs->file->bs->filename);
1192                     ret = -EINVAL;
1193                     goto out;
1194                 }
1195             }
1196 
1197             extent_path = g_strconcat(desc_file_dir, fname, NULL);
1198         }
1199 
1200         ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents);
1201         assert(ret < 32);
1202 
1203         extent_role = BDRV_CHILD_DATA;
1204         if (strcmp(type, "FLAT") != 0 && strcmp(type, "VMFS") != 0) {
1205             /* non-flat extents have metadata */
1206             extent_role |= BDRV_CHILD_METADATA;
1207         }
1208 
1209         extent_file = bdrv_open_child(extent_path, options, extent_opt_prefix,
1210                                       bs, &child_of_bds, extent_role, false,
1211                                       &local_err);
1212         g_free(extent_path);
1213         if (!extent_file) {
1214             error_propagate(errp, local_err);
1215             ret = -EINVAL;
1216             goto out;
1217         }
1218 
1219         /* save to extents array */
1220         if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
1221             /* FLAT extent */
1222 
1223             ret = vmdk_add_extent(bs, extent_file, true, sectors,
1224                             0, 0, 0, 0, 0, &extent, errp);
1225             if (ret < 0) {
1226                 bdrv_graph_wrlock(NULL);
1227                 bdrv_unref_child(bs, extent_file);
1228                 bdrv_graph_wrunlock();
1229                 goto out;
1230             }
1231             extent->flat_start_offset = flat_offset << 9;
1232         } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
1233             /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
1234             char *buf = vmdk_read_desc(extent_file, 0, errp);
1235             if (!buf) {
1236                 ret = -EINVAL;
1237             } else {
1238                 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf,
1239                                        options, errp);
1240             }
1241             g_free(buf);
1242             if (ret) {
1243                 bdrv_graph_wrlock(NULL);
1244                 bdrv_unref_child(bs, extent_file);
1245                 bdrv_graph_wrunlock();
1246                 goto out;
1247             }
1248             extent = &s->extents[s->num_extents - 1];
1249         } else if (!strcmp(type, "SESPARSE")) {
1250             ret = vmdk_open_se_sparse(bs, extent_file, bs->open_flags, errp);
1251             if (ret) {
1252                 bdrv_graph_wrlock(NULL);
1253                 bdrv_unref_child(bs, extent_file);
1254                 bdrv_graph_wrunlock();
1255                 goto out;
1256             }
1257             extent = &s->extents[s->num_extents - 1];
1258         } else {
1259             error_setg(errp, "Unsupported extent type '%s'", type);
1260             bdrv_graph_wrlock(NULL);
1261             bdrv_unref_child(bs, extent_file);
1262             bdrv_graph_wrunlock();
1263             ret = -ENOTSUP;
1264             goto out;
1265         }
1266         extent->type = g_strdup(type);
1267     }
1268 
1269     ret = 0;
1270     goto out;
1271 
1272 invalid:
1273     np = next_line(p);
1274     assert(np != p);
1275     if (np[-1] == '\n') {
1276         np--;
1277     }
1278     error_setg(errp, "Invalid extent line: %.*s", (int)(np - p), p);
1279     ret = -EINVAL;
1280 
1281 out:
1282     g_free(desc_file_dir);
1283     return ret;
1284 }
1285 
1286 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
1287                                QDict *options, Error **errp)
1288 {
1289     int ret;
1290     char ct[128];
1291     BDRVVmdkState *s = bs->opaque;
1292 
1293     if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
1294         error_setg(errp, "invalid VMDK image descriptor");
1295         ret = -EINVAL;
1296         goto exit;
1297     }
1298     if (strcmp(ct, "monolithicFlat") &&
1299         strcmp(ct, "vmfs") &&
1300         strcmp(ct, "vmfsSparse") &&
1301         strcmp(ct, "seSparse") &&
1302         strcmp(ct, "twoGbMaxExtentSparse") &&
1303         strcmp(ct, "twoGbMaxExtentFlat")) {
1304         error_setg(errp, "Unsupported image type '%s'", ct);
1305         ret = -ENOTSUP;
1306         goto exit;
1307     }
1308     s->create_type = g_strdup(ct);
1309     s->desc_offset = 0;
1310     ret = vmdk_parse_extents(buf, bs, options, errp);
1311 exit:
1312     return ret;
1313 }
1314 
1315 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
1316                      Error **errp)
1317 {
1318     char *buf;
1319     int ret;
1320     BDRVVmdkState *s = bs->opaque;
1321     uint32_t magic;
1322 
1323     GRAPH_RDLOCK_GUARD_MAINLOOP();
1324 
1325     ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
1326     if (ret < 0) {
1327         return ret;
1328     }
1329 
1330     buf = vmdk_read_desc(bs->file, 0, errp);
1331     if (!buf) {
1332         return -EINVAL;
1333     }
1334 
1335     magic = ldl_be_p(buf);
1336     switch (magic) {
1337         case VMDK3_MAGIC:
1338         case VMDK4_MAGIC:
1339             ret = vmdk_open_sparse(bs, bs->file, flags, buf, options,
1340                                    errp);
1341             s->desc_offset = 0x200;
1342             break;
1343         default:
1344             /* No data in the descriptor file */
1345             bs->file->role &= ~BDRV_CHILD_DATA;
1346 
1347             /* Must succeed because we have given up permissions if anything */
1348             bdrv_child_refresh_perms(bs, bs->file, &error_abort);
1349 
1350             ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
1351             break;
1352     }
1353     if (ret) {
1354         goto fail;
1355     }
1356 
1357     /* try to open parent images, if exist */
1358     ret = vmdk_parent_open(bs);
1359     if (ret) {
1360         goto fail;
1361     }
1362     ret = vmdk_read_cid(bs, 0, &s->cid);
1363     if (ret) {
1364         goto fail;
1365     }
1366     ret = vmdk_read_cid(bs, 1, &s->parent_cid);
1367     if (ret) {
1368         goto fail;
1369     }
1370     qemu_co_mutex_init(&s->lock);
1371 
1372     /* Disable migration when VMDK images are used */
1373     error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "
1374                "does not support live migration",
1375                bdrv_get_device_or_node_name(bs));
1376     ret = migrate_add_blocker(s->migration_blocker, errp);
1377     if (ret < 0) {
1378         error_free(s->migration_blocker);
1379         goto fail;
1380     }
1381 
1382     g_free(buf);
1383     return 0;
1384 
1385 fail:
1386     g_free(buf);
1387     g_free(s->create_type);
1388     s->create_type = NULL;
1389     vmdk_free_extents(bs);
1390     return ret;
1391 }
1392 
1393 
1394 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
1395 {
1396     BDRVVmdkState *s = bs->opaque;
1397     int i;
1398 
1399     for (i = 0; i < s->num_extents; i++) {
1400         if (!s->extents[i].flat) {
1401             bs->bl.pwrite_zeroes_alignment =
1402                 MAX(bs->bl.pwrite_zeroes_alignment,
1403                     s->extents[i].cluster_sectors << BDRV_SECTOR_BITS);
1404         }
1405     }
1406 }
1407 
1408 /**
1409  * get_whole_cluster
1410  *
1411  * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1412  * to the cluster at @cluster_sector_num. If @zeroed is true, we're overwriting
1413  * a zeroed cluster in the current layer and must not copy data from the
1414  * backing file.
1415  *
1416  * If @skip_start_sector < @skip_end_sector, the relative range
1417  * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1418  * it for call to write user data in the request.
1419  */
1420 static int coroutine_fn GRAPH_RDLOCK
1421 get_whole_cluster(BlockDriverState *bs, VmdkExtent *extent,
1422                   uint64_t cluster_offset, uint64_t offset,
1423                   uint64_t skip_start_bytes, uint64_t skip_end_bytes,
1424                   bool zeroed)
1425 {
1426     int ret = VMDK_OK;
1427     int64_t cluster_bytes;
1428     uint8_t *whole_grain;
1429     bool copy_from_backing;
1430 
1431     /* For COW, align request sector_num to cluster start */
1432     cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
1433     offset = QEMU_ALIGN_DOWN(offset, cluster_bytes);
1434     whole_grain = qemu_blockalign(bs, cluster_bytes);
1435     copy_from_backing = bs->backing && !zeroed;
1436 
1437     if (!copy_from_backing) {
1438         memset(whole_grain, 0, skip_start_bytes);
1439         memset(whole_grain + skip_end_bytes, 0, cluster_bytes - skip_end_bytes);
1440     }
1441 
1442     assert(skip_end_bytes <= cluster_bytes);
1443     /* we will be here if it's first write on non-exist grain(cluster).
1444      * try to read from parent image, if exist */
1445     if (bs->backing && !vmdk_is_cid_valid(bs)) {
1446         ret = VMDK_ERROR;
1447         goto exit;
1448     }
1449 
1450     /* Read backing data before skip range */
1451     if (skip_start_bytes > 0) {
1452         if (copy_from_backing) {
1453             /* qcow2 emits this on bs->file instead of bs->backing */
1454             BLKDBG_CO_EVENT(extent->file, BLKDBG_COW_READ);
1455             ret = bdrv_co_pread(bs->backing, offset, skip_start_bytes,
1456                                 whole_grain, 0);
1457             if (ret < 0) {
1458                 ret = VMDK_ERROR;
1459                 goto exit;
1460             }
1461         }
1462         BLKDBG_CO_EVENT(extent->file, BLKDBG_COW_WRITE);
1463         ret = bdrv_co_pwrite(extent->file, cluster_offset, skip_start_bytes,
1464                              whole_grain, 0);
1465         if (ret < 0) {
1466             ret = VMDK_ERROR;
1467             goto exit;
1468         }
1469     }
1470     /* Read backing data after skip range */
1471     if (skip_end_bytes < cluster_bytes) {
1472         if (copy_from_backing) {
1473             /* qcow2 emits this on bs->file instead of bs->backing */
1474             BLKDBG_CO_EVENT(extent->file, BLKDBG_COW_READ);
1475             ret = bdrv_co_pread(bs->backing, offset + skip_end_bytes,
1476                                 cluster_bytes - skip_end_bytes,
1477                                 whole_grain + skip_end_bytes, 0);
1478             if (ret < 0) {
1479                 ret = VMDK_ERROR;
1480                 goto exit;
1481             }
1482         }
1483         BLKDBG_CO_EVENT(extent->file, BLKDBG_COW_WRITE);
1484         ret = bdrv_co_pwrite(extent->file, cluster_offset + skip_end_bytes,
1485                              cluster_bytes - skip_end_bytes,
1486                              whole_grain + skip_end_bytes, 0);
1487         if (ret < 0) {
1488             ret = VMDK_ERROR;
1489             goto exit;
1490         }
1491     }
1492 
1493     ret = VMDK_OK;
1494 exit:
1495     qemu_vfree(whole_grain);
1496     return ret;
1497 }
1498 
1499 static int coroutine_fn GRAPH_RDLOCK
1500 vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data, uint32_t offset)
1501 {
1502     offset = cpu_to_le32(offset);
1503     /* update L2 table */
1504     BLKDBG_CO_EVENT(extent->file, BLKDBG_L2_UPDATE);
1505     if (bdrv_co_pwrite(extent->file,
1506                        ((int64_t)m_data->l2_offset * 512)
1507                            + (m_data->l2_index * sizeof(offset)),
1508                        sizeof(offset), &offset, 0) < 0) {
1509         return VMDK_ERROR;
1510     }
1511     /* update backup L2 table */
1512     if (extent->l1_backup_table_offset != 0) {
1513         m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1514         if (bdrv_co_pwrite(extent->file,
1515                            ((int64_t)m_data->l2_offset * 512)
1516                                + (m_data->l2_index * sizeof(offset)),
1517                            sizeof(offset), &offset, 0) < 0) {
1518             return VMDK_ERROR;
1519         }
1520     }
1521     if (bdrv_co_flush(extent->file->bs) < 0) {
1522         return VMDK_ERROR;
1523     }
1524     if (m_data->l2_cache_entry) {
1525         *m_data->l2_cache_entry = offset;
1526     }
1527 
1528     return VMDK_OK;
1529 }
1530 
1531 /**
1532  * get_cluster_offset
1533  *
1534  * Look up cluster offset in extent file by sector number, and store in
1535  * @cluster_offset.
1536  *
1537  * For flat extents, the start offset as parsed from the description file is
1538  * returned.
1539  *
1540  * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1541  * offset for a new cluster and update L2 cache. If there is a backing file,
1542  * COW is done before returning; otherwise, zeroes are written to the allocated
1543  * cluster. Both COW and zero writing skips the sector range
1544  * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1545  * has new data to write there.
1546  *
1547  * Returns: VMDK_OK if cluster exists and mapped in the image.
1548  *          VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1549  *          VMDK_ERROR if failed.
1550  */
1551 static int coroutine_fn GRAPH_RDLOCK
1552 get_cluster_offset(BlockDriverState *bs, VmdkExtent *extent,
1553                    VmdkMetaData *m_data, uint64_t offset, bool allocate,
1554                    uint64_t *cluster_offset, uint64_t skip_start_bytes,
1555                    uint64_t skip_end_bytes)
1556 {
1557     unsigned int l1_index, l2_offset, l2_index;
1558     int min_index, i, j;
1559     uint32_t min_count;
1560     void *l2_table;
1561     bool zeroed = false;
1562     int64_t ret;
1563     int64_t cluster_sector;
1564     unsigned int l2_size_bytes = extent->l2_size * extent->entry_size;
1565 
1566     if (m_data) {
1567         m_data->new_allocation = false;
1568     }
1569     if (extent->flat) {
1570         *cluster_offset = extent->flat_start_offset;
1571         return VMDK_OK;
1572     }
1573 
1574     offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1575     l1_index = (offset >> 9) / extent->l1_entry_sectors;
1576     if (l1_index >= extent->l1_size) {
1577         return VMDK_ERROR;
1578     }
1579     if (extent->sesparse) {
1580         uint64_t l2_offset_u64;
1581 
1582         assert(extent->entry_size == sizeof(uint64_t));
1583 
1584         l2_offset_u64 = ((uint64_t *)extent->l1_table)[l1_index];
1585         if (l2_offset_u64 == 0) {
1586             l2_offset = 0;
1587         } else if ((l2_offset_u64 & 0xffffffff00000000) != 0x1000000000000000) {
1588             /*
1589              * Top most nibble is 0x1 if grain table is allocated.
1590              * strict check - top most 4 bytes must be 0x10000000 since max
1591              * supported size is 64TB for disk - so no more than 64TB / 16MB
1592              * grain directories which is smaller than uint32,
1593              * where 16MB is the only supported default grain table coverage.
1594              */
1595             return VMDK_ERROR;
1596         } else {
1597             l2_offset_u64 = l2_offset_u64 & 0x00000000ffffffff;
1598             l2_offset_u64 = extent->sesparse_l2_tables_offset +
1599                 l2_offset_u64 * l2_size_bytes / SECTOR_SIZE;
1600             if (l2_offset_u64 > 0x00000000ffffffff) {
1601                 return VMDK_ERROR;
1602             }
1603             l2_offset = (unsigned int)(l2_offset_u64);
1604         }
1605     } else {
1606         assert(extent->entry_size == sizeof(uint32_t));
1607         l2_offset = ((uint32_t *)extent->l1_table)[l1_index];
1608     }
1609     if (!l2_offset) {
1610         return VMDK_UNALLOC;
1611     }
1612     for (i = 0; i < L2_CACHE_SIZE; i++) {
1613         if (l2_offset == extent->l2_cache_offsets[i]) {
1614             /* increment the hit count */
1615             if (++extent->l2_cache_counts[i] == 0xffffffff) {
1616                 for (j = 0; j < L2_CACHE_SIZE; j++) {
1617                     extent->l2_cache_counts[j] >>= 1;
1618                 }
1619             }
1620             l2_table = (char *)extent->l2_cache + (i * l2_size_bytes);
1621             goto found;
1622         }
1623     }
1624     /* not found: load a new entry in the least used one */
1625     min_index = 0;
1626     min_count = 0xffffffff;
1627     for (i = 0; i < L2_CACHE_SIZE; i++) {
1628         if (extent->l2_cache_counts[i] < min_count) {
1629             min_count = extent->l2_cache_counts[i];
1630             min_index = i;
1631         }
1632     }
1633     l2_table = (char *)extent->l2_cache + (min_index * l2_size_bytes);
1634     BLKDBG_CO_EVENT(extent->file, BLKDBG_L2_LOAD);
1635     if (bdrv_co_pread(extent->file,
1636                 (int64_t)l2_offset * 512,
1637                 l2_size_bytes,
1638                 l2_table, 0
1639             ) < 0) {
1640         return VMDK_ERROR;
1641     }
1642 
1643     extent->l2_cache_offsets[min_index] = l2_offset;
1644     extent->l2_cache_counts[min_index] = 1;
1645  found:
1646     l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1647     if (m_data) {
1648         m_data->l1_index = l1_index;
1649         m_data->l2_index = l2_index;
1650         m_data->l2_offset = l2_offset;
1651         m_data->l2_cache_entry = ((uint32_t *)l2_table) + l2_index;
1652     }
1653 
1654     if (extent->sesparse) {
1655         cluster_sector = le64_to_cpu(((uint64_t *)l2_table)[l2_index]);
1656         switch (cluster_sector & 0xf000000000000000) {
1657         case 0x0000000000000000:
1658             /* unallocated grain */
1659             if (cluster_sector != 0) {
1660                 return VMDK_ERROR;
1661             }
1662             break;
1663         case 0x1000000000000000:
1664             /* scsi-unmapped grain - fallthrough */
1665         case 0x2000000000000000:
1666             /* zero grain */
1667             zeroed = true;
1668             break;
1669         case 0x3000000000000000:
1670             /* allocated grain */
1671             cluster_sector = (((cluster_sector & 0x0fff000000000000) >> 48) |
1672                               ((cluster_sector & 0x0000ffffffffffff) << 12));
1673             cluster_sector = extent->sesparse_clusters_offset +
1674                 cluster_sector * extent->cluster_sectors;
1675             break;
1676         default:
1677             return VMDK_ERROR;
1678         }
1679     } else {
1680         cluster_sector = le32_to_cpu(((uint32_t *)l2_table)[l2_index]);
1681 
1682         if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1683             zeroed = true;
1684         }
1685     }
1686 
1687     if (!cluster_sector || zeroed) {
1688         if (!allocate) {
1689             return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1690         }
1691         assert(!extent->sesparse);
1692 
1693         if (extent->next_cluster_sector >= VMDK_EXTENT_MAX_SECTORS) {
1694             return VMDK_ERROR;
1695         }
1696 
1697         cluster_sector = extent->next_cluster_sector;
1698         extent->next_cluster_sector += extent->cluster_sectors;
1699 
1700         /* First of all we write grain itself, to avoid race condition
1701          * that may to corrupt the image.
1702          * This problem may occur because of insufficient space on host disk
1703          * or inappropriate VM shutdown.
1704          */
1705         ret = get_whole_cluster(bs, extent, cluster_sector * BDRV_SECTOR_SIZE,
1706                                 offset, skip_start_bytes, skip_end_bytes,
1707                                 zeroed);
1708         if (ret) {
1709             return ret;
1710         }
1711         if (m_data) {
1712             m_data->new_allocation = true;
1713         }
1714     }
1715     *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1716     return VMDK_OK;
1717 }
1718 
1719 static VmdkExtent *find_extent(BDRVVmdkState *s,
1720                                 int64_t sector_num, VmdkExtent *start_hint)
1721 {
1722     VmdkExtent *extent = start_hint;
1723 
1724     if (!extent) {
1725         extent = &s->extents[0];
1726     }
1727     while (extent < &s->extents[s->num_extents]) {
1728         if (sector_num < extent->end_sector) {
1729             return extent;
1730         }
1731         extent++;
1732     }
1733     return NULL;
1734 }
1735 
1736 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent *extent,
1737                                                    int64_t offset)
1738 {
1739     uint64_t extent_begin_offset, extent_relative_offset;
1740     uint64_t cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1741 
1742     extent_begin_offset =
1743         (extent->end_sector - extent->sectors) * BDRV_SECTOR_SIZE;
1744     extent_relative_offset = offset - extent_begin_offset;
1745     return extent_relative_offset % cluster_size;
1746 }
1747 
1748 static int coroutine_fn GRAPH_RDLOCK
1749 vmdk_co_block_status(BlockDriverState *bs, bool want_zero,
1750                      int64_t offset, int64_t bytes, int64_t *pnum,
1751                      int64_t *map, BlockDriverState **file)
1752 {
1753     BDRVVmdkState *s = bs->opaque;
1754     int64_t index_in_cluster, n, ret;
1755     uint64_t cluster_offset;
1756     VmdkExtent *extent;
1757 
1758     extent = find_extent(s, offset >> BDRV_SECTOR_BITS, NULL);
1759     if (!extent) {
1760         return -EIO;
1761     }
1762     qemu_co_mutex_lock(&s->lock);
1763     ret = get_cluster_offset(bs, extent, NULL, offset, false, &cluster_offset,
1764                              0, 0);
1765     qemu_co_mutex_unlock(&s->lock);
1766 
1767     index_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1768     switch (ret) {
1769     case VMDK_ERROR:
1770         ret = -EIO;
1771         break;
1772     case VMDK_UNALLOC:
1773         ret = 0;
1774         break;
1775     case VMDK_ZEROED:
1776         ret = BDRV_BLOCK_ZERO;
1777         break;
1778     case VMDK_OK:
1779         ret = BDRV_BLOCK_DATA;
1780         if (!extent->compressed) {
1781             ret |= BDRV_BLOCK_OFFSET_VALID;
1782             *map = cluster_offset + index_in_cluster;
1783             if (extent->flat) {
1784                 ret |= BDRV_BLOCK_RECURSE;
1785             }
1786         } else {
1787             ret |= BDRV_BLOCK_COMPRESSED;
1788         }
1789         *file = extent->file->bs;
1790         break;
1791     }
1792 
1793     n = extent->cluster_sectors * BDRV_SECTOR_SIZE - index_in_cluster;
1794     *pnum = MIN(n, bytes);
1795     return ret;
1796 }
1797 
1798 static int coroutine_fn GRAPH_RDLOCK
1799 vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1800                   int64_t offset_in_cluster, QEMUIOVector *qiov,
1801                   uint64_t qiov_offset, uint64_t n_bytes,
1802                   uint64_t offset)
1803 {
1804     int ret;
1805     VmdkGrainMarker *data = NULL;
1806     uLongf buf_len;
1807     QEMUIOVector local_qiov;
1808     int64_t write_offset;
1809     int64_t write_end_sector;
1810 
1811     if (extent->compressed) {
1812         void *compressed_data;
1813 
1814         /* Only whole clusters */
1815         if (offset_in_cluster ||
1816             n_bytes > (extent->cluster_sectors * SECTOR_SIZE) ||
1817             (n_bytes < (extent->cluster_sectors * SECTOR_SIZE) &&
1818              offset + n_bytes != extent->end_sector * SECTOR_SIZE))
1819         {
1820             ret = -EINVAL;
1821             goto out;
1822         }
1823 
1824         if (!extent->has_marker) {
1825             ret = -EINVAL;
1826             goto out;
1827         }
1828         buf_len = (extent->cluster_sectors << 9) * 2;
1829         data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1830 
1831         compressed_data = g_malloc(n_bytes);
1832         qemu_iovec_to_buf(qiov, qiov_offset, compressed_data, n_bytes);
1833         ret = compress(data->data, &buf_len, compressed_data, n_bytes);
1834         g_free(compressed_data);
1835 
1836         if (ret != Z_OK || buf_len == 0) {
1837             ret = -EINVAL;
1838             goto out;
1839         }
1840 
1841         data->lba = cpu_to_le64(offset >> BDRV_SECTOR_BITS);
1842         data->size = cpu_to_le32(buf_len);
1843 
1844         n_bytes = buf_len + sizeof(VmdkGrainMarker);
1845         qemu_iovec_init_buf(&local_qiov, data, n_bytes);
1846 
1847         BLKDBG_CO_EVENT(extent->file, BLKDBG_WRITE_COMPRESSED);
1848     } else {
1849         qemu_iovec_init(&local_qiov, qiov->niov);
1850         qemu_iovec_concat(&local_qiov, qiov, qiov_offset, n_bytes);
1851 
1852         BLKDBG_CO_EVENT(extent->file, BLKDBG_WRITE_AIO);
1853     }
1854 
1855     write_offset = cluster_offset + offset_in_cluster;
1856     ret = bdrv_co_pwritev(extent->file, write_offset, n_bytes,
1857                           &local_qiov, 0);
1858 
1859     write_end_sector = DIV_ROUND_UP(write_offset + n_bytes, BDRV_SECTOR_SIZE);
1860 
1861     if (extent->compressed) {
1862         extent->next_cluster_sector = write_end_sector;
1863     } else {
1864         extent->next_cluster_sector = MAX(extent->next_cluster_sector,
1865                                           write_end_sector);
1866     }
1867 
1868     if (ret < 0) {
1869         goto out;
1870     }
1871     ret = 0;
1872  out:
1873     g_free(data);
1874     if (!extent->compressed) {
1875         qemu_iovec_destroy(&local_qiov);
1876     }
1877     return ret;
1878 }
1879 
1880 static int coroutine_fn GRAPH_RDLOCK
1881 vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1882                  int64_t offset_in_cluster, QEMUIOVector *qiov, int bytes)
1883 {
1884     int ret;
1885     int cluster_bytes, buf_bytes;
1886     uint8_t *cluster_buf, *compressed_data;
1887     uint8_t *uncomp_buf;
1888     uint32_t data_len;
1889     VmdkGrainMarker *marker;
1890     uLongf buf_len;
1891 
1892 
1893     if (!extent->compressed) {
1894         BLKDBG_CO_EVENT(extent->file, BLKDBG_READ_AIO);
1895         ret = bdrv_co_preadv(extent->file,
1896                              cluster_offset + offset_in_cluster, bytes,
1897                              qiov, 0);
1898         if (ret < 0) {
1899             return ret;
1900         }
1901         return 0;
1902     }
1903     cluster_bytes = extent->cluster_sectors * 512;
1904     /* Read two clusters in case GrainMarker + compressed data > one cluster */
1905     buf_bytes = cluster_bytes * 2;
1906     cluster_buf = g_malloc(buf_bytes);
1907     uncomp_buf = g_malloc(cluster_bytes);
1908     BLKDBG_CO_EVENT(extent->file, BLKDBG_READ_COMPRESSED);
1909     ret = bdrv_co_pread(extent->file, cluster_offset, buf_bytes, cluster_buf,
1910                         0);
1911     if (ret < 0) {
1912         goto out;
1913     }
1914     compressed_data = cluster_buf;
1915     buf_len = cluster_bytes;
1916     data_len = cluster_bytes;
1917     if (extent->has_marker) {
1918         marker = (VmdkGrainMarker *)cluster_buf;
1919         compressed_data = marker->data;
1920         data_len = le32_to_cpu(marker->size);
1921     }
1922     if (!data_len || data_len > buf_bytes) {
1923         ret = -EINVAL;
1924         goto out;
1925     }
1926     ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1927     if (ret != Z_OK) {
1928         ret = -EINVAL;
1929         goto out;
1930 
1931     }
1932     if (offset_in_cluster < 0 ||
1933             offset_in_cluster + bytes > buf_len) {
1934         ret = -EINVAL;
1935         goto out;
1936     }
1937     qemu_iovec_from_buf(qiov, 0, uncomp_buf + offset_in_cluster, bytes);
1938     ret = 0;
1939 
1940  out:
1941     g_free(uncomp_buf);
1942     g_free(cluster_buf);
1943     return ret;
1944 }
1945 
1946 static int coroutine_fn GRAPH_RDLOCK
1947 vmdk_co_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
1948                QEMUIOVector *qiov, BdrvRequestFlags flags)
1949 {
1950     BDRVVmdkState *s = bs->opaque;
1951     int ret;
1952     uint64_t n_bytes, offset_in_cluster;
1953     VmdkExtent *extent = NULL;
1954     QEMUIOVector local_qiov;
1955     uint64_t cluster_offset;
1956     uint64_t bytes_done = 0;
1957 
1958     qemu_iovec_init(&local_qiov, qiov->niov);
1959     qemu_co_mutex_lock(&s->lock);
1960 
1961     while (bytes > 0) {
1962         extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1963         if (!extent) {
1964             ret = -EIO;
1965             goto fail;
1966         }
1967         ret = get_cluster_offset(bs, extent, NULL,
1968                                  offset, false, &cluster_offset, 0, 0);
1969         offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1970 
1971         n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1972                              - offset_in_cluster);
1973 
1974         if (ret != VMDK_OK) {
1975             /* if not allocated, try to read from parent image, if exist */
1976             if (bs->backing && ret != VMDK_ZEROED) {
1977                 if (!vmdk_is_cid_valid(bs)) {
1978                     ret = -EINVAL;
1979                     goto fail;
1980                 }
1981 
1982                 qemu_iovec_reset(&local_qiov);
1983                 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1984 
1985                 /* qcow2 emits this on bs->file instead of bs->backing */
1986                 BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1987                 ret = bdrv_co_preadv(bs->backing, offset, n_bytes,
1988                                      &local_qiov, 0);
1989                 if (ret < 0) {
1990                     goto fail;
1991                 }
1992             } else {
1993                 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
1994             }
1995         } else {
1996             qemu_iovec_reset(&local_qiov);
1997             qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1998 
1999             ret = vmdk_read_extent(extent, cluster_offset, offset_in_cluster,
2000                                    &local_qiov, n_bytes);
2001             if (ret) {
2002                 goto fail;
2003             }
2004         }
2005         bytes -= n_bytes;
2006         offset += n_bytes;
2007         bytes_done += n_bytes;
2008     }
2009 
2010     ret = 0;
2011 fail:
2012     qemu_co_mutex_unlock(&s->lock);
2013     qemu_iovec_destroy(&local_qiov);
2014 
2015     return ret;
2016 }
2017 
2018 /**
2019  * vmdk_write:
2020  * @zeroed:       buf is ignored (data is zero), use zeroed_grain GTE feature
2021  *                if possible, otherwise return -ENOTSUP.
2022  * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
2023  *                with each cluster. By dry run we can find if the zero write
2024  *                is possible without modifying image data.
2025  *
2026  * Returns: error code with 0 for success.
2027  */
2028 static int coroutine_fn GRAPH_RDLOCK
2029 vmdk_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
2030              QEMUIOVector *qiov, bool zeroed, bool zero_dry_run)
2031 {
2032     BDRVVmdkState *s = bs->opaque;
2033     VmdkExtent *extent = NULL;
2034     int ret;
2035     int64_t offset_in_cluster, n_bytes;
2036     uint64_t cluster_offset;
2037     uint64_t bytes_done = 0;
2038     VmdkMetaData m_data;
2039 
2040     if (DIV_ROUND_UP(offset, BDRV_SECTOR_SIZE) > bs->total_sectors) {
2041         error_report("Wrong offset: offset=0x%" PRIx64
2042                      " total_sectors=0x%" PRIx64,
2043                      offset, bs->total_sectors);
2044         return -EIO;
2045     }
2046 
2047     while (bytes > 0) {
2048         extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
2049         if (!extent) {
2050             return -EIO;
2051         }
2052         if (extent->sesparse) {
2053             return -ENOTSUP;
2054         }
2055         offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
2056         n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
2057                              - offset_in_cluster);
2058 
2059         ret = get_cluster_offset(bs, extent, &m_data, offset,
2060                                  !(extent->compressed || zeroed),
2061                                  &cluster_offset, offset_in_cluster,
2062                                  offset_in_cluster + n_bytes);
2063         if (extent->compressed) {
2064             if (ret == VMDK_OK) {
2065                 /* Refuse write to allocated cluster for streamOptimized */
2066                 error_report("Could not write to allocated cluster"
2067                               " for streamOptimized");
2068                 return -EIO;
2069             } else if (!zeroed) {
2070                 /* allocate */
2071                 ret = get_cluster_offset(bs, extent, &m_data, offset,
2072                                          true, &cluster_offset, 0, 0);
2073             }
2074         }
2075         if (ret == VMDK_ERROR) {
2076             return -EINVAL;
2077         }
2078         if (zeroed) {
2079             /* Do zeroed write, buf is ignored */
2080             if (extent->has_zero_grain &&
2081                     offset_in_cluster == 0 &&
2082                     n_bytes >= extent->cluster_sectors * BDRV_SECTOR_SIZE) {
2083                 n_bytes = extent->cluster_sectors * BDRV_SECTOR_SIZE;
2084                 if (!zero_dry_run && ret != VMDK_ZEROED) {
2085                     /* update L2 tables */
2086                     if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
2087                             != VMDK_OK) {
2088                         return -EIO;
2089                     }
2090                 }
2091             } else {
2092                 return -ENOTSUP;
2093             }
2094         } else {
2095             ret = vmdk_write_extent(extent, cluster_offset, offset_in_cluster,
2096                                     qiov, bytes_done, n_bytes, offset);
2097             if (ret) {
2098                 return ret;
2099             }
2100             if (m_data.new_allocation) {
2101                 /* update L2 tables */
2102                 if (vmdk_L2update(extent, &m_data,
2103                                   cluster_offset >> BDRV_SECTOR_BITS)
2104                         != VMDK_OK) {
2105                     return -EIO;
2106                 }
2107             }
2108         }
2109         bytes -= n_bytes;
2110         offset += n_bytes;
2111         bytes_done += n_bytes;
2112 
2113         /* update CID on the first write every time the virtual disk is
2114          * opened */
2115         if (!s->cid_updated) {
2116             ret = vmdk_write_cid(bs, g_random_int());
2117             if (ret < 0) {
2118                 return ret;
2119             }
2120             s->cid_updated = true;
2121         }
2122     }
2123     return 0;
2124 }
2125 
2126 static int coroutine_fn GRAPH_RDLOCK
2127 vmdk_co_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
2128                 QEMUIOVector *qiov, BdrvRequestFlags flags)
2129 {
2130     int ret;
2131     BDRVVmdkState *s = bs->opaque;
2132     qemu_co_mutex_lock(&s->lock);
2133     ret = vmdk_pwritev(bs, offset, bytes, qiov, false, false);
2134     qemu_co_mutex_unlock(&s->lock);
2135     return ret;
2136 }
2137 
2138 static int coroutine_fn GRAPH_RDLOCK
2139 vmdk_co_pwritev_compressed(BlockDriverState *bs, int64_t offset, int64_t bytes,
2140                            QEMUIOVector *qiov)
2141 {
2142     if (bytes == 0) {
2143         /* The caller will write bytes 0 to signal EOF.
2144          * When receive it, we align EOF to a sector boundary. */
2145         BDRVVmdkState *s = bs->opaque;
2146         int i, ret;
2147         int64_t length;
2148 
2149         for (i = 0; i < s->num_extents; i++) {
2150             length = bdrv_co_getlength(s->extents[i].file->bs);
2151             if (length < 0) {
2152                 return length;
2153             }
2154             length = QEMU_ALIGN_UP(length, BDRV_SECTOR_SIZE);
2155             ret = bdrv_co_truncate(s->extents[i].file, length, false,
2156                                    PREALLOC_MODE_OFF, 0, NULL);
2157             if (ret < 0) {
2158                 return ret;
2159             }
2160         }
2161         return 0;
2162     }
2163     return vmdk_co_pwritev(bs, offset, bytes, qiov, 0);
2164 }
2165 
2166 static int coroutine_fn GRAPH_RDLOCK
2167 vmdk_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
2168                       BdrvRequestFlags flags)
2169 {
2170     int ret;
2171     BDRVVmdkState *s = bs->opaque;
2172 
2173     qemu_co_mutex_lock(&s->lock);
2174     /* write zeroes could fail if sectors not aligned to cluster, test it with
2175      * dry_run == true before really updating image */
2176     ret = vmdk_pwritev(bs, offset, bytes, NULL, true, true);
2177     if (!ret) {
2178         ret = vmdk_pwritev(bs, offset, bytes, NULL, true, false);
2179     }
2180     qemu_co_mutex_unlock(&s->lock);
2181     return ret;
2182 }
2183 
2184 static int coroutine_fn GRAPH_UNLOCKED
2185 vmdk_init_extent(BlockBackend *blk, int64_t filesize, bool flat, bool compress,
2186                  bool zeroed_grain, Error **errp)
2187 {
2188     int ret, i;
2189     VMDK4Header header;
2190     uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
2191     uint32_t *gd_buf = NULL;
2192     int gd_buf_size;
2193 
2194     if (flat) {
2195         ret = blk_co_truncate(blk, filesize, false, PREALLOC_MODE_OFF, 0, errp);
2196         goto exit;
2197     }
2198     magic = cpu_to_be32(VMDK4_MAGIC);
2199     memset(&header, 0, sizeof(header));
2200     if (compress) {
2201         header.version = 3;
2202     } else if (zeroed_grain) {
2203         header.version = 2;
2204     } else {
2205         header.version = 1;
2206     }
2207     header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
2208                    | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
2209                    | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
2210     header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
2211     header.capacity = filesize / BDRV_SECTOR_SIZE;
2212     header.granularity = 128;
2213     header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
2214 
2215     grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
2216     gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
2217                            BDRV_SECTOR_SIZE);
2218     gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
2219     gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
2220 
2221     header.desc_offset = 1;
2222     header.desc_size = 20;
2223     header.rgd_offset = header.desc_offset + header.desc_size;
2224     header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
2225     header.grain_offset =
2226         ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
2227                  header.granularity);
2228     /* swap endianness for all header fields */
2229     header.version = cpu_to_le32(header.version);
2230     header.flags = cpu_to_le32(header.flags);
2231     header.capacity = cpu_to_le64(header.capacity);
2232     header.granularity = cpu_to_le64(header.granularity);
2233     header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
2234     header.desc_offset = cpu_to_le64(header.desc_offset);
2235     header.desc_size = cpu_to_le64(header.desc_size);
2236     header.rgd_offset = cpu_to_le64(header.rgd_offset);
2237     header.gd_offset = cpu_to_le64(header.gd_offset);
2238     header.grain_offset = cpu_to_le64(header.grain_offset);
2239     header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
2240 
2241     header.check_bytes[0] = 0xa;
2242     header.check_bytes[1] = 0x20;
2243     header.check_bytes[2] = 0xd;
2244     header.check_bytes[3] = 0xa;
2245 
2246     /* write all the data */
2247     ret = blk_co_pwrite(blk, 0, sizeof(magic), &magic, 0);
2248     if (ret < 0) {
2249         error_setg(errp, QERR_IO_ERROR);
2250         goto exit;
2251     }
2252     ret = blk_co_pwrite(blk, sizeof(magic), sizeof(header), &header, 0);
2253     if (ret < 0) {
2254         error_setg(errp, QERR_IO_ERROR);
2255         goto exit;
2256     }
2257 
2258     ret = blk_co_truncate(blk, le64_to_cpu(header.grain_offset) << 9, false,
2259                           PREALLOC_MODE_OFF, 0, errp);
2260     if (ret < 0) {
2261         goto exit;
2262     }
2263 
2264     /* write grain directory */
2265     gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
2266     gd_buf = g_malloc0(gd_buf_size);
2267     for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
2268          i < gt_count; i++, tmp += gt_size) {
2269         gd_buf[i] = cpu_to_le32(tmp);
2270     }
2271     ret = blk_co_pwrite(blk, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
2272                         gd_buf_size, gd_buf, 0);
2273     if (ret < 0) {
2274         error_setg(errp, QERR_IO_ERROR);
2275         goto exit;
2276     }
2277 
2278     /* write backup grain directory */
2279     for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
2280          i < gt_count; i++, tmp += gt_size) {
2281         gd_buf[i] = cpu_to_le32(tmp);
2282     }
2283     ret = blk_co_pwrite(blk, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
2284                         gd_buf_size, gd_buf, 0);
2285     if (ret < 0) {
2286         error_setg(errp, QERR_IO_ERROR);
2287     }
2288 
2289     ret = 0;
2290 exit:
2291     g_free(gd_buf);
2292     return ret;
2293 }
2294 
2295 static int coroutine_fn GRAPH_UNLOCKED
2296 vmdk_create_extent(const char *filename, int64_t filesize, bool flat,
2297                    bool compress, bool zeroed_grain, BlockBackend **pbb,
2298                    QemuOpts *opts, Error **errp)
2299 {
2300     int ret;
2301     BlockBackend *blk = NULL;
2302 
2303     ret = bdrv_co_create_file(filename, opts, errp);
2304     if (ret < 0) {
2305         goto exit;
2306     }
2307 
2308     blk = blk_co_new_open(filename, NULL, NULL,
2309                           BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
2310                           errp);
2311     if (blk == NULL) {
2312         ret = -EIO;
2313         goto exit;
2314     }
2315 
2316     blk_set_allow_write_beyond_eof(blk, true);
2317 
2318     ret = vmdk_init_extent(blk, filesize, flat, compress, zeroed_grain, errp);
2319 exit:
2320     if (blk) {
2321         if (pbb) {
2322             *pbb = blk;
2323         } else {
2324             blk_co_unref(blk);
2325             blk = NULL;
2326         }
2327     }
2328     return ret;
2329 }
2330 
2331 static int filename_decompose(const char *filename, char *path, char *prefix,
2332                               char *postfix, size_t buf_len, Error **errp)
2333 {
2334     const char *p, *q;
2335 
2336     if (filename == NULL || !strlen(filename)) {
2337         error_setg(errp, "No filename provided");
2338         return VMDK_ERROR;
2339     }
2340     p = strrchr(filename, '/');
2341     if (p == NULL) {
2342         p = strrchr(filename, '\\');
2343     }
2344     if (p == NULL) {
2345         p = strrchr(filename, ':');
2346     }
2347     if (p != NULL) {
2348         p++;
2349         if (p - filename >= buf_len) {
2350             return VMDK_ERROR;
2351         }
2352         pstrcpy(path, p - filename + 1, filename);
2353     } else {
2354         p = filename;
2355         path[0] = '\0';
2356     }
2357     q = strrchr(p, '.');
2358     if (q == NULL) {
2359         pstrcpy(prefix, buf_len, p);
2360         postfix[0] = '\0';
2361     } else {
2362         if (q - p >= buf_len) {
2363             return VMDK_ERROR;
2364         }
2365         pstrcpy(prefix, q - p + 1, p);
2366         pstrcpy(postfix, buf_len, q);
2367     }
2368     return VMDK_OK;
2369 }
2370 
2371 /*
2372  * idx == 0: get or create the descriptor file (also the image file if in a
2373  *           non-split format.
2374  * idx >= 1: get the n-th extent if in a split subformat
2375  */
2376 typedef BlockBackend * coroutine_fn GRAPH_UNLOCKED_PTR
2377     (*vmdk_create_extent_fn)(int64_t size, int idx, bool flat, bool split,
2378                              bool compress, bool zeroed_grain, void *opaque,
2379                              Error **errp);
2380 
2381 static void vmdk_desc_add_extent(GString *desc,
2382                                  const char *extent_line_fmt,
2383                                  int64_t size, const char *filename)
2384 {
2385     char *basename = g_path_get_basename(filename);
2386 
2387     g_string_append_printf(desc, extent_line_fmt,
2388                            DIV_ROUND_UP(size, BDRV_SECTOR_SIZE), basename);
2389     g_free(basename);
2390 }
2391 
2392 static int coroutine_fn GRAPH_UNLOCKED
2393 vmdk_co_do_create(int64_t size,
2394                   BlockdevVmdkSubformat subformat,
2395                   BlockdevVmdkAdapterType adapter_type,
2396                   const char *backing_file,
2397                   const char *hw_version,
2398                   const char *toolsversion,
2399                   bool compat6,
2400                   bool zeroed_grain,
2401                   vmdk_create_extent_fn extent_fn,
2402                   void *opaque,
2403                   Error **errp)
2404 {
2405     int extent_idx;
2406     BlockBackend *blk = NULL;
2407     BlockBackend *extent_blk;
2408     Error *local_err = NULL;
2409     char *desc = NULL;
2410     int ret = 0;
2411     bool flat, split, compress;
2412     GString *ext_desc_lines;
2413     const int64_t split_size = 0x80000000;  /* VMDK has constant split size */
2414     int64_t extent_size;
2415     int64_t created_size = 0;
2416     const char *extent_line_fmt;
2417     char *parent_desc_line = g_malloc0(BUF_SIZE);
2418     uint32_t parent_cid = 0xffffffff;
2419     uint32_t number_heads = 16;
2420     uint32_t desc_offset = 0, desc_len;
2421     const char desc_template[] =
2422         "# Disk DescriptorFile\n"
2423         "version=1\n"
2424         "CID=%" PRIx32 "\n"
2425         "parentCID=%" PRIx32 "\n"
2426         "createType=\"%s\"\n"
2427         "%s"
2428         "\n"
2429         "# Extent description\n"
2430         "%s"
2431         "\n"
2432         "# The Disk Data Base\n"
2433         "#DDB\n"
2434         "\n"
2435         "ddb.virtualHWVersion = \"%s\"\n"
2436         "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
2437         "ddb.geometry.heads = \"%" PRIu32 "\"\n"
2438         "ddb.geometry.sectors = \"63\"\n"
2439         "ddb.adapterType = \"%s\"\n"
2440         "ddb.toolsVersion = \"%s\"\n";
2441 
2442     ext_desc_lines = g_string_new(NULL);
2443 
2444     /* Read out options */
2445     if (compat6) {
2446         if (hw_version) {
2447             error_setg(errp,
2448                        "compat6 cannot be enabled with hwversion set");
2449             ret = -EINVAL;
2450             goto exit;
2451         }
2452         hw_version = "6";
2453     }
2454     if (!hw_version) {
2455         hw_version = "4";
2456     }
2457     if (!toolsversion) {
2458         toolsversion = "2147483647";
2459     }
2460 
2461     if (adapter_type != BLOCKDEV_VMDK_ADAPTER_TYPE_IDE) {
2462         /* that's the number of heads with which vmware operates when
2463            creating, exporting, etc. vmdk files with a non-ide adapter type */
2464         number_heads = 255;
2465     }
2466     split = (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT) ||
2467             (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTSPARSE);
2468     flat = (subformat == BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICFLAT) ||
2469            (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT);
2470     compress = subformat == BLOCKDEV_VMDK_SUBFORMAT_STREAMOPTIMIZED;
2471 
2472     if (flat) {
2473         extent_line_fmt = "RW %" PRId64 " FLAT \"%s\" 0\n";
2474     } else {
2475         extent_line_fmt = "RW %" PRId64 " SPARSE \"%s\"\n";
2476     }
2477     if (flat && backing_file) {
2478         error_setg(errp, "Flat image can't have backing file");
2479         ret = -ENOTSUP;
2480         goto exit;
2481     }
2482     if (flat && zeroed_grain) {
2483         error_setg(errp, "Flat image can't enable zeroed grain");
2484         ret = -ENOTSUP;
2485         goto exit;
2486     }
2487 
2488     /* Create extents */
2489     if (split) {
2490         extent_size = split_size;
2491     } else {
2492         extent_size = size;
2493     }
2494     if (!split && !flat) {
2495         created_size = extent_size;
2496     } else {
2497         created_size = 0;
2498     }
2499     /* Get the descriptor file BDS */
2500     blk = extent_fn(created_size, 0, flat, split, compress, zeroed_grain,
2501                     opaque, errp);
2502     if (!blk) {
2503         ret = -EIO;
2504         goto exit;
2505     }
2506     if (!split && !flat) {
2507         vmdk_desc_add_extent(ext_desc_lines, extent_line_fmt, created_size,
2508                              blk_bs(blk)->filename);
2509     }
2510 
2511     if (backing_file) {
2512         BlockBackend *backing;
2513         char *full_backing =
2514             bdrv_get_full_backing_filename_from_filename(blk_bs(blk)->filename,
2515                                                          backing_file,
2516                                                          &local_err);
2517         if (local_err) {
2518             error_propagate(errp, local_err);
2519             ret = -ENOENT;
2520             goto exit;
2521         }
2522         assert(full_backing);
2523 
2524         backing = blk_co_new_open(full_backing, NULL, NULL,
2525                                   BDRV_O_NO_BACKING, errp);
2526         g_free(full_backing);
2527         if (backing == NULL) {
2528             ret = -EIO;
2529             goto exit;
2530         }
2531         if (strcmp(blk_bs(backing)->drv->format_name, "vmdk")) {
2532             error_setg(errp, "Invalid backing file format: %s. Must be vmdk",
2533                        blk_bs(backing)->drv->format_name);
2534             blk_co_unref(backing);
2535             ret = -EINVAL;
2536             goto exit;
2537         }
2538         ret = vmdk_read_cid(blk_bs(backing), 0, &parent_cid);
2539         blk_co_unref(backing);
2540         if (ret) {
2541             error_setg(errp, "Failed to read parent CID");
2542             goto exit;
2543         }
2544         snprintf(parent_desc_line, BUF_SIZE,
2545                 "parentFileNameHint=\"%s\"", backing_file);
2546     }
2547     extent_idx = 1;
2548     while (created_size < size) {
2549         int64_t cur_size = MIN(size - created_size, extent_size);
2550         extent_blk = extent_fn(cur_size, extent_idx, flat, split, compress,
2551                                zeroed_grain, opaque, errp);
2552         if (!extent_blk) {
2553             ret = -EINVAL;
2554             goto exit;
2555         }
2556         vmdk_desc_add_extent(ext_desc_lines, extent_line_fmt, cur_size,
2557                              blk_bs(extent_blk)->filename);
2558         created_size += cur_size;
2559         extent_idx++;
2560         blk_co_unref(extent_blk);
2561     }
2562 
2563     /* Check whether we got excess extents */
2564     extent_blk = extent_fn(-1, extent_idx, flat, split, compress, zeroed_grain,
2565                            opaque, NULL);
2566     if (extent_blk) {
2567         blk_co_unref(extent_blk);
2568         error_setg(errp, "List of extents contains unused extents");
2569         ret = -EINVAL;
2570         goto exit;
2571     }
2572 
2573     /* generate descriptor file */
2574     desc = g_strdup_printf(desc_template,
2575                            g_random_int(),
2576                            parent_cid,
2577                            BlockdevVmdkSubformat_str(subformat),
2578                            parent_desc_line,
2579                            ext_desc_lines->str,
2580                            hw_version,
2581                            size /
2582                                (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
2583                            number_heads,
2584                            BlockdevVmdkAdapterType_str(adapter_type),
2585                            toolsversion);
2586     desc_len = strlen(desc);
2587     /* the descriptor offset = 0x200 */
2588     if (!split && !flat) {
2589         desc_offset = 0x200;
2590     }
2591 
2592     ret = blk_co_pwrite(blk, desc_offset, desc_len, desc, 0);
2593     if (ret < 0) {
2594         error_setg_errno(errp, -ret, "Could not write description");
2595         goto exit;
2596     }
2597     /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2598      * for description file */
2599     if (desc_offset == 0) {
2600         ret = blk_co_truncate(blk, desc_len, false, PREALLOC_MODE_OFF, 0, errp);
2601         if (ret < 0) {
2602             goto exit;
2603         }
2604     }
2605     ret = 0;
2606 exit:
2607     if (blk) {
2608         blk_co_unref(blk);
2609     }
2610     g_free(desc);
2611     g_free(parent_desc_line);
2612     g_string_free(ext_desc_lines, true);
2613     return ret;
2614 }
2615 
2616 typedef struct {
2617     char *path;
2618     char *prefix;
2619     char *postfix;
2620     QemuOpts *opts;
2621 } VMDKCreateOptsData;
2622 
2623 static BlockBackend * coroutine_fn GRAPH_UNLOCKED
2624 vmdk_co_create_opts_cb(int64_t size, int idx, bool flat, bool split,
2625                        bool compress, bool zeroed_grain, void *opaque,
2626                        Error **errp)
2627 {
2628     BlockBackend *blk = NULL;
2629     BlockDriverState *bs = NULL;
2630     VMDKCreateOptsData *data = opaque;
2631     char *ext_filename = NULL;
2632     char *rel_filename = NULL;
2633 
2634     /* We're done, don't create excess extents. */
2635     if (size == -1) {
2636         assert(errp == NULL);
2637         return NULL;
2638     }
2639 
2640     if (idx == 0) {
2641         rel_filename = g_strdup_printf("%s%s", data->prefix, data->postfix);
2642     } else if (split) {
2643         rel_filename = g_strdup_printf("%s-%c%03d%s",
2644                                        data->prefix,
2645                                        flat ? 'f' : 's', idx, data->postfix);
2646     } else {
2647         assert(idx == 1);
2648         rel_filename = g_strdup_printf("%s-flat%s", data->prefix, data->postfix);
2649     }
2650 
2651     ext_filename = g_strdup_printf("%s%s", data->path, rel_filename);
2652     g_free(rel_filename);
2653 
2654     if (vmdk_create_extent(ext_filename, size,
2655                            flat, compress, zeroed_grain, &blk, data->opts,
2656                            errp)) {
2657         goto exit;
2658     }
2659     bdrv_co_unref(bs);
2660 exit:
2661     g_free(ext_filename);
2662     return blk;
2663 }
2664 
2665 static int coroutine_fn GRAPH_UNLOCKED
2666 vmdk_co_create_opts(BlockDriver *drv, const char *filename,
2667                     QemuOpts *opts, Error **errp)
2668 {
2669     Error *local_err = NULL;
2670     char *desc = NULL;
2671     int64_t total_size = 0;
2672     char *adapter_type = NULL;
2673     BlockdevVmdkAdapterType adapter_type_enum;
2674     char *backing_file = NULL;
2675     char *hw_version = NULL;
2676     char *toolsversion = NULL;
2677     char *fmt = NULL;
2678     BlockdevVmdkSubformat subformat;
2679     int ret = 0;
2680     char *path = g_malloc0(PATH_MAX);
2681     char *prefix = g_malloc0(PATH_MAX);
2682     char *postfix = g_malloc0(PATH_MAX);
2683     char *desc_line = g_malloc0(BUF_SIZE);
2684     char *ext_filename = g_malloc0(PATH_MAX);
2685     char *desc_filename = g_malloc0(PATH_MAX);
2686     char *parent_desc_line = g_malloc0(BUF_SIZE);
2687     bool zeroed_grain;
2688     bool compat6;
2689     VMDKCreateOptsData data;
2690     char *backing_fmt = NULL;
2691 
2692     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2693     if (backing_fmt && strcmp(backing_fmt, "vmdk") != 0) {
2694         error_setg(errp, "backing_file must be a vmdk image");
2695         ret = -EINVAL;
2696         goto exit;
2697     }
2698 
2699     if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
2700         ret = -EINVAL;
2701         goto exit;
2702     }
2703     /* Read out options */
2704     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2705                           BDRV_SECTOR_SIZE);
2706     adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
2707     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2708     hw_version = qemu_opt_get_del(opts, BLOCK_OPT_HWVERSION);
2709     toolsversion = qemu_opt_get_del(opts, BLOCK_OPT_TOOLSVERSION);
2710     compat6 = qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false);
2711     if (strcmp(hw_version, "undefined") == 0) {
2712         g_free(hw_version);
2713         hw_version = NULL;
2714     }
2715     fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
2716     zeroed_grain = qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false);
2717 
2718     if (adapter_type) {
2719         adapter_type_enum = qapi_enum_parse(&BlockdevVmdkAdapterType_lookup,
2720                                             adapter_type,
2721                                             BLOCKDEV_VMDK_ADAPTER_TYPE_IDE,
2722                                             &local_err);
2723         if (local_err) {
2724             error_propagate(errp, local_err);
2725             ret = -EINVAL;
2726             goto exit;
2727         }
2728     } else {
2729         adapter_type_enum = BLOCKDEV_VMDK_ADAPTER_TYPE_IDE;
2730     }
2731 
2732     if (!fmt) {
2733         /* Default format to monolithicSparse */
2734         subformat = BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE;
2735     } else {
2736         subformat = qapi_enum_parse(&BlockdevVmdkSubformat_lookup,
2737                                     fmt,
2738                                     BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE,
2739                                     &local_err);
2740         if (local_err) {
2741             error_propagate(errp, local_err);
2742             ret = -EINVAL;
2743             goto exit;
2744         }
2745     }
2746     data = (VMDKCreateOptsData){
2747         .prefix = prefix,
2748         .postfix = postfix,
2749         .path = path,
2750         .opts = opts,
2751     };
2752     ret = vmdk_co_do_create(total_size, subformat, adapter_type_enum,
2753                             backing_file, hw_version, toolsversion, compat6,
2754                             zeroed_grain, vmdk_co_create_opts_cb, &data, errp);
2755 
2756 exit:
2757     g_free(backing_fmt);
2758     g_free(adapter_type);
2759     g_free(backing_file);
2760     g_free(hw_version);
2761     g_free(toolsversion);
2762     g_free(fmt);
2763     g_free(desc);
2764     g_free(path);
2765     g_free(prefix);
2766     g_free(postfix);
2767     g_free(desc_line);
2768     g_free(ext_filename);
2769     g_free(desc_filename);
2770     g_free(parent_desc_line);
2771     return ret;
2772 }
2773 
2774 static BlockBackend * coroutine_fn GRAPH_UNLOCKED
2775 vmdk_co_create_cb(int64_t size, int idx, bool flat, bool split, bool compress,
2776                   bool zeroed_grain, void *opaque, Error **errp)
2777 {
2778     int ret;
2779     BlockDriverState *bs;
2780     BlockBackend *blk;
2781     BlockdevCreateOptionsVmdk *opts = opaque;
2782 
2783     if (idx == 0) {
2784         bs = bdrv_co_open_blockdev_ref(opts->file, errp);
2785     } else {
2786         int i;
2787         BlockdevRefList *list = opts->extents;
2788         for (i = 1; i < idx; i++) {
2789             if (!list || !list->next) {
2790                 error_setg(errp, "Extent [%d] not specified", i);
2791                 return NULL;
2792             }
2793             list = list->next;
2794         }
2795         if (!list) {
2796             error_setg(errp, "Extent [%d] not specified", idx - 1);
2797             return NULL;
2798         }
2799         bs = bdrv_co_open_blockdev_ref(list->value, errp);
2800     }
2801     if (!bs) {
2802         return NULL;
2803     }
2804     blk = blk_co_new_with_bs(bs,
2805                              BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE |
2806                                 BLK_PERM_RESIZE,
2807                              BLK_PERM_ALL,
2808                              errp);
2809     if (!blk) {
2810         return NULL;
2811     }
2812     blk_set_allow_write_beyond_eof(blk, true);
2813     bdrv_co_unref(bs);
2814 
2815     if (size != -1) {
2816         ret = vmdk_init_extent(blk, size, flat, compress, zeroed_grain, errp);
2817         if (ret) {
2818             blk_co_unref(blk);
2819             blk = NULL;
2820         }
2821     }
2822     return blk;
2823 }
2824 
2825 static int coroutine_fn GRAPH_UNLOCKED
2826 vmdk_co_create(BlockdevCreateOptions *create_options, Error **errp)
2827 {
2828     BlockdevCreateOptionsVmdk *opts;
2829 
2830     opts = &create_options->u.vmdk;
2831 
2832     /* Validate options */
2833     if (!QEMU_IS_ALIGNED(opts->size, BDRV_SECTOR_SIZE)) {
2834         error_setg(errp, "Image size must be a multiple of 512 bytes");
2835         return -EINVAL;
2836     }
2837 
2838     return vmdk_co_do_create(opts->size,
2839                              opts->subformat,
2840                              opts->adapter_type,
2841                              opts->backing_file,
2842                              opts->hwversion,
2843                              opts->toolsversion,
2844                              false,
2845                              opts->zeroed_grain,
2846                              vmdk_co_create_cb,
2847                              opts, errp);
2848 }
2849 
2850 static void vmdk_close(BlockDriverState *bs)
2851 {
2852     BDRVVmdkState *s = bs->opaque;
2853 
2854     vmdk_free_extents(bs);
2855     g_free(s->create_type);
2856 
2857     migrate_del_blocker(s->migration_blocker);
2858     error_free(s->migration_blocker);
2859 }
2860 
2861 static int64_t coroutine_fn GRAPH_RDLOCK
2862 vmdk_co_get_allocated_file_size(BlockDriverState *bs)
2863 {
2864     int i;
2865     int64_t ret = 0;
2866     int64_t r;
2867     BDRVVmdkState *s = bs->opaque;
2868 
2869     ret = bdrv_co_get_allocated_file_size(bs->file->bs);
2870     if (ret < 0) {
2871         return ret;
2872     }
2873     for (i = 0; i < s->num_extents; i++) {
2874         if (s->extents[i].file == bs->file) {
2875             continue;
2876         }
2877         r = bdrv_co_get_allocated_file_size(s->extents[i].file->bs);
2878         if (r < 0) {
2879             return r;
2880         }
2881         ret += r;
2882     }
2883     return ret;
2884 }
2885 
2886 static int vmdk_has_zero_init(BlockDriverState *bs)
2887 {
2888     int i;
2889     BDRVVmdkState *s = bs->opaque;
2890 
2891     /* If has a flat extent and its underlying storage doesn't have zero init,
2892      * return 0. */
2893     for (i = 0; i < s->num_extents; i++) {
2894         if (s->extents[i].flat) {
2895             if (!bdrv_has_zero_init(s->extents[i].file->bs)) {
2896                 return 0;
2897             }
2898         }
2899     }
2900     return 1;
2901 }
2902 
2903 static VmdkExtentInfo *vmdk_get_extent_info(VmdkExtent *extent)
2904 {
2905     VmdkExtentInfo *info = g_new0(VmdkExtentInfo, 1);
2906 
2907     bdrv_refresh_filename(extent->file->bs);
2908     *info = (VmdkExtentInfo){
2909         .filename         = g_strdup(extent->file->bs->filename),
2910         .format           = g_strdup(extent->type),
2911         .virtual_size     = extent->sectors * BDRV_SECTOR_SIZE,
2912         .compressed       = extent->compressed,
2913         .has_compressed   = extent->compressed,
2914         .cluster_size     = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2915         .has_cluster_size = !extent->flat,
2916     };
2917 
2918     return info;
2919 }
2920 
2921 static int coroutine_fn GRAPH_RDLOCK
2922 vmdk_co_check(BlockDriverState *bs, BdrvCheckResult *result, BdrvCheckMode fix)
2923 {
2924     BDRVVmdkState *s = bs->opaque;
2925     VmdkExtent *extent = NULL;
2926     int64_t sector_num = 0;
2927     int64_t total_sectors = bdrv_co_nb_sectors(bs);
2928     int ret;
2929     uint64_t cluster_offset;
2930 
2931     if (fix) {
2932         return -ENOTSUP;
2933     }
2934 
2935     for (;;) {
2936         if (sector_num >= total_sectors) {
2937             return 0;
2938         }
2939         extent = find_extent(s, sector_num, extent);
2940         if (!extent) {
2941             fprintf(stderr,
2942                     "ERROR: could not find extent for sector %" PRId64 "\n",
2943                     sector_num);
2944             ret = -EINVAL;
2945             break;
2946         }
2947         ret = get_cluster_offset(bs, extent, NULL,
2948                                  sector_num << BDRV_SECTOR_BITS,
2949                                  false, &cluster_offset, 0, 0);
2950         if (ret == VMDK_ERROR) {
2951             fprintf(stderr,
2952                     "ERROR: could not get cluster_offset for sector %"
2953                     PRId64 "\n", sector_num);
2954             break;
2955         }
2956         if (ret == VMDK_OK) {
2957             int64_t extent_len = bdrv_co_getlength(extent->file->bs);
2958             if (extent_len < 0) {
2959                 fprintf(stderr,
2960                         "ERROR: could not get extent file length for sector %"
2961                         PRId64 "\n", sector_num);
2962                 ret = extent_len;
2963                 break;
2964             }
2965             if (cluster_offset >= extent_len) {
2966                 fprintf(stderr,
2967                         "ERROR: cluster offset for sector %"
2968                         PRId64 " points after EOF\n", sector_num);
2969                 ret = -EINVAL;
2970                 break;
2971             }
2972         }
2973         sector_num += extent->cluster_sectors;
2974     }
2975 
2976     result->corruptions++;
2977     return ret;
2978 }
2979 
2980 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs,
2981                                                  Error **errp)
2982 {
2983     int i;
2984     BDRVVmdkState *s = bs->opaque;
2985     ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2986     VmdkExtentInfoList **tail;
2987 
2988     *spec_info = (ImageInfoSpecific){
2989         .type = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2990         .u = {
2991             .vmdk.data = g_new0(ImageInfoSpecificVmdk, 1),
2992         },
2993     };
2994 
2995     *spec_info->u.vmdk.data = (ImageInfoSpecificVmdk) {
2996         .create_type = g_strdup(s->create_type),
2997         .cid = s->cid,
2998         .parent_cid = s->parent_cid,
2999     };
3000 
3001     tail = &spec_info->u.vmdk.data->extents;
3002     for (i = 0; i < s->num_extents; i++) {
3003         QAPI_LIST_APPEND(tail, vmdk_get_extent_info(&s->extents[i]));
3004     }
3005 
3006     return spec_info;
3007 }
3008 
3009 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
3010 {
3011     return a->flat == b->flat &&
3012            a->compressed == b->compressed &&
3013            (a->flat || a->cluster_sectors == b->cluster_sectors);
3014 }
3015 
3016 static int coroutine_fn
3017 vmdk_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3018 {
3019     int i;
3020     BDRVVmdkState *s = bs->opaque;
3021     assert(s->num_extents);
3022 
3023     /* See if we have multiple extents but they have different cases */
3024     for (i = 1; i < s->num_extents; i++) {
3025         if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
3026             return -ENOTSUP;
3027         }
3028     }
3029     bdi->needs_compressed_writes = s->extents[0].compressed;
3030     if (!s->extents[0].flat) {
3031         bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
3032     }
3033     return 0;
3034 }
3035 
3036 static void vmdk_gather_child_options(BlockDriverState *bs, QDict *target,
3037                                       bool backing_overridden)
3038 {
3039     /* No children but file and backing can be explicitly specified (TODO) */
3040     qdict_put(target, "file",
3041               qobject_ref(bs->file->bs->full_open_options));
3042 
3043     if (backing_overridden) {
3044         if (bs->backing) {
3045             qdict_put(target, "backing",
3046                       qobject_ref(bs->backing->bs->full_open_options));
3047         } else {
3048             qdict_put_null(target, "backing");
3049         }
3050     }
3051 }
3052 
3053 static QemuOptsList vmdk_create_opts = {
3054     .name = "vmdk-create-opts",
3055     .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
3056     .desc = {
3057         {
3058             .name = BLOCK_OPT_SIZE,
3059             .type = QEMU_OPT_SIZE,
3060             .help = "Virtual disk size"
3061         },
3062         {
3063             .name = BLOCK_OPT_ADAPTER_TYPE,
3064             .type = QEMU_OPT_STRING,
3065             .help = "Virtual adapter type, can be one of "
3066                     "ide (default), lsilogic, buslogic or legacyESX"
3067         },
3068         {
3069             .name = BLOCK_OPT_BACKING_FILE,
3070             .type = QEMU_OPT_STRING,
3071             .help = "File name of a base image"
3072         },
3073         {
3074             .name = BLOCK_OPT_BACKING_FMT,
3075             .type = QEMU_OPT_STRING,
3076             .help = "Must be 'vmdk' if present",
3077         },
3078         {
3079             .name = BLOCK_OPT_COMPAT6,
3080             .type = QEMU_OPT_BOOL,
3081             .help = "VMDK version 6 image",
3082             .def_value_str = "off"
3083         },
3084         {
3085             .name = BLOCK_OPT_HWVERSION,
3086             .type = QEMU_OPT_STRING,
3087             .help = "VMDK hardware version",
3088             .def_value_str = "undefined"
3089         },
3090         {
3091             .name = BLOCK_OPT_TOOLSVERSION,
3092             .type = QEMU_OPT_STRING,
3093             .help = "VMware guest tools version",
3094         },
3095         {
3096             .name = BLOCK_OPT_SUBFMT,
3097             .type = QEMU_OPT_STRING,
3098             .help =
3099                 "VMDK flat extent format, can be one of "
3100                 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
3101         },
3102         {
3103             .name = BLOCK_OPT_ZEROED_GRAIN,
3104             .type = QEMU_OPT_BOOL,
3105             .help = "Enable efficient zero writes "
3106                     "using the zeroed-grain GTE feature"
3107         },
3108         { /* end of list */ }
3109     }
3110 };
3111 
3112 static BlockDriver bdrv_vmdk = {
3113     .format_name                  = "vmdk",
3114     .instance_size                = sizeof(BDRVVmdkState),
3115     .bdrv_probe                   = vmdk_probe,
3116     .bdrv_open                    = vmdk_open,
3117     .bdrv_co_check                = vmdk_co_check,
3118     .bdrv_reopen_prepare          = vmdk_reopen_prepare,
3119     .bdrv_reopen_commit           = vmdk_reopen_commit,
3120     .bdrv_reopen_abort            = vmdk_reopen_abort,
3121     .bdrv_child_perm              = bdrv_default_perms,
3122     .bdrv_co_preadv               = vmdk_co_preadv,
3123     .bdrv_co_pwritev              = vmdk_co_pwritev,
3124     .bdrv_co_pwritev_compressed   = vmdk_co_pwritev_compressed,
3125     .bdrv_co_pwrite_zeroes        = vmdk_co_pwrite_zeroes,
3126     .bdrv_close                   = vmdk_close,
3127     .bdrv_co_create_opts          = vmdk_co_create_opts,
3128     .bdrv_co_create               = vmdk_co_create,
3129     .bdrv_co_block_status         = vmdk_co_block_status,
3130     .bdrv_co_get_allocated_file_size = vmdk_co_get_allocated_file_size,
3131     .bdrv_has_zero_init           = vmdk_has_zero_init,
3132     .bdrv_get_specific_info       = vmdk_get_specific_info,
3133     .bdrv_refresh_limits          = vmdk_refresh_limits,
3134     .bdrv_co_get_info             = vmdk_co_get_info,
3135     .bdrv_gather_child_options    = vmdk_gather_child_options,
3136 
3137     .is_format                    = true,
3138     .supports_backing             = true,
3139     .create_opts                  = &vmdk_create_opts,
3140 };
3141 
3142 static void bdrv_vmdk_init(void)
3143 {
3144     bdrv_register(&bdrv_vmdk);
3145 }
3146 
3147 block_init(bdrv_vmdk_init);
3148