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