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