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