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