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/osdep.h" 27 #include "qapi/error.h" 28 #include "block/block_int.h" 29 #include "system/block-backend.h" 30 #include "qobject/qdict.h" 31 #include "qemu/error-report.h" 32 #include "qemu/module.h" 33 #include "qemu/option.h" 34 #include "qemu/bswap.h" 35 #include "qemu/memalign.h" 36 #include "migration/blocker.h" 37 #include "qemu/cutils.h" 38 #include <zlib.h> 39 40 #define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D') 41 #define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V') 42 #define VMDK4_COMPRESSION_DEFLATE 1 43 #define VMDK4_FLAG_NL_DETECT (1 << 0) 44 #define VMDK4_FLAG_RGD (1 << 1) 45 /* Zeroed-grain enable bit */ 46 #define VMDK4_FLAG_ZERO_GRAIN (1 << 2) 47 #define VMDK4_FLAG_COMPRESS (1 << 16) 48 #define VMDK4_FLAG_MARKER (1 << 17) 49 #define VMDK4_GD_AT_END 0xffffffffffffffffULL 50 51 #define VMDK_EXTENT_MAX_SECTORS (1ULL << 32) 52 53 #define VMDK_GTE_ZEROED 0x1 54 55 /* VMDK internal error codes */ 56 #define VMDK_OK 0 57 #define VMDK_ERROR (-1) 58 /* Cluster not allocated */ 59 #define VMDK_UNALLOC (-2) 60 #define VMDK_ZEROED (-3) 61 62 #define BLOCK_OPT_ZEROED_GRAIN "zeroed_grain" 63 #define BLOCK_OPT_TOOLSVERSION "toolsversion" 64 65 typedef struct { 66 uint32_t version; 67 uint32_t flags; 68 uint32_t disk_sectors; 69 uint32_t granularity; 70 uint32_t l1dir_offset; 71 uint32_t l1dir_size; 72 uint32_t file_sectors; 73 uint32_t cylinders; 74 uint32_t heads; 75 uint32_t sectors_per_track; 76 } QEMU_PACKED VMDK3Header; 77 78 typedef struct { 79 uint32_t version; 80 uint32_t flags; 81 uint64_t capacity; 82 uint64_t granularity; 83 uint64_t desc_offset; 84 uint64_t desc_size; 85 /* Number of GrainTableEntries per GrainTable */ 86 uint32_t num_gtes_per_gt; 87 uint64_t rgd_offset; 88 uint64_t gd_offset; 89 uint64_t grain_offset; 90 char filler[1]; 91 char check_bytes[4]; 92 uint16_t compressAlgorithm; 93 } QEMU_PACKED VMDK4Header; 94 95 typedef struct VMDKSESparseConstHeader { 96 uint64_t magic; 97 uint64_t version; 98 uint64_t capacity; 99 uint64_t grain_size; 100 uint64_t grain_table_size; 101 uint64_t flags; 102 uint64_t reserved1; 103 uint64_t reserved2; 104 uint64_t reserved3; 105 uint64_t reserved4; 106 uint64_t volatile_header_offset; 107 uint64_t volatile_header_size; 108 uint64_t journal_header_offset; 109 uint64_t journal_header_size; 110 uint64_t journal_offset; 111 uint64_t journal_size; 112 uint64_t grain_dir_offset; 113 uint64_t grain_dir_size; 114 uint64_t grain_tables_offset; 115 uint64_t grain_tables_size; 116 uint64_t free_bitmap_offset; 117 uint64_t free_bitmap_size; 118 uint64_t backmap_offset; 119 uint64_t backmap_size; 120 uint64_t grains_offset; 121 uint64_t grains_size; 122 uint8_t pad[304]; 123 } QEMU_PACKED VMDKSESparseConstHeader; 124 125 typedef struct VMDKSESparseVolatileHeader { 126 uint64_t magic; 127 uint64_t free_gt_number; 128 uint64_t next_txn_seq_number; 129 uint64_t replay_journal; 130 uint8_t pad[480]; 131 } QEMU_PACKED VMDKSESparseVolatileHeader; 132 133 #define L2_CACHE_SIZE 16 134 135 typedef struct VmdkExtent { 136 BdrvChild *file; 137 bool flat; 138 bool compressed; 139 bool has_marker; 140 bool has_zero_grain; 141 bool sesparse; 142 uint64_t sesparse_l2_tables_offset; 143 uint64_t sesparse_clusters_offset; 144 int32_t entry_size; 145 int version; 146 int64_t sectors; 147 int64_t end_sector; 148 int64_t flat_start_offset; 149 int64_t l1_table_offset; 150 int64_t l1_backup_table_offset; 151 void *l1_table; 152 uint32_t *l1_backup_table; 153 unsigned int l1_size; 154 uint32_t l1_entry_sectors; 155 156 unsigned int l2_size; 157 void *l2_cache; 158 uint32_t l2_cache_offsets[L2_CACHE_SIZE]; 159 uint32_t l2_cache_counts[L2_CACHE_SIZE]; 160 161 int64_t cluster_sectors; 162 int64_t next_cluster_sector; 163 char *type; 164 } VmdkExtent; 165 166 typedef struct BDRVVmdkState { 167 CoMutex lock; 168 uint64_t desc_offset; 169 bool cid_updated; 170 bool cid_checked; 171 uint32_t cid; 172 uint32_t parent_cid; 173 int num_extents; 174 /* Extent array with num_extents entries, ascend ordered by address */ 175 VmdkExtent *extents; 176 Error *migration_blocker; 177 char *create_type; 178 } BDRVVmdkState; 179 180 typedef struct BDRVVmdkReopenState { 181 bool *extents_using_bs_file; 182 } BDRVVmdkReopenState; 183 184 typedef struct VmdkMetaData { 185 unsigned int l1_index; 186 unsigned int l2_index; 187 unsigned int l2_offset; 188 bool new_allocation; 189 uint32_t *l2_cache_entry; 190 } VmdkMetaData; 191 192 typedef struct VmdkGrainMarker { 193 uint64_t lba; 194 uint32_t size; 195 uint8_t data[]; 196 } QEMU_PACKED VmdkGrainMarker; 197 198 enum { 199 MARKER_END_OF_STREAM = 0, 200 MARKER_GRAIN_TABLE = 1, 201 MARKER_GRAIN_DIRECTORY = 2, 202 MARKER_FOOTER = 3, 203 }; 204 205 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename) 206 { 207 uint32_t magic; 208 209 if (buf_size < 4) { 210 return 0; 211 } 212 magic = be32_to_cpu(*(uint32_t *)buf); 213 if (magic == VMDK3_MAGIC || 214 magic == VMDK4_MAGIC) { 215 return 100; 216 } else { 217 const char *p = (const char *)buf; 218 const char *end = p + buf_size; 219 while (p < end) { 220 if (*p == '#') { 221 /* skip comment line */ 222 while (p < end && *p != '\n') { 223 p++; 224 } 225 p++; 226 continue; 227 } 228 if (*p == ' ') { 229 while (p < end && *p == ' ') { 230 p++; 231 } 232 /* skip '\r' if windows line endings used. */ 233 if (p < end && *p == '\r') { 234 p++; 235 } 236 /* only accept blank lines before 'version=' line */ 237 if (p == end || *p != '\n') { 238 return 0; 239 } 240 p++; 241 continue; 242 } 243 if (end - p >= strlen("version=X\n")) { 244 if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 || 245 strncmp("version=2\n", p, strlen("version=2\n")) == 0 || 246 strncmp("version=3\n", p, strlen("version=3\n")) == 0) { 247 return 100; 248 } 249 } 250 if (end - p >= strlen("version=X\r\n")) { 251 if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 || 252 strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0 || 253 strncmp("version=3\r\n", p, strlen("version=3\r\n")) == 0) { 254 return 100; 255 } 256 } 257 return 0; 258 } 259 return 0; 260 } 261 } 262 263 #define SECTOR_SIZE 512 264 #define DESC_SIZE (20 * SECTOR_SIZE) /* 20 sectors of 512 bytes each */ 265 #define BUF_SIZE 4096 266 #define HEADER_SIZE 512 /* first sector of 512 bytes */ 267 268 static void vmdk_free_extents(BlockDriverState *bs) 269 { 270 int i; 271 BDRVVmdkState *s = bs->opaque; 272 VmdkExtent *e; 273 274 bdrv_graph_wrlock_drained(); 275 for (i = 0; i < s->num_extents; i++) { 276 e = &s->extents[i]; 277 g_free(e->l1_table); 278 g_free(e->l2_cache); 279 g_free(e->l1_backup_table); 280 g_free(e->type); 281 if (e->file != bs->file) { 282 bdrv_unref_child(bs, e->file); 283 } 284 } 285 bdrv_graph_wrunlock(); 286 287 g_free(s->extents); 288 } 289 290 static void vmdk_free_last_extent(BlockDriverState *bs) 291 { 292 BDRVVmdkState *s = bs->opaque; 293 294 if (s->num_extents == 0) { 295 return; 296 } 297 s->num_extents--; 298 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents); 299 } 300 301 /* Return -ve errno, or 0 on success and write CID into *pcid. */ 302 static int GRAPH_RDLOCK 303 vmdk_read_cid(BlockDriverState *bs, int parent, uint32_t *pcid) 304 { 305 char *desc; 306 uint32_t cid; 307 const char *p_name, *cid_str; 308 size_t cid_str_size; 309 BDRVVmdkState *s = bs->opaque; 310 int ret; 311 312 desc = g_malloc0(DESC_SIZE); 313 ret = bdrv_pread(bs->file, s->desc_offset, DESC_SIZE, desc, 0); 314 if (ret < 0) { 315 goto out; 316 } 317 318 if (parent) { 319 cid_str = "parentCID"; 320 cid_str_size = sizeof("parentCID"); 321 } else { 322 cid_str = "CID"; 323 cid_str_size = sizeof("CID"); 324 } 325 326 desc[DESC_SIZE - 1] = '\0'; 327 p_name = strstr(desc, cid_str); 328 if (p_name == NULL) { 329 ret = -EINVAL; 330 goto out; 331 } 332 p_name += cid_str_size; 333 if (sscanf(p_name, "%" SCNx32, &cid) != 1) { 334 ret = -EINVAL; 335 goto out; 336 } 337 *pcid = cid; 338 ret = 0; 339 340 out: 341 g_free(desc); 342 return ret; 343 } 344 345 static int coroutine_fn GRAPH_RDLOCK 346 vmdk_write_cid(BlockDriverState *bs, uint32_t cid) 347 { 348 char *desc, *tmp_desc; 349 char *p_name, *tmp_str; 350 BDRVVmdkState *s = bs->opaque; 351 int ret = 0; 352 353 size_t desc_buf_size; 354 355 if (s->desc_offset == 0) { 356 desc_buf_size = bdrv_getlength(bs->file->bs); 357 if (desc_buf_size > 16ULL << 20) { 358 error_report("VMDK description file too big"); 359 return -EFBIG; 360 } 361 } else { 362 desc_buf_size = DESC_SIZE; 363 } 364 365 desc = g_malloc0(desc_buf_size); 366 tmp_desc = g_malloc0(desc_buf_size); 367 ret = bdrv_co_pread(bs->file, s->desc_offset, desc_buf_size, desc, 0); 368 if (ret < 0) { 369 goto out; 370 } 371 372 desc[desc_buf_size - 1] = '\0'; 373 tmp_str = strstr(desc, "parentCID"); 374 if (tmp_str == NULL) { 375 ret = -EINVAL; 376 goto out; 377 } 378 379 pstrcpy(tmp_desc, desc_buf_size, tmp_str); 380 p_name = strstr(desc, "CID"); 381 if (p_name != NULL) { 382 p_name += sizeof("CID"); 383 snprintf(p_name, desc_buf_size - (p_name - desc), "%" PRIx32 "\n", cid); 384 pstrcat(desc, desc_buf_size, tmp_desc); 385 } 386 387 ret = bdrv_co_pwrite_sync(bs->file, s->desc_offset, desc_buf_size, desc, 0); 388 389 out: 390 g_free(desc); 391 g_free(tmp_desc); 392 return ret; 393 } 394 395 static int coroutine_fn GRAPH_RDLOCK vmdk_is_cid_valid(BlockDriverState *bs) 396 { 397 BDRVVmdkState *s = bs->opaque; 398 uint32_t cur_pcid; 399 400 if (!s->cid_checked && bs->backing) { 401 BlockDriverState *p_bs = bs->backing->bs; 402 403 if (strcmp(p_bs->drv->format_name, "vmdk")) { 404 /* Backing file is not in vmdk format, so it does not have 405 * a CID, which makes the overlay's parent CID invalid */ 406 return 0; 407 } 408 409 if (vmdk_read_cid(p_bs, 0, &cur_pcid) != 0) { 410 /* read failure: report as not valid */ 411 return 0; 412 } 413 if (s->parent_cid != cur_pcid) { 414 /* CID not valid */ 415 return 0; 416 } 417 } 418 s->cid_checked = true; 419 /* CID valid */ 420 return 1; 421 } 422 423 static int vmdk_reopen_prepare(BDRVReopenState *state, 424 BlockReopenQueue *queue, Error **errp) 425 { 426 BDRVVmdkState *s; 427 BDRVVmdkReopenState *rs; 428 int i; 429 430 GLOBAL_STATE_CODE(); 431 GRAPH_RDLOCK_GUARD_MAINLOOP(); 432 433 assert(state != NULL); 434 assert(state->bs != NULL); 435 assert(state->opaque == NULL); 436 437 s = state->bs->opaque; 438 439 rs = g_new0(BDRVVmdkReopenState, 1); 440 state->opaque = rs; 441 442 /* 443 * Check whether there are any extents stored in bs->file; if bs->file 444 * changes, we will need to update their .file pointers to follow suit 445 */ 446 rs->extents_using_bs_file = g_new(bool, s->num_extents); 447 for (i = 0; i < s->num_extents; i++) { 448 rs->extents_using_bs_file[i] = s->extents[i].file == state->bs->file; 449 } 450 451 return 0; 452 } 453 454 static void vmdk_reopen_clean(BDRVReopenState *state) 455 { 456 BDRVVmdkReopenState *rs = state->opaque; 457 458 g_free(rs->extents_using_bs_file); 459 g_free(rs); 460 state->opaque = NULL; 461 } 462 463 static void vmdk_reopen_commit(BDRVReopenState *state) 464 { 465 BDRVVmdkState *s = state->bs->opaque; 466 BDRVVmdkReopenState *rs = state->opaque; 467 int i; 468 469 GLOBAL_STATE_CODE(); 470 GRAPH_RDLOCK_GUARD_MAINLOOP(); 471 472 for (i = 0; i < s->num_extents; i++) { 473 if (rs->extents_using_bs_file[i]) { 474 s->extents[i].file = state->bs->file; 475 } 476 } 477 478 vmdk_reopen_clean(state); 479 } 480 481 static void vmdk_reopen_abort(BDRVReopenState *state) 482 { 483 vmdk_reopen_clean(state); 484 } 485 486 static int GRAPH_RDLOCK vmdk_parent_open(BlockDriverState *bs) 487 { 488 char *p_name; 489 char *desc; 490 BDRVVmdkState *s = bs->opaque; 491 int ret; 492 493 desc = g_malloc0(DESC_SIZE + 1); 494 ret = bdrv_pread(bs->file, s->desc_offset, DESC_SIZE, desc, 0); 495 if (ret < 0) { 496 goto out; 497 } 498 499 p_name = strstr(desc, "parentFileNameHint"); 500 if (p_name != NULL) { 501 char *end_name; 502 503 p_name += sizeof("parentFileNameHint") + 1; 504 end_name = strchr(p_name, '\"'); 505 if (end_name == NULL) { 506 ret = -EINVAL; 507 goto out; 508 } 509 if ((end_name - p_name) > sizeof(bs->auto_backing_file) - 1) { 510 ret = -EINVAL; 511 goto out; 512 } 513 514 pstrcpy(bs->auto_backing_file, end_name - p_name + 1, p_name); 515 pstrcpy(bs->backing_file, sizeof(bs->backing_file), 516 bs->auto_backing_file); 517 pstrcpy(bs->backing_format, sizeof(bs->backing_format), 518 "vmdk"); 519 } 520 521 out: 522 g_free(desc); 523 return ret; 524 } 525 526 /* Create and append extent to the extent array. Return the added VmdkExtent 527 * address. return NULL if allocation failed. */ 528 static int vmdk_add_extent(BlockDriverState *bs, 529 BdrvChild *file, bool flat, int64_t sectors, 530 int64_t l1_offset, int64_t l1_backup_offset, 531 uint32_t l1_size, 532 int l2_size, uint64_t cluster_sectors, 533 VmdkExtent **new_extent, 534 Error **errp) 535 { 536 VmdkExtent *extent; 537 BDRVVmdkState *s = bs->opaque; 538 int64_t nb_sectors; 539 540 if (cluster_sectors > 0x200000) { 541 /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */ 542 error_setg(errp, "Invalid granularity, image may be corrupt"); 543 return -EFBIG; 544 } 545 if (l1_size > 32 * 1024 * 1024) { 546 /* 547 * Although with big capacity and small l1_entry_sectors, we can get a 548 * big l1_size, we don't want unbounded value to allocate the table. 549 * Limit it to 32M, which is enough to store: 550 * 8TB - for both VMDK3 & VMDK4 with 551 * minimal cluster size: 512B 552 * minimal L2 table size: 512 entries 553 * 8 TB is still more than the maximal value supported for 554 * VMDK3 & VMDK4 which is 2TB. 555 * 64TB - for "ESXi seSparse Extent" 556 * minimal cluster size: 512B (default is 4KB) 557 * L2 table size: 4096 entries (const). 558 * 64TB is more than the maximal value supported for 559 * seSparse VMDKs (which is slightly less than 64TB) 560 */ 561 error_setg(errp, "L1 size too big"); 562 return -EFBIG; 563 } 564 565 nb_sectors = bdrv_nb_sectors(file->bs); 566 if (nb_sectors < 0) { 567 return nb_sectors; 568 } 569 570 s->extents = g_renew(VmdkExtent, s->extents, s->num_extents + 1); 571 extent = &s->extents[s->num_extents]; 572 s->num_extents++; 573 574 memset(extent, 0, sizeof(VmdkExtent)); 575 extent->file = file; 576 extent->flat = flat; 577 extent->sectors = sectors; 578 extent->l1_table_offset = l1_offset; 579 extent->l1_backup_table_offset = l1_backup_offset; 580 extent->l1_size = l1_size; 581 extent->l1_entry_sectors = l2_size * cluster_sectors; 582 extent->l2_size = l2_size; 583 extent->cluster_sectors = flat ? sectors : cluster_sectors; 584 extent->next_cluster_sector = ROUND_UP(nb_sectors, cluster_sectors); 585 extent->entry_size = sizeof(uint32_t); 586 587 if (s->num_extents > 1) { 588 extent->end_sector = (*(extent - 1)).end_sector + extent->sectors; 589 } else { 590 extent->end_sector = extent->sectors; 591 } 592 bs->total_sectors = extent->end_sector; 593 if (new_extent) { 594 *new_extent = extent; 595 } 596 return 0; 597 } 598 599 static int GRAPH_RDLOCK 600 vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent, Error **errp) 601 { 602 int ret; 603 size_t l1_size; 604 int i; 605 606 /* read the L1 table */ 607 l1_size = extent->l1_size * extent->entry_size; 608 extent->l1_table = g_try_malloc(l1_size); 609 if (l1_size && extent->l1_table == NULL) { 610 return -ENOMEM; 611 } 612 613 ret = bdrv_pread(extent->file, extent->l1_table_offset, l1_size, 614 extent->l1_table, 0); 615 if (ret < 0) { 616 bdrv_refresh_filename(extent->file->bs); 617 error_setg_errno(errp, -ret, 618 "Could not read l1 table from extent '%s'", 619 extent->file->bs->filename); 620 goto fail_l1; 621 } 622 for (i = 0; i < extent->l1_size; i++) { 623 if (extent->entry_size == sizeof(uint64_t)) { 624 le64_to_cpus((uint64_t *)extent->l1_table + i); 625 } else { 626 assert(extent->entry_size == sizeof(uint32_t)); 627 le32_to_cpus((uint32_t *)extent->l1_table + i); 628 } 629 } 630 631 if (extent->l1_backup_table_offset) { 632 assert(!extent->sesparse); 633 extent->l1_backup_table = g_try_malloc(l1_size); 634 if (l1_size && extent->l1_backup_table == NULL) { 635 ret = -ENOMEM; 636 goto fail_l1; 637 } 638 ret = bdrv_pread(extent->file, extent->l1_backup_table_offset, 639 l1_size, extent->l1_backup_table, 0); 640 if (ret < 0) { 641 bdrv_refresh_filename(extent->file->bs); 642 error_setg_errno(errp, -ret, 643 "Could not read l1 backup table from extent '%s'", 644 extent->file->bs->filename); 645 goto fail_l1b; 646 } 647 for (i = 0; i < extent->l1_size; i++) { 648 le32_to_cpus(&extent->l1_backup_table[i]); 649 } 650 } 651 652 extent->l2_cache = 653 g_malloc(extent->entry_size * extent->l2_size * L2_CACHE_SIZE); 654 return 0; 655 fail_l1b: 656 g_free(extent->l1_backup_table); 657 fail_l1: 658 g_free(extent->l1_table); 659 return ret; 660 } 661 662 static int GRAPH_RDLOCK 663 vmdk_open_vmfs_sparse(BlockDriverState *bs, BdrvChild *file, int flags, 664 Error **errp) 665 { 666 int ret; 667 uint32_t magic; 668 VMDK3Header header; 669 VmdkExtent *extent = NULL; 670 671 ret = bdrv_pread(file, sizeof(magic), sizeof(header), &header, 0); 672 if (ret < 0) { 673 bdrv_refresh_filename(file->bs); 674 error_setg_errno(errp, -ret, 675 "Could not read header from file '%s'", 676 file->bs->filename); 677 return ret; 678 } 679 ret = vmdk_add_extent(bs, file, false, 680 le32_to_cpu(header.disk_sectors), 681 (int64_t)le32_to_cpu(header.l1dir_offset) << 9, 682 0, 683 le32_to_cpu(header.l1dir_size), 684 4096, 685 le32_to_cpu(header.granularity), 686 &extent, 687 errp); 688 if (ret < 0) { 689 return ret; 690 } 691 ret = vmdk_init_tables(bs, extent, errp); 692 if (ret) { 693 /* free extent allocated by vmdk_add_extent */ 694 vmdk_free_last_extent(bs); 695 } 696 return ret; 697 } 698 699 #define SESPARSE_CONST_HEADER_MAGIC UINT64_C(0x00000000cafebabe) 700 #define SESPARSE_VOLATILE_HEADER_MAGIC UINT64_C(0x00000000cafecafe) 701 702 /* Strict checks - format not officially documented */ 703 static int check_se_sparse_const_header(VMDKSESparseConstHeader *header, 704 Error **errp) 705 { 706 header->magic = le64_to_cpu(header->magic); 707 header->version = le64_to_cpu(header->version); 708 header->grain_size = le64_to_cpu(header->grain_size); 709 header->grain_table_size = le64_to_cpu(header->grain_table_size); 710 header->flags = le64_to_cpu(header->flags); 711 header->reserved1 = le64_to_cpu(header->reserved1); 712 header->reserved2 = le64_to_cpu(header->reserved2); 713 header->reserved3 = le64_to_cpu(header->reserved3); 714 header->reserved4 = le64_to_cpu(header->reserved4); 715 716 header->volatile_header_offset = 717 le64_to_cpu(header->volatile_header_offset); 718 header->volatile_header_size = le64_to_cpu(header->volatile_header_size); 719 720 header->journal_header_offset = le64_to_cpu(header->journal_header_offset); 721 header->journal_header_size = le64_to_cpu(header->journal_header_size); 722 723 header->journal_offset = le64_to_cpu(header->journal_offset); 724 header->journal_size = le64_to_cpu(header->journal_size); 725 726 header->grain_dir_offset = le64_to_cpu(header->grain_dir_offset); 727 header->grain_dir_size = le64_to_cpu(header->grain_dir_size); 728 729 header->grain_tables_offset = le64_to_cpu(header->grain_tables_offset); 730 header->grain_tables_size = le64_to_cpu(header->grain_tables_size); 731 732 header->free_bitmap_offset = le64_to_cpu(header->free_bitmap_offset); 733 header->free_bitmap_size = le64_to_cpu(header->free_bitmap_size); 734 735 header->backmap_offset = le64_to_cpu(header->backmap_offset); 736 header->backmap_size = le64_to_cpu(header->backmap_size); 737 738 header->grains_offset = le64_to_cpu(header->grains_offset); 739 header->grains_size = le64_to_cpu(header->grains_size); 740 741 if (header->magic != SESPARSE_CONST_HEADER_MAGIC) { 742 error_setg(errp, "Bad const header magic: 0x%016" PRIx64, 743 header->magic); 744 return -EINVAL; 745 } 746 747 if (header->version != 0x0000000200000001) { 748 error_setg(errp, "Unsupported version: 0x%016" PRIx64, 749 header->version); 750 return -ENOTSUP; 751 } 752 753 if (header->grain_size != 8) { 754 error_setg(errp, "Unsupported grain size: %" PRIu64, 755 header->grain_size); 756 return -ENOTSUP; 757 } 758 759 if (header->grain_table_size != 64) { 760 error_setg(errp, "Unsupported grain table size: %" PRIu64, 761 header->grain_table_size); 762 return -ENOTSUP; 763 } 764 765 if (header->flags != 0) { 766 error_setg(errp, "Unsupported flags: 0x%016" PRIx64, 767 header->flags); 768 return -ENOTSUP; 769 } 770 771 if (header->reserved1 != 0 || header->reserved2 != 0 || 772 header->reserved3 != 0 || header->reserved4 != 0) { 773 error_setg(errp, "Unsupported reserved bits:" 774 " 0x%016" PRIx64 " 0x%016" PRIx64 775 " 0x%016" PRIx64 " 0x%016" PRIx64, 776 header->reserved1, header->reserved2, 777 header->reserved3, header->reserved4); 778 return -ENOTSUP; 779 } 780 781 /* check that padding is 0 */ 782 if (!buffer_is_zero(header->pad, sizeof(header->pad))) { 783 error_setg(errp, "Unsupported non-zero const header padding"); 784 return -ENOTSUP; 785 } 786 787 return 0; 788 } 789 790 static int check_se_sparse_volatile_header(VMDKSESparseVolatileHeader *header, 791 Error **errp) 792 { 793 header->magic = le64_to_cpu(header->magic); 794 header->free_gt_number = le64_to_cpu(header->free_gt_number); 795 header->next_txn_seq_number = le64_to_cpu(header->next_txn_seq_number); 796 header->replay_journal = le64_to_cpu(header->replay_journal); 797 798 if (header->magic != SESPARSE_VOLATILE_HEADER_MAGIC) { 799 error_setg(errp, "Bad volatile header magic: 0x%016" PRIx64, 800 header->magic); 801 return -EINVAL; 802 } 803 804 if (header->replay_journal) { 805 error_setg(errp, "Image is dirty, Replaying journal not supported"); 806 return -ENOTSUP; 807 } 808 809 /* check that padding is 0 */ 810 if (!buffer_is_zero(header->pad, sizeof(header->pad))) { 811 error_setg(errp, "Unsupported non-zero volatile header padding"); 812 return -ENOTSUP; 813 } 814 815 return 0; 816 } 817 818 static int GRAPH_RDLOCK 819 vmdk_open_se_sparse(BlockDriverState *bs, BdrvChild *file, int flags, 820 Error **errp) 821 { 822 int ret; 823 VMDKSESparseConstHeader const_header; 824 VMDKSESparseVolatileHeader volatile_header; 825 VmdkExtent *extent = NULL; 826 827 ret = bdrv_apply_auto_read_only(bs, 828 "No write support for seSparse images available", errp); 829 if (ret < 0) { 830 return ret; 831 } 832 833 assert(sizeof(const_header) == SECTOR_SIZE); 834 835 ret = bdrv_pread(file, 0, sizeof(const_header), &const_header, 0); 836 if (ret < 0) { 837 bdrv_refresh_filename(file->bs); 838 error_setg_errno(errp, -ret, 839 "Could not read const header from file '%s'", 840 file->bs->filename); 841 return ret; 842 } 843 844 /* check const header */ 845 ret = check_se_sparse_const_header(&const_header, errp); 846 if (ret < 0) { 847 return ret; 848 } 849 850 assert(sizeof(volatile_header) == SECTOR_SIZE); 851 852 ret = bdrv_pread(file, const_header.volatile_header_offset * SECTOR_SIZE, 853 sizeof(volatile_header), &volatile_header, 0); 854 if (ret < 0) { 855 bdrv_refresh_filename(file->bs); 856 error_setg_errno(errp, -ret, 857 "Could not read volatile header from file '%s'", 858 file->bs->filename); 859 return ret; 860 } 861 862 /* check volatile header */ 863 ret = check_se_sparse_volatile_header(&volatile_header, errp); 864 if (ret < 0) { 865 return ret; 866 } 867 868 ret = vmdk_add_extent(bs, file, false, 869 const_header.capacity, 870 const_header.grain_dir_offset * SECTOR_SIZE, 871 0, 872 const_header.grain_dir_size * 873 SECTOR_SIZE / sizeof(uint64_t), 874 const_header.grain_table_size * 875 SECTOR_SIZE / sizeof(uint64_t), 876 const_header.grain_size, 877 &extent, 878 errp); 879 if (ret < 0) { 880 return ret; 881 } 882 883 extent->sesparse = true; 884 extent->sesparse_l2_tables_offset = const_header.grain_tables_offset; 885 extent->sesparse_clusters_offset = const_header.grains_offset; 886 extent->entry_size = sizeof(uint64_t); 887 888 ret = vmdk_init_tables(bs, extent, errp); 889 if (ret) { 890 /* free extent allocated by vmdk_add_extent */ 891 vmdk_free_last_extent(bs); 892 } 893 894 return ret; 895 } 896 897 static int vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf, 898 QDict *options, Error **errp); 899 900 static char *vmdk_read_desc(BdrvChild *file, uint64_t desc_offset, Error **errp) 901 { 902 int64_t size; 903 char *buf; 904 int ret; 905 906 size = bdrv_getlength(file->bs); 907 if (size < 0) { 908 error_setg_errno(errp, -size, "Could not access file"); 909 return NULL; 910 } 911 912 if (size < 4) { 913 /* Both descriptor file and sparse image must be much larger than 4 914 * bytes, also callers of vmdk_read_desc want to compare the first 4 915 * bytes with VMDK4_MAGIC, let's error out if less is read. */ 916 error_setg(errp, "File is too small, not a valid image"); 917 return NULL; 918 } 919 920 size = MIN(size, (1 << 20) - 1); /* avoid unbounded allocation */ 921 buf = g_malloc(size + 1); 922 923 ret = bdrv_pread(file, desc_offset, size, buf, 0); 924 if (ret < 0) { 925 error_setg_errno(errp, -ret, "Could not read from file"); 926 g_free(buf); 927 return NULL; 928 } 929 buf[size] = 0; 930 931 return buf; 932 } 933 934 static int GRAPH_RDLOCK 935 vmdk_open_vmdk4(BlockDriverState *bs, BdrvChild *file, int flags, 936 QDict *options, Error **errp) 937 { 938 int ret; 939 uint32_t magic; 940 uint32_t l1_size, l1_entry_sectors; 941 VMDK4Header header; 942 VmdkExtent *extent = NULL; 943 BDRVVmdkState *s = bs->opaque; 944 int64_t l1_backup_offset = 0; 945 bool compressed; 946 947 ret = bdrv_pread(file, sizeof(magic), sizeof(header), &header, 0); 948 if (ret < 0) { 949 bdrv_refresh_filename(file->bs); 950 error_setg_errno(errp, -ret, 951 "Could not read header from file '%s'", 952 file->bs->filename); 953 return -EINVAL; 954 } 955 if (header.capacity == 0) { 956 uint64_t desc_offset = le64_to_cpu(header.desc_offset); 957 if (desc_offset) { 958 char *buf = vmdk_read_desc(file, desc_offset << 9, errp); 959 if (!buf) { 960 return -EINVAL; 961 } 962 ret = vmdk_open_desc_file(bs, flags, buf, options, errp); 963 g_free(buf); 964 return ret; 965 } 966 } 967 968 if (!s->create_type) { 969 s->create_type = g_strdup("monolithicSparse"); 970 } 971 972 if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) { 973 /* 974 * The footer takes precedence over the header, so read it in. The 975 * footer starts at offset -1024 from the end: One sector for the 976 * footer, and another one for the end-of-stream marker. 977 */ 978 struct { 979 struct { 980 uint64_t val; 981 uint32_t size; 982 uint32_t type; 983 uint8_t pad[512 - 16]; 984 } QEMU_PACKED footer_marker; 985 986 uint32_t magic; 987 VMDK4Header header; 988 uint8_t pad[512 - 4 - sizeof(VMDK4Header)]; 989 990 struct { 991 uint64_t val; 992 uint32_t size; 993 uint32_t type; 994 uint8_t pad[512 - 16]; 995 } QEMU_PACKED eos_marker; 996 } QEMU_PACKED footer; 997 998 ret = bdrv_pread(file, bs->file->bs->total_sectors * 512 - 1536, 999 sizeof(footer), &footer, 0); 1000 if (ret < 0) { 1001 error_setg_errno(errp, -ret, "Failed to read footer"); 1002 return ret; 1003 } 1004 1005 /* Some sanity checks for the footer */ 1006 if (be32_to_cpu(footer.magic) != VMDK4_MAGIC || 1007 le32_to_cpu(footer.footer_marker.size) != 0 || 1008 le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER || 1009 le64_to_cpu(footer.eos_marker.val) != 0 || 1010 le32_to_cpu(footer.eos_marker.size) != 0 || 1011 le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM) 1012 { 1013 error_setg(errp, "Invalid footer"); 1014 return -EINVAL; 1015 } 1016 1017 header = footer.header; 1018 } 1019 1020 compressed = 1021 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE; 1022 if (le32_to_cpu(header.version) > 3) { 1023 error_setg(errp, "Unsupported VMDK version %" PRIu32, 1024 le32_to_cpu(header.version)); 1025 return -ENOTSUP; 1026 } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR) && 1027 !compressed) { 1028 /* VMware KB 2064959 explains that version 3 added support for 1029 * persistent changed block tracking (CBT), and backup software can 1030 * read it as version=1 if it doesn't care about the changed area 1031 * information. So we are safe to enable read only. */ 1032 error_setg(errp, "VMDK version 3 must be read only"); 1033 return -EINVAL; 1034 } 1035 1036 if (le32_to_cpu(header.num_gtes_per_gt) > 512) { 1037 error_setg(errp, "L2 table size too big"); 1038 return -EINVAL; 1039 } 1040 1041 l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gt) 1042 * le64_to_cpu(header.granularity); 1043 if (l1_entry_sectors == 0) { 1044 error_setg(errp, "L1 entry size is invalid"); 1045 return -EINVAL; 1046 } 1047 l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1) 1048 / l1_entry_sectors; 1049 if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) { 1050 l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9; 1051 } 1052 if (bdrv_nb_sectors(file->bs) < le64_to_cpu(header.grain_offset)) { 1053 error_setg(errp, "File truncated, expecting at least %" PRId64 " bytes", 1054 (int64_t)(le64_to_cpu(header.grain_offset) 1055 * BDRV_SECTOR_SIZE)); 1056 return -EINVAL; 1057 } 1058 1059 ret = vmdk_add_extent(bs, file, false, 1060 le64_to_cpu(header.capacity), 1061 le64_to_cpu(header.gd_offset) << 9, 1062 l1_backup_offset, 1063 l1_size, 1064 le32_to_cpu(header.num_gtes_per_gt), 1065 le64_to_cpu(header.granularity), 1066 &extent, 1067 errp); 1068 if (ret < 0) { 1069 return ret; 1070 } 1071 extent->compressed = 1072 le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE; 1073 if (extent->compressed) { 1074 g_free(s->create_type); 1075 s->create_type = g_strdup("streamOptimized"); 1076 } 1077 extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER; 1078 extent->version = le32_to_cpu(header.version); 1079 extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN; 1080 ret = vmdk_init_tables(bs, extent, errp); 1081 if (ret) { 1082 /* free extent allocated by vmdk_add_extent */ 1083 vmdk_free_last_extent(bs); 1084 } 1085 return ret; 1086 } 1087 1088 /* find an option value out of descriptor file */ 1089 static int vmdk_parse_description(const char *desc, const char *opt_name, 1090 char *buf, int buf_size) 1091 { 1092 char *opt_pos, *opt_end; 1093 const char *end = desc + strlen(desc); 1094 1095 opt_pos = strstr(desc, opt_name); 1096 if (!opt_pos) { 1097 return VMDK_ERROR; 1098 } 1099 /* Skip "=\"" following opt_name */ 1100 opt_pos += strlen(opt_name) + 2; 1101 if (opt_pos >= end) { 1102 return VMDK_ERROR; 1103 } 1104 opt_end = opt_pos; 1105 while (opt_end < end && *opt_end != '"') { 1106 opt_end++; 1107 } 1108 if (opt_end == end || buf_size < opt_end - opt_pos + 1) { 1109 return VMDK_ERROR; 1110 } 1111 pstrcpy(buf, opt_end - opt_pos + 1, opt_pos); 1112 return VMDK_OK; 1113 } 1114 1115 /* Open an extent file and append to bs array */ 1116 static int GRAPH_RDLOCK 1117 vmdk_open_sparse(BlockDriverState *bs, BdrvChild *file, int flags, 1118 char *buf, QDict *options, Error **errp) 1119 { 1120 uint32_t magic; 1121 1122 magic = ldl_be_p(buf); 1123 switch (magic) { 1124 case VMDK3_MAGIC: 1125 return vmdk_open_vmfs_sparse(bs, file, flags, errp); 1126 case VMDK4_MAGIC: 1127 return vmdk_open_vmdk4(bs, file, flags, options, errp); 1128 default: 1129 error_setg(errp, "Image not in VMDK format"); 1130 return -EINVAL; 1131 } 1132 } 1133 1134 static const char *next_line(const char *s) 1135 { 1136 while (*s) { 1137 if (*s == '\n') { 1138 return s + 1; 1139 } 1140 s++; 1141 } 1142 return s; 1143 } 1144 1145 static int GRAPH_RDLOCK 1146 vmdk_parse_extents(const char *desc, BlockDriverState *bs, QDict *options, 1147 Error **errp) 1148 { 1149 ERRP_GUARD(); 1150 int ret; 1151 int matches; 1152 char access[11]; 1153 char type[11]; 1154 char fname[512]; 1155 const char *p, *np; 1156 int64_t sectors = 0; 1157 int64_t flat_offset; 1158 char *desc_file_dir = NULL; 1159 char *extent_path; 1160 BdrvChild *extent_file; 1161 BdrvChildRole extent_role; 1162 BDRVVmdkState *s = bs->opaque; 1163 VmdkExtent *extent = NULL; 1164 char extent_opt_prefix[32]; 1165 Error *local_err = NULL; 1166 1167 GLOBAL_STATE_CODE(); 1168 1169 for (p = desc; *p; p = next_line(p)) { 1170 /* parse extent line in one of below formats: 1171 * 1172 * RW [size in sectors] FLAT "file-name.vmdk" OFFSET 1173 * RW [size in sectors] SPARSE "file-name.vmdk" 1174 * RW [size in sectors] VMFS "file-name.vmdk" 1175 * RW [size in sectors] VMFSSPARSE "file-name.vmdk" 1176 * RW [size in sectors] SESPARSE "file-name.vmdk" 1177 */ 1178 flat_offset = -1; 1179 matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64, 1180 access, §ors, type, fname, &flat_offset); 1181 if (matches < 4 || strcmp(access, "RW")) { 1182 continue; 1183 } else if (!strcmp(type, "FLAT")) { 1184 if (matches != 5 || flat_offset < 0) { 1185 goto invalid; 1186 } 1187 } else if (!strcmp(type, "VMFS")) { 1188 if (matches == 4) { 1189 flat_offset = 0; 1190 } else { 1191 goto invalid; 1192 } 1193 } else if (matches != 4) { 1194 goto invalid; 1195 } 1196 1197 if (sectors <= 0 || 1198 (strcmp(type, "FLAT") && strcmp(type, "SPARSE") && 1199 strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE") && 1200 strcmp(type, "SESPARSE")) || 1201 (strcmp(access, "RW"))) { 1202 continue; 1203 } 1204 1205 if (path_is_absolute(fname)) { 1206 extent_path = g_strdup(fname); 1207 } else { 1208 if (!desc_file_dir) { 1209 desc_file_dir = bdrv_dirname(bs->file->bs, errp); 1210 if (!desc_file_dir) { 1211 bdrv_refresh_filename(bs->file->bs); 1212 error_prepend(errp, "Cannot use relative paths with VMDK " 1213 "descriptor file '%s': ", 1214 bs->file->bs->filename); 1215 ret = -EINVAL; 1216 goto out; 1217 } 1218 } 1219 1220 extent_path = g_strconcat(desc_file_dir, fname, NULL); 1221 } 1222 1223 ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents); 1224 assert(ret < 32); 1225 1226 extent_role = BDRV_CHILD_DATA; 1227 if (strcmp(type, "FLAT") != 0 && strcmp(type, "VMFS") != 0) { 1228 /* non-flat extents have metadata */ 1229 extent_role |= BDRV_CHILD_METADATA; 1230 } 1231 1232 bdrv_graph_rdunlock_main_loop(); 1233 extent_file = bdrv_open_child(extent_path, options, extent_opt_prefix, 1234 bs, &child_of_bds, extent_role, false, 1235 &local_err); 1236 bdrv_graph_rdlock_main_loop(); 1237 g_free(extent_path); 1238 if (!extent_file) { 1239 error_propagate(errp, local_err); 1240 ret = -EINVAL; 1241 goto out; 1242 } 1243 1244 /* save to extents array */ 1245 if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) { 1246 /* FLAT extent */ 1247 1248 ret = vmdk_add_extent(bs, extent_file, true, sectors, 1249 0, 0, 0, 0, 0, &extent, errp); 1250 if (ret < 0) { 1251 bdrv_graph_rdunlock_main_loop(); 1252 bdrv_graph_wrlock_drained(); 1253 bdrv_unref_child(bs, extent_file); 1254 bdrv_graph_wrunlock(); 1255 bdrv_graph_rdlock_main_loop(); 1256 goto out; 1257 } 1258 extent->flat_start_offset = flat_offset << 9; 1259 } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) { 1260 /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/ 1261 char *buf = vmdk_read_desc(extent_file, 0, errp); 1262 if (!buf) { 1263 ret = -EINVAL; 1264 } else { 1265 ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf, 1266 options, errp); 1267 } 1268 g_free(buf); 1269 if (ret) { 1270 bdrv_graph_rdunlock_main_loop(); 1271 bdrv_graph_wrlock_drained(); 1272 bdrv_unref_child(bs, extent_file); 1273 bdrv_graph_wrunlock(); 1274 bdrv_graph_rdlock_main_loop(); 1275 goto out; 1276 } 1277 extent = &s->extents[s->num_extents - 1]; 1278 } else if (!strcmp(type, "SESPARSE")) { 1279 ret = vmdk_open_se_sparse(bs, extent_file, bs->open_flags, errp); 1280 if (ret) { 1281 bdrv_graph_rdunlock_main_loop(); 1282 bdrv_graph_wrlock_drained(); 1283 bdrv_unref_child(bs, extent_file); 1284 bdrv_graph_wrunlock(); 1285 bdrv_graph_rdlock_main_loop(); 1286 goto out; 1287 } 1288 extent = &s->extents[s->num_extents - 1]; 1289 } else { 1290 error_setg(errp, "Unsupported extent type '%s'", type); 1291 bdrv_graph_rdunlock_main_loop(); 1292 bdrv_graph_wrlock_drained(); 1293 bdrv_unref_child(bs, extent_file); 1294 bdrv_graph_wrunlock(); 1295 bdrv_graph_rdlock_main_loop(); 1296 ret = -ENOTSUP; 1297 goto out; 1298 } 1299 extent->type = g_strdup(type); 1300 } 1301 1302 ret = 0; 1303 goto out; 1304 1305 invalid: 1306 np = next_line(p); 1307 assert(np != p); 1308 if (np[-1] == '\n') { 1309 np--; 1310 } 1311 error_setg(errp, "Invalid extent line: %.*s", (int)(np - p), p); 1312 ret = -EINVAL; 1313 1314 out: 1315 g_free(desc_file_dir); 1316 return ret; 1317 } 1318 1319 static int GRAPH_RDLOCK 1320 vmdk_open_desc_file(BlockDriverState *bs, int flags, char *buf, QDict *options, 1321 Error **errp) 1322 { 1323 int ret; 1324 char ct[128]; 1325 BDRVVmdkState *s = bs->opaque; 1326 1327 if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) { 1328 error_setg(errp, "invalid VMDK image descriptor"); 1329 ret = -EINVAL; 1330 goto exit; 1331 } 1332 if (strcmp(ct, "monolithicFlat") && 1333 strcmp(ct, "vmfs") && 1334 strcmp(ct, "vmfsSparse") && 1335 strcmp(ct, "seSparse") && 1336 strcmp(ct, "twoGbMaxExtentSparse") && 1337 strcmp(ct, "twoGbMaxExtentFlat")) { 1338 error_setg(errp, "Unsupported image type '%s'", ct); 1339 ret = -ENOTSUP; 1340 goto exit; 1341 } 1342 s->create_type = g_strdup(ct); 1343 s->desc_offset = 0; 1344 ret = vmdk_parse_extents(buf, bs, options, errp); 1345 exit: 1346 return ret; 1347 } 1348 1349 static int vmdk_open(BlockDriverState *bs, QDict *options, int flags, 1350 Error **errp) 1351 { 1352 char *buf; 1353 int ret; 1354 BDRVVmdkState *s = bs->opaque; 1355 uint32_t magic; 1356 1357 ret = bdrv_open_file_child(NULL, options, "file", bs, errp); 1358 if (ret < 0) { 1359 return ret; 1360 } 1361 1362 GRAPH_RDLOCK_GUARD_MAINLOOP(); 1363 1364 buf = vmdk_read_desc(bs->file, 0, errp); 1365 if (!buf) { 1366 return -EINVAL; 1367 } 1368 1369 magic = ldl_be_p(buf); 1370 switch (magic) { 1371 case VMDK3_MAGIC: 1372 case VMDK4_MAGIC: 1373 ret = vmdk_open_sparse(bs, bs->file, flags, buf, options, 1374 errp); 1375 s->desc_offset = 0x200; 1376 break; 1377 default: 1378 /* No data in the descriptor file */ 1379 bs->file->role &= ~BDRV_CHILD_DATA; 1380 1381 /* Must succeed because we have given up permissions if anything */ 1382 bdrv_child_refresh_perms(bs, bs->file, &error_abort); 1383 1384 ret = vmdk_open_desc_file(bs, flags, buf, options, errp); 1385 break; 1386 } 1387 if (ret) { 1388 goto fail; 1389 } 1390 1391 /* try to open parent images, if exist */ 1392 ret = vmdk_parent_open(bs); 1393 if (ret) { 1394 goto fail; 1395 } 1396 ret = vmdk_read_cid(bs, 0, &s->cid); 1397 if (ret) { 1398 goto fail; 1399 } 1400 ret = vmdk_read_cid(bs, 1, &s->parent_cid); 1401 if (ret) { 1402 goto fail; 1403 } 1404 qemu_co_mutex_init(&s->lock); 1405 1406 /* Disable migration when VMDK images are used */ 1407 error_setg(&s->migration_blocker, "The vmdk format used by node '%s' " 1408 "does not support live migration", 1409 bdrv_get_device_or_node_name(bs)); 1410 ret = migrate_add_blocker_normal(&s->migration_blocker, errp); 1411 if (ret < 0) { 1412 goto fail; 1413 } 1414 1415 g_free(buf); 1416 return 0; 1417 1418 fail: 1419 g_free(buf); 1420 g_free(s->create_type); 1421 s->create_type = NULL; 1422 vmdk_free_extents(bs); 1423 return ret; 1424 } 1425 1426 1427 static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp) 1428 { 1429 BDRVVmdkState *s = bs->opaque; 1430 int i; 1431 1432 for (i = 0; i < s->num_extents; i++) { 1433 if (!s->extents[i].flat) { 1434 bs->bl.pwrite_zeroes_alignment = 1435 MAX(bs->bl.pwrite_zeroes_alignment, 1436 s->extents[i].cluster_sectors << BDRV_SECTOR_BITS); 1437 } 1438 } 1439 } 1440 1441 /** 1442 * get_whole_cluster 1443 * 1444 * Copy backing file's cluster that covers @sector_num, otherwise write zero, 1445 * to the cluster at @cluster_sector_num. If @zeroed is true, we're overwriting 1446 * a zeroed cluster in the current layer and must not copy data from the 1447 * backing file. 1448 * 1449 * If @skip_start_sector < @skip_end_sector, the relative range 1450 * [@skip_start_sector, @skip_end_sector) is not copied or written, and leave 1451 * it for call to write user data in the request. 1452 */ 1453 static int coroutine_fn GRAPH_RDLOCK 1454 get_whole_cluster(BlockDriverState *bs, VmdkExtent *extent, 1455 uint64_t cluster_offset, uint64_t offset, 1456 uint64_t skip_start_bytes, uint64_t skip_end_bytes, 1457 bool zeroed) 1458 { 1459 int ret = VMDK_OK; 1460 int64_t cluster_bytes; 1461 uint8_t *whole_grain; 1462 bool copy_from_backing; 1463 1464 /* For COW, align request sector_num to cluster start */ 1465 cluster_bytes = extent->cluster_sectors << BDRV_SECTOR_BITS; 1466 offset = QEMU_ALIGN_DOWN(offset, cluster_bytes); 1467 whole_grain = qemu_blockalign(bs, cluster_bytes); 1468 copy_from_backing = bs->backing && !zeroed; 1469 1470 if (!copy_from_backing) { 1471 memset(whole_grain, 0, skip_start_bytes); 1472 memset(whole_grain + skip_end_bytes, 0, cluster_bytes - skip_end_bytes); 1473 } 1474 1475 assert(skip_end_bytes <= cluster_bytes); 1476 /* we will be here if it's first write on non-exist grain(cluster). 1477 * try to read from parent image, if exist */ 1478 if (bs->backing && !vmdk_is_cid_valid(bs)) { 1479 ret = VMDK_ERROR; 1480 goto exit; 1481 } 1482 1483 /* Read backing data before skip range */ 1484 if (skip_start_bytes > 0) { 1485 if (copy_from_backing) { 1486 /* qcow2 emits this on bs->file instead of bs->backing */ 1487 BLKDBG_CO_EVENT(extent->file, BLKDBG_COW_READ); 1488 ret = bdrv_co_pread(bs->backing, offset, skip_start_bytes, 1489 whole_grain, 0); 1490 if (ret < 0) { 1491 ret = VMDK_ERROR; 1492 goto exit; 1493 } 1494 } 1495 BLKDBG_CO_EVENT(extent->file, BLKDBG_COW_WRITE); 1496 ret = bdrv_co_pwrite(extent->file, cluster_offset, skip_start_bytes, 1497 whole_grain, 0); 1498 if (ret < 0) { 1499 ret = VMDK_ERROR; 1500 goto exit; 1501 } 1502 } 1503 /* Read backing data after skip range */ 1504 if (skip_end_bytes < cluster_bytes) { 1505 if (copy_from_backing) { 1506 /* qcow2 emits this on bs->file instead of bs->backing */ 1507 BLKDBG_CO_EVENT(extent->file, BLKDBG_COW_READ); 1508 ret = bdrv_co_pread(bs->backing, offset + skip_end_bytes, 1509 cluster_bytes - skip_end_bytes, 1510 whole_grain + skip_end_bytes, 0); 1511 if (ret < 0) { 1512 ret = VMDK_ERROR; 1513 goto exit; 1514 } 1515 } 1516 BLKDBG_CO_EVENT(extent->file, BLKDBG_COW_WRITE); 1517 ret = bdrv_co_pwrite(extent->file, cluster_offset + skip_end_bytes, 1518 cluster_bytes - skip_end_bytes, 1519 whole_grain + skip_end_bytes, 0); 1520 if (ret < 0) { 1521 ret = VMDK_ERROR; 1522 goto exit; 1523 } 1524 } 1525 1526 ret = VMDK_OK; 1527 exit: 1528 qemu_vfree(whole_grain); 1529 return ret; 1530 } 1531 1532 static int coroutine_fn GRAPH_RDLOCK 1533 vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data, uint32_t offset) 1534 { 1535 offset = cpu_to_le32(offset); 1536 /* update L2 table */ 1537 BLKDBG_CO_EVENT(extent->file, BLKDBG_L2_UPDATE); 1538 if (bdrv_co_pwrite(extent->file, 1539 ((int64_t)m_data->l2_offset * 512) 1540 + (m_data->l2_index * sizeof(offset)), 1541 sizeof(offset), &offset, 0) < 0) { 1542 return VMDK_ERROR; 1543 } 1544 /* update backup L2 table */ 1545 if (extent->l1_backup_table_offset != 0) { 1546 m_data->l2_offset = extent->l1_backup_table[m_data->l1_index]; 1547 if (bdrv_co_pwrite(extent->file, 1548 ((int64_t)m_data->l2_offset * 512) 1549 + (m_data->l2_index * sizeof(offset)), 1550 sizeof(offset), &offset, 0) < 0) { 1551 return VMDK_ERROR; 1552 } 1553 } 1554 if (bdrv_co_flush(extent->file->bs) < 0) { 1555 return VMDK_ERROR; 1556 } 1557 if (m_data->l2_cache_entry) { 1558 *m_data->l2_cache_entry = offset; 1559 } 1560 1561 return VMDK_OK; 1562 } 1563 1564 /** 1565 * get_cluster_offset 1566 * 1567 * Look up cluster offset in extent file by sector number, and store in 1568 * @cluster_offset. 1569 * 1570 * For flat extents, the start offset as parsed from the description file is 1571 * returned. 1572 * 1573 * For sparse extents, look up in L1, L2 table. If allocate is true, return an 1574 * offset for a new cluster and update L2 cache. If there is a backing file, 1575 * COW is done before returning; otherwise, zeroes are written to the allocated 1576 * cluster. Both COW and zero writing skips the sector range 1577 * [@skip_start_sector, @skip_end_sector) passed in by caller, because caller 1578 * has new data to write there. 1579 * 1580 * Returns: VMDK_OK if cluster exists and mapped in the image. 1581 * VMDK_UNALLOC if cluster is not mapped and @allocate is false. 1582 * VMDK_ERROR if failed. 1583 */ 1584 static int coroutine_fn GRAPH_RDLOCK 1585 get_cluster_offset(BlockDriverState *bs, VmdkExtent *extent, 1586 VmdkMetaData *m_data, uint64_t offset, bool allocate, 1587 uint64_t *cluster_offset, uint64_t skip_start_bytes, 1588 uint64_t skip_end_bytes) 1589 { 1590 unsigned int l1_index, l2_offset, l2_index; 1591 int min_index, i, j; 1592 uint32_t min_count; 1593 void *l2_table; 1594 bool zeroed = false; 1595 int64_t ret; 1596 int64_t cluster_sector; 1597 unsigned int l2_size_bytes = extent->l2_size * extent->entry_size; 1598 1599 if (m_data) { 1600 m_data->new_allocation = false; 1601 } 1602 if (extent->flat) { 1603 *cluster_offset = extent->flat_start_offset; 1604 return VMDK_OK; 1605 } 1606 1607 offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE; 1608 l1_index = (offset >> 9) / extent->l1_entry_sectors; 1609 if (l1_index >= extent->l1_size) { 1610 return VMDK_ERROR; 1611 } 1612 if (extent->sesparse) { 1613 uint64_t l2_offset_u64; 1614 1615 assert(extent->entry_size == sizeof(uint64_t)); 1616 1617 l2_offset_u64 = ((uint64_t *)extent->l1_table)[l1_index]; 1618 if (l2_offset_u64 == 0) { 1619 l2_offset = 0; 1620 } else if ((l2_offset_u64 & 0xffffffff00000000) != 0x1000000000000000) { 1621 /* 1622 * Top most nibble is 0x1 if grain table is allocated. 1623 * strict check - top most 4 bytes must be 0x10000000 since max 1624 * supported size is 64TB for disk - so no more than 64TB / 16MB 1625 * grain directories which is smaller than uint32, 1626 * where 16MB is the only supported default grain table coverage. 1627 */ 1628 return VMDK_ERROR; 1629 } else { 1630 l2_offset_u64 = l2_offset_u64 & 0x00000000ffffffff; 1631 l2_offset_u64 = extent->sesparse_l2_tables_offset + 1632 l2_offset_u64 * l2_size_bytes / SECTOR_SIZE; 1633 if (l2_offset_u64 > 0x00000000ffffffff) { 1634 return VMDK_ERROR; 1635 } 1636 l2_offset = (unsigned int)(l2_offset_u64); 1637 } 1638 } else { 1639 assert(extent->entry_size == sizeof(uint32_t)); 1640 l2_offset = ((uint32_t *)extent->l1_table)[l1_index]; 1641 } 1642 if (!l2_offset) { 1643 return VMDK_UNALLOC; 1644 } 1645 for (i = 0; i < L2_CACHE_SIZE; i++) { 1646 if (l2_offset == extent->l2_cache_offsets[i]) { 1647 /* increment the hit count */ 1648 if (++extent->l2_cache_counts[i] == 0xffffffff) { 1649 for (j = 0; j < L2_CACHE_SIZE; j++) { 1650 extent->l2_cache_counts[j] >>= 1; 1651 } 1652 } 1653 l2_table = (char *)extent->l2_cache + (i * l2_size_bytes); 1654 goto found; 1655 } 1656 } 1657 /* not found: load a new entry in the least used one */ 1658 min_index = 0; 1659 min_count = 0xffffffff; 1660 for (i = 0; i < L2_CACHE_SIZE; i++) { 1661 if (extent->l2_cache_counts[i] < min_count) { 1662 min_count = extent->l2_cache_counts[i]; 1663 min_index = i; 1664 } 1665 } 1666 l2_table = (char *)extent->l2_cache + (min_index * l2_size_bytes); 1667 BLKDBG_CO_EVENT(extent->file, BLKDBG_L2_LOAD); 1668 if (bdrv_co_pread(extent->file, 1669 (int64_t)l2_offset * 512, 1670 l2_size_bytes, 1671 l2_table, 0 1672 ) < 0) { 1673 return VMDK_ERROR; 1674 } 1675 1676 extent->l2_cache_offsets[min_index] = l2_offset; 1677 extent->l2_cache_counts[min_index] = 1; 1678 found: 1679 l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size; 1680 if (m_data) { 1681 m_data->l1_index = l1_index; 1682 m_data->l2_index = l2_index; 1683 m_data->l2_offset = l2_offset; 1684 m_data->l2_cache_entry = ((uint32_t *)l2_table) + l2_index; 1685 } 1686 1687 if (extent->sesparse) { 1688 cluster_sector = le64_to_cpu(((uint64_t *)l2_table)[l2_index]); 1689 switch (cluster_sector & 0xf000000000000000) { 1690 case 0x0000000000000000: 1691 /* unallocated grain */ 1692 if (cluster_sector != 0) { 1693 return VMDK_ERROR; 1694 } 1695 break; 1696 case 0x1000000000000000: 1697 /* scsi-unmapped grain - fallthrough */ 1698 case 0x2000000000000000: 1699 /* zero grain */ 1700 zeroed = true; 1701 break; 1702 case 0x3000000000000000: 1703 /* allocated grain */ 1704 cluster_sector = (((cluster_sector & 0x0fff000000000000) >> 48) | 1705 ((cluster_sector & 0x0000ffffffffffff) << 12)); 1706 cluster_sector = extent->sesparse_clusters_offset + 1707 cluster_sector * extent->cluster_sectors; 1708 break; 1709 default: 1710 return VMDK_ERROR; 1711 } 1712 } else { 1713 cluster_sector = le32_to_cpu(((uint32_t *)l2_table)[l2_index]); 1714 1715 if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) { 1716 zeroed = true; 1717 } 1718 } 1719 1720 if (!cluster_sector || zeroed) { 1721 if (!allocate) { 1722 return zeroed ? VMDK_ZEROED : VMDK_UNALLOC; 1723 } 1724 assert(!extent->sesparse); 1725 1726 if (extent->next_cluster_sector >= VMDK_EXTENT_MAX_SECTORS) { 1727 return VMDK_ERROR; 1728 } 1729 1730 cluster_sector = extent->next_cluster_sector; 1731 extent->next_cluster_sector += extent->cluster_sectors; 1732 1733 /* First of all we write grain itself, to avoid race condition 1734 * that may to corrupt the image. 1735 * This problem may occur because of insufficient space on host disk 1736 * or inappropriate VM shutdown. 1737 */ 1738 ret = get_whole_cluster(bs, extent, cluster_sector * BDRV_SECTOR_SIZE, 1739 offset, skip_start_bytes, skip_end_bytes, 1740 zeroed); 1741 if (ret) { 1742 return ret; 1743 } 1744 if (m_data) { 1745 m_data->new_allocation = true; 1746 } 1747 } 1748 *cluster_offset = cluster_sector << BDRV_SECTOR_BITS; 1749 return VMDK_OK; 1750 } 1751 1752 static VmdkExtent *find_extent(BDRVVmdkState *s, 1753 int64_t sector_num, VmdkExtent *start_hint) 1754 { 1755 VmdkExtent *extent = start_hint; 1756 1757 if (!extent) { 1758 extent = &s->extents[0]; 1759 } 1760 while (extent < &s->extents[s->num_extents]) { 1761 if (sector_num < extent->end_sector) { 1762 return extent; 1763 } 1764 extent++; 1765 } 1766 return NULL; 1767 } 1768 1769 static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent *extent, 1770 int64_t offset) 1771 { 1772 uint64_t extent_begin_offset, extent_relative_offset; 1773 uint64_t cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE; 1774 1775 extent_begin_offset = 1776 (extent->end_sector - extent->sectors) * BDRV_SECTOR_SIZE; 1777 extent_relative_offset = offset - extent_begin_offset; 1778 return extent_relative_offset % cluster_size; 1779 } 1780 1781 static int coroutine_fn GRAPH_RDLOCK 1782 vmdk_co_block_status(BlockDriverState *bs, unsigned int mode, 1783 int64_t offset, int64_t bytes, int64_t *pnum, 1784 int64_t *map, BlockDriverState **file) 1785 { 1786 BDRVVmdkState *s = bs->opaque; 1787 int64_t index_in_cluster, n, ret; 1788 uint64_t cluster_offset; 1789 VmdkExtent *extent; 1790 1791 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, NULL); 1792 if (!extent) { 1793 return -EIO; 1794 } 1795 qemu_co_mutex_lock(&s->lock); 1796 ret = get_cluster_offset(bs, extent, NULL, offset, false, &cluster_offset, 1797 0, 0); 1798 qemu_co_mutex_unlock(&s->lock); 1799 1800 index_in_cluster = vmdk_find_offset_in_cluster(extent, offset); 1801 switch (ret) { 1802 case VMDK_ERROR: 1803 ret = -EIO; 1804 break; 1805 case VMDK_UNALLOC: 1806 ret = 0; 1807 break; 1808 case VMDK_ZEROED: 1809 ret = BDRV_BLOCK_ZERO; 1810 break; 1811 case VMDK_OK: 1812 ret = BDRV_BLOCK_DATA; 1813 if (!extent->compressed) { 1814 ret |= BDRV_BLOCK_OFFSET_VALID; 1815 *map = cluster_offset + index_in_cluster; 1816 if (extent->flat) { 1817 ret |= BDRV_BLOCK_RECURSE; 1818 } 1819 } else { 1820 ret |= BDRV_BLOCK_COMPRESSED; 1821 } 1822 *file = extent->file->bs; 1823 break; 1824 } 1825 1826 n = extent->cluster_sectors * BDRV_SECTOR_SIZE - index_in_cluster; 1827 *pnum = MIN(n, bytes); 1828 return ret; 1829 } 1830 1831 static int coroutine_fn GRAPH_RDLOCK 1832 vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset, 1833 int64_t offset_in_cluster, QEMUIOVector *qiov, 1834 uint64_t qiov_offset, uint64_t n_bytes, 1835 uint64_t offset) 1836 { 1837 int ret; 1838 VmdkGrainMarker *data = NULL; 1839 uLongf buf_len; 1840 QEMUIOVector local_qiov; 1841 int64_t write_offset; 1842 int64_t write_end_sector; 1843 1844 if (extent->compressed) { 1845 void *compressed_data; 1846 1847 /* Only whole clusters */ 1848 if (offset_in_cluster || 1849 n_bytes > (extent->cluster_sectors * SECTOR_SIZE) || 1850 (n_bytes < (extent->cluster_sectors * SECTOR_SIZE) && 1851 offset + n_bytes != extent->end_sector * SECTOR_SIZE)) 1852 { 1853 ret = -EINVAL; 1854 goto out; 1855 } 1856 1857 if (!extent->has_marker) { 1858 ret = -EINVAL; 1859 goto out; 1860 } 1861 buf_len = (extent->cluster_sectors << 9) * 2; 1862 data = g_malloc(buf_len + sizeof(VmdkGrainMarker)); 1863 1864 compressed_data = g_malloc(n_bytes); 1865 qemu_iovec_to_buf(qiov, qiov_offset, compressed_data, n_bytes); 1866 ret = compress(data->data, &buf_len, compressed_data, n_bytes); 1867 g_free(compressed_data); 1868 1869 if (ret != Z_OK || buf_len == 0) { 1870 ret = -EINVAL; 1871 goto out; 1872 } 1873 1874 data->lba = cpu_to_le64(offset >> BDRV_SECTOR_BITS); 1875 data->size = cpu_to_le32(buf_len); 1876 1877 n_bytes = buf_len + sizeof(VmdkGrainMarker); 1878 qemu_iovec_init_buf(&local_qiov, data, n_bytes); 1879 1880 BLKDBG_CO_EVENT(extent->file, BLKDBG_WRITE_COMPRESSED); 1881 } else { 1882 qemu_iovec_init(&local_qiov, qiov->niov); 1883 qemu_iovec_concat(&local_qiov, qiov, qiov_offset, n_bytes); 1884 1885 BLKDBG_CO_EVENT(extent->file, BLKDBG_WRITE_AIO); 1886 } 1887 1888 write_offset = cluster_offset + offset_in_cluster; 1889 ret = bdrv_co_pwritev(extent->file, write_offset, n_bytes, 1890 &local_qiov, 0); 1891 1892 write_end_sector = DIV_ROUND_UP(write_offset + n_bytes, BDRV_SECTOR_SIZE); 1893 1894 if (extent->compressed) { 1895 extent->next_cluster_sector = write_end_sector; 1896 } else { 1897 extent->next_cluster_sector = MAX(extent->next_cluster_sector, 1898 write_end_sector); 1899 } 1900 1901 if (ret < 0) { 1902 goto out; 1903 } 1904 ret = 0; 1905 out: 1906 g_free(data); 1907 if (!extent->compressed) { 1908 qemu_iovec_destroy(&local_qiov); 1909 } 1910 return ret; 1911 } 1912 1913 static int coroutine_fn GRAPH_RDLOCK 1914 vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset, 1915 int64_t offset_in_cluster, QEMUIOVector *qiov, int bytes) 1916 { 1917 int ret; 1918 int cluster_bytes, buf_bytes; 1919 uint8_t *cluster_buf, *compressed_data; 1920 uint8_t *uncomp_buf; 1921 uint32_t data_len; 1922 VmdkGrainMarker *marker; 1923 uLongf buf_len; 1924 1925 1926 if (!extent->compressed) { 1927 BLKDBG_CO_EVENT(extent->file, BLKDBG_READ_AIO); 1928 ret = bdrv_co_preadv(extent->file, 1929 cluster_offset + offset_in_cluster, bytes, 1930 qiov, 0); 1931 if (ret < 0) { 1932 return ret; 1933 } 1934 return 0; 1935 } 1936 cluster_bytes = extent->cluster_sectors * 512; 1937 /* Read two clusters in case GrainMarker + compressed data > one cluster */ 1938 buf_bytes = cluster_bytes * 2; 1939 cluster_buf = g_malloc(buf_bytes); 1940 uncomp_buf = g_malloc(cluster_bytes); 1941 BLKDBG_CO_EVENT(extent->file, BLKDBG_READ_COMPRESSED); 1942 ret = bdrv_co_pread(extent->file, cluster_offset, buf_bytes, cluster_buf, 1943 0); 1944 if (ret < 0) { 1945 goto out; 1946 } 1947 compressed_data = cluster_buf; 1948 buf_len = cluster_bytes; 1949 data_len = cluster_bytes; 1950 if (extent->has_marker) { 1951 marker = (VmdkGrainMarker *)cluster_buf; 1952 compressed_data = marker->data; 1953 data_len = le32_to_cpu(marker->size); 1954 } 1955 if (!data_len || data_len > buf_bytes) { 1956 ret = -EINVAL; 1957 goto out; 1958 } 1959 ret = uncompress(uncomp_buf, &buf_len, compressed_data, data_len); 1960 if (ret != Z_OK) { 1961 ret = -EINVAL; 1962 goto out; 1963 1964 } 1965 if (offset_in_cluster < 0 || 1966 offset_in_cluster + bytes > buf_len) { 1967 ret = -EINVAL; 1968 goto out; 1969 } 1970 qemu_iovec_from_buf(qiov, 0, uncomp_buf + offset_in_cluster, bytes); 1971 ret = 0; 1972 1973 out: 1974 g_free(uncomp_buf); 1975 g_free(cluster_buf); 1976 return ret; 1977 } 1978 1979 static int coroutine_fn GRAPH_RDLOCK 1980 vmdk_co_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes, 1981 QEMUIOVector *qiov, BdrvRequestFlags flags) 1982 { 1983 BDRVVmdkState *s = bs->opaque; 1984 int ret; 1985 uint64_t n_bytes, offset_in_cluster; 1986 VmdkExtent *extent = NULL; 1987 QEMUIOVector local_qiov; 1988 uint64_t cluster_offset; 1989 uint64_t bytes_done = 0; 1990 1991 qemu_iovec_init(&local_qiov, qiov->niov); 1992 qemu_co_mutex_lock(&s->lock); 1993 1994 while (bytes > 0) { 1995 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent); 1996 if (!extent) { 1997 ret = -EIO; 1998 goto fail; 1999 } 2000 ret = get_cluster_offset(bs, extent, NULL, 2001 offset, false, &cluster_offset, 0, 0); 2002 offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset); 2003 2004 n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE 2005 - offset_in_cluster); 2006 2007 if (ret != VMDK_OK) { 2008 /* if not allocated, try to read from parent image, if exist */ 2009 if (bs->backing && ret != VMDK_ZEROED) { 2010 if (!vmdk_is_cid_valid(bs)) { 2011 ret = -EINVAL; 2012 goto fail; 2013 } 2014 2015 qemu_iovec_reset(&local_qiov); 2016 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes); 2017 2018 /* qcow2 emits this on bs->file instead of bs->backing */ 2019 BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_BACKING_AIO); 2020 ret = bdrv_co_preadv(bs->backing, offset, n_bytes, 2021 &local_qiov, 0); 2022 if (ret < 0) { 2023 goto fail; 2024 } 2025 } else { 2026 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes); 2027 } 2028 } else { 2029 qemu_iovec_reset(&local_qiov); 2030 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes); 2031 2032 ret = vmdk_read_extent(extent, cluster_offset, offset_in_cluster, 2033 &local_qiov, n_bytes); 2034 if (ret) { 2035 goto fail; 2036 } 2037 } 2038 bytes -= n_bytes; 2039 offset += n_bytes; 2040 bytes_done += n_bytes; 2041 } 2042 2043 ret = 0; 2044 fail: 2045 qemu_co_mutex_unlock(&s->lock); 2046 qemu_iovec_destroy(&local_qiov); 2047 2048 return ret; 2049 } 2050 2051 /** 2052 * vmdk_write: 2053 * @zeroed: buf is ignored (data is zero), use zeroed_grain GTE feature 2054 * if possible, otherwise return -ENOTSUP. 2055 * @zero_dry_run: used for zeroed == true only, don't update L2 table, just try 2056 * with each cluster. By dry run we can find if the zero write 2057 * is possible without modifying image data. 2058 * 2059 * Returns: error code with 0 for success. 2060 */ 2061 static int coroutine_fn GRAPH_RDLOCK 2062 vmdk_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes, 2063 QEMUIOVector *qiov, bool zeroed, bool zero_dry_run) 2064 { 2065 BDRVVmdkState *s = bs->opaque; 2066 VmdkExtent *extent = NULL; 2067 int ret; 2068 int64_t offset_in_cluster, n_bytes; 2069 uint64_t cluster_offset; 2070 uint64_t bytes_done = 0; 2071 VmdkMetaData m_data; 2072 2073 if (DIV_ROUND_UP(offset, BDRV_SECTOR_SIZE) > bs->total_sectors) { 2074 error_report("Wrong offset: offset=0x%" PRIx64 2075 " total_sectors=0x%" PRIx64, 2076 offset, bs->total_sectors); 2077 return -EIO; 2078 } 2079 2080 while (bytes > 0) { 2081 extent = find_extent(s, offset >> BDRV_SECTOR_BITS, extent); 2082 if (!extent) { 2083 return -EIO; 2084 } 2085 if (extent->sesparse) { 2086 return -ENOTSUP; 2087 } 2088 offset_in_cluster = vmdk_find_offset_in_cluster(extent, offset); 2089 n_bytes = MIN(bytes, extent->cluster_sectors * BDRV_SECTOR_SIZE 2090 - offset_in_cluster); 2091 2092 ret = get_cluster_offset(bs, extent, &m_data, offset, 2093 !(extent->compressed || zeroed), 2094 &cluster_offset, offset_in_cluster, 2095 offset_in_cluster + n_bytes); 2096 if (extent->compressed) { 2097 if (ret == VMDK_OK) { 2098 /* Refuse write to allocated cluster for streamOptimized */ 2099 error_report("Could not write to allocated cluster" 2100 " for streamOptimized"); 2101 return -EIO; 2102 } else if (!zeroed) { 2103 /* allocate */ 2104 ret = get_cluster_offset(bs, extent, &m_data, offset, 2105 true, &cluster_offset, 0, 0); 2106 } 2107 } 2108 if (ret == VMDK_ERROR) { 2109 return -EINVAL; 2110 } 2111 if (zeroed) { 2112 /* Do zeroed write, buf is ignored */ 2113 if (extent->has_zero_grain && 2114 offset_in_cluster == 0 && 2115 n_bytes >= extent->cluster_sectors * BDRV_SECTOR_SIZE) { 2116 n_bytes = extent->cluster_sectors * BDRV_SECTOR_SIZE; 2117 if (!zero_dry_run && ret != VMDK_ZEROED) { 2118 /* update L2 tables */ 2119 if (vmdk_L2update(extent, &m_data, VMDK_GTE_ZEROED) 2120 != VMDK_OK) { 2121 return -EIO; 2122 } 2123 } 2124 } else { 2125 return -ENOTSUP; 2126 } 2127 } else { 2128 ret = vmdk_write_extent(extent, cluster_offset, offset_in_cluster, 2129 qiov, bytes_done, n_bytes, offset); 2130 if (ret) { 2131 return ret; 2132 } 2133 if (m_data.new_allocation) { 2134 /* update L2 tables */ 2135 if (vmdk_L2update(extent, &m_data, 2136 cluster_offset >> BDRV_SECTOR_BITS) 2137 != VMDK_OK) { 2138 return -EIO; 2139 } 2140 } 2141 } 2142 bytes -= n_bytes; 2143 offset += n_bytes; 2144 bytes_done += n_bytes; 2145 2146 /* update CID on the first write every time the virtual disk is 2147 * opened */ 2148 if (!s->cid_updated) { 2149 ret = vmdk_write_cid(bs, g_random_int()); 2150 if (ret < 0) { 2151 return ret; 2152 } 2153 s->cid_updated = true; 2154 } 2155 } 2156 return 0; 2157 } 2158 2159 static int coroutine_fn GRAPH_RDLOCK 2160 vmdk_co_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes, 2161 QEMUIOVector *qiov, BdrvRequestFlags flags) 2162 { 2163 int ret; 2164 BDRVVmdkState *s = bs->opaque; 2165 qemu_co_mutex_lock(&s->lock); 2166 ret = vmdk_pwritev(bs, offset, bytes, qiov, false, false); 2167 qemu_co_mutex_unlock(&s->lock); 2168 return ret; 2169 } 2170 2171 static int coroutine_fn GRAPH_RDLOCK 2172 vmdk_co_pwritev_compressed(BlockDriverState *bs, int64_t offset, int64_t bytes, 2173 QEMUIOVector *qiov) 2174 { 2175 if (bytes == 0) { 2176 /* The caller will write bytes 0 to signal EOF. 2177 * When receive it, we align EOF to a sector boundary. */ 2178 BDRVVmdkState *s = bs->opaque; 2179 int i, ret; 2180 int64_t length; 2181 2182 for (i = 0; i < s->num_extents; i++) { 2183 length = bdrv_co_getlength(s->extents[i].file->bs); 2184 if (length < 0) { 2185 return length; 2186 } 2187 length = QEMU_ALIGN_UP(length, BDRV_SECTOR_SIZE); 2188 ret = bdrv_co_truncate(s->extents[i].file, length, false, 2189 PREALLOC_MODE_OFF, 0, NULL); 2190 if (ret < 0) { 2191 return ret; 2192 } 2193 } 2194 return 0; 2195 } 2196 return vmdk_co_pwritev(bs, offset, bytes, qiov, 0); 2197 } 2198 2199 static int coroutine_fn GRAPH_RDLOCK 2200 vmdk_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes, 2201 BdrvRequestFlags flags) 2202 { 2203 int ret; 2204 BDRVVmdkState *s = bs->opaque; 2205 2206 qemu_co_mutex_lock(&s->lock); 2207 /* write zeroes could fail if sectors not aligned to cluster, test it with 2208 * dry_run == true before really updating image */ 2209 ret = vmdk_pwritev(bs, offset, bytes, NULL, true, true); 2210 if (!ret) { 2211 ret = vmdk_pwritev(bs, offset, bytes, NULL, true, false); 2212 } 2213 qemu_co_mutex_unlock(&s->lock); 2214 return ret; 2215 } 2216 2217 static int coroutine_fn GRAPH_UNLOCKED 2218 vmdk_init_extent(BlockBackend *blk, int64_t filesize, bool flat, bool compress, 2219 bool zeroed_grain, Error **errp) 2220 { 2221 int ret, i; 2222 VMDK4Header header; 2223 uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count; 2224 uint32_t *gd_buf = NULL; 2225 int gd_buf_size; 2226 2227 if (flat) { 2228 ret = blk_co_truncate(blk, filesize, false, PREALLOC_MODE_OFF, 0, errp); 2229 goto exit; 2230 } 2231 magic = cpu_to_be32(VMDK4_MAGIC); 2232 memset(&header, 0, sizeof(header)); 2233 if (compress) { 2234 header.version = 3; 2235 } else if (zeroed_grain) { 2236 header.version = 2; 2237 } else { 2238 header.version = 1; 2239 } 2240 header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT 2241 | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0) 2242 | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0); 2243 header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0; 2244 header.capacity = filesize / BDRV_SECTOR_SIZE; 2245 header.granularity = 128; 2246 header.num_gtes_per_gt = BDRV_SECTOR_SIZE; 2247 2248 grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity); 2249 gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t), 2250 BDRV_SECTOR_SIZE); 2251 gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt); 2252 gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE); 2253 2254 header.desc_offset = 1; 2255 header.desc_size = 20; 2256 header.rgd_offset = header.desc_offset + header.desc_size; 2257 header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count); 2258 header.grain_offset = 2259 ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count), 2260 header.granularity); 2261 /* swap endianness for all header fields */ 2262 header.version = cpu_to_le32(header.version); 2263 header.flags = cpu_to_le32(header.flags); 2264 header.capacity = cpu_to_le64(header.capacity); 2265 header.granularity = cpu_to_le64(header.granularity); 2266 header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt); 2267 header.desc_offset = cpu_to_le64(header.desc_offset); 2268 header.desc_size = cpu_to_le64(header.desc_size); 2269 header.rgd_offset = cpu_to_le64(header.rgd_offset); 2270 header.gd_offset = cpu_to_le64(header.gd_offset); 2271 header.grain_offset = cpu_to_le64(header.grain_offset); 2272 header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm); 2273 2274 header.check_bytes[0] = 0xa; 2275 header.check_bytes[1] = 0x20; 2276 header.check_bytes[2] = 0xd; 2277 header.check_bytes[3] = 0xa; 2278 2279 /* write all the data */ 2280 ret = blk_co_pwrite(blk, 0, sizeof(magic), &magic, 0); 2281 if (ret < 0) { 2282 error_setg_errno(errp, -ret, "failed to write VMDK magic"); 2283 goto exit; 2284 } 2285 ret = blk_co_pwrite(blk, sizeof(magic), sizeof(header), &header, 0); 2286 if (ret < 0) { 2287 error_setg_errno(errp, -ret, "failed to write VMDK header"); 2288 goto exit; 2289 } 2290 2291 ret = blk_co_truncate(blk, le64_to_cpu(header.grain_offset) << 9, false, 2292 PREALLOC_MODE_OFF, 0, errp); 2293 if (ret < 0) { 2294 goto exit; 2295 } 2296 2297 /* write grain directory */ 2298 gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE; 2299 gd_buf = g_malloc0(gd_buf_size); 2300 for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors; 2301 i < gt_count; i++, tmp += gt_size) { 2302 gd_buf[i] = cpu_to_le32(tmp); 2303 } 2304 ret = blk_co_pwrite(blk, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE, 2305 gd_buf_size, gd_buf, 0); 2306 if (ret < 0) { 2307 error_setg_errno(errp, -ret, "failed to write VMDK grain directory"); 2308 goto exit; 2309 } 2310 2311 /* write backup grain directory */ 2312 for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors; 2313 i < gt_count; i++, tmp += gt_size) { 2314 gd_buf[i] = cpu_to_le32(tmp); 2315 } 2316 ret = blk_co_pwrite(blk, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE, 2317 gd_buf_size, gd_buf, 0); 2318 if (ret < 0) { 2319 error_setg_errno(errp, -ret, 2320 "failed to write VMDK backup grain directory"); 2321 } 2322 2323 ret = 0; 2324 exit: 2325 g_free(gd_buf); 2326 return ret; 2327 } 2328 2329 static int coroutine_fn GRAPH_UNLOCKED 2330 vmdk_create_extent(const char *filename, int64_t filesize, bool flat, 2331 bool compress, bool zeroed_grain, BlockBackend **pbb, 2332 QemuOpts *opts, Error **errp) 2333 { 2334 int ret; 2335 BlockBackend *blk = NULL; 2336 2337 ret = bdrv_co_create_file(filename, opts, errp); 2338 if (ret < 0) { 2339 goto exit; 2340 } 2341 2342 blk = blk_co_new_open(filename, NULL, NULL, 2343 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, 2344 errp); 2345 if (blk == NULL) { 2346 ret = -EIO; 2347 goto exit; 2348 } 2349 2350 blk_set_allow_write_beyond_eof(blk, true); 2351 2352 ret = vmdk_init_extent(blk, filesize, flat, compress, zeroed_grain, errp); 2353 exit: 2354 if (blk) { 2355 if (pbb) { 2356 *pbb = blk; 2357 } else { 2358 blk_co_unref(blk); 2359 blk = NULL; 2360 } 2361 } 2362 return ret; 2363 } 2364 2365 static int filename_decompose(const char *filename, char *path, char *prefix, 2366 char *postfix, size_t buf_len, Error **errp) 2367 { 2368 const char *p, *q; 2369 2370 if (filename == NULL || !strlen(filename)) { 2371 error_setg(errp, "No filename provided"); 2372 return VMDK_ERROR; 2373 } 2374 p = strrchr(filename, '/'); 2375 if (p == NULL) { 2376 p = strrchr(filename, '\\'); 2377 } 2378 if (p == NULL) { 2379 p = strrchr(filename, ':'); 2380 } 2381 if (p != NULL) { 2382 p++; 2383 if (p - filename >= buf_len) { 2384 return VMDK_ERROR; 2385 } 2386 pstrcpy(path, p - filename + 1, filename); 2387 } else { 2388 p = filename; 2389 path[0] = '\0'; 2390 } 2391 q = strrchr(p, '.'); 2392 if (q == NULL) { 2393 pstrcpy(prefix, buf_len, p); 2394 postfix[0] = '\0'; 2395 } else { 2396 if (q - p >= buf_len) { 2397 return VMDK_ERROR; 2398 } 2399 pstrcpy(prefix, q - p + 1, p); 2400 pstrcpy(postfix, buf_len, q); 2401 } 2402 return VMDK_OK; 2403 } 2404 2405 /* 2406 * idx == 0: get or create the descriptor file (also the image file if in a 2407 * non-split format. 2408 * idx >= 1: get the n-th extent if in a split subformat 2409 */ 2410 typedef BlockBackend * coroutine_fn GRAPH_UNLOCKED_PTR 2411 (*vmdk_create_extent_fn)(int64_t size, int idx, bool flat, bool split, 2412 bool compress, bool zeroed_grain, void *opaque, 2413 Error **errp); 2414 2415 static void vmdk_desc_add_extent(GString *desc, 2416 const char *extent_line_fmt, 2417 int64_t size, const char *filename) 2418 { 2419 char *basename = g_path_get_basename(filename); 2420 2421 g_string_append_printf(desc, extent_line_fmt, 2422 DIV_ROUND_UP(size, BDRV_SECTOR_SIZE), basename); 2423 g_free(basename); 2424 } 2425 2426 static int coroutine_fn GRAPH_UNLOCKED 2427 vmdk_co_do_create(int64_t size, 2428 BlockdevVmdkSubformat subformat, 2429 BlockdevVmdkAdapterType adapter_type, 2430 const char *backing_file, 2431 const char *hw_version, 2432 const char *toolsversion, 2433 bool compat6, 2434 bool zeroed_grain, 2435 vmdk_create_extent_fn extent_fn, 2436 void *opaque, 2437 Error **errp) 2438 { 2439 int extent_idx; 2440 BlockBackend *blk = NULL; 2441 BlockBackend *extent_blk; 2442 Error *local_err = NULL; 2443 char *desc = NULL; 2444 int ret = 0; 2445 bool flat, split, compress; 2446 GString *ext_desc_lines; 2447 const int64_t split_size = 0x80000000; /* VMDK has constant split size */ 2448 int64_t extent_size; 2449 int64_t created_size = 0; 2450 const char *extent_line_fmt; 2451 char *parent_desc_line = g_malloc0(BUF_SIZE); 2452 uint32_t parent_cid = 0xffffffff; 2453 uint32_t number_heads = 16; 2454 uint32_t desc_offset = 0, desc_len; 2455 const char desc_template[] = 2456 "# Disk DescriptorFile\n" 2457 "version=1\n" 2458 "CID=%" PRIx32 "\n" 2459 "parentCID=%" PRIx32 "\n" 2460 "createType=\"%s\"\n" 2461 "%s" 2462 "\n" 2463 "# Extent description\n" 2464 "%s" 2465 "\n" 2466 "# The Disk Data Base\n" 2467 "#DDB\n" 2468 "\n" 2469 "ddb.virtualHWVersion = \"%s\"\n" 2470 "ddb.geometry.cylinders = \"%" PRId64 "\"\n" 2471 "ddb.geometry.heads = \"%" PRIu32 "\"\n" 2472 "ddb.geometry.sectors = \"63\"\n" 2473 "ddb.adapterType = \"%s\"\n" 2474 "ddb.toolsVersion = \"%s\"\n"; 2475 2476 ext_desc_lines = g_string_new(NULL); 2477 2478 /* Read out options */ 2479 if (compat6) { 2480 if (hw_version) { 2481 error_setg(errp, 2482 "compat6 cannot be enabled with hwversion set"); 2483 ret = -EINVAL; 2484 goto exit; 2485 } 2486 hw_version = "6"; 2487 } 2488 if (!hw_version) { 2489 hw_version = "4"; 2490 } 2491 if (!toolsversion) { 2492 toolsversion = "2147483647"; 2493 } 2494 2495 if (adapter_type != BLOCKDEV_VMDK_ADAPTER_TYPE_IDE) { 2496 /* that's the number of heads with which vmware operates when 2497 creating, exporting, etc. vmdk files with a non-ide adapter type */ 2498 number_heads = 255; 2499 } 2500 split = (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT) || 2501 (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTSPARSE); 2502 flat = (subformat == BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICFLAT) || 2503 (subformat == BLOCKDEV_VMDK_SUBFORMAT_TWOGBMAXEXTENTFLAT); 2504 compress = subformat == BLOCKDEV_VMDK_SUBFORMAT_STREAMOPTIMIZED; 2505 2506 if (flat) { 2507 extent_line_fmt = "RW %" PRId64 " FLAT \"%s\" 0\n"; 2508 } else { 2509 extent_line_fmt = "RW %" PRId64 " SPARSE \"%s\"\n"; 2510 } 2511 if (flat && backing_file) { 2512 error_setg(errp, "Flat image can't have backing file"); 2513 ret = -ENOTSUP; 2514 goto exit; 2515 } 2516 if (flat && zeroed_grain) { 2517 error_setg(errp, "Flat image can't enable zeroed grain"); 2518 ret = -ENOTSUP; 2519 goto exit; 2520 } 2521 2522 /* Create extents */ 2523 if (split) { 2524 extent_size = split_size; 2525 } else { 2526 extent_size = size; 2527 } 2528 if (!split && !flat) { 2529 created_size = extent_size; 2530 } else { 2531 created_size = 0; 2532 } 2533 /* Get the descriptor file BDS */ 2534 blk = extent_fn(created_size, 0, flat, split, compress, zeroed_grain, 2535 opaque, errp); 2536 if (!blk) { 2537 ret = -EIO; 2538 goto exit; 2539 } 2540 if (!split && !flat) { 2541 vmdk_desc_add_extent(ext_desc_lines, extent_line_fmt, created_size, 2542 blk_bs(blk)->filename); 2543 } 2544 2545 if (backing_file) { 2546 BlockBackend *backing; 2547 char *full_backing = 2548 bdrv_get_full_backing_filename_from_filename(blk_bs(blk)->filename, 2549 backing_file, 2550 &local_err); 2551 if (local_err) { 2552 error_propagate(errp, local_err); 2553 ret = -ENOENT; 2554 goto exit; 2555 } 2556 assert(full_backing); 2557 2558 backing = blk_co_new_open(full_backing, NULL, NULL, 2559 BDRV_O_NO_BACKING, errp); 2560 g_free(full_backing); 2561 if (backing == NULL) { 2562 ret = -EIO; 2563 goto exit; 2564 } 2565 if (strcmp(blk_bs(backing)->drv->format_name, "vmdk")) { 2566 error_setg(errp, "Invalid backing file format: %s. Must be vmdk", 2567 blk_bs(backing)->drv->format_name); 2568 blk_co_unref(backing); 2569 ret = -EINVAL; 2570 goto exit; 2571 } 2572 2573 bdrv_graph_co_rdlock(); 2574 ret = vmdk_read_cid(blk_bs(backing), 0, &parent_cid); 2575 bdrv_graph_co_rdunlock(); 2576 blk_co_unref(backing); 2577 if (ret) { 2578 error_setg(errp, "Failed to read parent CID"); 2579 goto exit; 2580 } 2581 snprintf(parent_desc_line, BUF_SIZE, 2582 "parentFileNameHint=\"%s\"", backing_file); 2583 } 2584 extent_idx = 1; 2585 while (created_size < size) { 2586 int64_t cur_size = MIN(size - created_size, extent_size); 2587 extent_blk = extent_fn(cur_size, extent_idx, flat, split, compress, 2588 zeroed_grain, opaque, errp); 2589 if (!extent_blk) { 2590 ret = -EINVAL; 2591 goto exit; 2592 } 2593 vmdk_desc_add_extent(ext_desc_lines, extent_line_fmt, cur_size, 2594 blk_bs(extent_blk)->filename); 2595 created_size += cur_size; 2596 extent_idx++; 2597 blk_co_unref(extent_blk); 2598 } 2599 2600 /* Check whether we got excess extents */ 2601 extent_blk = extent_fn(-1, extent_idx, flat, split, compress, zeroed_grain, 2602 opaque, NULL); 2603 if (extent_blk) { 2604 blk_co_unref(extent_blk); 2605 error_setg(errp, "List of extents contains unused extents"); 2606 ret = -EINVAL; 2607 goto exit; 2608 } 2609 2610 /* generate descriptor file */ 2611 desc = g_strdup_printf(desc_template, 2612 g_random_int(), 2613 parent_cid, 2614 BlockdevVmdkSubformat_str(subformat), 2615 parent_desc_line, 2616 ext_desc_lines->str, 2617 hw_version, 2618 size / 2619 (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE), 2620 number_heads, 2621 BlockdevVmdkAdapterType_str(adapter_type), 2622 toolsversion); 2623 desc_len = strlen(desc); 2624 /* the descriptor offset = 0x200 */ 2625 if (!split && !flat) { 2626 desc_offset = 0x200; 2627 } 2628 2629 ret = blk_co_pwrite(blk, desc_offset, desc_len, desc, 0); 2630 if (ret < 0) { 2631 error_setg_errno(errp, -ret, "Could not write description"); 2632 goto exit; 2633 } 2634 /* bdrv_pwrite write padding zeros to align to sector, we don't need that 2635 * for description file */ 2636 if (desc_offset == 0) { 2637 ret = blk_co_truncate(blk, desc_len, false, PREALLOC_MODE_OFF, 0, errp); 2638 if (ret < 0) { 2639 goto exit; 2640 } 2641 } 2642 ret = 0; 2643 exit: 2644 if (blk) { 2645 blk_co_unref(blk); 2646 } 2647 g_free(desc); 2648 g_free(parent_desc_line); 2649 g_string_free(ext_desc_lines, true); 2650 return ret; 2651 } 2652 2653 typedef struct { 2654 char *path; 2655 char *prefix; 2656 char *postfix; 2657 QemuOpts *opts; 2658 } VMDKCreateOptsData; 2659 2660 static BlockBackend * coroutine_fn GRAPH_UNLOCKED 2661 vmdk_co_create_opts_cb(int64_t size, int idx, bool flat, bool split, 2662 bool compress, bool zeroed_grain, void *opaque, 2663 Error **errp) 2664 { 2665 BlockBackend *blk = NULL; 2666 BlockDriverState *bs = NULL; 2667 VMDKCreateOptsData *data = opaque; 2668 char *ext_filename = NULL; 2669 char *rel_filename = NULL; 2670 2671 /* We're done, don't create excess extents. */ 2672 if (size == -1) { 2673 assert(errp == NULL); 2674 return NULL; 2675 } 2676 2677 if (idx == 0) { 2678 rel_filename = g_strdup_printf("%s%s", data->prefix, data->postfix); 2679 } else if (split) { 2680 rel_filename = g_strdup_printf("%s-%c%03d%s", 2681 data->prefix, 2682 flat ? 'f' : 's', idx, data->postfix); 2683 } else { 2684 assert(idx == 1); 2685 rel_filename = g_strdup_printf("%s-flat%s", data->prefix, data->postfix); 2686 } 2687 2688 ext_filename = g_strdup_printf("%s%s", data->path, rel_filename); 2689 g_free(rel_filename); 2690 2691 if (vmdk_create_extent(ext_filename, size, 2692 flat, compress, zeroed_grain, &blk, data->opts, 2693 errp)) { 2694 goto exit; 2695 } 2696 bdrv_co_unref(bs); 2697 exit: 2698 g_free(ext_filename); 2699 return blk; 2700 } 2701 2702 static int coroutine_fn GRAPH_UNLOCKED 2703 vmdk_co_create_opts(BlockDriver *drv, const char *filename, 2704 QemuOpts *opts, Error **errp) 2705 { 2706 Error *local_err = NULL; 2707 char *desc = NULL; 2708 int64_t total_size = 0; 2709 char *adapter_type = NULL; 2710 BlockdevVmdkAdapterType adapter_type_enum; 2711 char *backing_file = NULL; 2712 char *hw_version = NULL; 2713 char *toolsversion = NULL; 2714 char *fmt = NULL; 2715 BlockdevVmdkSubformat subformat; 2716 int ret = 0; 2717 char *path = g_malloc0(PATH_MAX); 2718 char *prefix = g_malloc0(PATH_MAX); 2719 char *postfix = g_malloc0(PATH_MAX); 2720 char *desc_line = g_malloc0(BUF_SIZE); 2721 char *ext_filename = g_malloc0(PATH_MAX); 2722 char *desc_filename = g_malloc0(PATH_MAX); 2723 char *parent_desc_line = g_malloc0(BUF_SIZE); 2724 bool zeroed_grain; 2725 bool compat6; 2726 VMDKCreateOptsData data; 2727 char *backing_fmt = NULL; 2728 2729 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT); 2730 if (backing_fmt && strcmp(backing_fmt, "vmdk") != 0) { 2731 error_setg(errp, "backing_file must be a vmdk image"); 2732 ret = -EINVAL; 2733 goto exit; 2734 } 2735 2736 if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) { 2737 ret = -EINVAL; 2738 goto exit; 2739 } 2740 /* Read out options */ 2741 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0), 2742 BDRV_SECTOR_SIZE); 2743 adapter_type = qemu_opt_get_del(opts, BLOCK_OPT_ADAPTER_TYPE); 2744 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE); 2745 hw_version = qemu_opt_get_del(opts, BLOCK_OPT_HWVERSION); 2746 toolsversion = qemu_opt_get_del(opts, BLOCK_OPT_TOOLSVERSION); 2747 compat6 = qemu_opt_get_bool_del(opts, BLOCK_OPT_COMPAT6, false); 2748 if (strcmp(hw_version, "undefined") == 0) { 2749 g_free(hw_version); 2750 hw_version = NULL; 2751 } 2752 fmt = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT); 2753 zeroed_grain = qemu_opt_get_bool_del(opts, BLOCK_OPT_ZEROED_GRAIN, false); 2754 2755 if (adapter_type) { 2756 adapter_type_enum = qapi_enum_parse(&BlockdevVmdkAdapterType_lookup, 2757 adapter_type, 2758 BLOCKDEV_VMDK_ADAPTER_TYPE_IDE, 2759 &local_err); 2760 if (local_err) { 2761 error_propagate(errp, local_err); 2762 ret = -EINVAL; 2763 goto exit; 2764 } 2765 } else { 2766 adapter_type_enum = BLOCKDEV_VMDK_ADAPTER_TYPE_IDE; 2767 } 2768 2769 if (!fmt) { 2770 /* Default format to monolithicSparse */ 2771 subformat = BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE; 2772 } else { 2773 subformat = qapi_enum_parse(&BlockdevVmdkSubformat_lookup, 2774 fmt, 2775 BLOCKDEV_VMDK_SUBFORMAT_MONOLITHICSPARSE, 2776 &local_err); 2777 if (local_err) { 2778 error_propagate(errp, local_err); 2779 ret = -EINVAL; 2780 goto exit; 2781 } 2782 } 2783 data = (VMDKCreateOptsData){ 2784 .prefix = prefix, 2785 .postfix = postfix, 2786 .path = path, 2787 .opts = opts, 2788 }; 2789 ret = vmdk_co_do_create(total_size, subformat, adapter_type_enum, 2790 backing_file, hw_version, toolsversion, compat6, 2791 zeroed_grain, vmdk_co_create_opts_cb, &data, errp); 2792 2793 exit: 2794 g_free(backing_fmt); 2795 g_free(adapter_type); 2796 g_free(backing_file); 2797 g_free(hw_version); 2798 g_free(toolsversion); 2799 g_free(fmt); 2800 g_free(desc); 2801 g_free(path); 2802 g_free(prefix); 2803 g_free(postfix); 2804 g_free(desc_line); 2805 g_free(ext_filename); 2806 g_free(desc_filename); 2807 g_free(parent_desc_line); 2808 return ret; 2809 } 2810 2811 static BlockBackend * coroutine_fn GRAPH_UNLOCKED 2812 vmdk_co_create_cb(int64_t size, int idx, bool flat, bool split, bool compress, 2813 bool zeroed_grain, void *opaque, Error **errp) 2814 { 2815 int ret; 2816 BlockDriverState *bs; 2817 BlockBackend *blk; 2818 BlockdevCreateOptionsVmdk *opts = opaque; 2819 2820 if (idx == 0) { 2821 bs = bdrv_co_open_blockdev_ref(opts->file, errp); 2822 } else { 2823 int i; 2824 BlockdevRefList *list = opts->extents; 2825 for (i = 1; i < idx; i++) { 2826 if (!list || !list->next) { 2827 error_setg(errp, "Extent [%d] not specified", i); 2828 return NULL; 2829 } 2830 list = list->next; 2831 } 2832 if (!list) { 2833 error_setg(errp, "Extent [%d] not specified", idx - 1); 2834 return NULL; 2835 } 2836 bs = bdrv_co_open_blockdev_ref(list->value, errp); 2837 } 2838 if (!bs) { 2839 return NULL; 2840 } 2841 blk = blk_co_new_with_bs(bs, 2842 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE | 2843 BLK_PERM_RESIZE, 2844 BLK_PERM_ALL, 2845 errp); 2846 if (!blk) { 2847 return NULL; 2848 } 2849 blk_set_allow_write_beyond_eof(blk, true); 2850 bdrv_co_unref(bs); 2851 2852 if (size != -1) { 2853 ret = vmdk_init_extent(blk, size, flat, compress, zeroed_grain, errp); 2854 if (ret) { 2855 blk_co_unref(blk); 2856 blk = NULL; 2857 } 2858 } 2859 return blk; 2860 } 2861 2862 static int coroutine_fn GRAPH_UNLOCKED 2863 vmdk_co_create(BlockdevCreateOptions *create_options, Error **errp) 2864 { 2865 BlockdevCreateOptionsVmdk *opts; 2866 2867 opts = &create_options->u.vmdk; 2868 2869 /* Validate options */ 2870 if (!QEMU_IS_ALIGNED(opts->size, BDRV_SECTOR_SIZE)) { 2871 error_setg(errp, "Image size must be a multiple of 512 bytes"); 2872 return -EINVAL; 2873 } 2874 2875 return vmdk_co_do_create(opts->size, 2876 opts->subformat, 2877 opts->adapter_type, 2878 opts->backing_file, 2879 opts->hwversion, 2880 opts->toolsversion, 2881 false, 2882 opts->zeroed_grain, 2883 vmdk_co_create_cb, 2884 opts, errp); 2885 } 2886 2887 static void vmdk_close(BlockDriverState *bs) 2888 { 2889 BDRVVmdkState *s = bs->opaque; 2890 2891 vmdk_free_extents(bs); 2892 g_free(s->create_type); 2893 2894 migrate_del_blocker(&s->migration_blocker); 2895 } 2896 2897 static int64_t coroutine_fn GRAPH_RDLOCK 2898 vmdk_co_get_allocated_file_size(BlockDriverState *bs) 2899 { 2900 int i; 2901 int64_t ret = 0; 2902 int64_t r; 2903 BDRVVmdkState *s = bs->opaque; 2904 2905 ret = bdrv_co_get_allocated_file_size(bs->file->bs); 2906 if (ret < 0) { 2907 return ret; 2908 } 2909 for (i = 0; i < s->num_extents; i++) { 2910 if (s->extents[i].file == bs->file) { 2911 continue; 2912 } 2913 r = bdrv_co_get_allocated_file_size(s->extents[i].file->bs); 2914 if (r < 0) { 2915 return r; 2916 } 2917 ret += r; 2918 } 2919 return ret; 2920 } 2921 2922 static int GRAPH_RDLOCK vmdk_has_zero_init(BlockDriverState *bs) 2923 { 2924 int i; 2925 BDRVVmdkState *s = bs->opaque; 2926 2927 /* If has a flat extent and its underlying storage doesn't have zero init, 2928 * return 0. */ 2929 for (i = 0; i < s->num_extents; i++) { 2930 if (s->extents[i].flat) { 2931 if (!bdrv_has_zero_init(s->extents[i].file->bs)) { 2932 return 0; 2933 } 2934 } 2935 } 2936 return 1; 2937 } 2938 2939 static VmdkExtentInfo * GRAPH_RDLOCK vmdk_get_extent_info(VmdkExtent *extent) 2940 { 2941 VmdkExtentInfo *info = g_new0(VmdkExtentInfo, 1); 2942 2943 bdrv_refresh_filename(extent->file->bs); 2944 *info = (VmdkExtentInfo){ 2945 .filename = g_strdup(extent->file->bs->filename), 2946 .format = g_strdup(extent->type), 2947 .virtual_size = extent->sectors * BDRV_SECTOR_SIZE, 2948 .compressed = extent->compressed, 2949 .has_compressed = extent->compressed, 2950 .cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE, 2951 .has_cluster_size = !extent->flat, 2952 }; 2953 2954 return info; 2955 } 2956 2957 static int coroutine_fn GRAPH_RDLOCK 2958 vmdk_co_check(BlockDriverState *bs, BdrvCheckResult *result, BdrvCheckMode fix) 2959 { 2960 BDRVVmdkState *s = bs->opaque; 2961 VmdkExtent *extent = NULL; 2962 int64_t sector_num = 0; 2963 int64_t total_sectors = bdrv_co_nb_sectors(bs); 2964 int ret; 2965 uint64_t cluster_offset; 2966 2967 if (fix) { 2968 return -ENOTSUP; 2969 } 2970 2971 for (;;) { 2972 if (sector_num >= total_sectors) { 2973 return 0; 2974 } 2975 extent = find_extent(s, sector_num, extent); 2976 if (!extent) { 2977 fprintf(stderr, 2978 "ERROR: could not find extent for sector %" PRId64 "\n", 2979 sector_num); 2980 ret = -EINVAL; 2981 break; 2982 } 2983 ret = get_cluster_offset(bs, extent, NULL, 2984 sector_num << BDRV_SECTOR_BITS, 2985 false, &cluster_offset, 0, 0); 2986 if (ret == VMDK_ERROR) { 2987 fprintf(stderr, 2988 "ERROR: could not get cluster_offset for sector %" 2989 PRId64 "\n", sector_num); 2990 break; 2991 } 2992 if (ret == VMDK_OK) { 2993 int64_t extent_len = bdrv_co_getlength(extent->file->bs); 2994 if (extent_len < 0) { 2995 fprintf(stderr, 2996 "ERROR: could not get extent file length for sector %" 2997 PRId64 "\n", sector_num); 2998 ret = extent_len; 2999 break; 3000 } 3001 if (cluster_offset >= extent_len) { 3002 fprintf(stderr, 3003 "ERROR: cluster offset for sector %" 3004 PRId64 " points after EOF\n", sector_num); 3005 ret = -EINVAL; 3006 break; 3007 } 3008 } 3009 sector_num += extent->cluster_sectors; 3010 } 3011 3012 result->corruptions++; 3013 return ret; 3014 } 3015 3016 static ImageInfoSpecific * GRAPH_RDLOCK 3017 vmdk_get_specific_info(BlockDriverState *bs, Error **errp) 3018 { 3019 int i; 3020 BDRVVmdkState *s = bs->opaque; 3021 ImageInfoSpecific *spec_info = g_new0(ImageInfoSpecific, 1); 3022 VmdkExtentInfoList **tail; 3023 3024 *spec_info = (ImageInfoSpecific){ 3025 .type = IMAGE_INFO_SPECIFIC_KIND_VMDK, 3026 .u = { 3027 .vmdk.data = g_new0(ImageInfoSpecificVmdk, 1), 3028 }, 3029 }; 3030 3031 *spec_info->u.vmdk.data = (ImageInfoSpecificVmdk) { 3032 .create_type = g_strdup(s->create_type), 3033 .cid = s->cid, 3034 .parent_cid = s->parent_cid, 3035 }; 3036 3037 tail = &spec_info->u.vmdk.data->extents; 3038 for (i = 0; i < s->num_extents; i++) { 3039 QAPI_LIST_APPEND(tail, vmdk_get_extent_info(&s->extents[i])); 3040 } 3041 3042 return spec_info; 3043 } 3044 3045 static bool vmdk_extents_type_eq(const VmdkExtent *a, const VmdkExtent *b) 3046 { 3047 return a->flat == b->flat && 3048 a->compressed == b->compressed && 3049 (a->flat || a->cluster_sectors == b->cluster_sectors); 3050 } 3051 3052 static int coroutine_fn 3053 vmdk_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 3054 { 3055 int i; 3056 BDRVVmdkState *s = bs->opaque; 3057 assert(s->num_extents); 3058 3059 /* See if we have multiple extents but they have different cases */ 3060 for (i = 1; i < s->num_extents; i++) { 3061 if (!vmdk_extents_type_eq(&s->extents[0], &s->extents[i])) { 3062 return -ENOTSUP; 3063 } 3064 } 3065 bdi->needs_compressed_writes = s->extents[0].compressed; 3066 if (!s->extents[0].flat) { 3067 bdi->cluster_size = s->extents[0].cluster_sectors << BDRV_SECTOR_BITS; 3068 } 3069 return 0; 3070 } 3071 3072 static void GRAPH_RDLOCK 3073 vmdk_gather_child_options(BlockDriverState *bs, QDict *target, 3074 bool backing_overridden) 3075 { 3076 /* No children but file and backing can be explicitly specified (TODO) */ 3077 qdict_put(target, "file", 3078 qobject_ref(bs->file->bs->full_open_options)); 3079 3080 if (backing_overridden) { 3081 if (bs->backing) { 3082 qdict_put(target, "backing", 3083 qobject_ref(bs->backing->bs->full_open_options)); 3084 } else { 3085 qdict_put_null(target, "backing"); 3086 } 3087 } 3088 } 3089 3090 static QemuOptsList vmdk_create_opts = { 3091 .name = "vmdk-create-opts", 3092 .head = QTAILQ_HEAD_INITIALIZER(vmdk_create_opts.head), 3093 .desc = { 3094 { 3095 .name = BLOCK_OPT_SIZE, 3096 .type = QEMU_OPT_SIZE, 3097 .help = "Virtual disk size" 3098 }, 3099 { 3100 .name = BLOCK_OPT_ADAPTER_TYPE, 3101 .type = QEMU_OPT_STRING, 3102 .help = "Virtual adapter type, can be one of " 3103 "ide (default), lsilogic, buslogic or legacyESX" 3104 }, 3105 { 3106 .name = BLOCK_OPT_BACKING_FILE, 3107 .type = QEMU_OPT_STRING, 3108 .help = "File name of a base image" 3109 }, 3110 { 3111 .name = BLOCK_OPT_BACKING_FMT, 3112 .type = QEMU_OPT_STRING, 3113 .help = "Must be 'vmdk' if present", 3114 }, 3115 { 3116 .name = BLOCK_OPT_COMPAT6, 3117 .type = QEMU_OPT_BOOL, 3118 .help = "VMDK version 6 image", 3119 .def_value_str = "off" 3120 }, 3121 { 3122 .name = BLOCK_OPT_HWVERSION, 3123 .type = QEMU_OPT_STRING, 3124 .help = "VMDK hardware version", 3125 .def_value_str = "undefined" 3126 }, 3127 { 3128 .name = BLOCK_OPT_TOOLSVERSION, 3129 .type = QEMU_OPT_STRING, 3130 .help = "VMware guest tools version", 3131 }, 3132 { 3133 .name = BLOCK_OPT_SUBFMT, 3134 .type = QEMU_OPT_STRING, 3135 .help = 3136 "VMDK flat extent format, can be one of " 3137 "{monolithicSparse (default) | monolithicFlat | twoGbMaxExtentSparse | twoGbMaxExtentFlat | streamOptimized} " 3138 }, 3139 { 3140 .name = BLOCK_OPT_ZEROED_GRAIN, 3141 .type = QEMU_OPT_BOOL, 3142 .help = "Enable efficient zero writes " 3143 "using the zeroed-grain GTE feature" 3144 }, 3145 { /* end of list */ } 3146 } 3147 }; 3148 3149 static BlockDriver bdrv_vmdk = { 3150 .format_name = "vmdk", 3151 .instance_size = sizeof(BDRVVmdkState), 3152 .bdrv_probe = vmdk_probe, 3153 .bdrv_open = vmdk_open, 3154 .bdrv_co_check = vmdk_co_check, 3155 .bdrv_reopen_prepare = vmdk_reopen_prepare, 3156 .bdrv_reopen_commit = vmdk_reopen_commit, 3157 .bdrv_reopen_abort = vmdk_reopen_abort, 3158 .bdrv_child_perm = bdrv_default_perms, 3159 .bdrv_co_preadv = vmdk_co_preadv, 3160 .bdrv_co_pwritev = vmdk_co_pwritev, 3161 .bdrv_co_pwritev_compressed = vmdk_co_pwritev_compressed, 3162 .bdrv_co_pwrite_zeroes = vmdk_co_pwrite_zeroes, 3163 .bdrv_close = vmdk_close, 3164 .bdrv_co_create_opts = vmdk_co_create_opts, 3165 .bdrv_co_create = vmdk_co_create, 3166 .bdrv_co_block_status = vmdk_co_block_status, 3167 .bdrv_co_get_allocated_file_size = vmdk_co_get_allocated_file_size, 3168 .bdrv_has_zero_init = vmdk_has_zero_init, 3169 .bdrv_get_specific_info = vmdk_get_specific_info, 3170 .bdrv_refresh_limits = vmdk_refresh_limits, 3171 .bdrv_co_get_info = vmdk_co_get_info, 3172 .bdrv_gather_child_options = vmdk_gather_child_options, 3173 3174 .is_format = true, 3175 .supports_backing = true, 3176 .create_opts = &vmdk_create_opts, 3177 }; 3178 3179 static void bdrv_vmdk_init(void) 3180 { 3181 bdrv_register(&bdrv_vmdk); 3182 } 3183 3184 block_init(bdrv_vmdk_init); 3185