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