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