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