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