]> git.proxmox.com Git - qemu.git/blob - block/vmdk.c
vmdk: check l1 size before opening image
[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 (l1_size > 512 * 1024 * 1024) {
601 /* although with big capacity and small l1_entry_sectors, we can get a
602 * big l1_size, we don't want unbounded value to allocate the table.
603 * Limit it to 512M, which is 16PB for default cluster and L2 table
604 * size */
605 error_report("L1 size too big");
606 return -EFBIG;
607 }
608 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
609 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
610 }
611 ret = vmdk_add_extent(bs, file, false,
612 le64_to_cpu(header.capacity),
613 le64_to_cpu(header.gd_offset) << 9,
614 l1_backup_offset,
615 l1_size,
616 le32_to_cpu(header.num_gtes_per_gte),
617 le64_to_cpu(header.granularity),
618 &extent);
619 if (ret < 0) {
620 return ret;
621 }
622 extent->compressed =
623 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
624 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
625 extent->version = le32_to_cpu(header.version);
626 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
627 ret = vmdk_init_tables(bs, extent);
628 if (ret) {
629 /* free extent allocated by vmdk_add_extent */
630 vmdk_free_last_extent(bs);
631 }
632 return ret;
633 }
634
635 /* find an option value out of descriptor file */
636 static int vmdk_parse_description(const char *desc, const char *opt_name,
637 char *buf, int buf_size)
638 {
639 char *opt_pos, *opt_end;
640 const char *end = desc + strlen(desc);
641
642 opt_pos = strstr(desc, opt_name);
643 if (!opt_pos) {
644 return VMDK_ERROR;
645 }
646 /* Skip "=\"" following opt_name */
647 opt_pos += strlen(opt_name) + 2;
648 if (opt_pos >= end) {
649 return VMDK_ERROR;
650 }
651 opt_end = opt_pos;
652 while (opt_end < end && *opt_end != '"') {
653 opt_end++;
654 }
655 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
656 return VMDK_ERROR;
657 }
658 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
659 return VMDK_OK;
660 }
661
662 /* Open an extent file and append to bs array */
663 static int vmdk_open_sparse(BlockDriverState *bs,
664 BlockDriverState *file,
665 int flags)
666 {
667 uint32_t magic;
668
669 if (bdrv_pread(file, 0, &magic, sizeof(magic)) != sizeof(magic)) {
670 return -EIO;
671 }
672
673 magic = be32_to_cpu(magic);
674 switch (magic) {
675 case VMDK3_MAGIC:
676 return vmdk_open_vmdk3(bs, file, flags);
677 break;
678 case VMDK4_MAGIC:
679 return vmdk_open_vmdk4(bs, file, flags);
680 break;
681 default:
682 return -EMEDIUMTYPE;
683 break;
684 }
685 }
686
687 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
688 const char *desc_file_path)
689 {
690 int ret;
691 char access[11];
692 char type[11];
693 char fname[512];
694 const char *p = desc;
695 int64_t sectors = 0;
696 int64_t flat_offset;
697 char extent_path[PATH_MAX];
698 BlockDriverState *extent_file;
699
700 while (*p) {
701 /* parse extent line:
702 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
703 * or
704 * RW [size in sectors] SPARSE "file-name.vmdk"
705 */
706 flat_offset = -1;
707 ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
708 access, &sectors, type, fname, &flat_offset);
709 if (ret < 4 || strcmp(access, "RW")) {
710 goto next_line;
711 } else if (!strcmp(type, "FLAT")) {
712 if (ret != 5 || flat_offset < 0) {
713 return -EINVAL;
714 }
715 } else if (ret != 4) {
716 return -EINVAL;
717 }
718
719 if (sectors <= 0 ||
720 (strcmp(type, "FLAT") && strcmp(type, "SPARSE")) ||
721 (strcmp(access, "RW"))) {
722 goto next_line;
723 }
724
725 path_combine(extent_path, sizeof(extent_path),
726 desc_file_path, fname);
727 ret = bdrv_file_open(&extent_file, extent_path, NULL, bs->open_flags);
728 if (ret) {
729 return ret;
730 }
731
732 /* save to extents array */
733 if (!strcmp(type, "FLAT")) {
734 /* FLAT extent */
735 VmdkExtent *extent;
736
737 ret = vmdk_add_extent(bs, extent_file, true, sectors,
738 0, 0, 0, 0, sectors, &extent);
739 if (ret < 0) {
740 return ret;
741 }
742 extent->flat_start_offset = flat_offset << 9;
743 } else if (!strcmp(type, "SPARSE")) {
744 /* SPARSE extent */
745 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags);
746 if (ret) {
747 bdrv_delete(extent_file);
748 return ret;
749 }
750 } else {
751 fprintf(stderr,
752 "VMDK: Not supported extent type \"%s\""".\n", type);
753 return -ENOTSUP;
754 }
755 next_line:
756 /* move to next line */
757 while (*p && *p != '\n') {
758 p++;
759 }
760 p++;
761 }
762 return 0;
763 }
764
765 static int vmdk_open_desc_file(BlockDriverState *bs, int flags,
766 uint64_t desc_offset)
767 {
768 int ret;
769 char *buf = NULL;
770 char ct[128];
771 BDRVVmdkState *s = bs->opaque;
772 int64_t size;
773
774 size = bdrv_getlength(bs->file);
775 if (size < 0) {
776 return -EINVAL;
777 }
778
779 size = MIN(size, 1 << 20); /* avoid unbounded allocation */
780 buf = g_malloc0(size + 1);
781
782 ret = bdrv_pread(bs->file, desc_offset, buf, size);
783 if (ret < 0) {
784 goto exit;
785 }
786 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
787 ret = -EMEDIUMTYPE;
788 goto exit;
789 }
790 if (strcmp(ct, "monolithicFlat") &&
791 strcmp(ct, "twoGbMaxExtentSparse") &&
792 strcmp(ct, "twoGbMaxExtentFlat")) {
793 fprintf(stderr,
794 "VMDK: Not supported image type \"%s\""".\n", ct);
795 ret = -ENOTSUP;
796 goto exit;
797 }
798 s->desc_offset = 0;
799 ret = vmdk_parse_extents(buf, bs, bs->file->filename);
800 exit:
801 g_free(buf);
802 return ret;
803 }
804
805 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags)
806 {
807 int ret;
808 BDRVVmdkState *s = bs->opaque;
809
810 if (vmdk_open_sparse(bs, bs->file, flags) == 0) {
811 s->desc_offset = 0x200;
812 } else {
813 ret = vmdk_open_desc_file(bs, flags, 0);
814 if (ret) {
815 goto fail;
816 }
817 }
818 /* try to open parent images, if exist */
819 ret = vmdk_parent_open(bs);
820 if (ret) {
821 goto fail;
822 }
823 s->parent_cid = vmdk_read_cid(bs, 1);
824 qemu_co_mutex_init(&s->lock);
825
826 /* Disable migration when VMDK images are used */
827 error_set(&s->migration_blocker,
828 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
829 "vmdk", bs->device_name, "live migration");
830 migrate_add_blocker(s->migration_blocker);
831
832 return 0;
833
834 fail:
835 vmdk_free_extents(bs);
836 return ret;
837 }
838
839 static int get_whole_cluster(BlockDriverState *bs,
840 VmdkExtent *extent,
841 uint64_t cluster_offset,
842 uint64_t offset,
843 bool allocate)
844 {
845 /* 128 sectors * 512 bytes each = grain size 64KB */
846 uint8_t whole_grain[extent->cluster_sectors * 512];
847
848 /* we will be here if it's first write on non-exist grain(cluster).
849 * try to read from parent image, if exist */
850 if (bs->backing_hd) {
851 int ret;
852
853 if (!vmdk_is_cid_valid(bs)) {
854 return VMDK_ERROR;
855 }
856
857 /* floor offset to cluster */
858 offset -= offset % (extent->cluster_sectors * 512);
859 ret = bdrv_read(bs->backing_hd, offset >> 9, whole_grain,
860 extent->cluster_sectors);
861 if (ret < 0) {
862 return VMDK_ERROR;
863 }
864
865 /* Write grain only into the active image */
866 ret = bdrv_write(extent->file, cluster_offset, whole_grain,
867 extent->cluster_sectors);
868 if (ret < 0) {
869 return VMDK_ERROR;
870 }
871 }
872 return VMDK_OK;
873 }
874
875 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data)
876 {
877 uint32_t offset;
878 QEMU_BUILD_BUG_ON(sizeof(offset) != sizeof(m_data->offset));
879 offset = cpu_to_le32(m_data->offset);
880 /* update L2 table */
881 if (bdrv_pwrite_sync(
882 extent->file,
883 ((int64_t)m_data->l2_offset * 512)
884 + (m_data->l2_index * sizeof(m_data->offset)),
885 &offset, sizeof(offset)) < 0) {
886 return VMDK_ERROR;
887 }
888 /* update backup L2 table */
889 if (extent->l1_backup_table_offset != 0) {
890 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
891 if (bdrv_pwrite_sync(
892 extent->file,
893 ((int64_t)m_data->l2_offset * 512)
894 + (m_data->l2_index * sizeof(m_data->offset)),
895 &offset, sizeof(offset)) < 0) {
896 return VMDK_ERROR;
897 }
898 }
899 if (m_data->l2_cache_entry) {
900 *m_data->l2_cache_entry = offset;
901 }
902
903 return VMDK_OK;
904 }
905
906 static int get_cluster_offset(BlockDriverState *bs,
907 VmdkExtent *extent,
908 VmdkMetaData *m_data,
909 uint64_t offset,
910 int allocate,
911 uint64_t *cluster_offset)
912 {
913 unsigned int l1_index, l2_offset, l2_index;
914 int min_index, i, j;
915 uint32_t min_count, *l2_table;
916 bool zeroed = false;
917
918 if (m_data) {
919 m_data->valid = 0;
920 }
921 if (extent->flat) {
922 *cluster_offset = extent->flat_start_offset;
923 return VMDK_OK;
924 }
925
926 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
927 l1_index = (offset >> 9) / extent->l1_entry_sectors;
928 if (l1_index >= extent->l1_size) {
929 return VMDK_ERROR;
930 }
931 l2_offset = extent->l1_table[l1_index];
932 if (!l2_offset) {
933 return VMDK_UNALLOC;
934 }
935 for (i = 0; i < L2_CACHE_SIZE; i++) {
936 if (l2_offset == extent->l2_cache_offsets[i]) {
937 /* increment the hit count */
938 if (++extent->l2_cache_counts[i] == 0xffffffff) {
939 for (j = 0; j < L2_CACHE_SIZE; j++) {
940 extent->l2_cache_counts[j] >>= 1;
941 }
942 }
943 l2_table = extent->l2_cache + (i * extent->l2_size);
944 goto found;
945 }
946 }
947 /* not found: load a new entry in the least used one */
948 min_index = 0;
949 min_count = 0xffffffff;
950 for (i = 0; i < L2_CACHE_SIZE; i++) {
951 if (extent->l2_cache_counts[i] < min_count) {
952 min_count = extent->l2_cache_counts[i];
953 min_index = i;
954 }
955 }
956 l2_table = extent->l2_cache + (min_index * extent->l2_size);
957 if (bdrv_pread(
958 extent->file,
959 (int64_t)l2_offset * 512,
960 l2_table,
961 extent->l2_size * sizeof(uint32_t)
962 ) != extent->l2_size * sizeof(uint32_t)) {
963 return VMDK_ERROR;
964 }
965
966 extent->l2_cache_offsets[min_index] = l2_offset;
967 extent->l2_cache_counts[min_index] = 1;
968 found:
969 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
970 *cluster_offset = le32_to_cpu(l2_table[l2_index]);
971
972 if (m_data) {
973 m_data->valid = 1;
974 m_data->l1_index = l1_index;
975 m_data->l2_index = l2_index;
976 m_data->offset = *cluster_offset;
977 m_data->l2_offset = l2_offset;
978 m_data->l2_cache_entry = &l2_table[l2_index];
979 }
980 if (extent->has_zero_grain && *cluster_offset == VMDK_GTE_ZEROED) {
981 zeroed = true;
982 }
983
984 if (!*cluster_offset || zeroed) {
985 if (!allocate) {
986 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
987 }
988
989 /* Avoid the L2 tables update for the images that have snapshots. */
990 *cluster_offset = bdrv_getlength(extent->file);
991 if (!extent->compressed) {
992 bdrv_truncate(
993 extent->file,
994 *cluster_offset + (extent->cluster_sectors << 9)
995 );
996 }
997
998 *cluster_offset >>= 9;
999 l2_table[l2_index] = cpu_to_le32(*cluster_offset);
1000
1001 /* First of all we write grain itself, to avoid race condition
1002 * that may to corrupt the image.
1003 * This problem may occur because of insufficient space on host disk
1004 * or inappropriate VM shutdown.
1005 */
1006 if (get_whole_cluster(
1007 bs, extent, *cluster_offset, offset, allocate) == -1) {
1008 return VMDK_ERROR;
1009 }
1010
1011 if (m_data) {
1012 m_data->offset = *cluster_offset;
1013 }
1014 }
1015 *cluster_offset <<= 9;
1016 return VMDK_OK;
1017 }
1018
1019 static VmdkExtent *find_extent(BDRVVmdkState *s,
1020 int64_t sector_num, VmdkExtent *start_hint)
1021 {
1022 VmdkExtent *extent = start_hint;
1023
1024 if (!extent) {
1025 extent = &s->extents[0];
1026 }
1027 while (extent < &s->extents[s->num_extents]) {
1028 if (sector_num < extent->end_sector) {
1029 return extent;
1030 }
1031 extent++;
1032 }
1033 return NULL;
1034 }
1035
1036 static int coroutine_fn vmdk_co_is_allocated(BlockDriverState *bs,
1037 int64_t sector_num, int nb_sectors, int *pnum)
1038 {
1039 BDRVVmdkState *s = bs->opaque;
1040 int64_t index_in_cluster, n, ret;
1041 uint64_t offset;
1042 VmdkExtent *extent;
1043
1044 extent = find_extent(s, sector_num, NULL);
1045 if (!extent) {
1046 return 0;
1047 }
1048 qemu_co_mutex_lock(&s->lock);
1049 ret = get_cluster_offset(bs, extent, NULL,
1050 sector_num * 512, 0, &offset);
1051 qemu_co_mutex_unlock(&s->lock);
1052
1053 ret = (ret == VMDK_OK || ret == VMDK_ZEROED);
1054
1055 index_in_cluster = sector_num % extent->cluster_sectors;
1056 n = extent->cluster_sectors - index_in_cluster;
1057 if (n > nb_sectors) {
1058 n = nb_sectors;
1059 }
1060 *pnum = n;
1061 return ret;
1062 }
1063
1064 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1065 int64_t offset_in_cluster, const uint8_t *buf,
1066 int nb_sectors, int64_t sector_num)
1067 {
1068 int ret;
1069 VmdkGrainMarker *data = NULL;
1070 uLongf buf_len;
1071 const uint8_t *write_buf = buf;
1072 int write_len = nb_sectors * 512;
1073
1074 if (extent->compressed) {
1075 if (!extent->has_marker) {
1076 ret = -EINVAL;
1077 goto out;
1078 }
1079 buf_len = (extent->cluster_sectors << 9) * 2;
1080 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1081 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1082 buf_len == 0) {
1083 ret = -EINVAL;
1084 goto out;
1085 }
1086 data->lba = sector_num;
1087 data->size = buf_len;
1088 write_buf = (uint8_t *)data;
1089 write_len = buf_len + sizeof(VmdkGrainMarker);
1090 }
1091 ret = bdrv_pwrite(extent->file,
1092 cluster_offset + offset_in_cluster,
1093 write_buf,
1094 write_len);
1095 if (ret != write_len) {
1096 ret = ret < 0 ? ret : -EIO;
1097 goto out;
1098 }
1099 ret = 0;
1100 out:
1101 g_free(data);
1102 return ret;
1103 }
1104
1105 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1106 int64_t offset_in_cluster, uint8_t *buf,
1107 int nb_sectors)
1108 {
1109 int ret;
1110 int cluster_bytes, buf_bytes;
1111 uint8_t *cluster_buf, *compressed_data;
1112 uint8_t *uncomp_buf;
1113 uint32_t data_len;
1114 VmdkGrainMarker *marker;
1115 uLongf buf_len;
1116
1117
1118 if (!extent->compressed) {
1119 ret = bdrv_pread(extent->file,
1120 cluster_offset + offset_in_cluster,
1121 buf, nb_sectors * 512);
1122 if (ret == nb_sectors * 512) {
1123 return 0;
1124 } else {
1125 return -EIO;
1126 }
1127 }
1128 cluster_bytes = extent->cluster_sectors * 512;
1129 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1130 buf_bytes = cluster_bytes * 2;
1131 cluster_buf = g_malloc(buf_bytes);
1132 uncomp_buf = g_malloc(cluster_bytes);
1133 ret = bdrv_pread(extent->file,
1134 cluster_offset,
1135 cluster_buf, buf_bytes);
1136 if (ret < 0) {
1137 goto out;
1138 }
1139 compressed_data = cluster_buf;
1140 buf_len = cluster_bytes;
1141 data_len = cluster_bytes;
1142 if (extent->has_marker) {
1143 marker = (VmdkGrainMarker *)cluster_buf;
1144 compressed_data = marker->data;
1145 data_len = le32_to_cpu(marker->size);
1146 }
1147 if (!data_len || data_len > buf_bytes) {
1148 ret = -EINVAL;
1149 goto out;
1150 }
1151 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1152 if (ret != Z_OK) {
1153 ret = -EINVAL;
1154 goto out;
1155
1156 }
1157 if (offset_in_cluster < 0 ||
1158 offset_in_cluster + nb_sectors * 512 > buf_len) {
1159 ret = -EINVAL;
1160 goto out;
1161 }
1162 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1163 ret = 0;
1164
1165 out:
1166 g_free(uncomp_buf);
1167 g_free(cluster_buf);
1168 return ret;
1169 }
1170
1171 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1172 uint8_t *buf, int nb_sectors)
1173 {
1174 BDRVVmdkState *s = bs->opaque;
1175 int ret;
1176 uint64_t n, index_in_cluster;
1177 uint64_t extent_begin_sector, extent_relative_sector_num;
1178 VmdkExtent *extent = NULL;
1179 uint64_t cluster_offset;
1180
1181 while (nb_sectors > 0) {
1182 extent = find_extent(s, sector_num, extent);
1183 if (!extent) {
1184 return -EIO;
1185 }
1186 ret = get_cluster_offset(
1187 bs, extent, NULL,
1188 sector_num << 9, 0, &cluster_offset);
1189 extent_begin_sector = extent->end_sector - extent->sectors;
1190 extent_relative_sector_num = sector_num - extent_begin_sector;
1191 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1192 n = extent->cluster_sectors - index_in_cluster;
1193 if (n > nb_sectors) {
1194 n = nb_sectors;
1195 }
1196 if (ret != VMDK_OK) {
1197 /* if not allocated, try to read from parent image, if exist */
1198 if (bs->backing_hd && ret != VMDK_ZEROED) {
1199 if (!vmdk_is_cid_valid(bs)) {
1200 return -EINVAL;
1201 }
1202 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1203 if (ret < 0) {
1204 return ret;
1205 }
1206 } else {
1207 memset(buf, 0, 512 * n);
1208 }
1209 } else {
1210 ret = vmdk_read_extent(extent,
1211 cluster_offset, index_in_cluster * 512,
1212 buf, n);
1213 if (ret) {
1214 return ret;
1215 }
1216 }
1217 nb_sectors -= n;
1218 sector_num += n;
1219 buf += n * 512;
1220 }
1221 return 0;
1222 }
1223
1224 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1225 uint8_t *buf, int nb_sectors)
1226 {
1227 int ret;
1228 BDRVVmdkState *s = bs->opaque;
1229 qemu_co_mutex_lock(&s->lock);
1230 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1231 qemu_co_mutex_unlock(&s->lock);
1232 return ret;
1233 }
1234
1235 /**
1236 * vmdk_write:
1237 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1238 * if possible, otherwise return -ENOTSUP.
1239 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1240 * with each cluster. By dry run we can find if the zero write
1241 * is possible without modifying image data.
1242 *
1243 * Returns: error code with 0 for success.
1244 */
1245 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1246 const uint8_t *buf, int nb_sectors,
1247 bool zeroed, bool zero_dry_run)
1248 {
1249 BDRVVmdkState *s = bs->opaque;
1250 VmdkExtent *extent = NULL;
1251 int n, ret;
1252 int64_t index_in_cluster;
1253 uint64_t extent_begin_sector, extent_relative_sector_num;
1254 uint64_t cluster_offset;
1255 VmdkMetaData m_data;
1256
1257 if (sector_num > bs->total_sectors) {
1258 fprintf(stderr,
1259 "(VMDK) Wrong offset: sector_num=0x%" PRIx64
1260 " total_sectors=0x%" PRIx64 "\n",
1261 sector_num, bs->total_sectors);
1262 return -EIO;
1263 }
1264
1265 while (nb_sectors > 0) {
1266 extent = find_extent(s, sector_num, extent);
1267 if (!extent) {
1268 return -EIO;
1269 }
1270 ret = get_cluster_offset(
1271 bs,
1272 extent,
1273 &m_data,
1274 sector_num << 9, !extent->compressed,
1275 &cluster_offset);
1276 if (extent->compressed) {
1277 if (ret == VMDK_OK) {
1278 /* Refuse write to allocated cluster for streamOptimized */
1279 fprintf(stderr,
1280 "VMDK: can't write to allocated cluster"
1281 " for streamOptimized\n");
1282 return -EIO;
1283 } else {
1284 /* allocate */
1285 ret = get_cluster_offset(
1286 bs,
1287 extent,
1288 &m_data,
1289 sector_num << 9, 1,
1290 &cluster_offset);
1291 }
1292 }
1293 if (ret == VMDK_ERROR) {
1294 return -EINVAL;
1295 }
1296 extent_begin_sector = extent->end_sector - extent->sectors;
1297 extent_relative_sector_num = sector_num - extent_begin_sector;
1298 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1299 n = extent->cluster_sectors - index_in_cluster;
1300 if (n > nb_sectors) {
1301 n = nb_sectors;
1302 }
1303 if (zeroed) {
1304 /* Do zeroed write, buf is ignored */
1305 if (extent->has_zero_grain &&
1306 index_in_cluster == 0 &&
1307 n >= extent->cluster_sectors) {
1308 n = extent->cluster_sectors;
1309 if (!zero_dry_run) {
1310 m_data.offset = VMDK_GTE_ZEROED;
1311 /* update L2 tables */
1312 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1313 return -EIO;
1314 }
1315 }
1316 } else {
1317 return -ENOTSUP;
1318 }
1319 } else {
1320 ret = vmdk_write_extent(extent,
1321 cluster_offset, index_in_cluster * 512,
1322 buf, n, sector_num);
1323 if (ret) {
1324 return ret;
1325 }
1326 if (m_data.valid) {
1327 /* update L2 tables */
1328 if (vmdk_L2update(extent, &m_data) != VMDK_OK) {
1329 return -EIO;
1330 }
1331 }
1332 }
1333 nb_sectors -= n;
1334 sector_num += n;
1335 buf += n * 512;
1336
1337 /* update CID on the first write every time the virtual disk is
1338 * opened */
1339 if (!s->cid_updated) {
1340 ret = vmdk_write_cid(bs, time(NULL));
1341 if (ret < 0) {
1342 return ret;
1343 }
1344 s->cid_updated = true;
1345 }
1346 }
1347 return 0;
1348 }
1349
1350 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1351 const uint8_t *buf, int nb_sectors)
1352 {
1353 int ret;
1354 BDRVVmdkState *s = bs->opaque;
1355 qemu_co_mutex_lock(&s->lock);
1356 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1357 qemu_co_mutex_unlock(&s->lock);
1358 return ret;
1359 }
1360
1361 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1362 int64_t sector_num,
1363 int nb_sectors)
1364 {
1365 int ret;
1366 BDRVVmdkState *s = bs->opaque;
1367 qemu_co_mutex_lock(&s->lock);
1368 /* write zeroes could fail if sectors not aligned to cluster, test it with
1369 * dry_run == true before really updating image */
1370 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1371 if (!ret) {
1372 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1373 }
1374 qemu_co_mutex_unlock(&s->lock);
1375 return ret;
1376 }
1377
1378
1379 static int vmdk_create_extent(const char *filename, int64_t filesize,
1380 bool flat, bool compress, bool zeroed_grain)
1381 {
1382 int ret, i;
1383 int fd = 0;
1384 VMDK4Header header;
1385 uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
1386
1387 fd = qemu_open(filename,
1388 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1389 0644);
1390 if (fd < 0) {
1391 return -errno;
1392 }
1393 if (flat) {
1394 ret = ftruncate(fd, filesize);
1395 if (ret < 0) {
1396 ret = -errno;
1397 }
1398 goto exit;
1399 }
1400 magic = cpu_to_be32(VMDK4_MAGIC);
1401 memset(&header, 0, sizeof(header));
1402 header.version = zeroed_grain ? 2 : 1;
1403 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1404 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1405 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1406 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1407 header.capacity = filesize / 512;
1408 header.granularity = 128;
1409 header.num_gtes_per_gte = 512;
1410
1411 grains = (filesize / 512 + header.granularity - 1) / header.granularity;
1412 gt_size = ((header.num_gtes_per_gte * sizeof(uint32_t)) + 511) >> 9;
1413 gt_count =
1414 (grains + header.num_gtes_per_gte - 1) / header.num_gtes_per_gte;
1415 gd_size = (gt_count * sizeof(uint32_t) + 511) >> 9;
1416
1417 header.desc_offset = 1;
1418 header.desc_size = 20;
1419 header.rgd_offset = header.desc_offset + header.desc_size;
1420 header.gd_offset = header.rgd_offset + gd_size + (gt_size * gt_count);
1421 header.grain_offset =
1422 ((header.gd_offset + gd_size + (gt_size * gt_count) +
1423 header.granularity - 1) / header.granularity) *
1424 header.granularity;
1425 /* swap endianness for all header fields */
1426 header.version = cpu_to_le32(header.version);
1427 header.flags = cpu_to_le32(header.flags);
1428 header.capacity = cpu_to_le64(header.capacity);
1429 header.granularity = cpu_to_le64(header.granularity);
1430 header.num_gtes_per_gte = cpu_to_le32(header.num_gtes_per_gte);
1431 header.desc_offset = cpu_to_le64(header.desc_offset);
1432 header.desc_size = cpu_to_le64(header.desc_size);
1433 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1434 header.gd_offset = cpu_to_le64(header.gd_offset);
1435 header.grain_offset = cpu_to_le64(header.grain_offset);
1436 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1437
1438 header.check_bytes[0] = 0xa;
1439 header.check_bytes[1] = 0x20;
1440 header.check_bytes[2] = 0xd;
1441 header.check_bytes[3] = 0xa;
1442
1443 /* write all the data */
1444 ret = qemu_write_full(fd, &magic, sizeof(magic));
1445 if (ret != sizeof(magic)) {
1446 ret = -errno;
1447 goto exit;
1448 }
1449 ret = qemu_write_full(fd, &header, sizeof(header));
1450 if (ret != sizeof(header)) {
1451 ret = -errno;
1452 goto exit;
1453 }
1454
1455 ret = ftruncate(fd, le64_to_cpu(header.grain_offset) << 9);
1456 if (ret < 0) {
1457 ret = -errno;
1458 goto exit;
1459 }
1460
1461 /* write grain directory */
1462 lseek(fd, le64_to_cpu(header.rgd_offset) << 9, SEEK_SET);
1463 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_size;
1464 i < gt_count; i++, tmp += gt_size) {
1465 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1466 if (ret != sizeof(tmp)) {
1467 ret = -errno;
1468 goto exit;
1469 }
1470 }
1471
1472 /* write backup grain directory */
1473 lseek(fd, le64_to_cpu(header.gd_offset) << 9, SEEK_SET);
1474 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_size;
1475 i < gt_count; i++, tmp += gt_size) {
1476 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1477 if (ret != sizeof(tmp)) {
1478 ret = -errno;
1479 goto exit;
1480 }
1481 }
1482
1483 ret = 0;
1484 exit:
1485 qemu_close(fd);
1486 return ret;
1487 }
1488
1489 static int filename_decompose(const char *filename, char *path, char *prefix,
1490 char *postfix, size_t buf_len)
1491 {
1492 const char *p, *q;
1493
1494 if (filename == NULL || !strlen(filename)) {
1495 fprintf(stderr, "Vmdk: no filename provided.\n");
1496 return VMDK_ERROR;
1497 }
1498 p = strrchr(filename, '/');
1499 if (p == NULL) {
1500 p = strrchr(filename, '\\');
1501 }
1502 if (p == NULL) {
1503 p = strrchr(filename, ':');
1504 }
1505 if (p != NULL) {
1506 p++;
1507 if (p - filename >= buf_len) {
1508 return VMDK_ERROR;
1509 }
1510 pstrcpy(path, p - filename + 1, filename);
1511 } else {
1512 p = filename;
1513 path[0] = '\0';
1514 }
1515 q = strrchr(p, '.');
1516 if (q == NULL) {
1517 pstrcpy(prefix, buf_len, p);
1518 postfix[0] = '\0';
1519 } else {
1520 if (q - p >= buf_len) {
1521 return VMDK_ERROR;
1522 }
1523 pstrcpy(prefix, q - p + 1, p);
1524 pstrcpy(postfix, buf_len, q);
1525 }
1526 return VMDK_OK;
1527 }
1528
1529 static int vmdk_create(const char *filename, QEMUOptionParameter *options)
1530 {
1531 int fd, idx = 0;
1532 char desc[BUF_SIZE];
1533 int64_t total_size = 0, filesize;
1534 const char *adapter_type = NULL;
1535 const char *backing_file = NULL;
1536 const char *fmt = NULL;
1537 int flags = 0;
1538 int ret = 0;
1539 bool flat, split, compress;
1540 char ext_desc_lines[BUF_SIZE] = "";
1541 char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];
1542 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1543 const char *desc_extent_line;
1544 char parent_desc_line[BUF_SIZE] = "";
1545 uint32_t parent_cid = 0xffffffff;
1546 uint32_t number_heads = 16;
1547 bool zeroed_grain = false;
1548 const char desc_template[] =
1549 "# Disk DescriptorFile\n"
1550 "version=1\n"
1551 "CID=%x\n"
1552 "parentCID=%x\n"
1553 "createType=\"%s\"\n"
1554 "%s"
1555 "\n"
1556 "# Extent description\n"
1557 "%s"
1558 "\n"
1559 "# The Disk Data Base\n"
1560 "#DDB\n"
1561 "\n"
1562 "ddb.virtualHWVersion = \"%d\"\n"
1563 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1564 "ddb.geometry.heads = \"%d\"\n"
1565 "ddb.geometry.sectors = \"63\"\n"
1566 "ddb.adapterType = \"%s\"\n";
1567
1568 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX)) {
1569 return -EINVAL;
1570 }
1571 /* Read out options */
1572 while (options && options->name) {
1573 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1574 total_size = options->value.n;
1575 } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {
1576 adapter_type = options->value.s;
1577 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1578 backing_file = options->value.s;
1579 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
1580 flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;
1581 } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {
1582 fmt = options->value.s;
1583 } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {
1584 zeroed_grain |= options->value.n;
1585 }
1586 options++;
1587 }
1588 if (!adapter_type) {
1589 adapter_type = "ide";
1590 } else if (strcmp(adapter_type, "ide") &&
1591 strcmp(adapter_type, "buslogic") &&
1592 strcmp(adapter_type, "lsilogic") &&
1593 strcmp(adapter_type, "legacyESX")) {
1594 fprintf(stderr, "VMDK: Unknown adapter type: '%s'.\n", adapter_type);
1595 return -EINVAL;
1596 }
1597 if (strcmp(adapter_type, "ide") != 0) {
1598 /* that's the number of heads with which vmware operates when
1599 creating, exporting, etc. vmdk files with a non-ide adapter type */
1600 number_heads = 255;
1601 }
1602 if (!fmt) {
1603 /* Default format to monolithicSparse */
1604 fmt = "monolithicSparse";
1605 } else if (strcmp(fmt, "monolithicFlat") &&
1606 strcmp(fmt, "monolithicSparse") &&
1607 strcmp(fmt, "twoGbMaxExtentSparse") &&
1608 strcmp(fmt, "twoGbMaxExtentFlat") &&
1609 strcmp(fmt, "streamOptimized")) {
1610 fprintf(stderr, "VMDK: Unknown subformat: %s\n", fmt);
1611 return -EINVAL;
1612 }
1613 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1614 strcmp(fmt, "twoGbMaxExtentSparse"));
1615 flat = !(strcmp(fmt, "monolithicFlat") &&
1616 strcmp(fmt, "twoGbMaxExtentFlat"));
1617 compress = !strcmp(fmt, "streamOptimized");
1618 if (flat) {
1619 desc_extent_line = "RW %lld FLAT \"%s\" 0\n";
1620 } else {
1621 desc_extent_line = "RW %lld SPARSE \"%s\"\n";
1622 }
1623 if (flat && backing_file) {
1624 /* not supporting backing file for flat image */
1625 return -ENOTSUP;
1626 }
1627 if (backing_file) {
1628 BlockDriverState *bs = bdrv_new("");
1629 ret = bdrv_open(bs, backing_file, NULL, 0, NULL);
1630 if (ret != 0) {
1631 bdrv_delete(bs);
1632 return ret;
1633 }
1634 if (strcmp(bs->drv->format_name, "vmdk")) {
1635 bdrv_delete(bs);
1636 return -EINVAL;
1637 }
1638 parent_cid = vmdk_read_cid(bs, 0);
1639 bdrv_delete(bs);
1640 snprintf(parent_desc_line, sizeof(parent_desc_line),
1641 "parentFileNameHint=\"%s\"", backing_file);
1642 }
1643
1644 /* Create extents */
1645 filesize = total_size;
1646 while (filesize > 0) {
1647 char desc_line[BUF_SIZE];
1648 char ext_filename[PATH_MAX];
1649 char desc_filename[PATH_MAX];
1650 int64_t size = filesize;
1651
1652 if (split && size > split_size) {
1653 size = split_size;
1654 }
1655 if (split) {
1656 snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",
1657 prefix, flat ? 'f' : 's', ++idx, postfix);
1658 } else if (flat) {
1659 snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",
1660 prefix, postfix);
1661 } else {
1662 snprintf(desc_filename, sizeof(desc_filename), "%s%s",
1663 prefix, postfix);
1664 }
1665 snprintf(ext_filename, sizeof(ext_filename), "%s%s",
1666 path, desc_filename);
1667
1668 if (vmdk_create_extent(ext_filename, size,
1669 flat, compress, zeroed_grain)) {
1670 return -EINVAL;
1671 }
1672 filesize -= size;
1673
1674 /* Format description line */
1675 snprintf(desc_line, sizeof(desc_line),
1676 desc_extent_line, size / 512, desc_filename);
1677 pstrcat(ext_desc_lines, sizeof(ext_desc_lines), desc_line);
1678 }
1679 /* generate descriptor file */
1680 snprintf(desc, sizeof(desc), desc_template,
1681 (unsigned int)time(NULL),
1682 parent_cid,
1683 fmt,
1684 parent_desc_line,
1685 ext_desc_lines,
1686 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1687 total_size / (int64_t)(63 * number_heads * 512), number_heads,
1688 adapter_type);
1689 if (split || flat) {
1690 fd = qemu_open(filename,
1691 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
1692 0644);
1693 } else {
1694 fd = qemu_open(filename,
1695 O_WRONLY | O_BINARY | O_LARGEFILE,
1696 0644);
1697 }
1698 if (fd < 0) {
1699 return -errno;
1700 }
1701 /* the descriptor offset = 0x200 */
1702 if (!split && !flat && 0x200 != lseek(fd, 0x200, SEEK_SET)) {
1703 ret = -errno;
1704 goto exit;
1705 }
1706 ret = qemu_write_full(fd, desc, strlen(desc));
1707 if (ret != strlen(desc)) {
1708 ret = -errno;
1709 goto exit;
1710 }
1711 ret = 0;
1712 exit:
1713 qemu_close(fd);
1714 return ret;
1715 }
1716
1717 static void vmdk_close(BlockDriverState *bs)
1718 {
1719 BDRVVmdkState *s = bs->opaque;
1720
1721 vmdk_free_extents(bs);
1722
1723 migrate_del_blocker(s->migration_blocker);
1724 error_free(s->migration_blocker);
1725 }
1726
1727 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
1728 {
1729 BDRVVmdkState *s = bs->opaque;
1730 int i, err;
1731 int ret = 0;
1732
1733 for (i = 0; i < s->num_extents; i++) {
1734 err = bdrv_co_flush(s->extents[i].file);
1735 if (err < 0) {
1736 ret = err;
1737 }
1738 }
1739 return ret;
1740 }
1741
1742 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
1743 {
1744 int i;
1745 int64_t ret = 0;
1746 int64_t r;
1747 BDRVVmdkState *s = bs->opaque;
1748
1749 ret = bdrv_get_allocated_file_size(bs->file);
1750 if (ret < 0) {
1751 return ret;
1752 }
1753 for (i = 0; i < s->num_extents; i++) {
1754 if (s->extents[i].file == bs->file) {
1755 continue;
1756 }
1757 r = bdrv_get_allocated_file_size(s->extents[i].file);
1758 if (r < 0) {
1759 return r;
1760 }
1761 ret += r;
1762 }
1763 return ret;
1764 }
1765
1766 static int vmdk_has_zero_init(BlockDriverState *bs)
1767 {
1768 int i;
1769 BDRVVmdkState *s = bs->opaque;
1770
1771 /* If has a flat extent and its underlying storage doesn't have zero init,
1772 * return 0. */
1773 for (i = 0; i < s->num_extents; i++) {
1774 if (s->extents[i].flat) {
1775 if (!bdrv_has_zero_init(s->extents[i].file)) {
1776 return 0;
1777 }
1778 }
1779 }
1780 return 1;
1781 }
1782
1783 static QEMUOptionParameter vmdk_create_options[] = {
1784 {
1785 .name = BLOCK_OPT_SIZE,
1786 .type = OPT_SIZE,
1787 .help = "Virtual disk size"
1788 },
1789 {
1790 .name = BLOCK_OPT_ADAPTER_TYPE,
1791 .type = OPT_STRING,
1792 .help = "Virtual adapter type, can be one of "
1793 "ide (default), lsilogic, buslogic or legacyESX"
1794 },
1795 {
1796 .name = BLOCK_OPT_BACKING_FILE,
1797 .type = OPT_STRING,
1798 .help = "File name of a base image"
1799 },
1800 {
1801 .name = BLOCK_OPT_COMPAT6,
1802 .type = OPT_FLAG,
1803 .help = "VMDK version 6 image"
1804 },
1805 {
1806 .name = BLOCK_OPT_SUBFMT,
1807 .type = OPT_STRING,
1808 .help =
1809 "VMDK flat extent format, can be one of "
1810 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
1811 },
1812 {
1813 .name = BLOCK_OPT_ZEROED_GRAIN,
1814 .type = OPT_FLAG,
1815 .help = "Enable efficient zero writes using the zeroed-grain GTE feature"
1816 },
1817 { NULL }
1818 };
1819
1820 static BlockDriver bdrv_vmdk = {
1821 .format_name = "vmdk",
1822 .instance_size = sizeof(BDRVVmdkState),
1823 .bdrv_probe = vmdk_probe,
1824 .bdrv_open = vmdk_open,
1825 .bdrv_reopen_prepare = vmdk_reopen_prepare,
1826 .bdrv_read = vmdk_co_read,
1827 .bdrv_write = vmdk_co_write,
1828 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
1829 .bdrv_close = vmdk_close,
1830 .bdrv_create = vmdk_create,
1831 .bdrv_co_flush_to_disk = vmdk_co_flush,
1832 .bdrv_co_is_allocated = vmdk_co_is_allocated,
1833 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
1834 .bdrv_has_zero_init = vmdk_has_zero_init,
1835
1836 .create_options = vmdk_create_options,
1837 };
1838
1839 static void bdrv_vmdk_init(void)
1840 {
1841 bdrv_register(&bdrv_vmdk);
1842 }
1843
1844 block_init(bdrv_vmdk_init);