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