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