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