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