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