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