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