xref: /openbmc/qemu/block/vmdk.c (revision 56c4bfb3)
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 
32 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
33 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
34 #define VMDK4_COMPRESSION_DEFLATE 1
35 #define VMDK4_FLAG_NL_DETECT (1 << 0)
36 #define VMDK4_FLAG_RGD (1 << 1)
37 /* Zeroed-grain enable bit */
38 #define VMDK4_FLAG_ZERO_GRAIN   (1 << 2)
39 #define VMDK4_FLAG_COMPRESS (1 << 16)
40 #define VMDK4_FLAG_MARKER (1 << 17)
41 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
42 
43 #define VMDK_GTE_ZEROED 0x1
44 
45 /* VMDK internal error codes */
46 #define VMDK_OK      0
47 #define VMDK_ERROR   (-1)
48 /* Cluster not allocated */
49 #define VMDK_UNALLOC (-2)
50 #define VMDK_ZEROED  (-3)
51 
52 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
53 
54 typedef struct {
55     uint32_t version;
56     uint32_t flags;
57     uint32_t disk_sectors;
58     uint32_t granularity;
59     uint32_t l1dir_offset;
60     uint32_t l1dir_size;
61     uint32_t file_sectors;
62     uint32_t cylinders;
63     uint32_t heads;
64     uint32_t sectors_per_track;
65 } QEMU_PACKED VMDK3Header;
66 
67 typedef struct {
68     uint32_t version;
69     uint32_t flags;
70     uint64_t capacity;
71     uint64_t granularity;
72     uint64_t desc_offset;
73     uint64_t desc_size;
74     /* Number of GrainTableEntries per GrainTable */
75     uint32_t num_gtes_per_gt;
76     uint64_t rgd_offset;
77     uint64_t gd_offset;
78     uint64_t grain_offset;
79     char filler[1];
80     char check_bytes[4];
81     uint16_t compressAlgorithm;
82 } QEMU_PACKED VMDK4Header;
83 
84 #define L2_CACHE_SIZE 16
85 
86 typedef struct VmdkExtent {
87     BlockDriverState *file;
88     bool flat;
89     bool compressed;
90     bool has_marker;
91     bool has_zero_grain;
92     int version;
93     int64_t sectors;
94     int64_t end_sector;
95     int64_t flat_start_offset;
96     int64_t l1_table_offset;
97     int64_t l1_backup_table_offset;
98     uint32_t *l1_table;
99     uint32_t *l1_backup_table;
100     unsigned int l1_size;
101     uint32_t l1_entry_sectors;
102 
103     unsigned int l2_size;
104     uint32_t *l2_cache;
105     uint32_t l2_cache_offsets[L2_CACHE_SIZE];
106     uint32_t l2_cache_counts[L2_CACHE_SIZE];
107 
108     unsigned int cluster_sectors;
109 } VmdkExtent;
110 
111 typedef struct BDRVVmdkState {
112     CoMutex lock;
113     uint64_t desc_offset;
114     bool cid_updated;
115     uint32_t parent_cid;
116     int num_extents;
117     /* Extent array with num_extents entries, ascend ordered by address */
118     VmdkExtent *extents;
119     Error *migration_blocker;
120 } BDRVVmdkState;
121 
122 typedef struct VmdkMetaData {
123     uint32_t offset;
124     unsigned int l1_index;
125     unsigned int l2_index;
126     unsigned int l2_offset;
127     int valid;
128     uint32_t *l2_cache_entry;
129 } VmdkMetaData;
130 
131 typedef struct VmdkGrainMarker {
132     uint64_t lba;
133     uint32_t size;
134     uint8_t  data[0];
135 } QEMU_PACKED VmdkGrainMarker;
136 
137 enum {
138     MARKER_END_OF_STREAM    = 0,
139     MARKER_GRAIN_TABLE      = 1,
140     MARKER_GRAIN_DIRECTORY  = 2,
141     MARKER_FOOTER           = 3,
142 };
143 
144 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
145 {
146     uint32_t magic;
147 
148     if (buf_size < 4) {
149         return 0;
150     }
151     magic = be32_to_cpu(*(uint32_t *)buf);
152     if (magic == VMDK3_MAGIC ||
153         magic == VMDK4_MAGIC) {
154         return 100;
155     } else {
156         const char *p = (const char *)buf;
157         const char *end = p + buf_size;
158         while (p < end) {
159             if (*p == '#') {
160                 /* skip comment line */
161                 while (p < end && *p != '\n') {
162                     p++;
163                 }
164                 p++;
165                 continue;
166             }
167             if (*p == ' ') {
168                 while (p < end && *p == ' ') {
169                     p++;
170                 }
171                 /* skip '\r' if windows line endings used. */
172                 if (p < end && *p == '\r') {
173                     p++;
174                 }
175                 /* only accept blank lines before 'version=' line */
176                 if (p == end || *p != '\n') {
177                     return 0;
178                 }
179                 p++;
180                 continue;
181             }
182             if (end - p >= strlen("version=X\n")) {
183                 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
184                     strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
185                     return 100;
186                 }
187             }
188             if (end - p >= strlen("version=X\r\n")) {
189                 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
190                     strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
191                     return 100;
192                 }
193             }
194             return 0;
195         }
196         return 0;
197     }
198 }
199 
200 #define CHECK_CID 1
201 
202 #define SECTOR_SIZE 512
203 #define DESC_SIZE (20 * SECTOR_SIZE)    /* 20 sectors of 512 bytes each */
204 #define BUF_SIZE 4096
205 #define HEADER_SIZE 512                 /* first sector of 512 bytes */
206 
207 static void vmdk_free_extents(BlockDriverState *bs)
208 {
209     int i;
210     BDRVVmdkState *s = bs->opaque;
211     VmdkExtent *e;
212 
213     for (i = 0; i < s->num_extents; i++) {
214         e = &s->extents[i];
215         g_free(e->l1_table);
216         g_free(e->l2_cache);
217         g_free(e->l1_backup_table);
218         if (e->file != bs->file) {
219             bdrv_delete(e->file);
220         }
221     }
222     g_free(s->extents);
223 }
224 
225 static void vmdk_free_last_extent(BlockDriverState *bs)
226 {
227     BDRVVmdkState *s = bs->opaque;
228 
229     if (s->num_extents == 0) {
230         return;
231     }
232     s->num_extents--;
233     s->extents = g_realloc(s->extents, s->num_extents * sizeof(VmdkExtent));
234 }
235 
236 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
237 {
238     char desc[DESC_SIZE];
239     uint32_t cid = 0xffffffff;
240     const char *p_name, *cid_str;
241     size_t cid_str_size;
242     BDRVVmdkState *s = bs->opaque;
243     int ret;
244 
245     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
246     if (ret < 0) {
247         return 0;
248     }
249 
250     if (parent) {
251         cid_str = "parentCID";
252         cid_str_size = sizeof("parentCID");
253     } else {
254         cid_str = "CID";
255         cid_str_size = sizeof("CID");
256     }
257 
258     desc[DESC_SIZE - 1] = '\0';
259     p_name = strstr(desc, cid_str);
260     if (p_name != NULL) {
261         p_name += cid_str_size;
262         sscanf(p_name, "%x", &cid);
263     }
264 
265     return cid;
266 }
267 
268 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
269 {
270     char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
271     char *p_name, *tmp_str;
272     BDRVVmdkState *s = bs->opaque;
273     int ret;
274 
275     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
276     if (ret < 0) {
277         return ret;
278     }
279 
280     desc[DESC_SIZE - 1] = '\0';
281     tmp_str = strstr(desc, "parentCID");
282     if (tmp_str == NULL) {
283         return -EINVAL;
284     }
285 
286     pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
287     p_name = strstr(desc, "CID");
288     if (p_name != NULL) {
289         p_name += sizeof("CID");
290         snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);
291         pstrcat(desc, sizeof(desc), tmp_desc);
292     }
293 
294     ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
295     if (ret < 0) {
296         return ret;
297     }
298 
299     return 0;
300 }
301 
302 static int vmdk_is_cid_valid(BlockDriverState *bs)
303 {
304 #ifdef CHECK_CID
305     BDRVVmdkState *s = bs->opaque;
306     BlockDriverState *p_bs = bs->backing_hd;
307     uint32_t cur_pcid;
308 
309     if (p_bs) {
310         cur_pcid = vmdk_read_cid(p_bs, 0);
311         if (s->parent_cid != cur_pcid) {
312             /* CID not valid */
313             return 0;
314         }
315     }
316 #endif
317     /* CID valid */
318     return 1;
319 }
320 
321 /* Queue extents, if any, for reopen() */
322 static int vmdk_reopen_prepare(BDRVReopenState *state,
323                                BlockReopenQueue *queue, Error **errp)
324 {
325     BDRVVmdkState *s;
326     int ret = -1;
327     int i;
328     VmdkExtent *e;
329 
330     assert(state != NULL);
331     assert(state->bs != NULL);
332 
333     if (queue == NULL) {
334         error_set(errp, ERROR_CLASS_GENERIC_ERROR,
335                  "No reopen queue for VMDK extents");
336         goto exit;
337     }
338 
339     s = state->bs->opaque;
340 
341     assert(s != NULL);
342 
343     for (i = 0; i < s->num_extents; i++) {
344         e = &s->extents[i];
345         if (e->file != state->bs->file) {
346             bdrv_reopen_queue(queue, e->file, state->flags);
347         }
348     }
349     ret = 0;
350 
351 exit:
352     return ret;
353 }
354 
355 static int vmdk_parent_open(BlockDriverState *bs)
356 {
357     char *p_name;
358     char desc[DESC_SIZE + 1];
359     BDRVVmdkState *s = bs->opaque;
360     int ret;
361 
362     desc[DESC_SIZE] = '\0';
363     ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
364     if (ret < 0) {
365         return ret;
366     }
367 
368     p_name = strstr(desc, "parentFileNameHint");
369     if (p_name != NULL) {
370         char *end_name;
371 
372         p_name += sizeof("parentFileNameHint") + 1;
373         end_name = strchr(p_name, '\"');
374         if (end_name == NULL) {
375             return -EINVAL;
376         }
377         if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
378             return -EINVAL;
379         }
380 
381         pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
382     }
383 
384     return 0;
385 }
386 
387 /* Create and append extent to the extent array. Return the added VmdkExtent
388  * address. return NULL if allocation failed. */
389 static int vmdk_add_extent(BlockDriverState *bs,
390                            BlockDriverState *file, bool flat, int64_t sectors,
391                            int64_t l1_offset, int64_t l1_backup_offset,
392                            uint32_t l1_size,
393                            int l2_size, uint64_t cluster_sectors,
394                            VmdkExtent **new_extent)
395 {
396     VmdkExtent *extent;
397     BDRVVmdkState *s = bs->opaque;
398 
399     if (cluster_sectors > 0x200000) {
400         /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
401         error_report("invalid granularity, image may be corrupt");
402         return -EINVAL;
403     }
404 
405     s->extents = g_realloc(s->extents,
406                               (s->num_extents + 1) * sizeof(VmdkExtent));
407     extent = &s->extents[s->num_extents];
408     s->num_extents++;
409 
410     memset(extent, 0, sizeof(VmdkExtent));
411     extent->file = file;
412     extent->flat = flat;
413     extent->sectors = sectors;
414     extent->l1_table_offset = l1_offset;
415     extent->l1_backup_table_offset = l1_backup_offset;
416     extent->l1_size = l1_size;
417     extent->l1_entry_sectors = l2_size * cluster_sectors;
418     extent->l2_size = l2_size;
419     extent->cluster_sectors = cluster_sectors;
420 
421     if (s->num_extents > 1) {
422         extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
423     } else {
424         extent->end_sector = extent->sectors;
425     }
426     bs->total_sectors = extent->end_sector;
427     if (new_extent) {
428         *new_extent = extent;
429     }
430     return 0;
431 }
432 
433 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent)
434 {
435     int ret;
436     int l1_size, i;
437 
438     /* read the L1 table */
439     l1_size = extent->l1_size * sizeof(uint32_t);
440     extent->l1_table = g_malloc(l1_size);
441     ret = bdrv_pread(extent->file,
442                     extent->l1_table_offset,
443                     extent->l1_table,
444                     l1_size);
445     if (ret < 0) {
446         goto fail_l1;
447     }
448     for (i = 0; i < extent->l1_size; i++) {
449         le32_to_cpus(&extent->l1_table[i]);
450     }
451 
452     if (extent->l1_backup_table_offset) {
453         extent->l1_backup_table = g_malloc(l1_size);
454         ret = bdrv_pread(extent->file,
455                         extent->l1_backup_table_offset,
456                         extent->l1_backup_table,
457                         l1_size);
458         if (ret < 0) {
459             goto fail_l1b;
460         }
461         for (i = 0; i < extent->l1_size; i++) {
462             le32_to_cpus(&extent->l1_backup_table[i]);
463         }
464     }
465 
466     extent->l2_cache =
467         g_malloc(extent->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
468     return 0;
469  fail_l1b:
470     g_free(extent->l1_backup_table);
471  fail_l1:
472     g_free(extent->l1_table);
473     return ret;
474 }
475 
476 static int vmdk_open_vmdk3(BlockDriverState *bs,
477                            BlockDriverState *file,
478                            int flags)
479 {
480     int ret;
481     uint32_t magic;
482     VMDK3Header header;
483     VmdkExtent *extent;
484 
485     ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
486     if (ret < 0) {
487         return ret;
488     }
489 
490     ret = vmdk_add_extent(bs,
491                              bs->file, false,
492                              le32_to_cpu(header.disk_sectors),
493                              le32_to_cpu(header.l1dir_offset) << 9,
494                              0, 1 << 6, 1 << 9,
495                              le32_to_cpu(header.granularity),
496                              &extent);
497     if (ret < 0) {
498         return ret;
499     }
500     ret = vmdk_init_tables(bs, extent);
501     if (ret) {
502         /* free extent allocated by vmdk_add_extent */
503         vmdk_free_last_extent(bs);
504     }
505     return ret;
506 }
507 
508 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
509                                uint64_t desc_offset);
510 
511 static int vmdk_open_vmdk4(BlockDriverState *bs,
512                            BlockDriverState *file,
513                            int flags)
514 {
515     int ret;
516     uint32_t magic;
517     uint32_t l1_size, l1_entry_sectors;
518     VMDK4Header header;
519     VmdkExtent *extent;
520     int64_t l1_backup_offset = 0;
521 
522     ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
523     if (ret < 0) {
524         return ret;
525     }
526     if (header.capacity == 0) {
527         uint64_t desc_offset = le64_to_cpu(header.desc_offset);
528         if (desc_offset) {
529             return vmdk_open_desc_file(bs, flags, desc_offset << 9);
530         }
531     }
532 
533     if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
534         /*
535          * The footer takes precedence over the header, so read it in. The
536          * footer starts at offset -1024 from the end: One sector for the
537          * footer, and another one for the end-of-stream marker.
538          */
539         struct {
540             struct {
541                 uint64_t val;
542                 uint32_t size;
543                 uint32_t type;
544                 uint8_t pad[512 - 16];
545             } QEMU_PACKED footer_marker;
546 
547             uint32_t magic;
548             VMDK4Header header;
549             uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
550 
551             struct {
552                 uint64_t val;
553                 uint32_t size;
554                 uint32_t type;
555                 uint8_t pad[512 - 16];
556             } QEMU_PACKED eos_marker;
557         } QEMU_PACKED footer;
558 
559         ret = bdrv_pread(file,
560             bs->file->total_sectors * 512 - 1536,
561             &footer, sizeof(footer));
562         if (ret < 0) {
563             return ret;
564         }
565 
566         /* Some sanity checks for the footer */
567         if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
568             le32_to_cpu(footer.footer_marker.size) != 0  ||
569             le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
570             le64_to_cpu(footer.eos_marker.val) != 0  ||
571             le32_to_cpu(footer.eos_marker.size) != 0  ||
572             le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
573         {
574             return -EINVAL;
575         }
576 
577         header = footer.header;
578     }
579 
580     if (le32_to_cpu(header.version) >= 3) {
581         char buf[64];
582         snprintf(buf, sizeof(buf), "VMDK version %d",
583                  le32_to_cpu(header.version));
584         qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
585                 bs->device_name, "vmdk", buf);
586         return -ENOTSUP;
587     }
588 
589     if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
590         error_report("L2 table size too big");
591         return -EINVAL;
592     }
593 
594     l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
595                         * le64_to_cpu(header.granularity);
596     if (l1_entry_sectors == 0) {
597         return -EINVAL;
598     }
599     l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
600                 / l1_entry_sectors;
601     if (l1_size > 512 * 1024 * 1024) {
602         /* although with big capacity and small l1_entry_sectors, we can get a
603          * big l1_size, we don't want unbounded value to allocate the table.
604          * Limit it to 512M, which is 16PB for default cluster and L2 table
605          * size */
606         error_report("L1 size too big");
607         return -EFBIG;
608     }
609     if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
610         l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
611     }
612     ret = vmdk_add_extent(bs, file, false,
613                           le64_to_cpu(header.capacity),
614                           le64_to_cpu(header.gd_offset) << 9,
615                           l1_backup_offset,
616                           l1_size,
617                           le32_to_cpu(header.num_gtes_per_gt),
618                           le64_to_cpu(header.granularity),
619                           &extent);
620     if (ret < 0) {
621         return ret;
622     }
623     extent->compressed =
624         le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
625     extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
626     extent->version = le32_to_cpu(header.version);
627     extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
628     ret = vmdk_init_tables(bs, extent);
629     if (ret) {
630         /* free extent allocated by vmdk_add_extent */
631         vmdk_free_last_extent(bs);
632     }
633     return ret;
634 }
635 
636 /* find an option value out of descriptor file */
637 static int vmdk_parse_description(const char *desc, const char *opt_name,
638         char *buf, int buf_size)
639 {
640     char *opt_pos, *opt_end;
641     const char *end = desc + strlen(desc);
642 
643     opt_pos = strstr(desc, opt_name);
644     if (!opt_pos) {
645         return VMDK_ERROR;
646     }
647     /* Skip "=\"" following opt_name */
648     opt_pos += strlen(opt_name) + 2;
649     if (opt_pos >= end) {
650         return VMDK_ERROR;
651     }
652     opt_end = opt_pos;
653     while (opt_end < end && *opt_end != '"') {
654         opt_end++;
655     }
656     if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
657         return VMDK_ERROR;
658     }
659     pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
660     return VMDK_OK;
661 }
662 
663 /* Open an extent file and append to bs array */
664 static int vmdk_open_sparse(BlockDriverState *bs,
665                             BlockDriverState *file,
666                             int flags)
667 {
668     uint32_t magic;
669 
670     if (bdrv_pread(file, 0, &magic, sizeof(magic)) != sizeof(magic)) {
671         return -EIO;
672     }
673 
674     magic = be32_to_cpu(magic);
675     switch (magic) {
676         case VMDK3_MAGIC:
677             return vmdk_open_vmdk3(bs, file, flags);
678             break;
679         case VMDK4_MAGIC:
680             return vmdk_open_vmdk4(bs, file, flags);
681             break;
682         default:
683             return -EMEDIUMTYPE;
684             break;
685     }
686 }
687 
688 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
689         const char *desc_file_path)
690 {
691     int ret;
692     char access[11];
693     char type[11];
694     char fname[512];
695     const char *p = desc;
696     int64_t sectors = 0;
697     int64_t flat_offset;
698     char extent_path[PATH_MAX];
699     BlockDriverState *extent_file;
700 
701     while (*p) {
702         /* parse extent line:
703          * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
704          * or
705          * RW [size in sectors] SPARSE "file-name.vmdk"
706          */
707         flat_offset = -1;
708         ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
709                 access, &sectors, type, fname, &flat_offset);
710         if (ret < 4 || strcmp(access, "RW")) {
711             goto next_line;
712         } else if (!strcmp(type, "FLAT")) {
713             if (ret != 5 || flat_offset < 0) {
714                 return -EINVAL;
715             }
716         } else if (ret != 4) {
717             return -EINVAL;
718         }
719 
720         if (sectors <= 0 ||
721             (strcmp(type, "FLAT") && strcmp(type, "SPARSE")) ||
722             (strcmp(access, "RW"))) {
723             goto next_line;
724         }
725 
726         path_combine(extent_path, sizeof(extent_path),
727                 desc_file_path, fname);
728         ret = bdrv_file_open(&extent_file, extent_path, NULL, bs->open_flags);
729         if (ret) {
730             return ret;
731         }
732 
733         /* save to extents array */
734         if (!strcmp(type, "FLAT")) {
735             /* FLAT extent */
736             VmdkExtent *extent;
737 
738             ret = vmdk_add_extent(bs, extent_file, true, sectors,
739                             0, 0, 0, 0, sectors, &extent);
740             if (ret < 0) {
741                 return ret;
742             }
743             extent->flat_start_offset = flat_offset << 9;
744         } else if (!strcmp(type, "SPARSE")) {
745             /* SPARSE extent */
746             ret = vmdk_open_sparse(bs, extent_file, bs->open_flags);
747             if (ret) {
748                 bdrv_delete(extent_file);
749                 return ret;
750             }
751         } else {
752             fprintf(stderr,
753                 "VMDK: Not supported extent type \"%s\""".\n", type);
754             return -ENOTSUP;
755         }
756 next_line:
757         /* move to next line */
758         while (*p && *p != '\n') {
759             p++;
760         }
761         p++;
762     }
763     return 0;
764 }
765 
766 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
767                                uint64_t desc_offset)
768 {
769     int ret;
770     char *buf = NULL;
771     char ct[128];
772     BDRVVmdkState *s = bs->opaque;
773     int64_t size;
774 
775     size = bdrv_getlength(bs->file);
776     if (size < 0) {
777         return -EINVAL;
778     }
779 
780     size = MIN(size, 1 << 20);  /* avoid unbounded allocation */
781     buf = g_malloc0(size + 1);
782 
783     ret = bdrv_pread(bs->file, desc_offset, buf, size);
784     if (ret < 0) {
785         goto exit;
786     }
787     if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
788         ret = -EMEDIUMTYPE;
789         goto exit;
790     }
791     if (strcmp(ct, "monolithicFlat") &&
792         strcmp(ct, "twoGbMaxExtentSparse") &&
793         strcmp(ct, "twoGbMaxExtentFlat")) {
794         fprintf(stderr,
795                 "VMDK: Not supported image type \"%s\""".\n", ct);
796         ret = -ENOTSUP;
797         goto exit;
798     }
799     s->desc_offset = 0;
800     ret = vmdk_parse_extents(buf, bs, bs->file->filename);
801 exit:
802     g_free(buf);
803     return ret;
804 }
805 
806 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags)
807 {
808     int ret;
809     BDRVVmdkState *s = bs->opaque;
810 
811     if (vmdk_open_sparse(bs, bs->file, flags) == 0) {
812         s->desc_offset = 0x200;
813     } else {
814         ret = vmdk_open_desc_file(bs, flags, 0);
815         if (ret) {
816             goto fail;
817         }
818     }
819     /* try to open parent images, if exist */
820     ret = vmdk_parent_open(bs);
821     if (ret) {
822         goto fail;
823     }
824     s->parent_cid = vmdk_read_cid(bs, 1);
825     qemu_co_mutex_init(&s->lock);
826 
827     /* Disable migration when VMDK images are used */
828     error_set(&s->migration_blocker,
829               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
830               "vmdk", bs->device_name, "live migration");
831     migrate_add_blocker(s->migration_blocker);
832 
833     return 0;
834 
835 fail:
836     vmdk_free_extents(bs);
837     return ret;
838 }
839 
840 static int get_whole_cluster(BlockDriverState *bs,
841                 VmdkExtent *extent,
842                 uint64_t cluster_offset,
843                 uint64_t offset,
844                 bool allocate)
845 {
846     int ret = VMDK_OK;
847     uint8_t *whole_grain = NULL;
848 
849     /* we will be here if it's first write on non-exist grain(cluster).
850      * try to read from parent image, if exist */
851     if (bs->backing_hd) {
852         whole_grain =
853             qemu_blockalign(bs, extent->cluster_sectors << BDRV_SECTOR_BITS);
854         if (!vmdk_is_cid_valid(bs)) {
855             ret = VMDK_ERROR;
856             goto exit;
857         }
858 
859         /* floor offset to cluster */
860         offset -= offset % (extent->cluster_sectors * 512);
861         ret = bdrv_read(bs->backing_hd, offset >> 9, whole_grain,
862                 extent->cluster_sectors);
863         if (ret < 0) {
864             ret = VMDK_ERROR;
865             goto exit;
866         }
867 
868         /* Write grain only into the active image */
869         ret = bdrv_write(extent->file, cluster_offset, whole_grain,
870                 extent->cluster_sectors);
871         if (ret < 0) {
872             ret = VMDK_ERROR;
873             goto exit;
874         }
875     }
876 exit:
877     qemu_vfree(whole_grain);
878     return ret;
879 }
880 
881 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data)
882 {
883     uint32_t offset;
884     QEMU_BUILD_BUG_ON(sizeof(offset) != sizeof(m_data->offset));
885     offset = cpu_to_le32(m_data->offset);
886     /* update L2 table */
887     if (bdrv_pwrite_sync(
888                 extent->file,
889                 ((int64_t)m_data->l2_offset * 512)
890                     + (m_data->l2_index * sizeof(m_data->offset)),
891                 &offset, sizeof(offset)) < 0) {
892         return VMDK_ERROR;
893     }
894     /* update backup L2 table */
895     if (extent->l1_backup_table_offset != 0) {
896         m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
897         if (bdrv_pwrite_sync(
898                     extent->file,
899                     ((int64_t)m_data->l2_offset * 512)
900                         + (m_data->l2_index * sizeof(m_data->offset)),
901                     &offset, sizeof(offset)) < 0) {
902             return VMDK_ERROR;
903         }
904     }
905     if (m_data->l2_cache_entry) {
906         *m_data->l2_cache_entry = offset;
907     }
908 
909     return VMDK_OK;
910 }
911 
912 static int get_cluster_offset(BlockDriverState *bs,
913                                     VmdkExtent *extent,
914                                     VmdkMetaData *m_data,
915                                     uint64_t offset,
916                                     int allocate,
917                                     uint64_t *cluster_offset)
918 {
919     unsigned int l1_index, l2_offset, l2_index;
920     int min_index, i, j;
921     uint32_t min_count, *l2_table;
922     bool zeroed = false;
923 
924     if (m_data) {
925         m_data->valid = 0;
926     }
927     if (extent->flat) {
928         *cluster_offset = extent->flat_start_offset;
929         return VMDK_OK;
930     }
931 
932     offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
933     l1_index = (offset >> 9) / extent->l1_entry_sectors;
934     if (l1_index >= extent->l1_size) {
935         return VMDK_ERROR;
936     }
937     l2_offset = extent->l1_table[l1_index];
938     if (!l2_offset) {
939         return VMDK_UNALLOC;
940     }
941     for (i = 0; i < L2_CACHE_SIZE; i++) {
942         if (l2_offset == extent->l2_cache_offsets[i]) {
943             /* increment the hit count */
944             if (++extent->l2_cache_counts[i] == 0xffffffff) {
945                 for (j = 0; j < L2_CACHE_SIZE; j++) {
946                     extent->l2_cache_counts[j] >>= 1;
947                 }
948             }
949             l2_table = extent->l2_cache + (i * extent->l2_size);
950             goto found;
951         }
952     }
953     /* not found: load a new entry in the least used one */
954     min_index = 0;
955     min_count = 0xffffffff;
956     for (i = 0; i < L2_CACHE_SIZE; i++) {
957         if (extent->l2_cache_counts[i] < min_count) {
958             min_count = extent->l2_cache_counts[i];
959             min_index = i;
960         }
961     }
962     l2_table = extent->l2_cache + (min_index * extent->l2_size);
963     if (bdrv_pread(
964                 extent->file,
965                 (int64_t)l2_offset * 512,
966                 l2_table,
967                 extent->l2_size * sizeof(uint32_t)
968             ) != extent->l2_size * sizeof(uint32_t)) {
969         return VMDK_ERROR;
970     }
971 
972     extent->l2_cache_offsets[min_index] = l2_offset;
973     extent->l2_cache_counts[min_index] = 1;
974  found:
975     l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
976     *cluster_offset = le32_to_cpu(l2_table[l2_index]);
977 
978     if (m_data) {
979         m_data->valid = 1;
980         m_data->l1_index = l1_index;
981         m_data->l2_index = l2_index;
982         m_data->offset = *cluster_offset;
983         m_data->l2_offset = l2_offset;
984         m_data->l2_cache_entry = &l2_table[l2_index];
985     }
986     if (extent->has_zero_grain && *cluster_offset == VMDK_GTE_ZEROED) {
987         zeroed = true;
988     }
989 
990     if (!*cluster_offset || zeroed) {
991         if (!allocate) {
992             return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
993         }
994 
995         /* Avoid the L2 tables update for the images that have snapshots. */
996         *cluster_offset = bdrv_getlength(extent->file);
997         if (!extent->compressed) {
998             bdrv_truncate(
999                 extent->file,
1000                 *cluster_offset + (extent->cluster_sectors << 9)
1001             );
1002         }
1003 
1004         *cluster_offset >>= 9;
1005         l2_table[l2_index] = cpu_to_le32(*cluster_offset);
1006 
1007         /* First of all we write grain itself, to avoid race condition
1008          * that may to corrupt the image.
1009          * This problem may occur because of insufficient space on host disk
1010          * or inappropriate VM shutdown.
1011          */
1012         if (get_whole_cluster(
1013                 bs, extent, *cluster_offset, offset, allocate) == -1) {
1014             return VMDK_ERROR;
1015         }
1016 
1017         if (m_data) {
1018             m_data->offset = *cluster_offset;
1019         }
1020     }
1021     *cluster_offset <<= 9;
1022     return VMDK_OK;
1023 }
1024 
1025 static VmdkExtent *find_extent(BDRVVmdkState *s,
1026                                 int64_t sector_num, VmdkExtent *start_hint)
1027 {
1028     VmdkExtent *extent = start_hint;
1029 
1030     if (!extent) {
1031         extent = &s->extents[0];
1032     }
1033     while (extent < &s->extents[s->num_extents]) {
1034         if (sector_num < extent->end_sector) {
1035             return extent;
1036         }
1037         extent++;
1038     }
1039     return NULL;
1040 }
1041 
1042 static int coroutine_fn vmdk_co_is_allocated(BlockDriverState *bs,
1043         int64_t sector_num, int nb_sectors, int *pnum)
1044 {
1045     BDRVVmdkState *s = bs->opaque;
1046     int64_t index_in_cluster, n, ret;
1047     uint64_t offset;
1048     VmdkExtent *extent;
1049 
1050     extent = find_extent(s, sector_num, NULL);
1051     if (!extent) {
1052         return 0;
1053     }
1054     qemu_co_mutex_lock(&s->lock);
1055     ret = get_cluster_offset(bs, extent, NULL,
1056                             sector_num * 512, 0, &offset);
1057     qemu_co_mutex_unlock(&s->lock);
1058 
1059     ret = (ret == VMDK_OK || ret == VMDK_ZEROED);
1060 
1061     index_in_cluster = sector_num % extent->cluster_sectors;
1062     n = extent->cluster_sectors - index_in_cluster;
1063     if (n > nb_sectors) {
1064         n = nb_sectors;
1065     }
1066     *pnum = n;
1067     return ret;
1068 }
1069 
1070 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1071                             int64_t offset_in_cluster, const uint8_t *buf,
1072                             int nb_sectors, int64_t sector_num)
1073 {
1074     int ret;
1075     VmdkGrainMarker *data = NULL;
1076     uLongf buf_len;
1077     const uint8_t *write_buf = buf;
1078     int write_len = nb_sectors * 512;
1079 
1080     if (extent->compressed) {
1081         if (!extent->has_marker) {
1082             ret = -EINVAL;
1083             goto out;
1084         }
1085         buf_len = (extent->cluster_sectors << 9) * 2;
1086         data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1087         if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1088                 buf_len == 0) {
1089             ret = -EINVAL;
1090             goto out;
1091         }
1092         data->lba = sector_num;
1093         data->size = buf_len;
1094         write_buf = (uint8_t *)data;
1095         write_len = buf_len + sizeof(VmdkGrainMarker);
1096     }
1097     ret = bdrv_pwrite(extent->file,
1098                         cluster_offset + offset_in_cluster,
1099                         write_buf,
1100                         write_len);
1101     if (ret != write_len) {
1102         ret = ret < 0 ? ret : -EIO;
1103         goto out;
1104     }
1105     ret = 0;
1106  out:
1107     g_free(data);
1108     return ret;
1109 }
1110 
1111 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1112                             int64_t offset_in_cluster, uint8_t *buf,
1113                             int nb_sectors)
1114 {
1115     int ret;
1116     int cluster_bytes, buf_bytes;
1117     uint8_t *cluster_buf, *compressed_data;
1118     uint8_t *uncomp_buf;
1119     uint32_t data_len;
1120     VmdkGrainMarker *marker;
1121     uLongf buf_len;
1122 
1123 
1124     if (!extent->compressed) {
1125         ret = bdrv_pread(extent->file,
1126                           cluster_offset + offset_in_cluster,
1127                           buf, nb_sectors * 512);
1128         if (ret == nb_sectors * 512) {
1129             return 0;
1130         } else {
1131             return -EIO;
1132         }
1133     }
1134     cluster_bytes = extent->cluster_sectors * 512;
1135     /* Read two clusters in case GrainMarker + compressed data > one cluster */
1136     buf_bytes = cluster_bytes * 2;
1137     cluster_buf = g_malloc(buf_bytes);
1138     uncomp_buf = g_malloc(cluster_bytes);
1139     ret = bdrv_pread(extent->file,
1140                 cluster_offset,
1141                 cluster_buf, buf_bytes);
1142     if (ret < 0) {
1143         goto out;
1144     }
1145     compressed_data = cluster_buf;
1146     buf_len = cluster_bytes;
1147     data_len = cluster_bytes;
1148     if (extent->has_marker) {
1149         marker = (VmdkGrainMarker *)cluster_buf;
1150         compressed_data = marker->data;
1151         data_len = le32_to_cpu(marker->size);
1152     }
1153     if (!data_len || data_len > buf_bytes) {
1154         ret = -EINVAL;
1155         goto out;
1156     }
1157     ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1158     if (ret != Z_OK) {
1159         ret = -EINVAL;
1160         goto out;
1161 
1162     }
1163     if (offset_in_cluster < 0 ||
1164             offset_in_cluster + nb_sectors * 512 > buf_len) {
1165         ret = -EINVAL;
1166         goto out;
1167     }
1168     memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1169     ret = 0;
1170 
1171  out:
1172     g_free(uncomp_buf);
1173     g_free(cluster_buf);
1174     return ret;
1175 }
1176 
1177 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1178                     uint8_t *buf, int nb_sectors)
1179 {
1180     BDRVVmdkState *s = bs->opaque;
1181     int ret;
1182     uint64_t n, index_in_cluster;
1183     uint64_t extent_begin_sector, extent_relative_sector_num;
1184     VmdkExtent *extent = NULL;
1185     uint64_t cluster_offset;
1186 
1187     while (nb_sectors > 0) {
1188         extent = find_extent(s, sector_num, extent);
1189         if (!extent) {
1190             return -EIO;
1191         }
1192         ret = get_cluster_offset(
1193                             bs, extent, NULL,
1194                             sector_num << 9, 0, &cluster_offset);
1195         extent_begin_sector = extent->end_sector - extent->sectors;
1196         extent_relative_sector_num = sector_num - extent_begin_sector;
1197         index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1198         n = extent->cluster_sectors - index_in_cluster;
1199         if (n > nb_sectors) {
1200             n = nb_sectors;
1201         }
1202         if (ret != VMDK_OK) {
1203             /* if not allocated, try to read from parent image, if exist */
1204             if (bs->backing_hd && ret != VMDK_ZEROED) {
1205                 if (!vmdk_is_cid_valid(bs)) {
1206                     return -EINVAL;
1207                 }
1208                 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1209                 if (ret < 0) {
1210                     return ret;
1211                 }
1212             } else {
1213                 memset(buf, 0, 512 * n);
1214             }
1215         } else {
1216             ret = vmdk_read_extent(extent,
1217                             cluster_offset, index_in_cluster * 512,
1218                             buf, n);
1219             if (ret) {
1220                 return ret;
1221             }
1222         }
1223         nb_sectors -= n;
1224         sector_num += n;
1225         buf += n * 512;
1226     }
1227     return 0;
1228 }
1229 
1230 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1231                                      uint8_t *buf, int nb_sectors)
1232 {
1233     int ret;
1234     BDRVVmdkState *s = bs->opaque;
1235     qemu_co_mutex_lock(&s->lock);
1236     ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1237     qemu_co_mutex_unlock(&s->lock);
1238     return ret;
1239 }
1240 
1241 /**
1242  * vmdk_write:
1243  * @zeroed:       buf is ignored (data is zero), use zeroed_grain GTE feature
1244  *                if possible, otherwise return -ENOTSUP.
1245  * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1246  *                with each cluster. By dry run we can find if the zero write
1247  *                is possible without modifying image data.
1248  *
1249  * Returns: error code with 0 for success.
1250  */
1251 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1252                       const uint8_t *buf, int nb_sectors,
1253                       bool zeroed, bool zero_dry_run)
1254 {
1255     BDRVVmdkState *s = bs->opaque;
1256     VmdkExtent *extent = NULL;
1257     int n, ret;
1258     int64_t index_in_cluster;
1259     uint64_t extent_begin_sector, extent_relative_sector_num;
1260     uint64_t cluster_offset;
1261     VmdkMetaData m_data;
1262 
1263     if (sector_num > bs->total_sectors) {
1264         fprintf(stderr,
1265                 "(VMDK) Wrong offset: sector_num=0x%" PRIx64
1266                 " total_sectors=0x%" PRIx64 "\n",
1267                 sector_num, bs->total_sectors);
1268         return -EIO;
1269     }
1270 
1271     while (nb_sectors > 0) {
1272         extent = find_extent(s, sector_num, extent);
1273         if (!extent) {
1274             return -EIO;
1275         }
1276         ret = get_cluster_offset(
1277                                 bs,
1278                                 extent,
1279                                 &m_data,
1280                                 sector_num << 9, !extent->compressed,
1281                                 &cluster_offset);
1282         if (extent->compressed) {
1283             if (ret == VMDK_OK) {
1284                 /* Refuse write to allocated cluster for streamOptimized */
1285                 fprintf(stderr,
1286                         "VMDK: can't write to allocated cluster"
1287                         " for streamOptimized\n");
1288                 return -EIO;
1289             } else {
1290                 /* allocate */
1291                 ret = get_cluster_offset(
1292                                         bs,
1293                                         extent,
1294                                         &m_data,
1295                                         sector_num << 9, 1,
1296                                         &cluster_offset);
1297             }
1298         }
1299         if (ret == VMDK_ERROR) {
1300             return -EINVAL;
1301         }
1302         extent_begin_sector = extent->end_sector - extent->sectors;
1303         extent_relative_sector_num = sector_num - extent_begin_sector;
1304         index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1305         n = extent->cluster_sectors - index_in_cluster;
1306         if (n > nb_sectors) {
1307             n = nb_sectors;
1308         }
1309         if (zeroed) {
1310             /* Do zeroed write, buf is ignored */
1311             if (extent->has_zero_grain &&
1312                     index_in_cluster == 0 &&
1313                     n >= extent->cluster_sectors) {
1314                 n = extent->cluster_sectors;
1315                 if (!zero_dry_run) {
1316                     m_data.offset = VMDK_GTE_ZEROED;
1317                     /* update L2 tables */
1318                     if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1319                         return -EIO;
1320                     }
1321                 }
1322             } else {
1323                 return -ENOTSUP;
1324             }
1325         } else {
1326             ret = vmdk_write_extent(extent,
1327                             cluster_offset, index_in_cluster * 512,
1328                             buf, n, sector_num);
1329             if (ret) {
1330                 return ret;
1331             }
1332             if (m_data.valid) {
1333                 /* update L2 tables */
1334                 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1335                     return -EIO;
1336                 }
1337             }
1338         }
1339         nb_sectors -= n;
1340         sector_num += n;
1341         buf += n * 512;
1342 
1343         /* update CID on the first write every time the virtual disk is
1344          * opened */
1345         if (!s->cid_updated) {
1346             ret = vmdk_write_cid(bs, time(NULL));
1347             if (ret < 0) {
1348                 return ret;
1349             }
1350             s->cid_updated = true;
1351         }
1352     }
1353     return 0;
1354 }
1355 
1356 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1357                                       const uint8_t *buf, int nb_sectors)
1358 {
1359     int ret;
1360     BDRVVmdkState *s = bs->opaque;
1361     qemu_co_mutex_lock(&s->lock);
1362     ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1363     qemu_co_mutex_unlock(&s->lock);
1364     return ret;
1365 }
1366 
1367 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1368                                              int64_t sector_num,
1369                                              int nb_sectors)
1370 {
1371     int ret;
1372     BDRVVmdkState *s = bs->opaque;
1373     qemu_co_mutex_lock(&s->lock);
1374     /* write zeroes could fail if sectors not aligned to cluster, test it with
1375      * dry_run == true before really updating image */
1376     ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1377     if (!ret) {
1378         ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1379     }
1380     qemu_co_mutex_unlock(&s->lock);
1381     return ret;
1382 }
1383 
1384 
1385 static int vmdk_create_extent(const char *filename, int64_t filesize,
1386                               bool flat, bool compress, bool zeroed_grain)
1387 {
1388     int ret, i;
1389     int fd = 0;
1390     VMDK4Header header;
1391     uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
1392 
1393     fd = qemu_open(filename,
1394                    O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1395                    0644);
1396     if (fd < 0) {
1397         return -errno;
1398     }
1399     if (flat) {
1400         ret = ftruncate(fd, filesize);
1401         if (ret < 0) {
1402             ret = -errno;
1403         }
1404         goto exit;
1405     }
1406     magic = cpu_to_be32(VMDK4_MAGIC);
1407     memset(&header, 0, sizeof(header));
1408     header.version = zeroed_grain ? 2 : 1;
1409     header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1410                    | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1411                    | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1412     header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1413     header.capacity = filesize / 512;
1414     header.granularity = 128;
1415     header.num_gtes_per_gt = 512;
1416 
1417     grains = (filesize / 512 + header.granularity - 1) / header.granularity;
1418     gt_size = ((header.num_gtes_per_gt * sizeof(uint32_t)) + 511) >> 9;
1419     gt_count =
1420         (grains + header.num_gtes_per_gt - 1) / header.num_gtes_per_gt;
1421     gd_size = (gt_count * sizeof(uint32_t) + 511) >> 9;
1422 
1423     header.desc_offset = 1;
1424     header.desc_size = 20;
1425     header.rgd_offset = header.desc_offset + header.desc_size;
1426     header.gd_offset = header.rgd_offset + gd_size + (gt_size * gt_count);
1427     header.grain_offset =
1428        ((header.gd_offset + gd_size + (gt_size * gt_count) +
1429          header.granularity - 1) / header.granularity) *
1430         header.granularity;
1431     /* swap endianness for all header fields */
1432     header.version = cpu_to_le32(header.version);
1433     header.flags = cpu_to_le32(header.flags);
1434     header.capacity = cpu_to_le64(header.capacity);
1435     header.granularity = cpu_to_le64(header.granularity);
1436     header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1437     header.desc_offset = cpu_to_le64(header.desc_offset);
1438     header.desc_size = cpu_to_le64(header.desc_size);
1439     header.rgd_offset = cpu_to_le64(header.rgd_offset);
1440     header.gd_offset = cpu_to_le64(header.gd_offset);
1441     header.grain_offset = cpu_to_le64(header.grain_offset);
1442     header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1443 
1444     header.check_bytes[0] = 0xa;
1445     header.check_bytes[1] = 0x20;
1446     header.check_bytes[2] = 0xd;
1447     header.check_bytes[3] = 0xa;
1448 
1449     /* write all the data */
1450     ret = qemu_write_full(fd, &magic, sizeof(magic));
1451     if (ret != sizeof(magic)) {
1452         ret = -errno;
1453         goto exit;
1454     }
1455     ret = qemu_write_full(fd, &header, sizeof(header));
1456     if (ret != sizeof(header)) {
1457         ret = -errno;
1458         goto exit;
1459     }
1460 
1461     ret = ftruncate(fd, le64_to_cpu(header.grain_offset) << 9);
1462     if (ret < 0) {
1463         ret = -errno;
1464         goto exit;
1465     }
1466 
1467     /* write grain directory */
1468     lseek(fd, le64_to_cpu(header.rgd_offset) << 9, SEEK_SET);
1469     for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_size;
1470          i < gt_count; i++, tmp += gt_size) {
1471         ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1472         if (ret != sizeof(tmp)) {
1473             ret = -errno;
1474             goto exit;
1475         }
1476     }
1477 
1478     /* write backup grain directory */
1479     lseek(fd, le64_to_cpu(header.gd_offset) << 9, SEEK_SET);
1480     for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_size;
1481          i < gt_count; i++, tmp += gt_size) {
1482         ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1483         if (ret != sizeof(tmp)) {
1484             ret = -errno;
1485             goto exit;
1486         }
1487     }
1488 
1489     ret = 0;
1490  exit:
1491     qemu_close(fd);
1492     return ret;
1493 }
1494 
1495 static int filename_decompose(const char *filename, char *path, char *prefix,
1496         char *postfix, size_t buf_len)
1497 {
1498     const char *p, *q;
1499 
1500     if (filename == NULL || !strlen(filename)) {
1501         fprintf(stderr, "Vmdk: no filename provided.\n");
1502         return VMDK_ERROR;
1503     }
1504     p = strrchr(filename, '/');
1505     if (p == NULL) {
1506         p = strrchr(filename, '\\');
1507     }
1508     if (p == NULL) {
1509         p = strrchr(filename, ':');
1510     }
1511     if (p != NULL) {
1512         p++;
1513         if (p - filename >= buf_len) {
1514             return VMDK_ERROR;
1515         }
1516         pstrcpy(path, p - filename + 1, filename);
1517     } else {
1518         p = filename;
1519         path[0] = '\0';
1520     }
1521     q = strrchr(p, '.');
1522     if (q == NULL) {
1523         pstrcpy(prefix, buf_len, p);
1524         postfix[0] = '\0';
1525     } else {
1526         if (q - p >= buf_len) {
1527             return VMDK_ERROR;
1528         }
1529         pstrcpy(prefix, q - p + 1, p);
1530         pstrcpy(postfix, buf_len, q);
1531     }
1532     return VMDK_OK;
1533 }
1534 
1535 static int vmdk_create(const char *filename, QEMUOptionParameter *options)
1536 {
1537     int fd, idx = 0;
1538     char desc[BUF_SIZE];
1539     int64_t total_size = 0, filesize;
1540     const char *adapter_type = NULL;
1541     const char *backing_file = NULL;
1542     const char *fmt = NULL;
1543     int flags = 0;
1544     int ret = 0;
1545     bool flat, split, compress;
1546     char ext_desc_lines[BUF_SIZE] = "";
1547     char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1548     const int64_t split_size = 0x80000000;  /* VMDK has constant split size */
1549     const char *desc_extent_line;
1550     char parent_desc_line[BUF_SIZE] = "";
1551     uint32_t parent_cid = 0xffffffff;
1552     uint32_t number_heads = 16;
1553     bool zeroed_grain = false;
1554     const char desc_template[] =
1555         "# Disk DescriptorFile\n"
1556         "version=1\n"
1557         "CID=%x\n"
1558         "parentCID=%x\n"
1559         "createType=\"%s\"\n"
1560         "%s"
1561         "\n"
1562         "# Extent description\n"
1563         "%s"
1564         "\n"
1565         "# The Disk Data Base\n"
1566         "#DDB\n"
1567         "\n"
1568         "ddb.virtualHWVersion = \"%d\"\n"
1569         "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1570         "ddb.geometry.heads = \"%d\"\n"
1571         "ddb.geometry.sectors = \"63\"\n"
1572         "ddb.adapterType = \"%s\"\n";
1573 
1574     if (filename_decompose(filename, path, prefix, postfix, PATH_MAX)) {
1575         return -EINVAL;
1576     }
1577     /* Read out options */
1578     while (options && options->name) {
1579         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1580             total_size = options->value.n;
1581         } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {
1582             adapter_type = options->value.s;
1583         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1584             backing_file = options->value.s;
1585         } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
1586             flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;
1587         } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {
1588             fmt = options->value.s;
1589         } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {
1590             zeroed_grain |= options->value.n;
1591         }
1592         options++;
1593     }
1594     if (!adapter_type) {
1595         adapter_type = "ide";
1596     } else if (strcmp(adapter_type, "ide") &&
1597                strcmp(adapter_type, "buslogic") &&
1598                strcmp(adapter_type, "lsilogic") &&
1599                strcmp(adapter_type, "legacyESX")) {
1600         fprintf(stderr, "VMDK: Unknown adapter type: '%s'.\n", adapter_type);
1601         return -EINVAL;
1602     }
1603     if (strcmp(adapter_type, "ide") != 0) {
1604         /* that's the number of heads with which vmware operates when
1605            creating, exporting, etc. vmdk files with a non-ide adapter type */
1606         number_heads = 255;
1607     }
1608     if (!fmt) {
1609         /* Default format to monolithicSparse */
1610         fmt = "monolithicSparse";
1611     } else if (strcmp(fmt, "monolithicFlat") &&
1612                strcmp(fmt, "monolithicSparse") &&
1613                strcmp(fmt, "twoGbMaxExtentSparse") &&
1614                strcmp(fmt, "twoGbMaxExtentFlat") &&
1615                strcmp(fmt, "streamOptimized")) {
1616         fprintf(stderr, "VMDK: Unknown subformat: %s\n", fmt);
1617         return -EINVAL;
1618     }
1619     split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1620               strcmp(fmt, "twoGbMaxExtentSparse"));
1621     flat = !(strcmp(fmt, "monolithicFlat") &&
1622              strcmp(fmt, "twoGbMaxExtentFlat"));
1623     compress = !strcmp(fmt, "streamOptimized");
1624     if (flat) {
1625         desc_extent_line = "RW %lld FLAT \"%s\" 0\n";
1626     } else {
1627         desc_extent_line = "RW %lld SPARSE \"%s\"\n";
1628     }
1629     if (flat && backing_file) {
1630         /* not supporting backing file for flat image */
1631         return -ENOTSUP;
1632     }
1633     if (backing_file) {
1634         BlockDriverState *bs = bdrv_new("");
1635         ret = bdrv_open(bs, backing_file, NULL, 0, NULL);
1636         if (ret != 0) {
1637             bdrv_delete(bs);
1638             return ret;
1639         }
1640         if (strcmp(bs->drv->format_name, "vmdk")) {
1641             bdrv_delete(bs);
1642             return -EINVAL;
1643         }
1644         parent_cid = vmdk_read_cid(bs, 0);
1645         bdrv_delete(bs);
1646         snprintf(parent_desc_line, sizeof(parent_desc_line),
1647                 "parentFileNameHint=\"%s\"", backing_file);
1648     }
1649 
1650     /* Create extents */
1651     filesize = total_size;
1652     while (filesize > 0) {
1653         char desc_line[BUF_SIZE];
1654         char ext_filename[PATH_MAX];
1655         char desc_filename[PATH_MAX];
1656         int64_t size = filesize;
1657 
1658         if (split && size > split_size) {
1659             size = split_size;
1660         }
1661         if (split) {
1662             snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1663                     prefix, flat ? 'f' : 's', ++idx, postfix);
1664         } else if (flat) {
1665             snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1666                     prefix, postfix);
1667         } else {
1668             snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1669                     prefix, postfix);
1670         }
1671         snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1672                 path, desc_filename);
1673 
1674         if (vmdk_create_extent(ext_filename, size,
1675                                flat, compress, zeroed_grain)) {
1676             return -EINVAL;
1677         }
1678         filesize -= size;
1679 
1680         /* Format description line */
1681         snprintf(desc_line, sizeof(desc_line),
1682                     desc_extent_line, size / 512, desc_filename);
1683         pstrcat(ext_desc_lines, sizeof(ext_desc_lines), desc_line);
1684     }
1685     /* generate descriptor file */
1686     snprintf(desc, sizeof(desc), desc_template,
1687             (unsigned int)time(NULL),
1688             parent_cid,
1689             fmt,
1690             parent_desc_line,
1691             ext_desc_lines,
1692             (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1693             total_size / (int64_t)(63 * number_heads * 512), number_heads,
1694                 adapter_type);
1695     if (split || flat) {
1696         fd = qemu_open(filename,
1697                        O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1698                        0644);
1699     } else {
1700         fd = qemu_open(filename,
1701                        O_WRONLY | O_BINARY | O_LARGEFILE,
1702                        0644);
1703     }
1704     if (fd < 0) {
1705         return -errno;
1706     }
1707     /* the descriptor offset = 0x200 */
1708     if (!split && !flat && 0x200 != lseek(fd, 0x200, SEEK_SET)) {
1709         ret = -errno;
1710         goto exit;
1711     }
1712     ret = qemu_write_full(fd, desc, strlen(desc));
1713     if (ret != strlen(desc)) {
1714         ret = -errno;
1715         goto exit;
1716     }
1717     ret = 0;
1718 exit:
1719     qemu_close(fd);
1720     return ret;
1721 }
1722 
1723 static void vmdk_close(BlockDriverState *bs)
1724 {
1725     BDRVVmdkState *s = bs->opaque;
1726 
1727     vmdk_free_extents(bs);
1728 
1729     migrate_del_blocker(s->migration_blocker);
1730     error_free(s->migration_blocker);
1731 }
1732 
1733 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1734 {
1735     BDRVVmdkState *s = bs->opaque;
1736     int i, err;
1737     int ret = 0;
1738 
1739     for (i = 0; i < s->num_extents; i++) {
1740         err = bdrv_co_flush(s->extents[i].file);
1741         if (err < 0) {
1742             ret = err;
1743         }
1744     }
1745     return ret;
1746 }
1747 
1748 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
1749 {
1750     int i;
1751     int64_t ret = 0;
1752     int64_t r;
1753     BDRVVmdkState *s = bs->opaque;
1754 
1755     ret = bdrv_get_allocated_file_size(bs->file);
1756     if (ret < 0) {
1757         return ret;
1758     }
1759     for (i = 0; i < s->num_extents; i++) {
1760         if (s->extents[i].file == bs->file) {
1761             continue;
1762         }
1763         r = bdrv_get_allocated_file_size(s->extents[i].file);
1764         if (r < 0) {
1765             return r;
1766         }
1767         ret += r;
1768     }
1769     return ret;
1770 }
1771 
1772 static int vmdk_has_zero_init(BlockDriverState *bs)
1773 {
1774     int i;
1775     BDRVVmdkState *s = bs->opaque;
1776 
1777     /* If has a flat extent and its underlying storage doesn't have zero init,
1778      * return 0. */
1779     for (i = 0; i < s->num_extents; i++) {
1780         if (s->extents[i].flat) {
1781             if (!bdrv_has_zero_init(s->extents[i].file)) {
1782                 return 0;
1783             }
1784         }
1785     }
1786     return 1;
1787 }
1788 
1789 static QEMUOptionParameter vmdk_create_options[] = {
1790     {
1791         .name = BLOCK_OPT_SIZE,
1792         .type = OPT_SIZE,
1793         .help = "Virtual disk size"
1794     },
1795     {
1796         .name = BLOCK_OPT_ADAPTER_TYPE,
1797         .type = OPT_STRING,
1798         .help = "Virtual adapter type, can be one of "
1799                 "ide (default), lsilogic, buslogic or legacyESX"
1800     },
1801     {
1802         .name = BLOCK_OPT_BACKING_FILE,
1803         .type = OPT_STRING,
1804         .help = "File name of a base image"
1805     },
1806     {
1807         .name = BLOCK_OPT_COMPAT6,
1808         .type = OPT_FLAG,
1809         .help = "VMDK version 6 image"
1810     },
1811     {
1812         .name = BLOCK_OPT_SUBFMT,
1813         .type = OPT_STRING,
1814         .help =
1815             "VMDK flat extent format, can be one of "
1816             "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
1817     },
1818     {
1819         .name = BLOCK_OPT_ZEROED_GRAIN,
1820         .type = OPT_FLAG,
1821         .help = "Enable efficient zero writes using the zeroed-grain GTE feature"
1822     },
1823     { NULL }
1824 };
1825 
1826 static BlockDriver bdrv_vmdk = {
1827     .format_name                  = "vmdk",
1828     .instance_size                = sizeof(BDRVVmdkState),
1829     .bdrv_probe                   = vmdk_probe,
1830     .bdrv_open                    = vmdk_open,
1831     .bdrv_reopen_prepare          = vmdk_reopen_prepare,
1832     .bdrv_read                    = vmdk_co_read,
1833     .bdrv_write                   = vmdk_co_write,
1834     .bdrv_co_write_zeroes         = vmdk_co_write_zeroes,
1835     .bdrv_close                   = vmdk_close,
1836     .bdrv_create                  = vmdk_create,
1837     .bdrv_co_flush_to_disk        = vmdk_co_flush,
1838     .bdrv_co_is_allocated         = vmdk_co_is_allocated,
1839     .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
1840     .bdrv_has_zero_init           = vmdk_has_zero_init,
1841 
1842     .create_options               = vmdk_create_options,
1843 };
1844 
1845 static void bdrv_vmdk_init(void)
1846 {
1847     bdrv_register(&bdrv_vmdk);
1848 }
1849 
1850 block_init(bdrv_vmdk_init);
1851