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