xref: /openbmc/qemu/block/vmdk.c (revision a37eaa53)
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/qerror.h"
31 #include "qemu/error-report.h"
32 #include "qemu/module.h"
33 #include "qemu/bswap.h"
34 #include "migration/blocker.h"
35 #include "qemu/cutils.h"
36 #include <zlib.h>
37 
38 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
39 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
40 #define VMDK4_COMPRESSION_DEFLATE 1
41 #define VMDK4_FLAG_NL_DETECT (1 << 0)
42 #define VMDK4_FLAG_RGD (1 << 1)
43 /* Zeroed-grain enable bit */
44 #define VMDK4_FLAG_ZERO_GRAIN   (1 << 2)
45 #define VMDK4_FLAG_COMPRESS (1 << 16)
46 #define VMDK4_FLAG_MARKER (1 << 17)
47 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
48 
49 #define VMDK_GTE_ZEROED 0x1
50 
51 /* VMDK internal error codes */
52 #define VMDK_OK      0
53 #define VMDK_ERROR   (-1)
54 /* Cluster not allocated */
55 #define VMDK_UNALLOC (-2)
56 #define VMDK_ZEROED  (-3)
57 
58 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
59 
60 typedef struct {
61     uint32_t version;
62     uint32_t flags;
63     uint32_t disk_sectors;
64     uint32_t granularity;
65     uint32_t l1dir_offset;
66     uint32_t l1dir_size;
67     uint32_t file_sectors;
68     uint32_t cylinders;
69     uint32_t heads;
70     uint32_t sectors_per_track;
71 } QEMU_PACKED VMDK3Header;
72 
73 typedef struct {
74     uint32_t version;
75     uint32_t flags;
76     uint64_t capacity;
77     uint64_t granularity;
78     uint64_t desc_offset;
79     uint64_t desc_size;
80     /* Number of GrainTableEntries per GrainTable */
81     uint32_t num_gtes_per_gt;
82     uint64_t rgd_offset;
83     uint64_t gd_offset;
84     uint64_t grain_offset;
85     char filler[1];
86     char check_bytes[4];
87     uint16_t compressAlgorithm;
88 } QEMU_PACKED VMDK4Header;
89 
90 #define L2_CACHE_SIZE 16
91 
92 typedef struct VmdkExtent {
93     BdrvChild *file;
94     bool flat;
95     bool compressed;
96     bool has_marker;
97     bool has_zero_grain;
98     int version;
99     int64_t sectors;
100     int64_t end_sector;
101     int64_t flat_start_offset;
102     int64_t l1_table_offset;
103     int64_t l1_backup_table_offset;
104     uint32_t *l1_table;
105     uint32_t *l1_backup_table;
106     unsigned int l1_size;
107     uint32_t l1_entry_sectors;
108 
109     unsigned int l2_size;
110     uint32_t *l2_cache;
111     uint32_t l2_cache_offsets[L2_CACHE_SIZE];
112     uint32_t l2_cache_counts[L2_CACHE_SIZE];
113 
114     int64_t cluster_sectors;
115     int64_t next_cluster_sector;
116     char *type;
117 } VmdkExtent;
118 
119 typedef struct BDRVVmdkState {
120     CoMutex lock;
121     uint64_t desc_offset;
122     bool cid_updated;
123     bool cid_checked;
124     uint32_t cid;
125     uint32_t parent_cid;
126     int num_extents;
127     /* Extent array with num_extents entries, ascend ordered by address */
128     VmdkExtent *extents;
129     Error *migration_blocker;
130     char *create_type;
131 } BDRVVmdkState;
132 
133 typedef struct VmdkMetaData {
134     unsigned int l1_index;
135     unsigned int l2_index;
136     unsigned int l2_offset;
137     int valid;
138     uint32_t *l2_cache_entry;
139 } VmdkMetaData;
140 
141 typedef struct VmdkGrainMarker {
142     uint64_t lba;
143     uint32_t size;
144     uint8_t  data[0];
145 } QEMU_PACKED VmdkGrainMarker;
146 
147 enum {
148     MARKER_END_OF_STREAM    = 0,
149     MARKER_GRAIN_TABLE      = 1,
150     MARKER_GRAIN_DIRECTORY  = 2,
151     MARKER_FOOTER           = 3,
152 };
153 
154 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
155 {
156     uint32_t magic;
157 
158     if (buf_size < 4) {
159         return 0;
160     }
161     magic = be32_to_cpu(*(uint32_t *)buf);
162     if (magic == VMDK3_MAGIC ||
163         magic == VMDK4_MAGIC) {
164         return 100;
165     } else {
166         const char *p = (const char *)buf;
167         const char *end = p + buf_size;
168         while (p < end) {
169             if (*p == '#') {
170                 /* skip comment line */
171                 while (p < end && *p != '\n') {
172                     p++;
173                 }
174                 p++;
175                 continue;
176             }
177             if (*p == ' ') {
178                 while (p < end && *p == ' ') {
179                     p++;
180                 }
181                 /* skip '\r' if windows line endings used. */
182                 if (p < end && *p == '\r') {
183                     p++;
184                 }
185                 /* only accept blank lines before 'version=' line */
186                 if (p == end || *p != '\n') {
187                     return 0;
188                 }
189                 p++;
190                 continue;
191             }
192             if (end - p >= strlen("version=X\n")) {
193                 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
194                     strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
195                     return 100;
196                 }
197             }
198             if (end - p >= strlen("version=X\r\n")) {
199                 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
200                     strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
201                     return 100;
202                 }
203             }
204             return 0;
205         }
206         return 0;
207     }
208 }
209 
210 #define SECTOR_SIZE 512
211 #define DESC_SIZE (20 * SECTOR_SIZE)    /* 20 sectors of 512 bytes each */
212 #define BUF_SIZE 4096
213 #define HEADER_SIZE 512                 /* first sector of 512 bytes */
214 
215 static void vmdk_free_extents(BlockDriverState *bs)
216 {
217     int i;
218     BDRVVmdkState *s = bs->opaque;
219     VmdkExtent *e;
220 
221     for (i = 0; i < s->num_extents; i++) {
222         e = &s->extents[i];
223         g_free(e->l1_table);
224         g_free(e->l2_cache);
225         g_free(e->l1_backup_table);
226         g_free(e->type);
227         if (e->file != bs->file) {
228             bdrv_unref_child(bs, e->file);
229         }
230     }
231     g_free(s->extents);
232 }
233 
234 static void vmdk_free_last_extent(BlockDriverState *bs)
235 {
236     BDRVVmdkState *s = bs->opaque;
237 
238     if (s->num_extents == 0) {
239         return;
240     }
241     s->num_extents--;
242     s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
243 }
244 
245 /* Return -ve errno, or 0 on success and write CID into *pcid. */
246 static int vmdk_read_cid(BlockDriverState *bs, int parent, uint32_t *pcid)
247 {
248     char *desc;
249     uint32_t cid;
250     const char *p_name, *cid_str;
251     size_t cid_str_size;
252     BDRVVmdkState *s = bs->opaque;
253     int ret;
254 
255     desc = g_malloc0(DESC_SIZE);
256     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
257     if (ret < 0) {
258         goto out;
259     }
260 
261     if (parent) {
262         cid_str = "parentCID";
263         cid_str_size = sizeof("parentCID");
264     } else {
265         cid_str = "CID";
266         cid_str_size = sizeof("CID");
267     }
268 
269     desc[DESC_SIZE - 1] = '\0';
270     p_name = strstr(desc, cid_str);
271     if (p_name == NULL) {
272         ret = -EINVAL;
273         goto out;
274     }
275     p_name += cid_str_size;
276     if (sscanf(p_name, "%" SCNx32, &cid) != 1) {
277         ret = -EINVAL;
278         goto out;
279     }
280     *pcid = cid;
281     ret = 0;
282 
283 out:
284     g_free(desc);
285     return ret;
286 }
287 
288 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
289 {
290     char *desc, *tmp_desc;
291     char *p_name, *tmp_str;
292     BDRVVmdkState *s = bs->opaque;
293     int ret = 0;
294 
295     desc = g_malloc0(DESC_SIZE);
296     tmp_desc = g_malloc0(DESC_SIZE);
297     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
298     if (ret < 0) {
299         goto out;
300     }
301 
302     desc[DESC_SIZE - 1] = '\0';
303     tmp_str = strstr(desc, "parentCID");
304     if (tmp_str == NULL) {
305         ret = -EINVAL;
306         goto out;
307     }
308 
309     pstrcpy(tmp_desc, DESC_SIZE, tmp_str);
310     p_name = strstr(desc, "CID");
311     if (p_name != NULL) {
312         p_name += sizeof("CID");
313         snprintf(p_name, DESC_SIZE - (p_name - desc), "%" PRIx32 "\n", cid);
314         pstrcat(desc, DESC_SIZE, tmp_desc);
315     }
316 
317     ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
318 
319 out:
320     g_free(desc);
321     g_free(tmp_desc);
322     return ret;
323 }
324 
325 static int vmdk_is_cid_valid(BlockDriverState *bs)
326 {
327     BDRVVmdkState *s = bs->opaque;
328     uint32_t cur_pcid;
329 
330     if (!s->cid_checked && bs->backing) {
331         BlockDriverState *p_bs = bs->backing->bs;
332 
333         if (vmdk_read_cid(p_bs, 0, &cur_pcid) != 0) {
334             /* read failure: report as not valid */
335             return 0;
336         }
337         if (s->parent_cid != cur_pcid) {
338             /* CID not valid */
339             return 0;
340         }
341     }
342     s->cid_checked = true;
343     /* CID valid */
344     return 1;
345 }
346 
347 /* We have nothing to do for VMDK reopen, stubs just return success */
348 static int vmdk_reopen_prepare(BDRVReopenState *state,
349                                BlockReopenQueue *queue, Error **errp)
350 {
351     assert(state != NULL);
352     assert(state->bs != NULL);
353     return 0;
354 }
355 
356 static int vmdk_parent_open(BlockDriverState *bs)
357 {
358     char *p_name;
359     char *desc;
360     BDRVVmdkState *s = bs->opaque;
361     int ret;
362 
363     desc = g_malloc0(DESC_SIZE + 1);
364     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
365     if (ret < 0) {
366         goto out;
367     }
368     ret = 0;
369 
370     p_name = strstr(desc, "parentFileNameHint");
371     if (p_name != NULL) {
372         char *end_name;
373 
374         p_name += sizeof("parentFileNameHint") + 1;
375         end_name = strchr(p_name, '\"');
376         if (end_name == NULL) {
377             ret = -EINVAL;
378             goto out;
379         }
380         if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
381             ret = -EINVAL;
382             goto out;
383         }
384 
385         pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
386     }
387 
388 out:
389     g_free(desc);
390     return ret;
391 }
392 
393 /* Create and append extent to the extent array. Return the added VmdkExtent
394  * address. return NULL if allocation failed. */
395 static int vmdk_add_extent(BlockDriverState *bs,
396                            BdrvChild *file, bool flat, int64_t sectors,
397                            int64_t l1_offset, int64_t l1_backup_offset,
398                            uint32_t l1_size,
399                            int l2_size, uint64_t cluster_sectors,
400                            VmdkExtent **new_extent,
401                            Error **errp)
402 {
403     VmdkExtent *extent;
404     BDRVVmdkState *s = bs->opaque;
405     int64_t nb_sectors;
406 
407     if (cluster_sectors > 0x200000) {
408         /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
409         error_setg(errp, "Invalid granularity, image may be corrupt");
410         return -EFBIG;
411     }
412     if (l1_size > 512 * 1024 * 1024) {
413         /* Although with big capacity and small l1_entry_sectors, we can get a
414          * big l1_size, we don't want unbounded value to allocate the table.
415          * Limit it to 512M, which is 16PB for default cluster and L2 table
416          * size */
417         error_setg(errp, "L1 size too big");
418         return -EFBIG;
419     }
420 
421     nb_sectors = bdrv_nb_sectors(file->bs);
422     if (nb_sectors < 0) {
423         return nb_sectors;
424     }
425 
426     s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
427     extent = &s->extents[s->num_extents];
428     s->num_extents++;
429 
430     memset(extent, 0, sizeof(VmdkExtent));
431     extent->file = file;
432     extent->flat = flat;
433     extent->sectors = sectors;
434     extent->l1_table_offset = l1_offset;
435     extent->l1_backup_table_offset = l1_backup_offset;
436     extent->l1_size = l1_size;
437     extent->l1_entry_sectors = l2_size * cluster_sectors;
438     extent->l2_size = l2_size;
439     extent->cluster_sectors = flat ? sectors : cluster_sectors;
440     extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
441 
442     if (s->num_extents > 1) {
443         extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
444     } else {
445         extent->end_sector = extent->sectors;
446     }
447     bs->total_sectors = extent->end_sector;
448     if (new_extent) {
449         *new_extent = extent;
450     }
451     return 0;
452 }
453 
454 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
455                             Error **errp)
456 {
457     int ret;
458     size_t l1_size;
459     int i;
460 
461     /* read the L1 table */
462     l1_size = extent->l1_size * sizeof(uint32_t);
463     extent->l1_table = g_try_malloc(l1_size);
464     if (l1_size && extent->l1_table == NULL) {
465         return -ENOMEM;
466     }
467 
468     ret = bdrv_pread(extent->file,
469                      extent->l1_table_offset,
470                      extent->l1_table,
471                      l1_size);
472     if (ret < 0) {
473         error_setg_errno(errp, -ret,
474                          "Could not read l1 table from extent '%s'",
475                          extent->file->bs->filename);
476         goto fail_l1;
477     }
478     for (i = 0; i < extent->l1_size; i++) {
479         le32_to_cpus(&extent->l1_table[i]);
480     }
481 
482     if (extent->l1_backup_table_offset) {
483         extent->l1_backup_table = g_try_malloc(l1_size);
484         if (l1_size && extent->l1_backup_table == NULL) {
485             ret = -ENOMEM;
486             goto fail_l1;
487         }
488         ret = bdrv_pread(extent->file,
489                          extent->l1_backup_table_offset,
490                          extent->l1_backup_table,
491                          l1_size);
492         if (ret < 0) {
493             error_setg_errno(errp, -ret,
494                              "Could not read l1 backup table from extent '%s'",
495                              extent->file->bs->filename);
496             goto fail_l1b;
497         }
498         for (i = 0; i < extent->l1_size; i++) {
499             le32_to_cpus(&extent->l1_backup_table[i]);
500         }
501     }
502 
503     extent->l2_cache =
504         g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
505     return 0;
506  fail_l1b:
507     g_free(extent->l1_backup_table);
508  fail_l1:
509     g_free(extent->l1_table);
510     return ret;
511 }
512 
513 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
514                                  BdrvChild *file,
515                                  int flags, Error **errp)
516 {
517     int ret;
518     uint32_t magic;
519     VMDK3Header header;
520     VmdkExtent *extent;
521 
522     ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
523     if (ret < 0) {
524         error_setg_errno(errp, -ret,
525                          "Could not read header from file '%s'",
526                          file->bs->filename);
527         return ret;
528     }
529     ret = vmdk_add_extent(bs, file, false,
530                           le32_to_cpu(header.disk_sectors),
531                           (int64_t)le32_to_cpu(header.l1dir_offset) << 9,
532                           0,
533                           le32_to_cpu(header.l1dir_size),
534                           4096,
535                           le32_to_cpu(header.granularity),
536                           &extent,
537                           errp);
538     if (ret < 0) {
539         return ret;
540     }
541     ret = vmdk_init_tables(bs, extent, errp);
542     if (ret) {
543         /* free extent allocated by vmdk_add_extent */
544         vmdk_free_last_extent(bs);
545     }
546     return ret;
547 }
548 
549 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
550                                QDict *options, Error **errp);
551 
552 static char *vmdk_read_desc(BdrvChild *file, uint64_t desc_offset, Error **errp)
553 {
554     int64_t size;
555     char *buf;
556     int ret;
557 
558     size = bdrv_getlength(file->bs);
559     if (size < 0) {
560         error_setg_errno(errp, -size, "Could not access file");
561         return NULL;
562     }
563 
564     if (size < 4) {
565         /* Both descriptor file and sparse image must be much larger than 4
566          * bytes, also callers of vmdk_read_desc want to compare the first 4
567          * bytes with VMDK4_MAGIC, let's error out if less is read. */
568         error_setg(errp, "File is too small, not a valid image");
569         return NULL;
570     }
571 
572     size = MIN(size, (1 << 20) - 1);  /* avoid unbounded allocation */
573     buf = g_malloc(size + 1);
574 
575     ret = bdrv_pread(file, desc_offset, buf, size);
576     if (ret < 0) {
577         error_setg_errno(errp, -ret, "Could not read from file");
578         g_free(buf);
579         return NULL;
580     }
581     buf[ret] = 0;
582 
583     return buf;
584 }
585 
586 static int vmdk_open_vmdk4(BlockDriverState *bs,
587                            BdrvChild *file,
588                            int flags, QDict *options, Error **errp)
589 {
590     int ret;
591     uint32_t magic;
592     uint32_t l1_size, l1_entry_sectors;
593     VMDK4Header header;
594     VmdkExtent *extent;
595     BDRVVmdkState *s = bs->opaque;
596     int64_t l1_backup_offset = 0;
597     bool compressed;
598 
599     ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
600     if (ret < 0) {
601         error_setg_errno(errp, -ret,
602                          "Could not read header from file '%s'",
603                          file->bs->filename);
604         return -EINVAL;
605     }
606     if (header.capacity == 0) {
607         uint64_t desc_offset = le64_to_cpu(header.desc_offset);
608         if (desc_offset) {
609             char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
610             if (!buf) {
611                 return -EINVAL;
612             }
613             ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
614             g_free(buf);
615             return ret;
616         }
617     }
618 
619     if (!s->create_type) {
620         s->create_type = g_strdup("monolithicSparse");
621     }
622 
623     if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
624         /*
625          * The footer takes precedence over the header, so read it in. The
626          * footer starts at offset -1024 from the end: One sector for the
627          * footer, and another one for the end-of-stream marker.
628          */
629         struct {
630             struct {
631                 uint64_t val;
632                 uint32_t size;
633                 uint32_t type;
634                 uint8_t pad[512 - 16];
635             } QEMU_PACKED footer_marker;
636 
637             uint32_t magic;
638             VMDK4Header header;
639             uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
640 
641             struct {
642                 uint64_t val;
643                 uint32_t size;
644                 uint32_t type;
645                 uint8_t pad[512 - 16];
646             } QEMU_PACKED eos_marker;
647         } QEMU_PACKED footer;
648 
649         ret = bdrv_pread(file,
650             bs->file->bs->total_sectors * 512 - 1536,
651             &footer, sizeof(footer));
652         if (ret < 0) {
653             error_setg_errno(errp, -ret, "Failed to read footer");
654             return ret;
655         }
656 
657         /* Some sanity checks for the footer */
658         if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
659             le32_to_cpu(footer.footer_marker.size) != 0  ||
660             le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
661             le64_to_cpu(footer.eos_marker.val) != 0  ||
662             le32_to_cpu(footer.eos_marker.size) != 0  ||
663             le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
664         {
665             error_setg(errp, "Invalid footer");
666             return -EINVAL;
667         }
668 
669         header = footer.header;
670     }
671 
672     compressed =
673         le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
674     if (le32_to_cpu(header.version) > 3) {
675         error_setg(errp, "Unsupported VMDK version %" PRIu32,
676                    le32_to_cpu(header.version));
677         return -ENOTSUP;
678     } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR) &&
679                !compressed) {
680         /* VMware KB 2064959 explains that version 3 added support for
681          * persistent changed block tracking (CBT), and backup software can
682          * read it as version=1 if it doesn't care about the changed area
683          * information. So we are safe to enable read only. */
684         error_setg(errp, "VMDK version 3 must be read only");
685         return -EINVAL;
686     }
687 
688     if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
689         error_setg(errp, "L2 table size too big");
690         return -EINVAL;
691     }
692 
693     l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
694                         * le64_to_cpu(header.granularity);
695     if (l1_entry_sectors == 0) {
696         error_setg(errp, "L1 entry size is invalid");
697         return -EINVAL;
698     }
699     l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
700                 / l1_entry_sectors;
701     if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
702         l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
703     }
704     if (bdrv_nb_sectors(file->bs) < le64_to_cpu(header.grain_offset)) {
705         error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
706                    (int64_t)(le64_to_cpu(header.grain_offset)
707                              * BDRV_SECTOR_SIZE));
708         return -EINVAL;
709     }
710 
711     ret = vmdk_add_extent(bs, file, false,
712                           le64_to_cpu(header.capacity),
713                           le64_to_cpu(header.gd_offset) << 9,
714                           l1_backup_offset,
715                           l1_size,
716                           le32_to_cpu(header.num_gtes_per_gt),
717                           le64_to_cpu(header.granularity),
718                           &extent,
719                           errp);
720     if (ret < 0) {
721         return ret;
722     }
723     extent->compressed =
724         le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
725     if (extent->compressed) {
726         g_free(s->create_type);
727         s->create_type = g_strdup("streamOptimized");
728     }
729     extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
730     extent->version = le32_to_cpu(header.version);
731     extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
732     ret = vmdk_init_tables(bs, extent, errp);
733     if (ret) {
734         /* free extent allocated by vmdk_add_extent */
735         vmdk_free_last_extent(bs);
736     }
737     return ret;
738 }
739 
740 /* find an option value out of descriptor file */
741 static int vmdk_parse_description(const char *desc, const char *opt_name,
742         char *buf, int buf_size)
743 {
744     char *opt_pos, *opt_end;
745     const char *end = desc + strlen(desc);
746 
747     opt_pos = strstr(desc, opt_name);
748     if (!opt_pos) {
749         return VMDK_ERROR;
750     }
751     /* Skip "=\"" following opt_name */
752     opt_pos += strlen(opt_name) + 2;
753     if (opt_pos >= end) {
754         return VMDK_ERROR;
755     }
756     opt_end = opt_pos;
757     while (opt_end < end && *opt_end != '"') {
758         opt_end++;
759     }
760     if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
761         return VMDK_ERROR;
762     }
763     pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
764     return VMDK_OK;
765 }
766 
767 /* Open an extent file and append to bs array */
768 static int vmdk_open_sparse(BlockDriverState *bs, BdrvChild *file, int flags,
769                             char *buf, QDict *options, Error **errp)
770 {
771     uint32_t magic;
772 
773     magic = ldl_be_p(buf);
774     switch (magic) {
775         case VMDK3_MAGIC:
776             return vmdk_open_vmfs_sparse(bs, file, flags, errp);
777             break;
778         case VMDK4_MAGIC:
779             return vmdk_open_vmdk4(bs, file, flags, options, errp);
780             break;
781         default:
782             error_setg(errp, "Image not in VMDK format");
783             return -EINVAL;
784             break;
785     }
786 }
787 
788 static const char *next_line(const char *s)
789 {
790     while (*s) {
791         if (*s == '\n') {
792             return s + 1;
793         }
794         s++;
795     }
796     return s;
797 }
798 
799 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
800                               const char *desc_file_path, QDict *options,
801                               Error **errp)
802 {
803     int ret;
804     int matches;
805     char access[11];
806     char type[11];
807     char fname[512];
808     const char *p, *np;
809     int64_t sectors = 0;
810     int64_t flat_offset;
811     char *extent_path;
812     BdrvChild *extent_file;
813     BDRVVmdkState *s = bs->opaque;
814     VmdkExtent *extent;
815     char extent_opt_prefix[32];
816     Error *local_err = NULL;
817 
818     for (p = desc; *p; p = next_line(p)) {
819         /* parse extent line in one of below formats:
820          *
821          * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
822          * RW [size in sectors] SPARSE "file-name.vmdk"
823          * RW [size in sectors] VMFS "file-name.vmdk"
824          * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
825          */
826         flat_offset = -1;
827         matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
828                          access, &sectors, type, fname, &flat_offset);
829         if (matches < 4 || strcmp(access, "RW")) {
830             continue;
831         } else if (!strcmp(type, "FLAT")) {
832             if (matches != 5 || flat_offset < 0) {
833                 goto invalid;
834             }
835         } else if (!strcmp(type, "VMFS")) {
836             if (matches == 4) {
837                 flat_offset = 0;
838             } else {
839                 goto invalid;
840             }
841         } else if (matches != 4) {
842             goto invalid;
843         }
844 
845         if (sectors <= 0 ||
846             (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
847              strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
848             (strcmp(access, "RW"))) {
849             continue;
850         }
851 
852         if (!path_is_absolute(fname) && !path_has_protocol(fname) &&
853             !desc_file_path[0])
854         {
855             error_setg(errp, "Cannot use relative extent paths with VMDK "
856                        "descriptor file '%s'", bs->file->bs->filename);
857             return -EINVAL;
858         }
859 
860         extent_path = g_malloc0(PATH_MAX);
861         path_combine(extent_path, PATH_MAX, desc_file_path, fname);
862 
863         ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents);
864         assert(ret < 32);
865 
866         extent_file = bdrv_open_child(extent_path, options, extent_opt_prefix,
867                                       bs, &child_file, false, &local_err);
868         g_free(extent_path);
869         if (local_err) {
870             error_propagate(errp, local_err);
871             return -EINVAL;
872         }
873 
874         /* save to extents array */
875         if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
876             /* FLAT extent */
877 
878             ret = vmdk_add_extent(bs, extent_file, true, sectors,
879                             0, 0, 0, 0, 0, &extent, errp);
880             if (ret < 0) {
881                 bdrv_unref_child(bs, extent_file);
882                 return ret;
883             }
884             extent->flat_start_offset = flat_offset << 9;
885         } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
886             /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
887             char *buf = vmdk_read_desc(extent_file, 0, errp);
888             if (!buf) {
889                 ret = -EINVAL;
890             } else {
891                 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf,
892                                        options, errp);
893             }
894             g_free(buf);
895             if (ret) {
896                 bdrv_unref_child(bs, extent_file);
897                 return ret;
898             }
899             extent = &s->extents[s->num_extents - 1];
900         } else {
901             error_setg(errp, "Unsupported extent type '%s'", type);
902             bdrv_unref_child(bs, extent_file);
903             return -ENOTSUP;
904         }
905         extent->type = g_strdup(type);
906     }
907     return 0;
908 
909 invalid:
910     np = next_line(p);
911     assert(np != p);
912     if (np[-1] == '\n') {
913         np--;
914     }
915     error_setg(errp, "Invalid extent line: %.*s", (int)(np - p), p);
916     return -EINVAL;
917 }
918 
919 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
920                                QDict *options, Error **errp)
921 {
922     int ret;
923     char ct[128];
924     BDRVVmdkState *s = bs->opaque;
925 
926     if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
927         error_setg(errp, "invalid VMDK image descriptor");
928         ret = -EINVAL;
929         goto exit;
930     }
931     if (strcmp(ct, "monolithicFlat") &&
932         strcmp(ct, "vmfs") &&
933         strcmp(ct, "vmfsSparse") &&
934         strcmp(ct, "twoGbMaxExtentSparse") &&
935         strcmp(ct, "twoGbMaxExtentFlat")) {
936         error_setg(errp, "Unsupported image type '%s'", ct);
937         ret = -ENOTSUP;
938         goto exit;
939     }
940     s->create_type = g_strdup(ct);
941     s->desc_offset = 0;
942     ret = vmdk_parse_extents(buf, bs, bs->file->bs->exact_filename, options,
943                              errp);
944 exit:
945     return ret;
946 }
947 
948 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
949                      Error **errp)
950 {
951     char *buf;
952     int ret;
953     BDRVVmdkState *s = bs->opaque;
954     uint32_t magic;
955     Error *local_err = NULL;
956 
957     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
958                                false, errp);
959     if (!bs->file) {
960         return -EINVAL;
961     }
962 
963     buf = vmdk_read_desc(bs->file, 0, errp);
964     if (!buf) {
965         return -EINVAL;
966     }
967 
968     magic = ldl_be_p(buf);
969     switch (magic) {
970         case VMDK3_MAGIC:
971         case VMDK4_MAGIC:
972             ret = vmdk_open_sparse(bs, bs->file, flags, buf, options,
973                                    errp);
974             s->desc_offset = 0x200;
975             break;
976         default:
977             ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
978             break;
979     }
980     if (ret) {
981         goto fail;
982     }
983 
984     /* try to open parent images, if exist */
985     ret = vmdk_parent_open(bs);
986     if (ret) {
987         goto fail;
988     }
989     ret = vmdk_read_cid(bs, 0, &s->cid);
990     if (ret) {
991         goto fail;
992     }
993     ret = vmdk_read_cid(bs, 1, &s->parent_cid);
994     if (ret) {
995         goto fail;
996     }
997     qemu_co_mutex_init(&s->lock);
998 
999     /* Disable migration when VMDK images are used */
1000     error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "
1001                "does not support live migration",
1002                bdrv_get_device_or_node_name(bs));
1003     ret = migrate_add_blocker(s->migration_blocker, &local_err);
1004     if (local_err) {
1005         error_propagate(errp, local_err);
1006         error_free(s->migration_blocker);
1007         goto fail;
1008     }
1009 
1010     g_free(buf);
1011     return 0;
1012 
1013 fail:
1014     g_free(buf);
1015     g_free(s->create_type);
1016     s->create_type = NULL;
1017     vmdk_free_extents(bs);
1018     return ret;
1019 }
1020 
1021 
1022 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
1023 {
1024     BDRVVmdkState *s = bs->opaque;
1025     int i;
1026 
1027     for (i = 0; i < s->num_extents; i++) {
1028         if (!s->extents[i].flat) {
1029             bs->bl.pwrite_zeroes_alignment =
1030                 MAX(bs->bl.pwrite_zeroes_alignment,
1031                     s->extents[i].cluster_sectors << BDRV_SECTOR_BITS);
1032         }
1033     }
1034 }
1035 
1036 /**
1037  * get_whole_cluster
1038  *
1039  * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1040  * to the cluster at @cluster_sector_num.
1041  *
1042  * If @skip_start_sector < @skip_end_sector, the relative range
1043  * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1044  * it for call to write user data in the request.
1045  */
1046 static int get_whole_cluster(BlockDriverState *bs,
1047                              VmdkExtent *extent,
1048                              uint64_t cluster_offset,
1049                              uint64_t offset,
1050                              uint64_t skip_start_bytes,
1051                              uint64_t skip_end_bytes)
1052 {
1053     int ret = VMDK_OK;
1054     int64_t cluster_bytes;
1055     uint8_t *whole_grain;
1056 
1057     /* For COW, align request sector_num to cluster start */
1058     cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
1059     offset = QEMU_ALIGN_DOWN(offset, cluster_bytes);
1060     whole_grain = qemu_blockalign(bs, cluster_bytes);
1061 
1062     if (!bs->backing) {
1063         memset(whole_grain, 0, skip_start_bytes);
1064         memset(whole_grain + skip_end_bytes, 0, cluster_bytes - skip_end_bytes);
1065     }
1066 
1067     assert(skip_end_bytes <= cluster_bytes);
1068     /* we will be here if it's first write on non-exist grain(cluster).
1069      * try to read from parent image, if exist */
1070     if (bs->backing && !vmdk_is_cid_valid(bs)) {
1071         ret = VMDK_ERROR;
1072         goto exit;
1073     }
1074 
1075     /* Read backing data before skip range */
1076     if (skip_start_bytes > 0) {
1077         if (bs->backing) {
1078             /* qcow2 emits this on bs->file instead of bs->backing */
1079             BLKDBG_EVENT(extent->file, BLKDBG_COW_READ);
1080             ret = bdrv_pread(bs->backing, offset, whole_grain,
1081                              skip_start_bytes);
1082             if (ret < 0) {
1083                 ret = VMDK_ERROR;
1084                 goto exit;
1085             }
1086         }
1087         BLKDBG_EVENT(extent->file, BLKDBG_COW_WRITE);
1088         ret = bdrv_pwrite(extent->file, cluster_offset, whole_grain,
1089                           skip_start_bytes);
1090         if (ret < 0) {
1091             ret = VMDK_ERROR;
1092             goto exit;
1093         }
1094     }
1095     /* Read backing data after skip range */
1096     if (skip_end_bytes < cluster_bytes) {
1097         if (bs->backing) {
1098             /* qcow2 emits this on bs->file instead of bs->backing */
1099             BLKDBG_EVENT(extent->file, BLKDBG_COW_READ);
1100             ret = bdrv_pread(bs->backing, offset + skip_end_bytes,
1101                              whole_grain + skip_end_bytes,
1102                              cluster_bytes - skip_end_bytes);
1103             if (ret < 0) {
1104                 ret = VMDK_ERROR;
1105                 goto exit;
1106             }
1107         }
1108         BLKDBG_EVENT(extent->file, BLKDBG_COW_WRITE);
1109         ret = bdrv_pwrite(extent->file, cluster_offset + skip_end_bytes,
1110                           whole_grain + skip_end_bytes,
1111                           cluster_bytes - skip_end_bytes);
1112         if (ret < 0) {
1113             ret = VMDK_ERROR;
1114             goto exit;
1115         }
1116     }
1117 
1118     ret = VMDK_OK;
1119 exit:
1120     qemu_vfree(whole_grain);
1121     return ret;
1122 }
1123 
1124 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1125                          uint32_t offset)
1126 {
1127     offset = cpu_to_le32(offset);
1128     /* update L2 table */
1129     BLKDBG_EVENT(extent->file, BLKDBG_L2_UPDATE);
1130     if (bdrv_pwrite_sync(extent->file,
1131                 ((int64_t)m_data->l2_offset * 512)
1132                     + (m_data->l2_index * sizeof(offset)),
1133                 &offset, sizeof(offset)) < 0) {
1134         return VMDK_ERROR;
1135     }
1136     /* update backup L2 table */
1137     if (extent->l1_backup_table_offset != 0) {
1138         m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1139         if (bdrv_pwrite_sync(extent->file,
1140                     ((int64_t)m_data->l2_offset * 512)
1141                         + (m_data->l2_index * sizeof(offset)),
1142                     &offset, sizeof(offset)) < 0) {
1143             return VMDK_ERROR;
1144         }
1145     }
1146     if (m_data->l2_cache_entry) {
1147         *m_data->l2_cache_entry = offset;
1148     }
1149 
1150     return VMDK_OK;
1151 }
1152 
1153 /**
1154  * get_cluster_offset
1155  *
1156  * Look up cluster offset in extent file by sector number, and store in
1157  * @cluster_offset.
1158  *
1159  * For flat extents, the start offset as parsed from the description file is
1160  * returned.
1161  *
1162  * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1163  * offset for a new cluster and update L2 cache. If there is a backing file,
1164  * COW is done before returning; otherwise, zeroes are written to the allocated
1165  * cluster. Both COW and zero writing skips the sector range
1166  * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1167  * has new data to write there.
1168  *
1169  * Returns: VMDK_OK if cluster exists and mapped in the image.
1170  *          VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1171  *          VMDK_ERROR if failed.
1172  */
1173 static int get_cluster_offset(BlockDriverState *bs,
1174                               VmdkExtent *extent,
1175                               VmdkMetaData *m_data,
1176                               uint64_t offset,
1177                               bool allocate,
1178                               uint64_t *cluster_offset,
1179                               uint64_t skip_start_bytes,
1180                               uint64_t skip_end_bytes)
1181 {
1182     unsigned int l1_index, l2_offset, l2_index;
1183     int min_index, i, j;
1184     uint32_t min_count, *l2_table;
1185     bool zeroed = false;
1186     int64_t ret;
1187     int64_t cluster_sector;
1188 
1189     if (m_data) {
1190         m_data->valid = 0;
1191     }
1192     if (extent->flat) {
1193         *cluster_offset = extent->flat_start_offset;
1194         return VMDK_OK;
1195     }
1196 
1197     offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1198     l1_index = (offset >> 9) / extent->l1_entry_sectors;
1199     if (l1_index >= extent->l1_size) {
1200         return VMDK_ERROR;
1201     }
1202     l2_offset = extent->l1_table[l1_index];
1203     if (!l2_offset) {
1204         return VMDK_UNALLOC;
1205     }
1206     for (i = 0; i < L2_CACHE_SIZE; i++) {
1207         if (l2_offset == extent->l2_cache_offsets[i]) {
1208             /* increment the hit count */
1209             if (++extent->l2_cache_counts[i] == 0xffffffff) {
1210                 for (j = 0; j < L2_CACHE_SIZE; j++) {
1211                     extent->l2_cache_counts[j] >>= 1;
1212                 }
1213             }
1214             l2_table = extent->l2_cache + (i * extent->l2_size);
1215             goto found;
1216         }
1217     }
1218     /* not found: load a new entry in the least used one */
1219     min_index = 0;
1220     min_count = 0xffffffff;
1221     for (i = 0; i < L2_CACHE_SIZE; i++) {
1222         if (extent->l2_cache_counts[i] < min_count) {
1223             min_count = extent->l2_cache_counts[i];
1224             min_index = i;
1225         }
1226     }
1227     l2_table = extent->l2_cache + (min_index * extent->l2_size);
1228     BLKDBG_EVENT(extent->file, BLKDBG_L2_LOAD);
1229     if (bdrv_pread(extent->file,
1230                 (int64_t)l2_offset * 512,
1231                 l2_table,
1232                 extent->l2_size * sizeof(uint32_t)
1233             ) != extent->l2_size * sizeof(uint32_t)) {
1234         return VMDK_ERROR;
1235     }
1236 
1237     extent->l2_cache_offsets[min_index] = l2_offset;
1238     extent->l2_cache_counts[min_index] = 1;
1239  found:
1240     l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1241     cluster_sector = le32_to_cpu(l2_table[l2_index]);
1242 
1243     if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1244         zeroed = true;
1245     }
1246 
1247     if (!cluster_sector || zeroed) {
1248         if (!allocate) {
1249             return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1250         }
1251 
1252         cluster_sector = extent->next_cluster_sector;
1253         extent->next_cluster_sector += extent->cluster_sectors;
1254 
1255         /* First of all we write grain itself, to avoid race condition
1256          * that may to corrupt the image.
1257          * This problem may occur because of insufficient space on host disk
1258          * or inappropriate VM shutdown.
1259          */
1260         ret = get_whole_cluster(bs, extent, cluster_sector * BDRV_SECTOR_SIZE,
1261                                 offset, skip_start_bytes, skip_end_bytes);
1262         if (ret) {
1263             return ret;
1264         }
1265         if (m_data) {
1266             m_data->valid = 1;
1267             m_data->l1_index = l1_index;
1268             m_data->l2_index = l2_index;
1269             m_data->l2_offset = l2_offset;
1270             m_data->l2_cache_entry = &l2_table[l2_index];
1271         }
1272     }
1273     *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1274     return VMDK_OK;
1275 }
1276 
1277 static VmdkExtent *find_extent(BDRVVmdkState *s,
1278                                 int64_t sector_num, VmdkExtent *start_hint)
1279 {
1280     VmdkExtent *extent = start_hint;
1281 
1282     if (!extent) {
1283         extent = &s->extents[0];
1284     }
1285     while (extent < &s->extents[s->num_extents]) {
1286         if (sector_num < extent->end_sector) {
1287             return extent;
1288         }
1289         extent++;
1290     }
1291     return NULL;
1292 }
1293 
1294 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent *extent,
1295                                                    int64_t offset)
1296 {
1297     uint64_t extent_begin_offset, extent_relative_offset;
1298     uint64_t cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1299 
1300     extent_begin_offset =
1301         (extent->end_sector - extent->sectors) * BDRV_SECTOR_SIZE;
1302     extent_relative_offset = offset - extent_begin_offset;
1303     return extent_relative_offset % cluster_size;
1304 }
1305 
1306 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent *extent,
1307                                                   int64_t sector_num)
1308 {
1309     uint64_t offset;
1310     offset = vmdk_find_offset_in_cluster(extent, sector_num * BDRV_SECTOR_SIZE);
1311     return offset / BDRV_SECTOR_SIZE;
1312 }
1313 
1314 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1315         int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1316 {
1317     BDRVVmdkState *s = bs->opaque;
1318     int64_t index_in_cluster, n, ret;
1319     uint64_t offset;
1320     VmdkExtent *extent;
1321 
1322     extent = find_extent(s, sector_num, NULL);
1323     if (!extent) {
1324         return 0;
1325     }
1326     qemu_co_mutex_lock(&s->lock);
1327     ret = get_cluster_offset(bs, extent, NULL,
1328                              sector_num * 512, false, &offset,
1329                              0, 0);
1330     qemu_co_mutex_unlock(&s->lock);
1331 
1332     index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1333     switch (ret) {
1334     case VMDK_ERROR:
1335         ret = -EIO;
1336         break;
1337     case VMDK_UNALLOC:
1338         ret = 0;
1339         break;
1340     case VMDK_ZEROED:
1341         ret = BDRV_BLOCK_ZERO;
1342         break;
1343     case VMDK_OK:
1344         ret = BDRV_BLOCK_DATA;
1345         if (!extent->compressed) {
1346             ret |= BDRV_BLOCK_OFFSET_VALID;
1347             ret |= (offset + (index_in_cluster << BDRV_SECTOR_BITS))
1348                     & BDRV_BLOCK_OFFSET_MASK;
1349         }
1350         *file = extent->file->bs;
1351         break;
1352     }
1353 
1354     n = extent->cluster_sectors - index_in_cluster;
1355     if (n > nb_sectors) {
1356         n = nb_sectors;
1357     }
1358     *pnum = n;
1359     return ret;
1360 }
1361 
1362 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1363                             int64_t offset_in_cluster, QEMUIOVector *qiov,
1364                             uint64_t qiov_offset, uint64_t n_bytes,
1365                             uint64_t offset)
1366 {
1367     int ret;
1368     VmdkGrainMarker *data = NULL;
1369     uLongf buf_len;
1370     QEMUIOVector local_qiov;
1371     struct iovec iov;
1372     int64_t write_offset;
1373     int64_t write_end_sector;
1374 
1375     if (extent->compressed) {
1376         void *compressed_data;
1377 
1378         if (!extent->has_marker) {
1379             ret = -EINVAL;
1380             goto out;
1381         }
1382         buf_len = (extent->cluster_sectors << 9) * 2;
1383         data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1384 
1385         compressed_data = g_malloc(n_bytes);
1386         qemu_iovec_to_buf(qiov, qiov_offset, compressed_data, n_bytes);
1387         ret = compress(data->data, &buf_len, compressed_data, n_bytes);
1388         g_free(compressed_data);
1389 
1390         if (ret != Z_OK || buf_len == 0) {
1391             ret = -EINVAL;
1392             goto out;
1393         }
1394 
1395         data->lba = cpu_to_le64(offset >> BDRV_SECTOR_BITS);
1396         data->size = cpu_to_le32(buf_len);
1397 
1398         n_bytes = buf_len + sizeof(VmdkGrainMarker);
1399         iov = (struct iovec) {
1400             .iov_base   = data,
1401             .iov_len    = n_bytes,
1402         };
1403         qemu_iovec_init_external(&local_qiov, &iov, 1);
1404 
1405         BLKDBG_EVENT(extent->file, BLKDBG_WRITE_COMPRESSED);
1406     } else {
1407         qemu_iovec_init(&local_qiov, qiov->niov);
1408         qemu_iovec_concat(&local_qiov, qiov, qiov_offset, n_bytes);
1409 
1410         BLKDBG_EVENT(extent->file, BLKDBG_WRITE_AIO);
1411     }
1412 
1413     write_offset = cluster_offset + offset_in_cluster;
1414     ret = bdrv_co_pwritev(extent->file, write_offset, n_bytes,
1415                           &local_qiov, 0);
1416 
1417     write_end_sector = DIV_ROUND_UP(write_offset + n_bytes, BDRV_SECTOR_SIZE);
1418 
1419     if (extent->compressed) {
1420         extent->next_cluster_sector = write_end_sector;
1421     } else {
1422         extent->next_cluster_sector = MAX(extent->next_cluster_sector,
1423                                           write_end_sector);
1424     }
1425 
1426     if (ret < 0) {
1427         goto out;
1428     }
1429     ret = 0;
1430  out:
1431     g_free(data);
1432     if (!extent->compressed) {
1433         qemu_iovec_destroy(&local_qiov);
1434     }
1435     return ret;
1436 }
1437 
1438 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1439                             int64_t offset_in_cluster, QEMUIOVector *qiov,
1440                             int bytes)
1441 {
1442     int ret;
1443     int cluster_bytes, buf_bytes;
1444     uint8_t *cluster_buf, *compressed_data;
1445     uint8_t *uncomp_buf;
1446     uint32_t data_len;
1447     VmdkGrainMarker *marker;
1448     uLongf buf_len;
1449 
1450 
1451     if (!extent->compressed) {
1452         BLKDBG_EVENT(extent->file, BLKDBG_READ_AIO);
1453         ret = bdrv_co_preadv(extent->file,
1454                              cluster_offset + offset_in_cluster, bytes,
1455                              qiov, 0);
1456         if (ret < 0) {
1457             return ret;
1458         }
1459         return 0;
1460     }
1461     cluster_bytes = extent->cluster_sectors * 512;
1462     /* Read two clusters in case GrainMarker + compressed data > one cluster */
1463     buf_bytes = cluster_bytes * 2;
1464     cluster_buf = g_malloc(buf_bytes);
1465     uncomp_buf = g_malloc(cluster_bytes);
1466     BLKDBG_EVENT(extent->file, BLKDBG_READ_COMPRESSED);
1467     ret = bdrv_pread(extent->file,
1468                 cluster_offset,
1469                 cluster_buf, buf_bytes);
1470     if (ret < 0) {
1471         goto out;
1472     }
1473     compressed_data = cluster_buf;
1474     buf_len = cluster_bytes;
1475     data_len = cluster_bytes;
1476     if (extent->has_marker) {
1477         marker = (VmdkGrainMarker *)cluster_buf;
1478         compressed_data = marker->data;
1479         data_len = le32_to_cpu(marker->size);
1480     }
1481     if (!data_len || data_len > buf_bytes) {
1482         ret = -EINVAL;
1483         goto out;
1484     }
1485     ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1486     if (ret != Z_OK) {
1487         ret = -EINVAL;
1488         goto out;
1489 
1490     }
1491     if (offset_in_cluster < 0 ||
1492             offset_in_cluster + bytes > buf_len) {
1493         ret = -EINVAL;
1494         goto out;
1495     }
1496     qemu_iovec_from_buf(qiov, 0, uncomp_buf + offset_in_cluster, bytes);
1497     ret = 0;
1498 
1499  out:
1500     g_free(uncomp_buf);
1501     g_free(cluster_buf);
1502     return ret;
1503 }
1504 
1505 static int coroutine_fn
1506 vmdk_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1507                QEMUIOVector *qiov, int flags)
1508 {
1509     BDRVVmdkState *s = bs->opaque;
1510     int ret;
1511     uint64_t n_bytes, offset_in_cluster;
1512     VmdkExtent *extent = NULL;
1513     QEMUIOVector local_qiov;
1514     uint64_t cluster_offset;
1515     uint64_t bytes_done = 0;
1516 
1517     qemu_iovec_init(&local_qiov, qiov->niov);
1518     qemu_co_mutex_lock(&s->lock);
1519 
1520     while (bytes > 0) {
1521         extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1522         if (!extent) {
1523             ret = -EIO;
1524             goto fail;
1525         }
1526         ret = get_cluster_offset(bs, extent, NULL,
1527                                  offset, false, &cluster_offset, 0, 0);
1528         offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1529 
1530         n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1531                              - offset_in_cluster);
1532 
1533         if (ret != VMDK_OK) {
1534             /* if not allocated, try to read from parent image, if exist */
1535             if (bs->backing && ret != VMDK_ZEROED) {
1536                 if (!vmdk_is_cid_valid(bs)) {
1537                     ret = -EINVAL;
1538                     goto fail;
1539                 }
1540 
1541                 qemu_iovec_reset(&local_qiov);
1542                 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1543 
1544                 /* qcow2 emits this on bs->file instead of bs->backing */
1545                 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1546                 ret = bdrv_co_preadv(bs->backing, offset, n_bytes,
1547                                      &local_qiov, 0);
1548                 if (ret < 0) {
1549                     goto fail;
1550                 }
1551             } else {
1552                 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
1553             }
1554         } else {
1555             qemu_iovec_reset(&local_qiov);
1556             qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
1557 
1558             ret = vmdk_read_extent(extent, cluster_offset, offset_in_cluster,
1559                                    &local_qiov, n_bytes);
1560             if (ret) {
1561                 goto fail;
1562             }
1563         }
1564         bytes -= n_bytes;
1565         offset += n_bytes;
1566         bytes_done += n_bytes;
1567     }
1568 
1569     ret = 0;
1570 fail:
1571     qemu_co_mutex_unlock(&s->lock);
1572     qemu_iovec_destroy(&local_qiov);
1573 
1574     return ret;
1575 }
1576 
1577 /**
1578  * vmdk_write:
1579  * @zeroed:       buf is ignored (data is zero), use zeroed_grain GTE feature
1580  *                if possible, otherwise return -ENOTSUP.
1581  * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1582  *                with each cluster. By dry run we can find if the zero write
1583  *                is possible without modifying image data.
1584  *
1585  * Returns: error code with 0 for success.
1586  */
1587 static int vmdk_pwritev(BlockDriverState *bs, uint64_t offset,
1588                        uint64_t bytes, QEMUIOVector *qiov,
1589                        bool zeroed, bool zero_dry_run)
1590 {
1591     BDRVVmdkState *s = bs->opaque;
1592     VmdkExtent *extent = NULL;
1593     int ret;
1594     int64_t offset_in_cluster, n_bytes;
1595     uint64_t cluster_offset;
1596     uint64_t bytes_done = 0;
1597     VmdkMetaData m_data;
1598 
1599     if (DIV_ROUND_UP(offset, BDRV_SECTOR_SIZE) > bs->total_sectors) {
1600         error_report("Wrong offset: offset=0x%" PRIx64
1601                      " total_sectors=0x%" PRIx64,
1602                      offset, bs->total_sectors);
1603         return -EIO;
1604     }
1605 
1606     while (bytes > 0) {
1607         extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent);
1608         if (!extent) {
1609             return -EIO;
1610         }
1611         offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset);
1612         n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE
1613                              - offset_in_cluster);
1614 
1615         ret = get_cluster_offset(bs, extent, &m_data, offset,
1616                                  !(extent->compressed || zeroed),
1617                                  &cluster_offset, offset_in_cluster,
1618                                  offset_in_cluster + n_bytes);
1619         if (extent->compressed) {
1620             if (ret == VMDK_OK) {
1621                 /* Refuse write to allocated cluster for streamOptimized */
1622                 error_report("Could not write to allocated cluster"
1623                               " for streamOptimized");
1624                 return -EIO;
1625             } else {
1626                 /* allocate */
1627                 ret = get_cluster_offset(bs, extent, &m_data, offset,
1628                                          true, &cluster_offset, 0, 0);
1629             }
1630         }
1631         if (ret == VMDK_ERROR) {
1632             return -EINVAL;
1633         }
1634         if (zeroed) {
1635             /* Do zeroed write, buf is ignored */
1636             if (extent->has_zero_grain &&
1637                     offset_in_cluster == 0 &&
1638                     n_bytes >= extent->cluster_sectors * BDRV_SECTOR_SIZE) {
1639                 n_bytes = extent->cluster_sectors * BDRV_SECTOR_SIZE;
1640                 if (!zero_dry_run) {
1641                     /* update L2 tables */
1642                     if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1643                             != VMDK_OK) {
1644                         return -EIO;
1645                     }
1646                 }
1647             } else {
1648                 return -ENOTSUP;
1649             }
1650         } else {
1651             ret = vmdk_write_extent(extent, cluster_offset, offset_in_cluster,
1652                                     qiov, bytes_done, n_bytes, offset);
1653             if (ret) {
1654                 return ret;
1655             }
1656             if (m_data.valid) {
1657                 /* update L2 tables */
1658                 if (vmdk_L2update(extent, &m_data,
1659                                   cluster_offset >> BDRV_SECTOR_BITS)
1660                         != VMDK_OK) {
1661                     return -EIO;
1662                 }
1663             }
1664         }
1665         bytes -= n_bytes;
1666         offset += n_bytes;
1667         bytes_done += n_bytes;
1668 
1669         /* update CID on the first write every time the virtual disk is
1670          * opened */
1671         if (!s->cid_updated) {
1672             ret = vmdk_write_cid(bs, g_random_int());
1673             if (ret < 0) {
1674                 return ret;
1675             }
1676             s->cid_updated = true;
1677         }
1678     }
1679     return 0;
1680 }
1681 
1682 static int coroutine_fn
1683 vmdk_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1684                 QEMUIOVector *qiov, int flags)
1685 {
1686     int ret;
1687     BDRVVmdkState *s = bs->opaque;
1688     qemu_co_mutex_lock(&s->lock);
1689     ret = vmdk_pwritev(bs, offset, bytes, qiov, false, false);
1690     qemu_co_mutex_unlock(&s->lock);
1691     return ret;
1692 }
1693 
1694 static int coroutine_fn
1695 vmdk_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1696                            uint64_t bytes, QEMUIOVector *qiov)
1697 {
1698     return vmdk_co_pwritev(bs, offset, bytes, qiov, 0);
1699 }
1700 
1701 static int coroutine_fn vmdk_co_pwrite_zeroes(BlockDriverState *bs,
1702                                               int64_t offset,
1703                                               int bytes,
1704                                               BdrvRequestFlags flags)
1705 {
1706     int ret;
1707     BDRVVmdkState *s = bs->opaque;
1708 
1709     qemu_co_mutex_lock(&s->lock);
1710     /* write zeroes could fail if sectors not aligned to cluster, test it with
1711      * dry_run == true before really updating image */
1712     ret = vmdk_pwritev(bs, offset, bytes, NULL, true, true);
1713     if (!ret) {
1714         ret = vmdk_pwritev(bs, offset, bytes, NULL, true, false);
1715     }
1716     qemu_co_mutex_unlock(&s->lock);
1717     return ret;
1718 }
1719 
1720 static int vmdk_create_extent(const char *filename, int64_t filesize,
1721                               bool flat, bool compress, bool zeroed_grain,
1722                               QemuOpts *opts, Error **errp)
1723 {
1724     int ret, i;
1725     BlockBackend *blk = NULL;
1726     VMDK4Header header;
1727     Error *local_err = NULL;
1728     uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1729     uint32_t *gd_buf = NULL;
1730     int gd_buf_size;
1731 
1732     ret = bdrv_create_file(filename, opts, &local_err);
1733     if (ret < 0) {
1734         error_propagate(errp, local_err);
1735         goto exit;
1736     }
1737 
1738     blk = blk_new_open(filename, NULL, NULL,
1739                        BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
1740                        &local_err);
1741     if (blk == NULL) {
1742         error_propagate(errp, local_err);
1743         ret = -EIO;
1744         goto exit;
1745     }
1746 
1747     blk_set_allow_write_beyond_eof(blk, true);
1748 
1749     if (flat) {
1750         ret = blk_truncate(blk, filesize, PREALLOC_MODE_OFF, errp);
1751         goto exit;
1752     }
1753     magic = cpu_to_be32(VMDK4_MAGIC);
1754     memset(&header, 0, sizeof(header));
1755     if (compress) {
1756         header.version = 3;
1757     } else if (zeroed_grain) {
1758         header.version = 2;
1759     } else {
1760         header.version = 1;
1761     }
1762     header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1763                    | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1764                    | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1765     header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1766     header.capacity = filesize / BDRV_SECTOR_SIZE;
1767     header.granularity = 128;
1768     header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1769 
1770     grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1771     gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1772                            BDRV_SECTOR_SIZE);
1773     gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1774     gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1775 
1776     header.desc_offset = 1;
1777     header.desc_size = 20;
1778     header.rgd_offset = header.desc_offset + header.desc_size;
1779     header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1780     header.grain_offset =
1781         ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1782                  header.granularity);
1783     /* swap endianness for all header fields */
1784     header.version = cpu_to_le32(header.version);
1785     header.flags = cpu_to_le32(header.flags);
1786     header.capacity = cpu_to_le64(header.capacity);
1787     header.granularity = cpu_to_le64(header.granularity);
1788     header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1789     header.desc_offset = cpu_to_le64(header.desc_offset);
1790     header.desc_size = cpu_to_le64(header.desc_size);
1791     header.rgd_offset = cpu_to_le64(header.rgd_offset);
1792     header.gd_offset = cpu_to_le64(header.gd_offset);
1793     header.grain_offset = cpu_to_le64(header.grain_offset);
1794     header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1795 
1796     header.check_bytes[0] = 0xa;
1797     header.check_bytes[1] = 0x20;
1798     header.check_bytes[2] = 0xd;
1799     header.check_bytes[3] = 0xa;
1800 
1801     /* write all the data */
1802     ret = blk_pwrite(blk, 0, &magic, sizeof(magic), 0);
1803     if (ret < 0) {
1804         error_setg(errp, QERR_IO_ERROR);
1805         goto exit;
1806     }
1807     ret = blk_pwrite(blk, sizeof(magic), &header, sizeof(header), 0);
1808     if (ret < 0) {
1809         error_setg(errp, QERR_IO_ERROR);
1810         goto exit;
1811     }
1812 
1813     ret = blk_truncate(blk, le64_to_cpu(header.grain_offset) << 9,
1814                        PREALLOC_MODE_OFF, errp);
1815     if (ret < 0) {
1816         goto exit;
1817     }
1818 
1819     /* write grain directory */
1820     gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1821     gd_buf = g_malloc0(gd_buf_size);
1822     for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1823          i < gt_count; i++, tmp += gt_size) {
1824         gd_buf[i] = cpu_to_le32(tmp);
1825     }
1826     ret = blk_pwrite(blk, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1827                      gd_buf, gd_buf_size, 0);
1828     if (ret < 0) {
1829         error_setg(errp, QERR_IO_ERROR);
1830         goto exit;
1831     }
1832 
1833     /* write backup grain directory */
1834     for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1835          i < gt_count; i++, tmp += gt_size) {
1836         gd_buf[i] = cpu_to_le32(tmp);
1837     }
1838     ret = blk_pwrite(blk, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1839                      gd_buf, gd_buf_size, 0);
1840     if (ret < 0) {
1841         error_setg(errp, QERR_IO_ERROR);
1842         goto exit;
1843     }
1844 
1845     ret = 0;
1846 exit:
1847     if (blk) {
1848         blk_unref(blk);
1849     }
1850     g_free(gd_buf);
1851     return ret;
1852 }
1853 
1854 static int filename_decompose(const char *filename, char *path, char *prefix,
1855                               char *postfix, size_t buf_len, Error **errp)
1856 {
1857     const char *p, *q;
1858 
1859     if (filename == NULL || !strlen(filename)) {
1860         error_setg(errp, "No filename provided");
1861         return VMDK_ERROR;
1862     }
1863     p = strrchr(filename, '/');
1864     if (p == NULL) {
1865         p = strrchr(filename, '\\');
1866     }
1867     if (p == NULL) {
1868         p = strrchr(filename, ':');
1869     }
1870     if (p != NULL) {
1871         p++;
1872         if (p - filename >= buf_len) {
1873             return VMDK_ERROR;
1874         }
1875         pstrcpy(path, p - filename + 1, filename);
1876     } else {
1877         p = filename;
1878         path[0] = '\0';
1879     }
1880     q = strrchr(p, '.');
1881     if (q == NULL) {
1882         pstrcpy(prefix, buf_len, p);
1883         postfix[0] = '\0';
1884     } else {
1885         if (q - p >= buf_len) {
1886             return VMDK_ERROR;
1887         }
1888         pstrcpy(prefix, q - p + 1, p);
1889         pstrcpy(postfix, buf_len, q);
1890     }
1891     return VMDK_OK;
1892 }
1893 
1894 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1895 {
1896     int idx = 0;
1897     BlockBackend *new_blk = NULL;
1898     Error *local_err = NULL;
1899     char *desc = NULL;
1900     int64_t total_size = 0, filesize;
1901     char *adapter_type = NULL;
1902     char *backing_file = NULL;
1903     char *hw_version = NULL;
1904     char *fmt = NULL;
1905     int ret = 0;
1906     bool flat, split, compress;
1907     GString *ext_desc_lines;
1908     char *path = g_malloc0(PATH_MAX);
1909     char *prefix = g_malloc0(PATH_MAX);
1910     char *postfix = g_malloc0(PATH_MAX);
1911     char *desc_line = g_malloc0(BUF_SIZE);
1912     char *ext_filename = g_malloc0(PATH_MAX);
1913     char *desc_filename = g_malloc0(PATH_MAX);
1914     const int64_t split_size = 0x80000000;  /* VMDK has constant split size */
1915     const char *desc_extent_line;
1916     char *parent_desc_line = g_malloc0(BUF_SIZE);
1917     uint32_t parent_cid = 0xffffffff;
1918     uint32_t number_heads = 16;
1919     bool zeroed_grain = false;
1920     uint32_t desc_offset = 0, desc_len;
1921     const char desc_template[] =
1922         "# Disk DescriptorFile\n"
1923         "version=1\n"
1924         "CID=%" PRIx32 "\n"
1925         "parentCID=%" PRIx32 "\n"
1926         "createType=\"%s\"\n"
1927         "%s"
1928         "\n"
1929         "# Extent description\n"
1930         "%s"
1931         "\n"
1932         "# The Disk Data Base\n"
1933         "#DDB\n"
1934         "\n"
1935         "ddb.virtualHWVersion = \"%s\"\n"
1936         "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1937         "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1938         "ddb.geometry.sectors = \"63\"\n"
1939         "ddb.adapterType = \"%s\"\n";
1940 
1941     ext_desc_lines = g_string_new(NULL);
1942 
1943     if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1944         ret = -EINVAL;
1945         goto exit;
1946     }
1947     /* Read out options */
1948     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1949                           BDRV_SECTOR_SIZE);
1950     adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1951     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1952     hw_version = qemu_opt_get_del(opts, BLOCK_OPT_HWVERSION);
1953     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1954         if (strcmp(hw_version, "undefined")) {
1955             error_setg(errp,
1956                        "compat6 cannot be enabled with hwversion set");
1957             ret = -EINVAL;
1958             goto exit;
1959         }
1960         g_free(hw_version);
1961         hw_version = g_strdup("6");
1962     }
1963     if (strcmp(hw_version, "undefined") == 0) {
1964         g_free(hw_version);
1965         hw_version = g_strdup("4");
1966     }
1967     fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1968     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1969         zeroed_grain = true;
1970     }
1971 
1972     if (!adapter_type) {
1973         adapter_type = g_strdup("ide");
1974     } else if (strcmp(adapter_type, "ide") &&
1975                strcmp(adapter_type, "buslogic") &&
1976                strcmp(adapter_type, "lsilogic") &&
1977                strcmp(adapter_type, "legacyESX")) {
1978         error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1979         ret = -EINVAL;
1980         goto exit;
1981     }
1982     if (strcmp(adapter_type, "ide") != 0) {
1983         /* that's the number of heads with which vmware operates when
1984            creating, exporting, etc. vmdk files with a non-ide adapter type */
1985         number_heads = 255;
1986     }
1987     if (!fmt) {
1988         /* Default format to monolithicSparse */
1989         fmt = g_strdup("monolithicSparse");
1990     } else if (strcmp(fmt, "monolithicFlat") &&
1991                strcmp(fmt, "monolithicSparse") &&
1992                strcmp(fmt, "twoGbMaxExtentSparse") &&
1993                strcmp(fmt, "twoGbMaxExtentFlat") &&
1994                strcmp(fmt, "streamOptimized")) {
1995         error_setg(errp, "Unknown subformat: '%s'", fmt);
1996         ret = -EINVAL;
1997         goto exit;
1998     }
1999     split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
2000               strcmp(fmt, "twoGbMaxExtentSparse"));
2001     flat = !(strcmp(fmt, "monolithicFlat") &&
2002              strcmp(fmt, "twoGbMaxExtentFlat"));
2003     compress = !strcmp(fmt, "streamOptimized");
2004     if (flat) {
2005         desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
2006     } else {
2007         desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
2008     }
2009     if (flat && backing_file) {
2010         error_setg(errp, "Flat image can't have backing file");
2011         ret = -ENOTSUP;
2012         goto exit;
2013     }
2014     if (flat && zeroed_grain) {
2015         error_setg(errp, "Flat image can't enable zeroed grain");
2016         ret = -ENOTSUP;
2017         goto exit;
2018     }
2019     if (backing_file) {
2020         BlockBackend *blk;
2021         char *full_backing = g_new0(char, PATH_MAX);
2022         bdrv_get_full_backing_filename_from_filename(filename, backing_file,
2023                                                      full_backing, PATH_MAX,
2024                                                      &local_err);
2025         if (local_err) {
2026             g_free(full_backing);
2027             error_propagate(errp, local_err);
2028             ret = -ENOENT;
2029             goto exit;
2030         }
2031 
2032         blk = blk_new_open(full_backing, NULL, NULL,
2033                            BDRV_O_NO_BACKING, errp);
2034         g_free(full_backing);
2035         if (blk == NULL) {
2036             ret = -EIO;
2037             goto exit;
2038         }
2039         if (strcmp(blk_bs(blk)->drv->format_name, "vmdk")) {
2040             blk_unref(blk);
2041             ret = -EINVAL;
2042             goto exit;
2043         }
2044         ret = vmdk_read_cid(blk_bs(blk), 0, &parent_cid);
2045         blk_unref(blk);
2046         if (ret) {
2047             goto exit;
2048         }
2049         snprintf(parent_desc_line, BUF_SIZE,
2050                 "parentFileNameHint=\"%s\"", backing_file);
2051     }
2052 
2053     /* Create extents */
2054     filesize = total_size;
2055     while (filesize > 0) {
2056         int64_t size = filesize;
2057 
2058         if (split && size > split_size) {
2059             size = split_size;
2060         }
2061         if (split) {
2062             snprintf(desc_filename, PATH_MAX, "%s-%c%03d%s",
2063                     prefix, flat ? 'f' : 's', ++idx, postfix);
2064         } else if (flat) {
2065             snprintf(desc_filename, PATH_MAX, "%s-flat%s", prefix, postfix);
2066         } else {
2067             snprintf(desc_filename, PATH_MAX, "%s%s", prefix, postfix);
2068         }
2069         snprintf(ext_filename, PATH_MAX, "%s%s", path, desc_filename);
2070 
2071         if (vmdk_create_extent(ext_filename, size,
2072                                flat, compress, zeroed_grain, opts, errp)) {
2073             ret = -EINVAL;
2074             goto exit;
2075         }
2076         filesize -= size;
2077 
2078         /* Format description line */
2079         snprintf(desc_line, BUF_SIZE,
2080                     desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
2081         g_string_append(ext_desc_lines, desc_line);
2082     }
2083     /* generate descriptor file */
2084     desc = g_strdup_printf(desc_template,
2085                            g_random_int(),
2086                            parent_cid,
2087                            fmt,
2088                            parent_desc_line,
2089                            ext_desc_lines->str,
2090                            hw_version,
2091                            total_size /
2092                                (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
2093                            number_heads,
2094                            adapter_type);
2095     desc_len = strlen(desc);
2096     /* the descriptor offset = 0x200 */
2097     if (!split && !flat) {
2098         desc_offset = 0x200;
2099     } else {
2100         ret = bdrv_create_file(filename, opts, &local_err);
2101         if (ret < 0) {
2102             error_propagate(errp, local_err);
2103             goto exit;
2104         }
2105     }
2106 
2107     new_blk = blk_new_open(filename, NULL, NULL,
2108                            BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
2109                            &local_err);
2110     if (new_blk == NULL) {
2111         error_propagate(errp, local_err);
2112         ret = -EIO;
2113         goto exit;
2114     }
2115 
2116     blk_set_allow_write_beyond_eof(new_blk, true);
2117 
2118     ret = blk_pwrite(new_blk, desc_offset, desc, desc_len, 0);
2119     if (ret < 0) {
2120         error_setg_errno(errp, -ret, "Could not write description");
2121         goto exit;
2122     }
2123     /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2124      * for description file */
2125     if (desc_offset == 0) {
2126         ret = blk_truncate(new_blk, desc_len, PREALLOC_MODE_OFF, errp);
2127     }
2128 exit:
2129     if (new_blk) {
2130         blk_unref(new_blk);
2131     }
2132     g_free(adapter_type);
2133     g_free(backing_file);
2134     g_free(hw_version);
2135     g_free(fmt);
2136     g_free(desc);
2137     g_free(path);
2138     g_free(prefix);
2139     g_free(postfix);
2140     g_free(desc_line);
2141     g_free(ext_filename);
2142     g_free(desc_filename);
2143     g_free(parent_desc_line);
2144     g_string_free(ext_desc_lines, true);
2145     return ret;
2146 }
2147 
2148 static void vmdk_close(BlockDriverState *bs)
2149 {
2150     BDRVVmdkState *s = bs->opaque;
2151 
2152     vmdk_free_extents(bs);
2153     g_free(s->create_type);
2154 
2155     migrate_del_blocker(s->migration_blocker);
2156     error_free(s->migration_blocker);
2157 }
2158 
2159 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
2160 {
2161     BDRVVmdkState *s = bs->opaque;
2162     int i, err;
2163     int ret = 0;
2164 
2165     for (i = 0; i < s->num_extents; i++) {
2166         err = bdrv_co_flush(s->extents[i].file->bs);
2167         if (err < 0) {
2168             ret = err;
2169         }
2170     }
2171     return ret;
2172 }
2173 
2174 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2175 {
2176     int i;
2177     int64_t ret = 0;
2178     int64_t r;
2179     BDRVVmdkState *s = bs->opaque;
2180 
2181     ret = bdrv_get_allocated_file_size(bs->file->bs);
2182     if (ret < 0) {
2183         return ret;
2184     }
2185     for (i = 0; i < s->num_extents; i++) {
2186         if (s->extents[i].file == bs->file) {
2187             continue;
2188         }
2189         r = bdrv_get_allocated_file_size(s->extents[i].file->bs);
2190         if (r < 0) {
2191             return r;
2192         }
2193         ret += r;
2194     }
2195     return ret;
2196 }
2197 
2198 static int vmdk_has_zero_init(BlockDriverState *bs)
2199 {
2200     int i;
2201     BDRVVmdkState *s = bs->opaque;
2202 
2203     /* If has a flat extent and its underlying storage doesn't have zero init,
2204      * return 0. */
2205     for (i = 0; i < s->num_extents; i++) {
2206         if (s->extents[i].flat) {
2207             if (!bdrv_has_zero_init(s->extents[i].file->bs)) {
2208                 return 0;
2209             }
2210         }
2211     }
2212     return 1;
2213 }
2214 
2215 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2216 {
2217     ImageInfo *info = g_new0(ImageInfo, 1);
2218 
2219     *info = (ImageInfo){
2220         .filename         = g_strdup(extent->file->bs->filename),
2221         .format           = g_strdup(extent->type),
2222         .virtual_size     = extent->sectors * BDRV_SECTOR_SIZE,
2223         .compressed       = extent->compressed,
2224         .has_compressed   = extent->compressed,
2225         .cluster_size     = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2226         .has_cluster_size = !extent->flat,
2227     };
2228 
2229     return info;
2230 }
2231 
2232 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2233                       BdrvCheckMode fix)
2234 {
2235     BDRVVmdkState *s = bs->opaque;
2236     VmdkExtent *extent = NULL;
2237     int64_t sector_num = 0;
2238     int64_t total_sectors = bdrv_nb_sectors(bs);
2239     int ret;
2240     uint64_t cluster_offset;
2241 
2242     if (fix) {
2243         return -ENOTSUP;
2244     }
2245 
2246     for (;;) {
2247         if (sector_num >= total_sectors) {
2248             return 0;
2249         }
2250         extent = find_extent(s, sector_num, extent);
2251         if (!extent) {
2252             fprintf(stderr,
2253                     "ERROR: could not find extent for sector %" PRId64 "\n",
2254                     sector_num);
2255             ret = -EINVAL;
2256             break;
2257         }
2258         ret = get_cluster_offset(bs, extent, NULL,
2259                                  sector_num << BDRV_SECTOR_BITS,
2260                                  false, &cluster_offset, 0, 0);
2261         if (ret == VMDK_ERROR) {
2262             fprintf(stderr,
2263                     "ERROR: could not get cluster_offset for sector %"
2264                     PRId64 "\n", sector_num);
2265             break;
2266         }
2267         if (ret == VMDK_OK) {
2268             int64_t extent_len = bdrv_getlength(extent->file->bs);
2269             if (extent_len < 0) {
2270                 fprintf(stderr,
2271                         "ERROR: could not get extent file length for sector %"
2272                         PRId64 "\n", sector_num);
2273                 ret = extent_len;
2274                 break;
2275             }
2276             if (cluster_offset >= extent_len) {
2277                 fprintf(stderr,
2278                         "ERROR: cluster offset for sector %"
2279                         PRId64 " points after EOF\n", sector_num);
2280                 ret = -EINVAL;
2281                 break;
2282             }
2283         }
2284         sector_num += extent->cluster_sectors;
2285     }
2286 
2287     result->corruptions++;
2288     return ret;
2289 }
2290 
2291 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2292 {
2293     int i;
2294     BDRVVmdkState *s = bs->opaque;
2295     ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2296     ImageInfoList **next;
2297 
2298     *spec_info = (ImageInfoSpecific){
2299         .type = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2300         .u = {
2301             .vmdk.data = g_new0(ImageInfoSpecificVmdk, 1),
2302         },
2303     };
2304 
2305     *spec_info->u.vmdk.data = (ImageInfoSpecificVmdk) {
2306         .create_type = g_strdup(s->create_type),
2307         .cid = s->cid,
2308         .parent_cid = s->parent_cid,
2309     };
2310 
2311     next = &spec_info->u.vmdk.data->extents;
2312     for (i = 0; i < s->num_extents; i++) {
2313         *next = g_new0(ImageInfoList, 1);
2314         (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2315         (*next)->next = NULL;
2316         next = &(*next)->next;
2317     }
2318 
2319     return spec_info;
2320 }
2321 
2322 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2323 {
2324     return a->flat == b->flat &&
2325            a->compressed == b->compressed &&
2326            (a->flat || a->cluster_sectors == b->cluster_sectors);
2327 }
2328 
2329 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2330 {
2331     int i;
2332     BDRVVmdkState *s = bs->opaque;
2333     assert(s->num_extents);
2334 
2335     /* See if we have multiple extents but they have different cases */
2336     for (i = 1; i < s->num_extents; i++) {
2337         if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2338             return -ENOTSUP;
2339         }
2340     }
2341     bdi->needs_compressed_writes = s->extents[0].compressed;
2342     if (!s->extents[0].flat) {
2343         bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2344     }
2345     return 0;
2346 }
2347 
2348 static QemuOptsList vmdk_create_opts = {
2349     .name = "vmdk-create-opts",
2350     .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2351     .desc = {
2352         {
2353             .name = BLOCK_OPT_SIZE,
2354             .type = QEMU_OPT_SIZE,
2355             .help = "Virtual disk size"
2356         },
2357         {
2358             .name = BLOCK_OPT_ADAPTER_TYPE,
2359             .type = QEMU_OPT_STRING,
2360             .help = "Virtual adapter type, can be one of "
2361                     "ide (default), lsilogic, buslogic or legacyESX"
2362         },
2363         {
2364             .name = BLOCK_OPT_BACKING_FILE,
2365             .type = QEMU_OPT_STRING,
2366             .help = "File name of a base image"
2367         },
2368         {
2369             .name = BLOCK_OPT_COMPAT6,
2370             .type = QEMU_OPT_BOOL,
2371             .help = "VMDK version 6 image",
2372             .def_value_str = "off"
2373         },
2374         {
2375             .name = BLOCK_OPT_HWVERSION,
2376             .type = QEMU_OPT_STRING,
2377             .help = "VMDK hardware version",
2378             .def_value_str = "undefined"
2379         },
2380         {
2381             .name = BLOCK_OPT_SUBFMT,
2382             .type = QEMU_OPT_STRING,
2383             .help =
2384                 "VMDK flat extent format, can be one of "
2385                 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2386         },
2387         {
2388             .name = BLOCK_OPT_ZEROED_GRAIN,
2389             .type = QEMU_OPT_BOOL,
2390             .help = "Enable efficient zero writes "
2391                     "using the zeroed-grain GTE feature"
2392         },
2393         { /* end of list */ }
2394     }
2395 };
2396 
2397 static BlockDriver bdrv_vmdk = {
2398     .format_name                  = "vmdk",
2399     .instance_size                = sizeof(BDRVVmdkState),
2400     .bdrv_probe                   = vmdk_probe,
2401     .bdrv_open                    = vmdk_open,
2402     .bdrv_check                   = vmdk_check,
2403     .bdrv_reopen_prepare          = vmdk_reopen_prepare,
2404     .bdrv_child_perm              = bdrv_format_default_perms,
2405     .bdrv_co_preadv               = vmdk_co_preadv,
2406     .bdrv_co_pwritev              = vmdk_co_pwritev,
2407     .bdrv_co_pwritev_compressed   = vmdk_co_pwritev_compressed,
2408     .bdrv_co_pwrite_zeroes        = vmdk_co_pwrite_zeroes,
2409     .bdrv_close                   = vmdk_close,
2410     .bdrv_create                  = vmdk_create,
2411     .bdrv_co_flush_to_disk        = vmdk_co_flush,
2412     .bdrv_co_get_block_status     = vmdk_co_get_block_status,
2413     .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2414     .bdrv_has_zero_init           = vmdk_has_zero_init,
2415     .bdrv_get_specific_info       = vmdk_get_specific_info,
2416     .bdrv_refresh_limits          = vmdk_refresh_limits,
2417     .bdrv_get_info                = vmdk_get_info,
2418 
2419     .supports_backing             = true,
2420     .create_opts                  = &vmdk_create_opts,
2421 };
2422 
2423 static void bdrv_vmdk_init(void)
2424 {
2425     bdrv_register(&bdrv_vmdk);
2426 }
2427 
2428 block_init(bdrv_vmdk_init);
2429