]> git.proxmox.com Git - mirror_qemu.git/blob - block/vmdk.c
vmdk: Use bdrv_open_image()
[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 #include <glib.h>
32
33 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
34 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
35 #define VMDK4_COMPRESSION_DEFLATE 1
36 #define VMDK4_FLAG_NL_DETECT (1 << 0)
37 #define VMDK4_FLAG_RGD (1 << 1)
38 /* Zeroed-grain enable bit */
39 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2)
40 #define VMDK4_FLAG_COMPRESS (1 << 16)
41 #define VMDK4_FLAG_MARKER (1 << 17)
42 #define VMDK4_GD_AT_END 0xffffffffffffffffULL
43
44 #define VMDK_GTE_ZEROED 0x1
45
46 /* VMDK internal error codes */
47 #define VMDK_OK 0
48 #define VMDK_ERROR (-1)
49 /* Cluster not allocated */
50 #define VMDK_UNALLOC (-2)
51 #define VMDK_ZEROED (-3)
52
53 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain"
54
55 typedef struct {
56 uint32_t version;
57 uint32_t flags;
58 uint32_t disk_sectors;
59 uint32_t granularity;
60 uint32_t l1dir_offset;
61 uint32_t l1dir_size;
62 uint32_t file_sectors;
63 uint32_t cylinders;
64 uint32_t heads;
65 uint32_t sectors_per_track;
66 } QEMU_PACKED VMDK3Header;
67
68 typedef struct {
69 uint32_t version;
70 uint32_t flags;
71 uint64_t capacity;
72 uint64_t granularity;
73 uint64_t desc_offset;
74 uint64_t desc_size;
75 /* Number of GrainTableEntries per GrainTable */
76 uint32_t num_gtes_per_gt;
77 uint64_t rgd_offset;
78 uint64_t gd_offset;
79 uint64_t grain_offset;
80 char filler[1];
81 char check_bytes[4];
82 uint16_t compressAlgorithm;
83 } QEMU_PACKED VMDK4Header;
84
85 #define L2_CACHE_SIZE 16
86
87 typedef struct VmdkExtent {
88 BlockDriverState *file;
89 bool flat;
90 bool compressed;
91 bool has_marker;
92 bool has_zero_grain;
93 int version;
94 int64_t sectors;
95 int64_t end_sector;
96 int64_t flat_start_offset;
97 int64_t l1_table_offset;
98 int64_t l1_backup_table_offset;
99 uint32_t *l1_table;
100 uint32_t *l1_backup_table;
101 unsigned int l1_size;
102 uint32_t l1_entry_sectors;
103
104 unsigned int l2_size;
105 uint32_t *l2_cache;
106 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
107 uint32_t l2_cache_counts[L2_CACHE_SIZE];
108
109 int64_t cluster_sectors;
110 int64_t next_cluster_sector;
111 char *type;
112 } VmdkExtent;
113
114 typedef struct BDRVVmdkState {
115 CoMutex lock;
116 uint64_t desc_offset;
117 bool cid_updated;
118 bool cid_checked;
119 uint32_t cid;
120 uint32_t parent_cid;
121 int num_extents;
122 /* Extent array with num_extents entries, ascend ordered by address */
123 VmdkExtent *extents;
124 Error *migration_blocker;
125 char *create_type;
126 } BDRVVmdkState;
127
128 typedef struct VmdkMetaData {
129 unsigned int l1_index;
130 unsigned int l2_index;
131 unsigned int l2_offset;
132 int valid;
133 uint32_t *l2_cache_entry;
134 } VmdkMetaData;
135
136 typedef struct VmdkGrainMarker {
137 uint64_t lba;
138 uint32_t size;
139 uint8_t data[0];
140 } QEMU_PACKED VmdkGrainMarker;
141
142 enum {
143 MARKER_END_OF_STREAM = 0,
144 MARKER_GRAIN_TABLE = 1,
145 MARKER_GRAIN_DIRECTORY = 2,
146 MARKER_FOOTER = 3,
147 };
148
149 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
150 {
151 uint32_t magic;
152
153 if (buf_size < 4) {
154 return 0;
155 }
156 magic = be32_to_cpu(*(uint32_t *)buf);
157 if (magic == VMDK3_MAGIC ||
158 magic == VMDK4_MAGIC) {
159 return 100;
160 } else {
161 const char *p = (const char *)buf;
162 const char *end = p + buf_size;
163 while (p < end) {
164 if (*p == '#') {
165 /* skip comment line */
166 while (p < end && *p != '\n') {
167 p++;
168 }
169 p++;
170 continue;
171 }
172 if (*p == ' ') {
173 while (p < end && *p == ' ') {
174 p++;
175 }
176 /* skip '\r' if windows line endings used. */
177 if (p < end && *p == '\r') {
178 p++;
179 }
180 /* only accept blank lines before 'version=' line */
181 if (p == end || *p != '\n') {
182 return 0;
183 }
184 p++;
185 continue;
186 }
187 if (end - p >= strlen("version=X\n")) {
188 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
189 strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
190 return 100;
191 }
192 }
193 if (end - p >= strlen("version=X\r\n")) {
194 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
195 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
196 return 100;
197 }
198 }
199 return 0;
200 }
201 return 0;
202 }
203 }
204
205 #define SECTOR_SIZE 512
206 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */
207 #define BUF_SIZE 4096
208 #define HEADER_SIZE 512 /* first sector of 512 bytes */
209
210 static void vmdk_free_extents(BlockDriverState *bs)
211 {
212 int i;
213 BDRVVmdkState *s = bs->opaque;
214 VmdkExtent *e;
215
216 for (i = 0; i < s->num_extents; i++) {
217 e = &s->extents[i];
218 g_free(e->l1_table);
219 g_free(e->l2_cache);
220 g_free(e->l1_backup_table);
221 g_free(e->type);
222 if (e->file != bs->file) {
223 bdrv_unref(e->file);
224 }
225 }
226 g_free(s->extents);
227 }
228
229 static void vmdk_free_last_extent(BlockDriverState *bs)
230 {
231 BDRVVmdkState *s = bs->opaque;
232
233 if (s->num_extents == 0) {
234 return;
235 }
236 s->num_extents--;
237 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents);
238 }
239
240 static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
241 {
242 char desc[DESC_SIZE];
243 uint32_t cid = 0xffffffff;
244 const char *p_name, *cid_str;
245 size_t cid_str_size;
246 BDRVVmdkState *s = bs->opaque;
247 int ret;
248
249 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
250 if (ret < 0) {
251 return 0;
252 }
253
254 if (parent) {
255 cid_str = "parentCID";
256 cid_str_size = sizeof("parentCID");
257 } else {
258 cid_str = "CID";
259 cid_str_size = sizeof("CID");
260 }
261
262 desc[DESC_SIZE - 1] = '\0';
263 p_name = strstr(desc, cid_str);
264 if (p_name != NULL) {
265 p_name += cid_str_size;
266 sscanf(p_name, "%" SCNx32, &cid);
267 }
268
269 return cid;
270 }
271
272 static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
273 {
274 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
275 char *p_name, *tmp_str;
276 BDRVVmdkState *s = bs->opaque;
277 int ret;
278
279 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
280 if (ret < 0) {
281 return ret;
282 }
283
284 desc[DESC_SIZE - 1] = '\0';
285 tmp_str = strstr(desc, "parentCID");
286 if (tmp_str == NULL) {
287 return -EINVAL;
288 }
289
290 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
291 p_name = strstr(desc, "CID");
292 if (p_name != NULL) {
293 p_name += sizeof("CID");
294 snprintf(p_name, sizeof(desc) - (p_name - desc), "%" PRIx32 "\n", cid);
295 pstrcat(desc, sizeof(desc), tmp_desc);
296 }
297
298 ret = bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE);
299 if (ret < 0) {
300 return ret;
301 }
302
303 return 0;
304 }
305
306 static int vmdk_is_cid_valid(BlockDriverState *bs)
307 {
308 BDRVVmdkState *s = bs->opaque;
309 BlockDriverState *p_bs = bs->backing_hd;
310 uint32_t cur_pcid;
311
312 if (!s->cid_checked && p_bs) {
313 cur_pcid = vmdk_read_cid(p_bs, 0);
314 if (s->parent_cid != cur_pcid) {
315 /* CID not valid */
316 return 0;
317 }
318 }
319 s->cid_checked = true;
320 /* CID valid */
321 return 1;
322 }
323
324 /* Queue extents, if any, for reopen() */
325 static int vmdk_reopen_prepare(BDRVReopenState *state,
326 BlockReopenQueue *queue, Error **errp)
327 {
328 BDRVVmdkState *s;
329 int ret = -1;
330 int i;
331 VmdkExtent *e;
332
333 assert(state != NULL);
334 assert(state->bs != NULL);
335
336 if (queue == NULL) {
337 error_setg(errp, "No reopen queue for VMDK extents");
338 goto exit;
339 }
340
341 s = state->bs->opaque;
342
343 assert(s != NULL);
344
345 for (i = 0; i < s->num_extents; i++) {
346 e = &s->extents[i];
347 if (e->file != state->bs->file) {
348 bdrv_reopen_queue(queue, e->file, state->flags);
349 }
350 }
351 ret = 0;
352
353 exit:
354 return ret;
355 }
356
357 static int vmdk_parent_open(BlockDriverState *bs)
358 {
359 char *p_name;
360 char desc[DESC_SIZE + 1];
361 BDRVVmdkState *s = bs->opaque;
362 int ret;
363
364 desc[DESC_SIZE] = '\0';
365 ret = bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE);
366 if (ret < 0) {
367 return ret;
368 }
369
370 p_name = strstr(desc, "parentFileNameHint");
371 if (p_name != NULL) {
372 char *end_name;
373
374 p_name += sizeof("parentFileNameHint") + 1;
375 end_name = strchr(p_name, '\"');
376 if (end_name == NULL) {
377 return -EINVAL;
378 }
379 if ((end_name - p_name) > sizeof(bs->backing_file) - 1) {
380 return -EINVAL;
381 }
382
383 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
384 }
385
386 return 0;
387 }
388
389 /* Create and append extent to the extent array. Return the added VmdkExtent
390 * address. return NULL if allocation failed. */
391 static int vmdk_add_extent(BlockDriverState *bs,
392 BlockDriverState *file, bool flat, int64_t sectors,
393 int64_t l1_offset, int64_t l1_backup_offset,
394 uint32_t l1_size,
395 int l2_size, uint64_t cluster_sectors,
396 VmdkExtent **new_extent,
397 Error **errp)
398 {
399 VmdkExtent *extent;
400 BDRVVmdkState *s = bs->opaque;
401 int64_t nb_sectors;
402
403 if (cluster_sectors > 0x200000) {
404 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */
405 error_setg(errp, "Invalid granularity, image may be corrupt");
406 return -EFBIG;
407 }
408 if (l1_size > 512 * 1024 * 1024) {
409 /* Although with big capacity and small l1_entry_sectors, we can get a
410 * big l1_size, we don't want unbounded value to allocate the table.
411 * Limit it to 512M, which is 16PB for default cluster and L2 table
412 * size */
413 error_setg(errp, "L1 size too big");
414 return -EFBIG;
415 }
416
417 nb_sectors = bdrv_nb_sectors(file);
418 if (nb_sectors < 0) {
419 return nb_sectors;
420 }
421
422 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1);
423 extent = &s->extents[s->num_extents];
424 s->num_extents++;
425
426 memset(extent, 0, sizeof(VmdkExtent));
427 extent->file = file;
428 extent->flat = flat;
429 extent->sectors = sectors;
430 extent->l1_table_offset = l1_offset;
431 extent->l1_backup_table_offset = l1_backup_offset;
432 extent->l1_size = l1_size;
433 extent->l1_entry_sectors = l2_size * cluster_sectors;
434 extent->l2_size = l2_size;
435 extent->cluster_sectors = flat ? sectors : cluster_sectors;
436 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors);
437
438 if (s->num_extents > 1) {
439 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
440 } else {
441 extent->end_sector = extent->sectors;
442 }
443 bs->total_sectors = extent->end_sector;
444 if (new_extent) {
445 *new_extent = extent;
446 }
447 return 0;
448 }
449
450 static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
451 Error **errp)
452 {
453 int ret;
454 size_t l1_size;
455 int i;
456
457 /* read the L1 table */
458 l1_size = extent->l1_size * sizeof(uint32_t);
459 extent->l1_table = g_try_malloc(l1_size);
460 if (l1_size && extent->l1_table == NULL) {
461 return -ENOMEM;
462 }
463
464 ret = bdrv_pread(extent->file,
465 extent->l1_table_offset,
466 extent->l1_table,
467 l1_size);
468 if (ret < 0) {
469 error_setg_errno(errp, -ret,
470 "Could not read l1 table from extent '%s'",
471 extent->file->filename);
472 goto fail_l1;
473 }
474 for (i = 0; i < extent->l1_size; i++) {
475 le32_to_cpus(&extent->l1_table[i]);
476 }
477
478 if (extent->l1_backup_table_offset) {
479 extent->l1_backup_table = g_try_malloc(l1_size);
480 if (l1_size && extent->l1_backup_table == NULL) {
481 ret = -ENOMEM;
482 goto fail_l1;
483 }
484 ret = bdrv_pread(extent->file,
485 extent->l1_backup_table_offset,
486 extent->l1_backup_table,
487 l1_size);
488 if (ret < 0) {
489 error_setg_errno(errp, -ret,
490 "Could not read l1 backup table from extent '%s'",
491 extent->file->filename);
492 goto fail_l1b;
493 }
494 for (i = 0; i < extent->l1_size; i++) {
495 le32_to_cpus(&extent->l1_backup_table[i]);
496 }
497 }
498
499 extent->l2_cache =
500 g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
501 return 0;
502 fail_l1b:
503 g_free(extent->l1_backup_table);
504 fail_l1:
505 g_free(extent->l1_table);
506 return ret;
507 }
508
509 static int vmdk_open_vmfs_sparse(BlockDriverState *bs,
510 BlockDriverState *file,
511 int flags, Error **errp)
512 {
513 int ret;
514 uint32_t magic;
515 VMDK3Header header;
516 VmdkExtent *extent;
517
518 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
519 if (ret < 0) {
520 error_setg_errno(errp, -ret,
521 "Could not read header from file '%s'",
522 file->filename);
523 return ret;
524 }
525 ret = vmdk_add_extent(bs, file, false,
526 le32_to_cpu(header.disk_sectors),
527 (int64_t)le32_to_cpu(header.l1dir_offset) << 9,
528 0,
529 le32_to_cpu(header.l1dir_size),
530 4096,
531 le32_to_cpu(header.granularity),
532 &extent,
533 errp);
534 if (ret < 0) {
535 return ret;
536 }
537 ret = vmdk_init_tables(bs, extent, errp);
538 if (ret) {
539 /* free extent allocated by vmdk_add_extent */
540 vmdk_free_last_extent(bs);
541 }
542 return ret;
543 }
544
545 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
546 QDict *options, Error **errp);
547
548 static char *vmdk_read_desc(BlockDriverState *file, uint64_t desc_offset,
549 Error **errp)
550 {
551 int64_t size;
552 char *buf;
553 int ret;
554
555 size = bdrv_getlength(file);
556 if (size < 0) {
557 error_setg_errno(errp, -size, "Could not access file");
558 return NULL;
559 }
560
561 if (size < 4) {
562 /* Both descriptor file and sparse image must be much larger than 4
563 * bytes, also callers of vmdk_read_desc want to compare the first 4
564 * bytes with VMDK4_MAGIC, let's error out if less is read. */
565 error_setg(errp, "File is too small, not a valid image");
566 return NULL;
567 }
568
569 size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */
570 buf = g_malloc(size + 1);
571
572 ret = bdrv_pread(file, desc_offset, buf, size);
573 if (ret < 0) {
574 error_setg_errno(errp, -ret, "Could not read from file");
575 g_free(buf);
576 return NULL;
577 }
578 buf[ret] = 0;
579
580 return buf;
581 }
582
583 static int vmdk_open_vmdk4(BlockDriverState *bs,
584 BlockDriverState *file,
585 int flags, QDict *options, Error **errp)
586 {
587 int ret;
588 uint32_t magic;
589 uint32_t l1_size, l1_entry_sectors;
590 VMDK4Header header;
591 VmdkExtent *extent;
592 BDRVVmdkState *s = bs->opaque;
593 int64_t l1_backup_offset = 0;
594
595 ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
596 if (ret < 0) {
597 error_setg_errno(errp, -ret,
598 "Could not read header from file '%s'",
599 file->filename);
600 return -EINVAL;
601 }
602 if (header.capacity == 0) {
603 uint64_t desc_offset = le64_to_cpu(header.desc_offset);
604 if (desc_offset) {
605 char *buf = vmdk_read_desc(file, desc_offset << 9, errp);
606 if (!buf) {
607 return -EINVAL;
608 }
609 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
610 g_free(buf);
611 return ret;
612 }
613 }
614
615 if (!s->create_type) {
616 s->create_type = g_strdup("monolithicSparse");
617 }
618
619 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
620 /*
621 * The footer takes precedence over the header, so read it in. The
622 * footer starts at offset -1024 from the end: One sector for the
623 * footer, and another one for the end-of-stream marker.
624 */
625 struct {
626 struct {
627 uint64_t val;
628 uint32_t size;
629 uint32_t type;
630 uint8_t pad[512 - 16];
631 } QEMU_PACKED footer_marker;
632
633 uint32_t magic;
634 VMDK4Header header;
635 uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
636
637 struct {
638 uint64_t val;
639 uint32_t size;
640 uint32_t type;
641 uint8_t pad[512 - 16];
642 } QEMU_PACKED eos_marker;
643 } QEMU_PACKED footer;
644
645 ret = bdrv_pread(file,
646 bs->file->total_sectors * 512 - 1536,
647 &footer, sizeof(footer));
648 if (ret < 0) {
649 error_setg_errno(errp, -ret, "Failed to read footer");
650 return ret;
651 }
652
653 /* Some sanity checks for the footer */
654 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
655 le32_to_cpu(footer.footer_marker.size) != 0 ||
656 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
657 le64_to_cpu(footer.eos_marker.val) != 0 ||
658 le32_to_cpu(footer.eos_marker.size) != 0 ||
659 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
660 {
661 error_setg(errp, "Invalid footer");
662 return -EINVAL;
663 }
664
665 header = footer.header;
666 }
667
668 if (le32_to_cpu(header.version) > 3) {
669 char buf[64];
670 snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
671 le32_to_cpu(header.version));
672 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
673 bdrv_get_device_or_node_name(bs), "vmdk", buf);
674 return -ENOTSUP;
675 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
676 /* VMware KB 2064959 explains that version 3 added support for
677 * persistent changed block tracking (CBT), and backup software can
678 * read it as version=1 if it doesn't care about the changed area
679 * information. So we are safe to enable read only. */
680 error_setg(errp, "VMDK version 3 must be read only");
681 return -EINVAL;
682 }
683
684 if (le32_to_cpu(header.num_gtes_per_gt) > 512) {
685 error_setg(errp, "L2 table size too big");
686 return -EINVAL;
687 }
688
689 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt)
690 * le64_to_cpu(header.granularity);
691 if (l1_entry_sectors == 0) {
692 error_setg(errp, "L1 entry size is invalid");
693 return -EINVAL;
694 }
695 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
696 / l1_entry_sectors;
697 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {
698 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;
699 }
700 if (bdrv_nb_sectors(file) < le64_to_cpu(header.grain_offset)) {
701 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes",
702 (int64_t)(le64_to_cpu(header.grain_offset)
703 * BDRV_SECTOR_SIZE));
704 return -EINVAL;
705 }
706
707 ret = vmdk_add_extent(bs, file, false,
708 le64_to_cpu(header.capacity),
709 le64_to_cpu(header.gd_offset) << 9,
710 l1_backup_offset,
711 l1_size,
712 le32_to_cpu(header.num_gtes_per_gt),
713 le64_to_cpu(header.granularity),
714 &extent,
715 errp);
716 if (ret < 0) {
717 return ret;
718 }
719 extent->compressed =
720 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;
721 if (extent->compressed) {
722 g_free(s->create_type);
723 s->create_type = g_strdup("streamOptimized");
724 }
725 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;
726 extent->version = le32_to_cpu(header.version);
727 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;
728 ret = vmdk_init_tables(bs, extent, errp);
729 if (ret) {
730 /* free extent allocated by vmdk_add_extent */
731 vmdk_free_last_extent(bs);
732 }
733 return ret;
734 }
735
736 /* find an option value out of descriptor file */
737 static int vmdk_parse_description(const char *desc, const char *opt_name,
738 char *buf, int buf_size)
739 {
740 char *opt_pos, *opt_end;
741 const char *end = desc + strlen(desc);
742
743 opt_pos = strstr(desc, opt_name);
744 if (!opt_pos) {
745 return VMDK_ERROR;
746 }
747 /* Skip "=\"" following opt_name */
748 opt_pos += strlen(opt_name) + 2;
749 if (opt_pos >= end) {
750 return VMDK_ERROR;
751 }
752 opt_end = opt_pos;
753 while (opt_end < end && *opt_end != '"') {
754 opt_end++;
755 }
756 if (opt_end == end || buf_size < opt_end - opt_pos + 1) {
757 return VMDK_ERROR;
758 }
759 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos);
760 return VMDK_OK;
761 }
762
763 /* Open an extent file and append to bs array */
764 static int vmdk_open_sparse(BlockDriverState *bs,
765 BlockDriverState *file, int flags,
766 char *buf, QDict *options, Error **errp)
767 {
768 uint32_t magic;
769
770 magic = ldl_be_p(buf);
771 switch (magic) {
772 case VMDK3_MAGIC:
773 return vmdk_open_vmfs_sparse(bs, file, flags, errp);
774 break;
775 case VMDK4_MAGIC:
776 return vmdk_open_vmdk4(bs, file, flags, options, errp);
777 break;
778 default:
779 error_setg(errp, "Image not in VMDK format");
780 return -EINVAL;
781 break;
782 }
783 }
784
785 static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,
786 const char *desc_file_path, QDict *options,
787 Error **errp)
788 {
789 int ret;
790 int matches;
791 char access[11];
792 char type[11];
793 char fname[512];
794 const char *p = desc;
795 int64_t sectors = 0;
796 int64_t flat_offset;
797 char *extent_path;
798 BlockDriverState *extent_file;
799 BDRVVmdkState *s = bs->opaque;
800 VmdkExtent *extent;
801 char extent_opt_prefix[32];
802
803 while (*p) {
804 /* parse extent line in one of below formats:
805 *
806 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET
807 * RW [size in sectors] SPARSE "file-name.vmdk"
808 * RW [size in sectors] VMFS "file-name.vmdk"
809 * RW [size in sectors] VMFSSPARSE "file-name.vmdk"
810 */
811 flat_offset = -1;
812 matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,
813 access, &sectors, type, fname, &flat_offset);
814 if (matches < 4 || strcmp(access, "RW")) {
815 goto next_line;
816 } else if (!strcmp(type, "FLAT")) {
817 if (matches != 5 || flat_offset < 0) {
818 error_setg(errp, "Invalid extent lines: \n%s", p);
819 return -EINVAL;
820 }
821 } else if (!strcmp(type, "VMFS")) {
822 if (matches == 4) {
823 flat_offset = 0;
824 } else {
825 error_setg(errp, "Invalid extent lines:\n%s", p);
826 return -EINVAL;
827 }
828 } else if (matches != 4) {
829 error_setg(errp, "Invalid extent lines:\n%s", p);
830 return -EINVAL;
831 }
832
833 if (sectors <= 0 ||
834 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&
835 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||
836 (strcmp(access, "RW"))) {
837 goto next_line;
838 }
839
840 if (!path_is_absolute(fname) && !path_has_protocol(fname) &&
841 !desc_file_path[0])
842 {
843 error_setg(errp, "Cannot use relative extent paths with VMDK "
844 "descriptor file '%s'", bs->file->filename);
845 return -EINVAL;
846 }
847
848 extent_path = g_malloc0(PATH_MAX);
849 path_combine(extent_path, PATH_MAX, desc_file_path, fname);
850 extent_file = NULL;
851
852 ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents);
853 assert(ret < 32);
854
855 ret = bdrv_open_image(&extent_file, extent_path,
856 options, extent_opt_prefix,
857 bs->open_flags | BDRV_O_PROTOCOL, false, errp);
858 g_free(extent_path);
859 if (ret) {
860 return ret;
861 }
862
863 /* save to extents array */
864 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {
865 /* FLAT extent */
866
867 ret = vmdk_add_extent(bs, extent_file, true, sectors,
868 0, 0, 0, 0, 0, &extent, errp);
869 if (ret < 0) {
870 bdrv_unref(extent_file);
871 return ret;
872 }
873 extent->flat_start_offset = flat_offset << 9;
874 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {
875 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/
876 char *buf = vmdk_read_desc(extent_file, 0, errp);
877 if (!buf) {
878 ret = -EINVAL;
879 } else {
880 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf,
881 options, errp);
882 }
883 g_free(buf);
884 if (ret) {
885 bdrv_unref(extent_file);
886 return ret;
887 }
888 extent = &s->extents[s->num_extents - 1];
889 } else {
890 error_setg(errp, "Unsupported extent type '%s'", type);
891 bdrv_unref(extent_file);
892 return -ENOTSUP;
893 }
894 extent->type = g_strdup(type);
895 next_line:
896 /* move to next line */
897 while (*p) {
898 if (*p == '\n') {
899 p++;
900 break;
901 }
902 p++;
903 }
904 }
905 return 0;
906 }
907
908 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf,
909 QDict *options, Error **errp)
910 {
911 int ret;
912 char ct[128];
913 BDRVVmdkState *s = bs->opaque;
914
915 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {
916 error_setg(errp, "invalid VMDK image descriptor");
917 ret = -EINVAL;
918 goto exit;
919 }
920 if (strcmp(ct, "monolithicFlat") &&
921 strcmp(ct, "vmfs") &&
922 strcmp(ct, "vmfsSparse") &&
923 strcmp(ct, "twoGbMaxExtentSparse") &&
924 strcmp(ct, "twoGbMaxExtentFlat")) {
925 error_setg(errp, "Unsupported image type '%s'", ct);
926 ret = -ENOTSUP;
927 goto exit;
928 }
929 s->create_type = g_strdup(ct);
930 s->desc_offset = 0;
931 ret = vmdk_parse_extents(buf, bs, bs->file->exact_filename, options, errp);
932 exit:
933 return ret;
934 }
935
936 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
937 Error **errp)
938 {
939 char *buf;
940 int ret;
941 BDRVVmdkState *s = bs->opaque;
942 uint32_t magic;
943
944 buf = vmdk_read_desc(bs->file, 0, errp);
945 if (!buf) {
946 return -EINVAL;
947 }
948
949 magic = ldl_be_p(buf);
950 switch (magic) {
951 case VMDK3_MAGIC:
952 case VMDK4_MAGIC:
953 ret = vmdk_open_sparse(bs, bs->file, flags, buf, options, errp);
954 s->desc_offset = 0x200;
955 break;
956 default:
957 ret = vmdk_open_desc_file(bs, flags, buf, options, errp);
958 break;
959 }
960 if (ret) {
961 goto fail;
962 }
963
964 /* try to open parent images, if exist */
965 ret = vmdk_parent_open(bs);
966 if (ret) {
967 goto fail;
968 }
969 s->cid = vmdk_read_cid(bs, 0);
970 s->parent_cid = vmdk_read_cid(bs, 1);
971 qemu_co_mutex_init(&s->lock);
972
973 /* Disable migration when VMDK images are used */
974 error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "
975 "does not support live migration",
976 bdrv_get_device_or_node_name(bs));
977 migrate_add_blocker(s->migration_blocker);
978 g_free(buf);
979 return 0;
980
981 fail:
982 g_free(buf);
983 g_free(s->create_type);
984 s->create_type = NULL;
985 vmdk_free_extents(bs);
986 return ret;
987 }
988
989
990 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)
991 {
992 BDRVVmdkState *s = bs->opaque;
993 int i;
994
995 for (i = 0; i < s->num_extents; i++) {
996 if (!s->extents[i].flat) {
997 bs->bl.write_zeroes_alignment =
998 MAX(bs->bl.write_zeroes_alignment,
999 s->extents[i].cluster_sectors);
1000 }
1001 }
1002 }
1003
1004 /**
1005 * get_whole_cluster
1006 *
1007 * Copy backing file's cluster that covers @sector_num, otherwise write zero,
1008 * to the cluster at @cluster_sector_num.
1009 *
1010 * If @skip_start_sector < @skip_end_sector, the relative range
1011 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave
1012 * it for call to write user data in the request.
1013 */
1014 static int get_whole_cluster(BlockDriverState *bs,
1015 VmdkExtent *extent,
1016 uint64_t cluster_sector_num,
1017 uint64_t sector_num,
1018 uint64_t skip_start_sector,
1019 uint64_t skip_end_sector)
1020 {
1021 int ret = VMDK_OK;
1022 int64_t cluster_bytes;
1023 uint8_t *whole_grain;
1024
1025 /* For COW, align request sector_num to cluster start */
1026 sector_num = QEMU_ALIGN_DOWN(sector_num, extent->cluster_sectors);
1027 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS;
1028 whole_grain = qemu_blockalign(bs, cluster_bytes);
1029
1030 if (!bs->backing_hd) {
1031 memset(whole_grain, 0, skip_start_sector << BDRV_SECTOR_BITS);
1032 memset(whole_grain + (skip_end_sector << BDRV_SECTOR_BITS), 0,
1033 cluster_bytes - (skip_end_sector << BDRV_SECTOR_BITS));
1034 }
1035
1036 assert(skip_end_sector <= extent->cluster_sectors);
1037 /* we will be here if it's first write on non-exist grain(cluster).
1038 * try to read from parent image, if exist */
1039 if (bs->backing_hd && !vmdk_is_cid_valid(bs)) {
1040 ret = VMDK_ERROR;
1041 goto exit;
1042 }
1043
1044 /* Read backing data before skip range */
1045 if (skip_start_sector > 0) {
1046 if (bs->backing_hd) {
1047 ret = bdrv_read(bs->backing_hd, sector_num,
1048 whole_grain, skip_start_sector);
1049 if (ret < 0) {
1050 ret = VMDK_ERROR;
1051 goto exit;
1052 }
1053 }
1054 ret = bdrv_write(extent->file, cluster_sector_num, whole_grain,
1055 skip_start_sector);
1056 if (ret < 0) {
1057 ret = VMDK_ERROR;
1058 goto exit;
1059 }
1060 }
1061 /* Read backing data after skip range */
1062 if (skip_end_sector < extent->cluster_sectors) {
1063 if (bs->backing_hd) {
1064 ret = bdrv_read(bs->backing_hd, sector_num + skip_end_sector,
1065 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1066 extent->cluster_sectors - skip_end_sector);
1067 if (ret < 0) {
1068 ret = VMDK_ERROR;
1069 goto exit;
1070 }
1071 }
1072 ret = bdrv_write(extent->file, cluster_sector_num + skip_end_sector,
1073 whole_grain + (skip_end_sector << BDRV_SECTOR_BITS),
1074 extent->cluster_sectors - skip_end_sector);
1075 if (ret < 0) {
1076 ret = VMDK_ERROR;
1077 goto exit;
1078 }
1079 }
1080
1081 exit:
1082 qemu_vfree(whole_grain);
1083 return ret;
1084 }
1085
1086 static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data,
1087 uint32_t offset)
1088 {
1089 offset = cpu_to_le32(offset);
1090 /* update L2 table */
1091 if (bdrv_pwrite_sync(
1092 extent->file,
1093 ((int64_t)m_data->l2_offset * 512)
1094 + (m_data->l2_index * sizeof(offset)),
1095 &offset, sizeof(offset)) < 0) {
1096 return VMDK_ERROR;
1097 }
1098 /* update backup L2 table */
1099 if (extent->l1_backup_table_offset != 0) {
1100 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
1101 if (bdrv_pwrite_sync(
1102 extent->file,
1103 ((int64_t)m_data->l2_offset * 512)
1104 + (m_data->l2_index * sizeof(offset)),
1105 &offset, sizeof(offset)) < 0) {
1106 return VMDK_ERROR;
1107 }
1108 }
1109 if (m_data->l2_cache_entry) {
1110 *m_data->l2_cache_entry = offset;
1111 }
1112
1113 return VMDK_OK;
1114 }
1115
1116 /**
1117 * get_cluster_offset
1118 *
1119 * Look up cluster offset in extent file by sector number, and store in
1120 * @cluster_offset.
1121 *
1122 * For flat extents, the start offset as parsed from the description file is
1123 * returned.
1124 *
1125 * For sparse extents, look up in L1, L2 table. If allocate is true, return an
1126 * offset for a new cluster and update L2 cache. If there is a backing file,
1127 * COW is done before returning; otherwise, zeroes are written to the allocated
1128 * cluster. Both COW and zero writing skips the sector range
1129 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller
1130 * has new data to write there.
1131 *
1132 * Returns: VMDK_OK if cluster exists and mapped in the image.
1133 * VMDK_UNALLOC if cluster is not mapped and @allocate is false.
1134 * VMDK_ERROR if failed.
1135 */
1136 static int get_cluster_offset(BlockDriverState *bs,
1137 VmdkExtent *extent,
1138 VmdkMetaData *m_data,
1139 uint64_t offset,
1140 bool allocate,
1141 uint64_t *cluster_offset,
1142 uint64_t skip_start_sector,
1143 uint64_t skip_end_sector)
1144 {
1145 unsigned int l1_index, l2_offset, l2_index;
1146 int min_index, i, j;
1147 uint32_t min_count, *l2_table;
1148 bool zeroed = false;
1149 int64_t ret;
1150 int64_t cluster_sector;
1151
1152 if (m_data) {
1153 m_data->valid = 0;
1154 }
1155 if (extent->flat) {
1156 *cluster_offset = extent->flat_start_offset;
1157 return VMDK_OK;
1158 }
1159
1160 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE;
1161 l1_index = (offset >> 9) / extent->l1_entry_sectors;
1162 if (l1_index >= extent->l1_size) {
1163 return VMDK_ERROR;
1164 }
1165 l2_offset = extent->l1_table[l1_index];
1166 if (!l2_offset) {
1167 return VMDK_UNALLOC;
1168 }
1169 for (i = 0; i < L2_CACHE_SIZE; i++) {
1170 if (l2_offset == extent->l2_cache_offsets[i]) {
1171 /* increment the hit count */
1172 if (++extent->l2_cache_counts[i] == 0xffffffff) {
1173 for (j = 0; j < L2_CACHE_SIZE; j++) {
1174 extent->l2_cache_counts[j] >>= 1;
1175 }
1176 }
1177 l2_table = extent->l2_cache + (i * extent->l2_size);
1178 goto found;
1179 }
1180 }
1181 /* not found: load a new entry in the least used one */
1182 min_index = 0;
1183 min_count = 0xffffffff;
1184 for (i = 0; i < L2_CACHE_SIZE; i++) {
1185 if (extent->l2_cache_counts[i] < min_count) {
1186 min_count = extent->l2_cache_counts[i];
1187 min_index = i;
1188 }
1189 }
1190 l2_table = extent->l2_cache + (min_index * extent->l2_size);
1191 if (bdrv_pread(
1192 extent->file,
1193 (int64_t)l2_offset * 512,
1194 l2_table,
1195 extent->l2_size * sizeof(uint32_t)
1196 ) != extent->l2_size * sizeof(uint32_t)) {
1197 return VMDK_ERROR;
1198 }
1199
1200 extent->l2_cache_offsets[min_index] = l2_offset;
1201 extent->l2_cache_counts[min_index] = 1;
1202 found:
1203 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
1204 cluster_sector = le32_to_cpu(l2_table[l2_index]);
1205
1206 if (m_data) {
1207 m_data->valid = 1;
1208 m_data->l1_index = l1_index;
1209 m_data->l2_index = l2_index;
1210 m_data->l2_offset = l2_offset;
1211 m_data->l2_cache_entry = &l2_table[l2_index];
1212 }
1213 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
1214 zeroed = true;
1215 }
1216
1217 if (!cluster_sector || zeroed) {
1218 if (!allocate) {
1219 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC;
1220 }
1221
1222 cluster_sector = extent->next_cluster_sector;
1223 extent->next_cluster_sector += extent->cluster_sectors;
1224
1225 /* First of all we write grain itself, to avoid race condition
1226 * that may to corrupt the image.
1227 * This problem may occur because of insufficient space on host disk
1228 * or inappropriate VM shutdown.
1229 */
1230 ret = get_whole_cluster(bs, extent,
1231 cluster_sector,
1232 offset >> BDRV_SECTOR_BITS,
1233 skip_start_sector, skip_end_sector);
1234 if (ret) {
1235 return ret;
1236 }
1237 }
1238 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
1239 return VMDK_OK;
1240 }
1241
1242 static VmdkExtent *find_extent(BDRVVmdkState *s,
1243 int64_t sector_num, VmdkExtent *start_hint)
1244 {
1245 VmdkExtent *extent = start_hint;
1246
1247 if (!extent) {
1248 extent = &s->extents[0];
1249 }
1250 while (extent < &s->extents[s->num_extents]) {
1251 if (sector_num < extent->end_sector) {
1252 return extent;
1253 }
1254 extent++;
1255 }
1256 return NULL;
1257 }
1258
1259 static inline uint64_t vmdk_find_index_in_cluster(VmdkExtent *extent,
1260 int64_t sector_num)
1261 {
1262 uint64_t index_in_cluster, extent_begin_sector, extent_relative_sector_num;
1263
1264 extent_begin_sector = extent->end_sector - extent->sectors;
1265 extent_relative_sector_num = sector_num - extent_begin_sector;
1266 index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;
1267 return index_in_cluster;
1268 }
1269
1270 static int64_t coroutine_fn vmdk_co_get_block_status(BlockDriverState *bs,
1271 int64_t sector_num, int nb_sectors, int *pnum)
1272 {
1273 BDRVVmdkState *s = bs->opaque;
1274 int64_t index_in_cluster, n, ret;
1275 uint64_t offset;
1276 VmdkExtent *extent;
1277
1278 extent = find_extent(s, sector_num, NULL);
1279 if (!extent) {
1280 return 0;
1281 }
1282 qemu_co_mutex_lock(&s->lock);
1283 ret = get_cluster_offset(bs, extent, NULL,
1284 sector_num * 512, false, &offset,
1285 0, 0);
1286 qemu_co_mutex_unlock(&s->lock);
1287
1288 switch (ret) {
1289 case VMDK_ERROR:
1290 ret = -EIO;
1291 break;
1292 case VMDK_UNALLOC:
1293 ret = 0;
1294 break;
1295 case VMDK_ZEROED:
1296 ret = BDRV_BLOCK_ZERO;
1297 break;
1298 case VMDK_OK:
1299 ret = BDRV_BLOCK_DATA;
1300 if (extent->file == bs->file && !extent->compressed) {
1301 ret |= BDRV_BLOCK_OFFSET_VALID | offset;
1302 }
1303
1304 break;
1305 }
1306
1307 index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1308 n = extent->cluster_sectors - index_in_cluster;
1309 if (n > nb_sectors) {
1310 n = nb_sectors;
1311 }
1312 *pnum = n;
1313 return ret;
1314 }
1315
1316 static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,
1317 int64_t offset_in_cluster, const uint8_t *buf,
1318 int nb_sectors, int64_t sector_num)
1319 {
1320 int ret;
1321 VmdkGrainMarker *data = NULL;
1322 uLongf buf_len;
1323 const uint8_t *write_buf = buf;
1324 int write_len = nb_sectors * 512;
1325 int64_t write_offset;
1326 int64_t write_end_sector;
1327
1328 if (extent->compressed) {
1329 if (!extent->has_marker) {
1330 ret = -EINVAL;
1331 goto out;
1332 }
1333 buf_len = (extent->cluster_sectors << 9) * 2;
1334 data = g_malloc(buf_len + sizeof(VmdkGrainMarker));
1335 if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||
1336 buf_len == 0) {
1337 ret = -EINVAL;
1338 goto out;
1339 }
1340 data->lba = sector_num;
1341 data->size = buf_len;
1342 write_buf = (uint8_t *)data;
1343 write_len = buf_len + sizeof(VmdkGrainMarker);
1344 }
1345 write_offset = cluster_offset + offset_in_cluster,
1346 ret = bdrv_pwrite(extent->file, write_offset, write_buf, write_len);
1347
1348 write_end_sector = DIV_ROUND_UP(write_offset + write_len, BDRV_SECTOR_SIZE);
1349
1350 extent->next_cluster_sector = MAX(extent->next_cluster_sector,
1351 write_end_sector);
1352
1353 if (ret != write_len) {
1354 ret = ret < 0 ? ret : -EIO;
1355 goto out;
1356 }
1357 ret = 0;
1358 out:
1359 g_free(data);
1360 return ret;
1361 }
1362
1363 static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
1364 int64_t offset_in_cluster, uint8_t *buf,
1365 int nb_sectors)
1366 {
1367 int ret;
1368 int cluster_bytes, buf_bytes;
1369 uint8_t *cluster_buf, *compressed_data;
1370 uint8_t *uncomp_buf;
1371 uint32_t data_len;
1372 VmdkGrainMarker *marker;
1373 uLongf buf_len;
1374
1375
1376 if (!extent->compressed) {
1377 ret = bdrv_pread(extent->file,
1378 cluster_offset + offset_in_cluster,
1379 buf, nb_sectors * 512);
1380 if (ret == nb_sectors * 512) {
1381 return 0;
1382 } else {
1383 return -EIO;
1384 }
1385 }
1386 cluster_bytes = extent->cluster_sectors * 512;
1387 /* Read two clusters in case GrainMarker + compressed data > one cluster */
1388 buf_bytes = cluster_bytes * 2;
1389 cluster_buf = g_malloc(buf_bytes);
1390 uncomp_buf = g_malloc(cluster_bytes);
1391 ret = bdrv_pread(extent->file,
1392 cluster_offset,
1393 cluster_buf, buf_bytes);
1394 if (ret < 0) {
1395 goto out;
1396 }
1397 compressed_data = cluster_buf;
1398 buf_len = cluster_bytes;
1399 data_len = cluster_bytes;
1400 if (extent->has_marker) {
1401 marker = (VmdkGrainMarker *)cluster_buf;
1402 compressed_data = marker->data;
1403 data_len = le32_to_cpu(marker->size);
1404 }
1405 if (!data_len || data_len > buf_bytes) {
1406 ret = -EINVAL;
1407 goto out;
1408 }
1409 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len);
1410 if (ret != Z_OK) {
1411 ret = -EINVAL;
1412 goto out;
1413
1414 }
1415 if (offset_in_cluster < 0 ||
1416 offset_in_cluster + nb_sectors * 512 > buf_len) {
1417 ret = -EINVAL;
1418 goto out;
1419 }
1420 memcpy(buf, uncomp_buf + offset_in_cluster, nb_sectors * 512);
1421 ret = 0;
1422
1423 out:
1424 g_free(uncomp_buf);
1425 g_free(cluster_buf);
1426 return ret;
1427 }
1428
1429 static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
1430 uint8_t *buf, int nb_sectors)
1431 {
1432 BDRVVmdkState *s = bs->opaque;
1433 int ret;
1434 uint64_t n, index_in_cluster;
1435 VmdkExtent *extent = NULL;
1436 uint64_t cluster_offset;
1437
1438 while (nb_sectors > 0) {
1439 extent = find_extent(s, sector_num, extent);
1440 if (!extent) {
1441 return -EIO;
1442 }
1443 ret = get_cluster_offset(bs, extent, NULL,
1444 sector_num << 9, false, &cluster_offset,
1445 0, 0);
1446 index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1447 n = extent->cluster_sectors - index_in_cluster;
1448 if (n > nb_sectors) {
1449 n = nb_sectors;
1450 }
1451 if (ret != VMDK_OK) {
1452 /* if not allocated, try to read from parent image, if exist */
1453 if (bs->backing_hd && ret != VMDK_ZEROED) {
1454 if (!vmdk_is_cid_valid(bs)) {
1455 return -EINVAL;
1456 }
1457 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
1458 if (ret < 0) {
1459 return ret;
1460 }
1461 } else {
1462 memset(buf, 0, 512 * n);
1463 }
1464 } else {
1465 ret = vmdk_read_extent(extent,
1466 cluster_offset, index_in_cluster * 512,
1467 buf, n);
1468 if (ret) {
1469 return ret;
1470 }
1471 }
1472 nb_sectors -= n;
1473 sector_num += n;
1474 buf += n * 512;
1475 }
1476 return 0;
1477 }
1478
1479 static coroutine_fn int vmdk_co_read(BlockDriverState *bs, int64_t sector_num,
1480 uint8_t *buf, int nb_sectors)
1481 {
1482 int ret;
1483 BDRVVmdkState *s = bs->opaque;
1484 qemu_co_mutex_lock(&s->lock);
1485 ret = vmdk_read(bs, sector_num, buf, nb_sectors);
1486 qemu_co_mutex_unlock(&s->lock);
1487 return ret;
1488 }
1489
1490 /**
1491 * vmdk_write:
1492 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature
1493 * if possible, otherwise return -ENOTSUP.
1494 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try
1495 * with each cluster. By dry run we can find if the zero write
1496 * is possible without modifying image data.
1497 *
1498 * Returns: error code with 0 for success.
1499 */
1500 static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
1501 const uint8_t *buf, int nb_sectors,
1502 bool zeroed, bool zero_dry_run)
1503 {
1504 BDRVVmdkState *s = bs->opaque;
1505 VmdkExtent *extent = NULL;
1506 int ret;
1507 int64_t index_in_cluster, n;
1508 uint64_t cluster_offset;
1509 VmdkMetaData m_data;
1510
1511 if (sector_num > bs->total_sectors) {
1512 error_report("Wrong offset: sector_num=0x%" PRIx64
1513 " total_sectors=0x%" PRIx64 "\n",
1514 sector_num, bs->total_sectors);
1515 return -EIO;
1516 }
1517
1518 while (nb_sectors > 0) {
1519 extent = find_extent(s, sector_num, extent);
1520 if (!extent) {
1521 return -EIO;
1522 }
1523 index_in_cluster = vmdk_find_index_in_cluster(extent, sector_num);
1524 n = extent->cluster_sectors - index_in_cluster;
1525 if (n > nb_sectors) {
1526 n = nb_sectors;
1527 }
1528 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1529 !(extent->compressed || zeroed),
1530 &cluster_offset,
1531 index_in_cluster, index_in_cluster + n);
1532 if (extent->compressed) {
1533 if (ret == VMDK_OK) {
1534 /* Refuse write to allocated cluster for streamOptimized */
1535 error_report("Could not write to allocated cluster"
1536 " for streamOptimized");
1537 return -EIO;
1538 } else {
1539 /* allocate */
1540 ret = get_cluster_offset(bs, extent, &m_data, sector_num << 9,
1541 true, &cluster_offset, 0, 0);
1542 }
1543 }
1544 if (ret == VMDK_ERROR) {
1545 return -EINVAL;
1546 }
1547 if (zeroed) {
1548 /* Do zeroed write, buf is ignored */
1549 if (extent->has_zero_grain &&
1550 index_in_cluster == 0 &&
1551 n >= extent->cluster_sectors) {
1552 n = extent->cluster_sectors;
1553 if (!zero_dry_run) {
1554 /* update L2 tables */
1555 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED)
1556 != VMDK_OK) {
1557 return -EIO;
1558 }
1559 }
1560 } else {
1561 return -ENOTSUP;
1562 }
1563 } else {
1564 ret = vmdk_write_extent(extent,
1565 cluster_offset, index_in_cluster * 512,
1566 buf, n, sector_num);
1567 if (ret) {
1568 return ret;
1569 }
1570 if (m_data.valid) {
1571 /* update L2 tables */
1572 if (vmdk_L2update(extent, &m_data,
1573 cluster_offset >> BDRV_SECTOR_BITS)
1574 != VMDK_OK) {
1575 return -EIO;
1576 }
1577 }
1578 }
1579 nb_sectors -= n;
1580 sector_num += n;
1581 buf += n * 512;
1582
1583 /* update CID on the first write every time the virtual disk is
1584 * opened */
1585 if (!s->cid_updated) {
1586 ret = vmdk_write_cid(bs, g_random_int());
1587 if (ret < 0) {
1588 return ret;
1589 }
1590 s->cid_updated = true;
1591 }
1592 }
1593 return 0;
1594 }
1595
1596 static coroutine_fn int vmdk_co_write(BlockDriverState *bs, int64_t sector_num,
1597 const uint8_t *buf, int nb_sectors)
1598 {
1599 int ret;
1600 BDRVVmdkState *s = bs->opaque;
1601 qemu_co_mutex_lock(&s->lock);
1602 ret = vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1603 qemu_co_mutex_unlock(&s->lock);
1604 return ret;
1605 }
1606
1607 static int vmdk_write_compressed(BlockDriverState *bs,
1608 int64_t sector_num,
1609 const uint8_t *buf,
1610 int nb_sectors)
1611 {
1612 BDRVVmdkState *s = bs->opaque;
1613 if (s->num_extents == 1 && s->extents[0].compressed) {
1614 return vmdk_write(bs, sector_num, buf, nb_sectors, false, false);
1615 } else {
1616 return -ENOTSUP;
1617 }
1618 }
1619
1620 static int coroutine_fn vmdk_co_write_zeroes(BlockDriverState *bs,
1621 int64_t sector_num,
1622 int nb_sectors,
1623 BdrvRequestFlags flags)
1624 {
1625 int ret;
1626 BDRVVmdkState *s = bs->opaque;
1627 qemu_co_mutex_lock(&s->lock);
1628 /* write zeroes could fail if sectors not aligned to cluster, test it with
1629 * dry_run == true before really updating image */
1630 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, true);
1631 if (!ret) {
1632 ret = vmdk_write(bs, sector_num, NULL, nb_sectors, true, false);
1633 }
1634 qemu_co_mutex_unlock(&s->lock);
1635 return ret;
1636 }
1637
1638 static int vmdk_create_extent(const char *filename, int64_t filesize,
1639 bool flat, bool compress, bool zeroed_grain,
1640 QemuOpts *opts, Error **errp)
1641 {
1642 int ret, i;
1643 BlockDriverState *bs = NULL;
1644 VMDK4Header header;
1645 Error *local_err = NULL;
1646 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;
1647 uint32_t *gd_buf = NULL;
1648 int gd_buf_size;
1649
1650 ret = bdrv_create_file(filename, opts, &local_err);
1651 if (ret < 0) {
1652 error_propagate(errp, local_err);
1653 goto exit;
1654 }
1655
1656 assert(bs == NULL);
1657 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1658 NULL, &local_err);
1659 if (ret < 0) {
1660 error_propagate(errp, local_err);
1661 goto exit;
1662 }
1663
1664 if (flat) {
1665 ret = bdrv_truncate(bs, filesize);
1666 if (ret < 0) {
1667 error_setg_errno(errp, -ret, "Could not truncate file");
1668 }
1669 goto exit;
1670 }
1671 magic = cpu_to_be32(VMDK4_MAGIC);
1672 memset(&header, 0, sizeof(header));
1673 header.version = zeroed_grain ? 2 : 1;
1674 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT
1675 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)
1676 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);
1677 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;
1678 header.capacity = filesize / BDRV_SECTOR_SIZE;
1679 header.granularity = 128;
1680 header.num_gtes_per_gt = BDRV_SECTOR_SIZE;
1681
1682 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);
1683 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),
1684 BDRV_SECTOR_SIZE);
1685 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);
1686 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);
1687
1688 header.desc_offset = 1;
1689 header.desc_size = 20;
1690 header.rgd_offset = header.desc_offset + header.desc_size;
1691 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);
1692 header.grain_offset =
1693 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),
1694 header.granularity);
1695 /* swap endianness for all header fields */
1696 header.version = cpu_to_le32(header.version);
1697 header.flags = cpu_to_le32(header.flags);
1698 header.capacity = cpu_to_le64(header.capacity);
1699 header.granularity = cpu_to_le64(header.granularity);
1700 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);
1701 header.desc_offset = cpu_to_le64(header.desc_offset);
1702 header.desc_size = cpu_to_le64(header.desc_size);
1703 header.rgd_offset = cpu_to_le64(header.rgd_offset);
1704 header.gd_offset = cpu_to_le64(header.gd_offset);
1705 header.grain_offset = cpu_to_le64(header.grain_offset);
1706 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);
1707
1708 header.check_bytes[0] = 0xa;
1709 header.check_bytes[1] = 0x20;
1710 header.check_bytes[2] = 0xd;
1711 header.check_bytes[3] = 0xa;
1712
1713 /* write all the data */
1714 ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));
1715 if (ret < 0) {
1716 error_set(errp, QERR_IO_ERROR);
1717 goto exit;
1718 }
1719 ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));
1720 if (ret < 0) {
1721 error_set(errp, QERR_IO_ERROR);
1722 goto exit;
1723 }
1724
1725 ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);
1726 if (ret < 0) {
1727 error_setg_errno(errp, -ret, "Could not truncate file");
1728 goto exit;
1729 }
1730
1731 /* write grain directory */
1732 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;
1733 gd_buf = g_malloc0(gd_buf_size);
1734 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;
1735 i < gt_count; i++, tmp += gt_size) {
1736 gd_buf[i] = cpu_to_le32(tmp);
1737 }
1738 ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,
1739 gd_buf, gd_buf_size);
1740 if (ret < 0) {
1741 error_set(errp, QERR_IO_ERROR);
1742 goto exit;
1743 }
1744
1745 /* write backup grain directory */
1746 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;
1747 i < gt_count; i++, tmp += gt_size) {
1748 gd_buf[i] = cpu_to_le32(tmp);
1749 }
1750 ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,
1751 gd_buf, gd_buf_size);
1752 if (ret < 0) {
1753 error_set(errp, QERR_IO_ERROR);
1754 goto exit;
1755 }
1756
1757 ret = 0;
1758 exit:
1759 if (bs) {
1760 bdrv_unref(bs);
1761 }
1762 g_free(gd_buf);
1763 return ret;
1764 }
1765
1766 static int filename_decompose(const char *filename, char *path, char *prefix,
1767 char *postfix, size_t buf_len, Error **errp)
1768 {
1769 const char *p, *q;
1770
1771 if (filename == NULL || !strlen(filename)) {
1772 error_setg(errp, "No filename provided");
1773 return VMDK_ERROR;
1774 }
1775 p = strrchr(filename, '/');
1776 if (p == NULL) {
1777 p = strrchr(filename, '\\');
1778 }
1779 if (p == NULL) {
1780 p = strrchr(filename, ':');
1781 }
1782 if (p != NULL) {
1783 p++;
1784 if (p - filename >= buf_len) {
1785 return VMDK_ERROR;
1786 }
1787 pstrcpy(path, p - filename + 1, filename);
1788 } else {
1789 p = filename;
1790 path[0] = '\0';
1791 }
1792 q = strrchr(p, '.');
1793 if (q == NULL) {
1794 pstrcpy(prefix, buf_len, p);
1795 postfix[0] = '\0';
1796 } else {
1797 if (q - p >= buf_len) {
1798 return VMDK_ERROR;
1799 }
1800 pstrcpy(prefix, q - p + 1, p);
1801 pstrcpy(postfix, buf_len, q);
1802 }
1803 return VMDK_OK;
1804 }
1805
1806 static int vmdk_create(const char *filename, QemuOpts *opts, Error **errp)
1807 {
1808 int idx = 0;
1809 BlockDriverState *new_bs = NULL;
1810 Error *local_err = NULL;
1811 char *desc = NULL;
1812 int64_t total_size = 0, filesize;
1813 char *adapter_type = NULL;
1814 char *backing_file = NULL;
1815 char *fmt = NULL;
1816 int flags = 0;
1817 int ret = 0;
1818 bool flat, split, compress;
1819 GString *ext_desc_lines;
1820 char *path = g_malloc0(PATH_MAX);
1821 char *prefix = g_malloc0(PATH_MAX);
1822 char *postfix = g_malloc0(PATH_MAX);
1823 char *desc_line = g_malloc0(BUF_SIZE);
1824 char *ext_filename = g_malloc0(PATH_MAX);
1825 char *desc_filename = g_malloc0(PATH_MAX);
1826 const int64_t split_size = 0x80000000; /* VMDK has constant split size */
1827 const char *desc_extent_line;
1828 char *parent_desc_line = g_malloc0(BUF_SIZE);
1829 uint32_t parent_cid = 0xffffffff;
1830 uint32_t number_heads = 16;
1831 bool zeroed_grain = false;
1832 uint32_t desc_offset = 0, desc_len;
1833 const char desc_template[] =
1834 "# Disk DescriptorFile\n"
1835 "version=1\n"
1836 "CID=%" PRIx32 "\n"
1837 "parentCID=%" PRIx32 "\n"
1838 "createType=\"%s\"\n"
1839 "%s"
1840 "\n"
1841 "# Extent description\n"
1842 "%s"
1843 "\n"
1844 "# The Disk Data Base\n"
1845 "#DDB\n"
1846 "\n"
1847 "ddb.virtualHWVersion = \"%d\"\n"
1848 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
1849 "ddb.geometry.heads = \"%" PRIu32 "\"\n"
1850 "ddb.geometry.sectors = \"63\"\n"
1851 "ddb.adapterType = \"%s\"\n";
1852
1853 ext_desc_lines = g_string_new(NULL);
1854
1855 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {
1856 ret = -EINVAL;
1857 goto exit;
1858 }
1859 /* Read out options */
1860 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1861 BDRV_SECTOR_SIZE);
1862 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE);
1863 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1864 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false)) {
1865 flags |= BLOCK_FLAG_COMPAT6;
1866 }
1867 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1868 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false)) {
1869 zeroed_grain = true;
1870 }
1871
1872 if (!adapter_type) {
1873 adapter_type = g_strdup("ide");
1874 } else if (strcmp(adapter_type, "ide") &&
1875 strcmp(adapter_type, "buslogic") &&
1876 strcmp(adapter_type, "lsilogic") &&
1877 strcmp(adapter_type, "legacyESX")) {
1878 error_setg(errp, "Unknown adapter type: '%s'", adapter_type);
1879 ret = -EINVAL;
1880 goto exit;
1881 }
1882 if (strcmp(adapter_type, "ide") != 0) {
1883 /* that's the number of heads with which vmware operates when
1884 creating, exporting, etc. vmdk files with a non-ide adapter type */
1885 number_heads = 255;
1886 }
1887 if (!fmt) {
1888 /* Default format to monolithicSparse */
1889 fmt = g_strdup("monolithicSparse");
1890 } else if (strcmp(fmt, "monolithicFlat") &&
1891 strcmp(fmt, "monolithicSparse") &&
1892 strcmp(fmt, "twoGbMaxExtentSparse") &&
1893 strcmp(fmt, "twoGbMaxExtentFlat") &&
1894 strcmp(fmt, "streamOptimized")) {
1895 error_setg(errp, "Unknown subformat: '%s'", fmt);
1896 ret = -EINVAL;
1897 goto exit;
1898 }
1899 split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&
1900 strcmp(fmt, "twoGbMaxExtentSparse"));
1901 flat = !(strcmp(fmt, "monolithicFlat") &&
1902 strcmp(fmt, "twoGbMaxExtentFlat"));
1903 compress = !strcmp(fmt, "streamOptimized");
1904 if (flat) {
1905 desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";
1906 } else {
1907 desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";
1908 }
1909 if (flat && backing_file) {
1910 error_setg(errp, "Flat image can't have backing file");
1911 ret = -ENOTSUP;
1912 goto exit;
1913 }
1914 if (flat && zeroed_grain) {
1915 error_setg(errp, "Flat image can't enable zeroed grain");
1916 ret = -ENOTSUP;
1917 goto exit;
1918 }
1919 if (backing_file) {
1920 BlockDriverState *bs = NULL;
1921 char *full_backing = g_new0(char, PATH_MAX);
1922 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
1923 full_backing, PATH_MAX,
1924 &local_err);
1925 if (local_err) {
1926 g_free(full_backing);
1927 error_propagate(errp, local_err);
1928 ret = -ENOENT;
1929 goto exit;
1930 }
1931 ret = bdrv_open(&bs, full_backing, NULL, NULL, BDRV_O_NO_BACKING, NULL,
1932 errp);
1933 g_free(full_backing);
1934 if (ret != 0) {
1935 goto exit;
1936 }
1937 if (strcmp(bs->drv->format_name, "vmdk")) {
1938 bdrv_unref(bs);
1939 ret = -EINVAL;
1940 goto exit;
1941 }
1942 parent_cid = vmdk_read_cid(bs, 0);
1943 bdrv_unref(bs);
1944 snprintf(parent_desc_line, BUF_SIZE,
1945 "parentFileNameHint=\"%s\"", backing_file);
1946 }
1947
1948 /* Create extents */
1949 filesize = total_size;
1950 while (filesize > 0) {
1951 int64_t size = filesize;
1952
1953 if (split && size > split_size) {
1954 size = split_size;
1955 }
1956 if (split) {
1957 snprintf(desc_filename, PATH_MAX, "%s-%c%03d%s",
1958 prefix, flat ? 'f' : 's', ++idx, postfix);
1959 } else if (flat) {
1960 snprintf(desc_filename, PATH_MAX, "%s-flat%s", prefix, postfix);
1961 } else {
1962 snprintf(desc_filename, PATH_MAX, "%s%s", prefix, postfix);
1963 }
1964 snprintf(ext_filename, PATH_MAX, "%s%s", path, desc_filename);
1965
1966 if (vmdk_create_extent(ext_filename, size,
1967 flat, compress, zeroed_grain, opts, errp)) {
1968 ret = -EINVAL;
1969 goto exit;
1970 }
1971 filesize -= size;
1972
1973 /* Format description line */
1974 snprintf(desc_line, BUF_SIZE,
1975 desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);
1976 g_string_append(ext_desc_lines, desc_line);
1977 }
1978 /* generate descriptor file */
1979 desc = g_strdup_printf(desc_template,
1980 g_random_int(),
1981 parent_cid,
1982 fmt,
1983 parent_desc_line,
1984 ext_desc_lines->str,
1985 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1986 total_size /
1987 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),
1988 number_heads,
1989 adapter_type);
1990 desc_len = strlen(desc);
1991 /* the descriptor offset = 0x200 */
1992 if (!split && !flat) {
1993 desc_offset = 0x200;
1994 } else {
1995 ret = bdrv_create_file(filename, opts, &local_err);
1996 if (ret < 0) {
1997 error_propagate(errp, local_err);
1998 goto exit;
1999 }
2000 }
2001 assert(new_bs == NULL);
2002 ret = bdrv_open(&new_bs, filename, NULL, NULL,
2003 BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
2004 if (ret < 0) {
2005 error_propagate(errp, local_err);
2006 goto exit;
2007 }
2008 ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);
2009 if (ret < 0) {
2010 error_setg_errno(errp, -ret, "Could not write description");
2011 goto exit;
2012 }
2013 /* bdrv_pwrite write padding zeros to align to sector, we don't need that
2014 * for description file */
2015 if (desc_offset == 0) {
2016 ret = bdrv_truncate(new_bs, desc_len);
2017 if (ret < 0) {
2018 error_setg_errno(errp, -ret, "Could not truncate file");
2019 }
2020 }
2021 exit:
2022 if (new_bs) {
2023 bdrv_unref(new_bs);
2024 }
2025 g_free(adapter_type);
2026 g_free(backing_file);
2027 g_free(fmt);
2028 g_free(desc);
2029 g_free(path);
2030 g_free(prefix);
2031 g_free(postfix);
2032 g_free(desc_line);
2033 g_free(ext_filename);
2034 g_free(desc_filename);
2035 g_free(parent_desc_line);
2036 g_string_free(ext_desc_lines, true);
2037 return ret;
2038 }
2039
2040 static void vmdk_close(BlockDriverState *bs)
2041 {
2042 BDRVVmdkState *s = bs->opaque;
2043
2044 vmdk_free_extents(bs);
2045 g_free(s->create_type);
2046
2047 migrate_del_blocker(s->migration_blocker);
2048 error_free(s->migration_blocker);
2049 }
2050
2051 static coroutine_fn int vmdk_co_flush(BlockDriverState *bs)
2052 {
2053 BDRVVmdkState *s = bs->opaque;
2054 int i, err;
2055 int ret = 0;
2056
2057 for (i = 0; i < s->num_extents; i++) {
2058 err = bdrv_co_flush(s->extents[i].file);
2059 if (err < 0) {
2060 ret = err;
2061 }
2062 }
2063 return ret;
2064 }
2065
2066 static int64_t vmdk_get_allocated_file_size(BlockDriverState *bs)
2067 {
2068 int i;
2069 int64_t ret = 0;
2070 int64_t r;
2071 BDRVVmdkState *s = bs->opaque;
2072
2073 ret = bdrv_get_allocated_file_size(bs->file);
2074 if (ret < 0) {
2075 return ret;
2076 }
2077 for (i = 0; i < s->num_extents; i++) {
2078 if (s->extents[i].file == bs->file) {
2079 continue;
2080 }
2081 r = bdrv_get_allocated_file_size(s->extents[i].file);
2082 if (r < 0) {
2083 return r;
2084 }
2085 ret += r;
2086 }
2087 return ret;
2088 }
2089
2090 static int vmdk_has_zero_init(BlockDriverState *bs)
2091 {
2092 int i;
2093 BDRVVmdkState *s = bs->opaque;
2094
2095 /* If has a flat extent and its underlying storage doesn't have zero init,
2096 * return 0. */
2097 for (i = 0; i < s->num_extents; i++) {
2098 if (s->extents[i].flat) {
2099 if (!bdrv_has_zero_init(s->extents[i].file)) {
2100 return 0;
2101 }
2102 }
2103 }
2104 return 1;
2105 }
2106
2107 static ImageInfo *vmdk_get_extent_info(VmdkExtent *extent)
2108 {
2109 ImageInfo *info = g_new0(ImageInfo, 1);
2110
2111 *info = (ImageInfo){
2112 .filename = g_strdup(extent->file->filename),
2113 .format = g_strdup(extent->type),
2114 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE,
2115 .compressed = extent->compressed,
2116 .has_compressed = extent->compressed,
2117 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE,
2118 .has_cluster_size = !extent->flat,
2119 };
2120
2121 return info;
2122 }
2123
2124 static int vmdk_check(BlockDriverState *bs, BdrvCheckResult *result,
2125 BdrvCheckMode fix)
2126 {
2127 BDRVVmdkState *s = bs->opaque;
2128 VmdkExtent *extent = NULL;
2129 int64_t sector_num = 0;
2130 int64_t total_sectors = bdrv_nb_sectors(bs);
2131 int ret;
2132 uint64_t cluster_offset;
2133
2134 if (fix) {
2135 return -ENOTSUP;
2136 }
2137
2138 for (;;) {
2139 if (sector_num >= total_sectors) {
2140 return 0;
2141 }
2142 extent = find_extent(s, sector_num, extent);
2143 if (!extent) {
2144 fprintf(stderr,
2145 "ERROR: could not find extent for sector %" PRId64 "\n",
2146 sector_num);
2147 break;
2148 }
2149 ret = get_cluster_offset(bs, extent, NULL,
2150 sector_num << BDRV_SECTOR_BITS,
2151 false, &cluster_offset, 0, 0);
2152 if (ret == VMDK_ERROR) {
2153 fprintf(stderr,
2154 "ERROR: could not get cluster_offset for sector %"
2155 PRId64 "\n", sector_num);
2156 break;
2157 }
2158 if (ret == VMDK_OK && cluster_offset >= bdrv_getlength(extent->file)) {
2159 fprintf(stderr,
2160 "ERROR: cluster offset for sector %"
2161 PRId64 " points after EOF\n", sector_num);
2162 break;
2163 }
2164 sector_num += extent->cluster_sectors;
2165 }
2166
2167 result->corruptions++;
2168 return 0;
2169 }
2170
2171 static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
2172 {
2173 int i;
2174 BDRVVmdkState *s = bs->opaque;
2175 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1);
2176 ImageInfoList **next;
2177
2178 *spec_info = (ImageInfoSpecific){
2179 .kind = IMAGE_INFO_SPECIFIC_KIND_VMDK,
2180 {
2181 .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
2182 },
2183 };
2184
2185 *spec_info->vmdk = (ImageInfoSpecificVmdk) {
2186 .create_type = g_strdup(s->create_type),
2187 .cid = s->cid,
2188 .parent_cid = s->parent_cid,
2189 };
2190
2191 next = &spec_info->vmdk->extents;
2192 for (i = 0; i < s->num_extents; i++) {
2193 *next = g_new0(ImageInfoList, 1);
2194 (*next)->value = vmdk_get_extent_info(&s->extents[i]);
2195 (*next)->next = NULL;
2196 next = &(*next)->next;
2197 }
2198
2199 return spec_info;
2200 }
2201
2202 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b)
2203 {
2204 return a->flat == b->flat &&
2205 a->compressed == b->compressed &&
2206 (a->flat || a->cluster_sectors == b->cluster_sectors);
2207 }
2208
2209 static int vmdk_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2210 {
2211 int i;
2212 BDRVVmdkState *s = bs->opaque;
2213 assert(s->num_extents);
2214
2215 /* See if we have multiple extents but they have different cases */
2216 for (i = 1; i < s->num_extents; i++) {
2217 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) {
2218 return -ENOTSUP;
2219 }
2220 }
2221 bdi->needs_compressed_writes = s->extents[0].compressed;
2222 if (!s->extents[0].flat) {
2223 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS;
2224 }
2225 return 0;
2226 }
2227
2228 static void vmdk_detach_aio_context(BlockDriverState *bs)
2229 {
2230 BDRVVmdkState *s = bs->opaque;
2231 int i;
2232
2233 for (i = 0; i < s->num_extents; i++) {
2234 bdrv_detach_aio_context(s->extents[i].file);
2235 }
2236 }
2237
2238 static void vmdk_attach_aio_context(BlockDriverState *bs,
2239 AioContext *new_context)
2240 {
2241 BDRVVmdkState *s = bs->opaque;
2242 int i;
2243
2244 for (i = 0; i < s->num_extents; i++) {
2245 bdrv_attach_aio_context(s->extents[i].file, new_context);
2246 }
2247 }
2248
2249 static QemuOptsList vmdk_create_opts = {
2250 .name = "vmdk-create-opts",
2251 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head),
2252 .desc = {
2253 {
2254 .name = BLOCK_OPT_SIZE,
2255 .type = QEMU_OPT_SIZE,
2256 .help = "Virtual disk size"
2257 },
2258 {
2259 .name = BLOCK_OPT_ADAPTER_TYPE,
2260 .type = QEMU_OPT_STRING,
2261 .help = "Virtual adapter type, can be one of "
2262 "ide (default), lsilogic, buslogic or legacyESX"
2263 },
2264 {
2265 .name = BLOCK_OPT_BACKING_FILE,
2266 .type = QEMU_OPT_STRING,
2267 .help = "File name of a base image"
2268 },
2269 {
2270 .name = BLOCK_OPT_COMPAT6,
2271 .type = QEMU_OPT_BOOL,
2272 .help = "VMDK version 6 image",
2273 .def_value_str = "off"
2274 },
2275 {
2276 .name = BLOCK_OPT_SUBFMT,
2277 .type = QEMU_OPT_STRING,
2278 .help =
2279 "VMDK flat extent format, can be one of "
2280 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} "
2281 },
2282 {
2283 .name = BLOCK_OPT_ZEROED_GRAIN,
2284 .type = QEMU_OPT_BOOL,
2285 .help = "Enable efficient zero writes "
2286 "using the zeroed-grain GTE feature"
2287 },
2288 { /* end of list */ }
2289 }
2290 };
2291
2292 static BlockDriver bdrv_vmdk = {
2293 .format_name = "vmdk",
2294 .instance_size = sizeof(BDRVVmdkState),
2295 .bdrv_probe = vmdk_probe,
2296 .bdrv_open = vmdk_open,
2297 .bdrv_check = vmdk_check,
2298 .bdrv_reopen_prepare = vmdk_reopen_prepare,
2299 .bdrv_read = vmdk_co_read,
2300 .bdrv_write = vmdk_co_write,
2301 .bdrv_write_compressed = vmdk_write_compressed,
2302 .bdrv_co_write_zeroes = vmdk_co_write_zeroes,
2303 .bdrv_close = vmdk_close,
2304 .bdrv_create = vmdk_create,
2305 .bdrv_co_flush_to_disk = vmdk_co_flush,
2306 .bdrv_co_get_block_status = vmdk_co_get_block_status,
2307 .bdrv_get_allocated_file_size = vmdk_get_allocated_file_size,
2308 .bdrv_has_zero_init = vmdk_has_zero_init,
2309 .bdrv_get_specific_info = vmdk_get_specific_info,
2310 .bdrv_refresh_limits = vmdk_refresh_limits,
2311 .bdrv_get_info = vmdk_get_info,
2312 .bdrv_detach_aio_context = vmdk_detach_aio_context,
2313 .bdrv_attach_aio_context = vmdk_attach_aio_context,
2314
2315 .supports_backing = true,
2316 .create_opts = &vmdk_create_opts,
2317 };
2318
2319 static void bdrv_vmdk_init(void)
2320 {
2321 bdrv_register(&bdrv_vmdk);
2322 }
2323
2324 block_init(bdrv_vmdk_init);