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