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