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