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