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