qemu/block/vdi.c
<<
>>
Prefs
   1/*
   2 * Block driver for the Virtual Disk Image (VDI) format
   3 *
   4 * Copyright (c) 2009, 2012 Stefan Weil
   5 *
   6 * This program is free software: you can redistribute it and/or modify
   7 * it under the terms of the GNU General Public License as published by
   8 * the Free Software Foundation, either version 2 of the License, or
   9 * (at your option) version 3 or any later version.
  10 *
  11 * This program is distributed in the hope that it will be useful,
  12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14 * GNU General Public License for more details.
  15 *
  16 * You should have received a copy of the GNU General Public License
  17 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18 *
  19 * Reference:
  20 * http://forums.virtualbox.org/viewtopic.php?t=8046
  21 *
  22 * This driver supports create / read / write operations on VDI images.
  23 *
  24 * Todo (see also TODO in code):
  25 *
  26 * Some features like snapshots are still missing.
  27 *
  28 * Deallocation of zero-filled blocks and shrinking images are missing, too
  29 * (might be added to common block layer).
  30 *
  31 * Allocation of blocks could be optimized (less writes to block map and
  32 * header).
  33 *
  34 * Read and write of adjacent blocks could be done in one operation
  35 * (current code uses one operation per block (1 MiB).
  36 *
  37 * The code is not thread safe (missing locks for changes in header and
  38 * block table, no problem with current QEMU).
  39 *
  40 * Hints:
  41 *
  42 * Blocks (VDI documentation) correspond to clusters (QEMU).
  43 * QEMU's backing files could be implemented using VDI snapshot files (TODO).
  44 * VDI snapshot files may also contain the complete machine state.
  45 * Maybe this machine state can be converted to QEMU PC machine snapshot data.
  46 *
  47 * The driver keeps a block cache (little endian entries) in memory.
  48 * For the standard block size (1 MiB), a 1 TiB disk will use 4 MiB RAM,
  49 * so this seems to be reasonable.
  50 */
  51
  52#include "qemu/osdep.h"
  53#include "qapi/error.h"
  54#include "block/block_int.h"
  55#include "sysemu/block-backend.h"
  56#include "qemu/module.h"
  57#include "qemu/bswap.h"
  58#include "migration/blocker.h"
  59#include "qemu/coroutine.h"
  60#include "qemu/cutils.h"
  61#include "qemu/uuid.h"
  62
  63/* Code configuration options. */
  64
  65/* Enable debug messages. */
  66//~ #define CONFIG_VDI_DEBUG
  67
  68/* Support write operations on VDI images. */
  69#define CONFIG_VDI_WRITE
  70
  71/* Support non-standard block (cluster) size. This is untested.
  72 * Maybe it will be needed for very large images.
  73 */
  74//~ #define CONFIG_VDI_BLOCK_SIZE
  75
  76/* Support static (fixed, pre-allocated) images. */
  77#define CONFIG_VDI_STATIC_IMAGE
  78
  79/* Command line option for static images. */
  80#define BLOCK_OPT_STATIC "static"
  81
  82#define KiB     1024
  83#define MiB     (KiB * KiB)
  84
  85#define SECTOR_SIZE 512
  86#define DEFAULT_CLUSTER_SIZE (1 * MiB)
  87
  88#if defined(CONFIG_VDI_DEBUG)
  89#define logout(fmt, ...) \
  90                fprintf(stderr, "vdi\t%-24s" fmt, __func__, ##__VA_ARGS__)
  91#else
  92#define logout(fmt, ...) ((void)0)
  93#endif
  94
  95/* Image signature. */
  96#define VDI_SIGNATURE 0xbeda107f
  97
  98/* Image version. */
  99#define VDI_VERSION_1_1 0x00010001
 100
 101/* Image type. */
 102#define VDI_TYPE_DYNAMIC 1
 103#define VDI_TYPE_STATIC  2
 104
 105/* Innotek / SUN images use these strings in header.text:
 106 * "<<< innotek VirtualBox Disk Image >>>\n"
 107 * "<<< Sun xVM VirtualBox Disk Image >>>\n"
 108 * "<<< Sun VirtualBox Disk Image >>>\n"
 109 * The value does not matter, so QEMU created images use a different text.
 110 */
 111#define VDI_TEXT "<<< QEMU VM Virtual Disk Image >>>\n"
 112
 113/* A never-allocated block; semantically arbitrary content. */
 114#define VDI_UNALLOCATED 0xffffffffU
 115
 116/* A discarded (no longer allocated) block; semantically zero-filled. */
 117#define VDI_DISCARDED   0xfffffffeU
 118
 119#define VDI_IS_ALLOCATED(X) ((X) < VDI_DISCARDED)
 120
 121/* The bmap will take up VDI_BLOCKS_IN_IMAGE_MAX * sizeof(uint32_t) bytes; since
 122 * the bmap is read and written in a single operation, its size needs to be
 123 * limited to INT_MAX; furthermore, when opening an image, the bmap size is
 124 * rounded up to be aligned on BDRV_SECTOR_SIZE.
 125 * Therefore this should satisfy the following:
 126 * VDI_BLOCKS_IN_IMAGE_MAX * sizeof(uint32_t) + BDRV_SECTOR_SIZE == INT_MAX + 1
 127 * (INT_MAX + 1 is the first value not representable as an int)
 128 * This guarantees that any value below or equal to the constant will, when
 129 * multiplied by sizeof(uint32_t) and rounded up to a BDRV_SECTOR_SIZE boundary,
 130 * still be below or equal to INT_MAX. */
 131#define VDI_BLOCKS_IN_IMAGE_MAX \
 132    ((unsigned)((INT_MAX + 1u - BDRV_SECTOR_SIZE) / sizeof(uint32_t)))
 133#define VDI_DISK_SIZE_MAX        ((uint64_t)VDI_BLOCKS_IN_IMAGE_MAX * \
 134                                  (uint64_t)DEFAULT_CLUSTER_SIZE)
 135
 136typedef struct {
 137    char text[0x40];
 138    uint32_t signature;
 139    uint32_t version;
 140    uint32_t header_size;
 141    uint32_t image_type;
 142    uint32_t image_flags;
 143    char description[256];
 144    uint32_t offset_bmap;
 145    uint32_t offset_data;
 146    uint32_t cylinders;         /* disk geometry, unused here */
 147    uint32_t heads;             /* disk geometry, unused here */
 148    uint32_t sectors;           /* disk geometry, unused here */
 149    uint32_t sector_size;
 150    uint32_t unused1;
 151    uint64_t disk_size;
 152    uint32_t block_size;
 153    uint32_t block_extra;       /* unused here */
 154    uint32_t blocks_in_image;
 155    uint32_t blocks_allocated;
 156    QemuUUID uuid_image;
 157    QemuUUID uuid_last_snap;
 158    QemuUUID uuid_link;
 159    QemuUUID uuid_parent;
 160    uint64_t unused2[7];
 161} QEMU_PACKED VdiHeader;
 162
 163typedef struct {
 164    /* The block map entries are little endian (even in memory). */
 165    uint32_t *bmap;
 166    /* Size of block (bytes). */
 167    uint32_t block_size;
 168    /* Size of block (sectors). */
 169    uint32_t block_sectors;
 170    /* First sector of block map. */
 171    uint32_t bmap_sector;
 172    /* VDI header (converted to host endianness). */
 173    VdiHeader header;
 174
 175    CoRwlock bmap_lock;
 176
 177    Error *migration_blocker;
 178} BDRVVdiState;
 179
 180static void vdi_header_to_cpu(VdiHeader *header)
 181{
 182    le32_to_cpus(&header->signature);
 183    le32_to_cpus(&header->version);
 184    le32_to_cpus(&header->header_size);
 185    le32_to_cpus(&header->image_type);
 186    le32_to_cpus(&header->image_flags);
 187    le32_to_cpus(&header->offset_bmap);
 188    le32_to_cpus(&header->offset_data);
 189    le32_to_cpus(&header->cylinders);
 190    le32_to_cpus(&header->heads);
 191    le32_to_cpus(&header->sectors);
 192    le32_to_cpus(&header->sector_size);
 193    le64_to_cpus(&header->disk_size);
 194    le32_to_cpus(&header->block_size);
 195    le32_to_cpus(&header->block_extra);
 196    le32_to_cpus(&header->blocks_in_image);
 197    le32_to_cpus(&header->blocks_allocated);
 198    qemu_uuid_bswap(&header->uuid_image);
 199    qemu_uuid_bswap(&header->uuid_last_snap);
 200    qemu_uuid_bswap(&header->uuid_link);
 201    qemu_uuid_bswap(&header->uuid_parent);
 202}
 203
 204static void vdi_header_to_le(VdiHeader *header)
 205{
 206    cpu_to_le32s(&header->signature);
 207    cpu_to_le32s(&header->version);
 208    cpu_to_le32s(&header->header_size);
 209    cpu_to_le32s(&header->image_type);
 210    cpu_to_le32s(&header->image_flags);
 211    cpu_to_le32s(&header->offset_bmap);
 212    cpu_to_le32s(&header->offset_data);
 213    cpu_to_le32s(&header->cylinders);
 214    cpu_to_le32s(&header->heads);
 215    cpu_to_le32s(&header->sectors);
 216    cpu_to_le32s(&header->sector_size);
 217    cpu_to_le64s(&header->disk_size);
 218    cpu_to_le32s(&header->block_size);
 219    cpu_to_le32s(&header->block_extra);
 220    cpu_to_le32s(&header->blocks_in_image);
 221    cpu_to_le32s(&header->blocks_allocated);
 222    qemu_uuid_bswap(&header->uuid_image);
 223    qemu_uuid_bswap(&header->uuid_last_snap);
 224    qemu_uuid_bswap(&header->uuid_link);
 225    qemu_uuid_bswap(&header->uuid_parent);
 226}
 227
 228#if defined(CONFIG_VDI_DEBUG)
 229static void vdi_header_print(VdiHeader *header)
 230{
 231    char uuid[37];
 232    logout("text        %s", header->text);
 233    logout("signature   0x%08x\n", header->signature);
 234    logout("header size 0x%04x\n", header->header_size);
 235    logout("image type  0x%04x\n", header->image_type);
 236    logout("image flags 0x%04x\n", header->image_flags);
 237    logout("description %s\n", header->description);
 238    logout("offset bmap 0x%04x\n", header->offset_bmap);
 239    logout("offset data 0x%04x\n", header->offset_data);
 240    logout("cylinders   0x%04x\n", header->cylinders);
 241    logout("heads       0x%04x\n", header->heads);
 242    logout("sectors     0x%04x\n", header->sectors);
 243    logout("sector size 0x%04x\n", header->sector_size);
 244    logout("image size  0x%" PRIx64 " B (%" PRIu64 " MiB)\n",
 245           header->disk_size, header->disk_size / MiB);
 246    logout("block size  0x%04x\n", header->block_size);
 247    logout("block extra 0x%04x\n", header->block_extra);
 248    logout("blocks tot. 0x%04x\n", header->blocks_in_image);
 249    logout("blocks all. 0x%04x\n", header->blocks_allocated);
 250    uuid_unparse(header->uuid_image, uuid);
 251    logout("uuid image  %s\n", uuid);
 252    uuid_unparse(header->uuid_last_snap, uuid);
 253    logout("uuid snap   %s\n", uuid);
 254    uuid_unparse(header->uuid_link, uuid);
 255    logout("uuid link   %s\n", uuid);
 256    uuid_unparse(header->uuid_parent, uuid);
 257    logout("uuid parent %s\n", uuid);
 258}
 259#endif
 260
 261static int vdi_check(BlockDriverState *bs, BdrvCheckResult *res,
 262                     BdrvCheckMode fix)
 263{
 264    /* TODO: additional checks possible. */
 265    BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
 266    uint32_t blocks_allocated = 0;
 267    uint32_t block;
 268    uint32_t *bmap;
 269    logout("\n");
 270
 271    if (fix) {
 272        return -ENOTSUP;
 273    }
 274
 275    bmap = g_try_new(uint32_t, s->header.blocks_in_image);
 276    if (s->header.blocks_in_image && bmap == NULL) {
 277        res->check_errors++;
 278        return -ENOMEM;
 279    }
 280
 281    memset(bmap, 0xff, s->header.blocks_in_image * sizeof(uint32_t));
 282
 283    /* Check block map and value of blocks_allocated. */
 284    for (block = 0; block < s->header.blocks_in_image; block++) {
 285        uint32_t bmap_entry = le32_to_cpu(s->bmap[block]);
 286        if (VDI_IS_ALLOCATED(bmap_entry)) {
 287            if (bmap_entry < s->header.blocks_in_image) {
 288                blocks_allocated++;
 289                if (!VDI_IS_ALLOCATED(bmap[bmap_entry])) {
 290                    bmap[bmap_entry] = bmap_entry;
 291                } else {
 292                    fprintf(stderr, "ERROR: block index %" PRIu32
 293                            " also used by %" PRIu32 "\n", bmap[bmap_entry], bmap_entry);
 294                    res->corruptions++;
 295                }
 296            } else {
 297                fprintf(stderr, "ERROR: block index %" PRIu32
 298                        " too large, is %" PRIu32 "\n", block, bmap_entry);
 299                res->corruptions++;
 300            }
 301        }
 302    }
 303    if (blocks_allocated != s->header.blocks_allocated) {
 304        fprintf(stderr, "ERROR: allocated blocks mismatch, is %" PRIu32
 305               ", should be %" PRIu32 "\n",
 306               blocks_allocated, s->header.blocks_allocated);
 307        res->corruptions++;
 308    }
 309
 310    g_free(bmap);
 311
 312    return 0;
 313}
 314
 315static int vdi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
 316{
 317    /* TODO: vdi_get_info would be needed for machine snapshots.
 318       vm_state_offset is still missing. */
 319    BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
 320    logout("\n");
 321    bdi->cluster_size = s->block_size;
 322    bdi->vm_state_offset = 0;
 323    bdi->unallocated_blocks_are_zero = true;
 324    return 0;
 325}
 326
 327static int vdi_make_empty(BlockDriverState *bs)
 328{
 329    /* TODO: missing code. */
 330    logout("\n");
 331    /* The return value for missing code must be 0, see block.c. */
 332    return 0;
 333}
 334
 335static int vdi_probe(const uint8_t *buf, int buf_size, const char *filename)
 336{
 337    const VdiHeader *header = (const VdiHeader *)buf;
 338    int ret = 0;
 339
 340    logout("\n");
 341
 342    if (buf_size < sizeof(*header)) {
 343        /* Header too small, no VDI. */
 344    } else if (le32_to_cpu(header->signature) == VDI_SIGNATURE) {
 345        ret = 100;
 346    }
 347
 348    if (ret == 0) {
 349        logout("no vdi image\n");
 350    } else {
 351        logout("%s", header->text);
 352    }
 353
 354    return ret;
 355}
 356
 357static int vdi_open(BlockDriverState *bs, QDict *options, int flags,
 358                    Error **errp)
 359{
 360    BDRVVdiState *s = bs->opaque;
 361    VdiHeader header;
 362    size_t bmap_size;
 363    int ret;
 364    Error *local_err = NULL;
 365
 366    bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
 367                               false, errp);
 368    if (!bs->file) {
 369        return -EINVAL;
 370    }
 371
 372    logout("\n");
 373
 374    ret = bdrv_read(bs->file, 0, (uint8_t *)&header, 1);
 375    if (ret < 0) {
 376        goto fail;
 377    }
 378
 379    vdi_header_to_cpu(&header);
 380#if defined(CONFIG_VDI_DEBUG)
 381    vdi_header_print(&header);
 382#endif
 383
 384    if (header.disk_size > VDI_DISK_SIZE_MAX) {
 385        error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64
 386                          ", max supported is 0x%" PRIx64 ")",
 387                          header.disk_size, VDI_DISK_SIZE_MAX);
 388        ret = -ENOTSUP;
 389        goto fail;
 390    }
 391
 392    if (header.disk_size % SECTOR_SIZE != 0) {
 393        /* 'VBoxManage convertfromraw' can create images with odd disk sizes.
 394           We accept them but round the disk size to the next multiple of
 395           SECTOR_SIZE. */
 396        logout("odd disk size %" PRIu64 " B, round up\n", header.disk_size);
 397        header.disk_size = ROUND_UP(header.disk_size, SECTOR_SIZE);
 398    }
 399
 400    if (header.signature != VDI_SIGNATURE) {
 401        error_setg(errp, "Image not in VDI format (bad signature %08" PRIx32
 402                   ")", header.signature);
 403        ret = -EINVAL;
 404        goto fail;
 405    } else if (header.version != VDI_VERSION_1_1) {
 406        error_setg(errp, "unsupported VDI image (version %" PRIu32 ".%" PRIu32
 407                   ")", header.version >> 16, header.version & 0xffff);
 408        ret = -ENOTSUP;
 409        goto fail;
 410    } else if (header.offset_bmap % SECTOR_SIZE != 0) {
 411        /* We only support block maps which start on a sector boundary. */
 412        error_setg(errp, "unsupported VDI image (unaligned block map offset "
 413                   "0x%" PRIx32 ")", header.offset_bmap);
 414        ret = -ENOTSUP;
 415        goto fail;
 416    } else if (header.offset_data % SECTOR_SIZE != 0) {
 417        /* We only support data blocks which start on a sector boundary. */
 418        error_setg(errp, "unsupported VDI image (unaligned data offset 0x%"
 419                   PRIx32 ")", header.offset_data);
 420        ret = -ENOTSUP;
 421        goto fail;
 422    } else if (header.sector_size != SECTOR_SIZE) {
 423        error_setg(errp, "unsupported VDI image (sector size %" PRIu32
 424                   " is not %u)", header.sector_size, SECTOR_SIZE);
 425        ret = -ENOTSUP;
 426        goto fail;
 427    } else if (header.block_size != DEFAULT_CLUSTER_SIZE) {
 428        error_setg(errp, "unsupported VDI image (block size %" PRIu32
 429                   " is not %u)", header.block_size, DEFAULT_CLUSTER_SIZE);
 430        ret = -ENOTSUP;
 431        goto fail;
 432    } else if (header.disk_size >
 433               (uint64_t)header.blocks_in_image * header.block_size) {
 434        error_setg(errp, "unsupported VDI image (disk size %" PRIu64 ", "
 435                   "image bitmap has room for %" PRIu64 ")",
 436                   header.disk_size,
 437                   (uint64_t)header.blocks_in_image * header.block_size);
 438        ret = -ENOTSUP;
 439        goto fail;
 440    } else if (!qemu_uuid_is_null(&header.uuid_link)) {
 441        error_setg(errp, "unsupported VDI image (non-NULL link UUID)");
 442        ret = -ENOTSUP;
 443        goto fail;
 444    } else if (!qemu_uuid_is_null(&header.uuid_parent)) {
 445        error_setg(errp, "unsupported VDI image (non-NULL parent UUID)");
 446        ret = -ENOTSUP;
 447        goto fail;
 448    } else if (header.blocks_in_image > VDI_BLOCKS_IN_IMAGE_MAX) {
 449        error_setg(errp, "unsupported VDI image "
 450                         "(too many blocks %u, max is %u)",
 451                          header.blocks_in_image, VDI_BLOCKS_IN_IMAGE_MAX);
 452        ret = -ENOTSUP;
 453        goto fail;
 454    }
 455
 456    bs->total_sectors = header.disk_size / SECTOR_SIZE;
 457
 458    s->block_size = header.block_size;
 459    s->block_sectors = header.block_size / SECTOR_SIZE;
 460    s->bmap_sector = header.offset_bmap / SECTOR_SIZE;
 461    s->header = header;
 462
 463    bmap_size = header.blocks_in_image * sizeof(uint32_t);
 464    bmap_size = DIV_ROUND_UP(bmap_size, SECTOR_SIZE);
 465    s->bmap = qemu_try_blockalign(bs->file->bs, bmap_size * SECTOR_SIZE);
 466    if (s->bmap == NULL) {
 467        ret = -ENOMEM;
 468        goto fail;
 469    }
 470
 471    ret = bdrv_read(bs->file, s->bmap_sector, (uint8_t *)s->bmap,
 472                    bmap_size);
 473    if (ret < 0) {
 474        goto fail_free_bmap;
 475    }
 476
 477    /* Disable migration when vdi images are used */
 478    error_setg(&s->migration_blocker, "The vdi format used by node '%s' "
 479               "does not support live migration",
 480               bdrv_get_device_or_node_name(bs));
 481    ret = migrate_add_blocker(s->migration_blocker, &local_err);
 482    if (local_err) {
 483        error_propagate(errp, local_err);
 484        error_free(s->migration_blocker);
 485        goto fail_free_bmap;
 486    }
 487
 488    qemu_co_rwlock_init(&s->bmap_lock);
 489
 490    return 0;
 491
 492 fail_free_bmap:
 493    qemu_vfree(s->bmap);
 494
 495 fail:
 496    return ret;
 497}
 498
 499static int vdi_reopen_prepare(BDRVReopenState *state,
 500                              BlockReopenQueue *queue, Error **errp)
 501{
 502    return 0;
 503}
 504
 505static int64_t coroutine_fn vdi_co_get_block_status(BlockDriverState *bs,
 506        int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
 507{
 508    /* TODO: Check for too large sector_num (in bdrv_is_allocated or here). */
 509    BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
 510    size_t bmap_index = sector_num / s->block_sectors;
 511    size_t sector_in_block = sector_num % s->block_sectors;
 512    int n_sectors = s->block_sectors - sector_in_block;
 513    uint32_t bmap_entry = le32_to_cpu(s->bmap[bmap_index]);
 514    uint64_t offset;
 515    int result;
 516
 517    logout("%p, %" PRId64 ", %d, %p\n", bs, sector_num, nb_sectors, pnum);
 518    if (n_sectors > nb_sectors) {
 519        n_sectors = nb_sectors;
 520    }
 521    *pnum = n_sectors;
 522    result = VDI_IS_ALLOCATED(bmap_entry);
 523    if (!result) {
 524        return 0;
 525    }
 526
 527    offset = s->header.offset_data +
 528                              (uint64_t)bmap_entry * s->block_size +
 529                              sector_in_block * SECTOR_SIZE;
 530    *file = bs->file->bs;
 531    return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
 532}
 533
 534static int coroutine_fn
 535vdi_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
 536              QEMUIOVector *qiov, int flags)
 537{
 538    BDRVVdiState *s = bs->opaque;
 539    QEMUIOVector local_qiov;
 540    uint32_t bmap_entry;
 541    uint32_t block_index;
 542    uint32_t offset_in_block;
 543    uint32_t n_bytes;
 544    uint64_t bytes_done = 0;
 545    int ret = 0;
 546
 547    logout("\n");
 548
 549    qemu_iovec_init(&local_qiov, qiov->niov);
 550
 551    while (ret >= 0 && bytes > 0) {
 552        block_index = offset / s->block_size;
 553        offset_in_block = offset % s->block_size;
 554        n_bytes = MIN(bytes, s->block_size - offset_in_block);
 555
 556        logout("will read %u bytes starting at offset %" PRIu64 "\n",
 557               n_bytes, offset);
 558
 559        /* prepare next AIO request */
 560        qemu_co_rwlock_rdlock(&s->bmap_lock);
 561        bmap_entry = le32_to_cpu(s->bmap[block_index]);
 562        qemu_co_rwlock_unlock(&s->bmap_lock);
 563        if (!VDI_IS_ALLOCATED(bmap_entry)) {
 564            /* Block not allocated, return zeros, no need to wait. */
 565            qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
 566            ret = 0;
 567        } else {
 568            uint64_t data_offset = s->header.offset_data +
 569                                   (uint64_t)bmap_entry * s->block_size +
 570                                   offset_in_block;
 571
 572            qemu_iovec_reset(&local_qiov);
 573            qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
 574
 575            ret = bdrv_co_preadv(bs->file, data_offset, n_bytes,
 576                                 &local_qiov, 0);
 577        }
 578        logout("%u bytes read\n", n_bytes);
 579
 580        bytes -= n_bytes;
 581        offset += n_bytes;
 582        bytes_done += n_bytes;
 583    }
 584
 585    qemu_iovec_destroy(&local_qiov);
 586
 587    return ret;
 588}
 589
 590static int coroutine_fn
 591vdi_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
 592               QEMUIOVector *qiov, int flags)
 593{
 594    BDRVVdiState *s = bs->opaque;
 595    QEMUIOVector local_qiov;
 596    uint32_t bmap_entry;
 597    uint32_t block_index;
 598    uint32_t offset_in_block;
 599    uint32_t n_bytes;
 600    uint64_t data_offset;
 601    uint32_t bmap_first = VDI_UNALLOCATED;
 602    uint32_t bmap_last = VDI_UNALLOCATED;
 603    uint8_t *block = NULL;
 604    uint64_t bytes_done = 0;
 605    int ret = 0;
 606
 607    logout("\n");
 608
 609    qemu_iovec_init(&local_qiov, qiov->niov);
 610
 611    while (ret >= 0 && bytes > 0) {
 612        block_index = offset / s->block_size;
 613        offset_in_block = offset % s->block_size;
 614        n_bytes = MIN(bytes, s->block_size - offset_in_block);
 615
 616        logout("will write %u bytes starting at offset %" PRIu64 "\n",
 617               n_bytes, offset);
 618
 619        /* prepare next AIO request */
 620        qemu_co_rwlock_rdlock(&s->bmap_lock);
 621        bmap_entry = le32_to_cpu(s->bmap[block_index]);
 622        if (!VDI_IS_ALLOCATED(bmap_entry)) {
 623            /* Allocate new block and write to it. */
 624            uint64_t data_offset;
 625            qemu_co_rwlock_upgrade(&s->bmap_lock);
 626            bmap_entry = le32_to_cpu(s->bmap[block_index]);
 627            if (VDI_IS_ALLOCATED(bmap_entry)) {
 628                /* A concurrent allocation did the work for us.  */
 629                qemu_co_rwlock_downgrade(&s->bmap_lock);
 630                goto nonallocating_write;
 631            }
 632
 633            bmap_entry = s->header.blocks_allocated;
 634            s->bmap[block_index] = cpu_to_le32(bmap_entry);
 635            s->header.blocks_allocated++;
 636            data_offset = s->header.offset_data +
 637                          (uint64_t)bmap_entry * s->block_size;
 638            if (block == NULL) {
 639                block = g_malloc(s->block_size);
 640                bmap_first = block_index;
 641            }
 642            bmap_last = block_index;
 643            /* Copy data to be written to new block and zero unused parts. */
 644            memset(block, 0, offset_in_block);
 645            qemu_iovec_to_buf(qiov, bytes_done, block + offset_in_block,
 646                              n_bytes);
 647            memset(block + offset_in_block + n_bytes, 0,
 648                   s->block_size - n_bytes - offset_in_block);
 649
 650            /* Write the new block under CoRwLock write-side protection,
 651             * so this full-cluster write does not overlap a partial write
 652             * of the same cluster, issued from the "else" branch.
 653             */
 654            ret = bdrv_pwrite(bs->file, data_offset, block, s->block_size);
 655            qemu_co_rwlock_unlock(&s->bmap_lock);
 656        } else {
 657nonallocating_write:
 658            data_offset = s->header.offset_data +
 659                           (uint64_t)bmap_entry * s->block_size +
 660                           offset_in_block;
 661            qemu_co_rwlock_unlock(&s->bmap_lock);
 662
 663            qemu_iovec_reset(&local_qiov);
 664            qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
 665
 666            ret = bdrv_co_pwritev(bs->file, data_offset, n_bytes,
 667                                  &local_qiov, 0);
 668        }
 669
 670        bytes -= n_bytes;
 671        offset += n_bytes;
 672        bytes_done += n_bytes;
 673
 674        logout("%u bytes written\n", n_bytes);
 675    }
 676
 677    qemu_iovec_destroy(&local_qiov);
 678
 679    logout("finished data write\n");
 680    if (ret < 0) {
 681        return ret;
 682    }
 683
 684    if (block) {
 685        /* One or more new blocks were allocated. */
 686        VdiHeader *header = (VdiHeader *) block;
 687        uint8_t *base;
 688        uint64_t offset;
 689        uint32_t n_sectors;
 690
 691        logout("now writing modified header\n");
 692        assert(VDI_IS_ALLOCATED(bmap_first));
 693        *header = s->header;
 694        vdi_header_to_le(header);
 695        ret = bdrv_write(bs->file, 0, block, 1);
 696        g_free(block);
 697        block = NULL;
 698
 699        if (ret < 0) {
 700            return ret;
 701        }
 702
 703        logout("now writing modified block map entry %u...%u\n",
 704               bmap_first, bmap_last);
 705        /* Write modified sectors from block map. */
 706        bmap_first /= (SECTOR_SIZE / sizeof(uint32_t));
 707        bmap_last /= (SECTOR_SIZE / sizeof(uint32_t));
 708        n_sectors = bmap_last - bmap_first + 1;
 709        offset = s->bmap_sector + bmap_first;
 710        base = ((uint8_t *)&s->bmap[0]) + bmap_first * SECTOR_SIZE;
 711        logout("will write %u block map sectors starting from entry %u\n",
 712               n_sectors, bmap_first);
 713        ret = bdrv_write(bs->file, offset, base, n_sectors);
 714    }
 715
 716    return ret;
 717}
 718
 719static int vdi_create(const char *filename, QemuOpts *opts, Error **errp)
 720{
 721    int ret = 0;
 722    uint64_t bytes = 0;
 723    uint32_t blocks;
 724    size_t block_size = DEFAULT_CLUSTER_SIZE;
 725    uint32_t image_type = VDI_TYPE_DYNAMIC;
 726    VdiHeader header;
 727    size_t i;
 728    size_t bmap_size;
 729    int64_t offset = 0;
 730    Error *local_err = NULL;
 731    BlockBackend *blk = NULL;
 732    uint32_t *bmap = NULL;
 733
 734    logout("\n");
 735
 736    /* Read out options. */
 737    bytes = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
 738                     BDRV_SECTOR_SIZE);
 739#if defined(CONFIG_VDI_BLOCK_SIZE)
 740    /* TODO: Additional checks (SECTOR_SIZE * 2^n, ...). */
 741    block_size = qemu_opt_get_size_del(opts,
 742                                       BLOCK_OPT_CLUSTER_SIZE,
 743                                       DEFAULT_CLUSTER_SIZE);
 744#endif
 745#if defined(CONFIG_VDI_STATIC_IMAGE)
 746    if (qemu_opt_get_bool_del(opts, BLOCK_OPT_STATIC, false)) {
 747        image_type = VDI_TYPE_STATIC;
 748    }
 749#endif
 750
 751    if (bytes > VDI_DISK_SIZE_MAX) {
 752        ret = -ENOTSUP;
 753        error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64
 754                          ", max supported is 0x%" PRIx64 ")",
 755                          bytes, VDI_DISK_SIZE_MAX);
 756        goto exit;
 757    }
 758
 759    ret = bdrv_create_file(filename, opts, &local_err);
 760    if (ret < 0) {
 761        error_propagate(errp, local_err);
 762        goto exit;
 763    }
 764
 765    blk = blk_new_open(filename, NULL, NULL,
 766                       BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
 767                       &local_err);
 768    if (blk == NULL) {
 769        error_propagate(errp, local_err);
 770        ret = -EIO;
 771        goto exit;
 772    }
 773
 774    blk_set_allow_write_beyond_eof(blk, true);
 775
 776    /* We need enough blocks to store the given disk size,
 777       so always round up. */
 778    blocks = DIV_ROUND_UP(bytes, block_size);
 779
 780    bmap_size = blocks * sizeof(uint32_t);
 781    bmap_size = ROUND_UP(bmap_size, SECTOR_SIZE);
 782
 783    memset(&header, 0, sizeof(header));
 784    pstrcpy(header.text, sizeof(header.text), VDI_TEXT);
 785    header.signature = VDI_SIGNATURE;
 786    header.version = VDI_VERSION_1_1;
 787    header.header_size = 0x180;
 788    header.image_type = image_type;
 789    header.offset_bmap = 0x200;
 790    header.offset_data = 0x200 + bmap_size;
 791    header.sector_size = SECTOR_SIZE;
 792    header.disk_size = bytes;
 793    header.block_size = block_size;
 794    header.blocks_in_image = blocks;
 795    if (image_type == VDI_TYPE_STATIC) {
 796        header.blocks_allocated = blocks;
 797    }
 798    qemu_uuid_generate(&header.uuid_image);
 799    qemu_uuid_generate(&header.uuid_last_snap);
 800    /* There is no need to set header.uuid_link or header.uuid_parent here. */
 801#if defined(CONFIG_VDI_DEBUG)
 802    vdi_header_print(&header);
 803#endif
 804    vdi_header_to_le(&header);
 805    ret = blk_pwrite(blk, offset, &header, sizeof(header), 0);
 806    if (ret < 0) {
 807        error_setg(errp, "Error writing header to %s", filename);
 808        goto exit;
 809    }
 810    offset += sizeof(header);
 811
 812    if (bmap_size > 0) {
 813        bmap = g_try_malloc0(bmap_size);
 814        if (bmap == NULL) {
 815            ret = -ENOMEM;
 816            error_setg(errp, "Could not allocate bmap");
 817            goto exit;
 818        }
 819        for (i = 0; i < blocks; i++) {
 820            if (image_type == VDI_TYPE_STATIC) {
 821                bmap[i] = i;
 822            } else {
 823                bmap[i] = VDI_UNALLOCATED;
 824            }
 825        }
 826        ret = blk_pwrite(blk, offset, bmap, bmap_size, 0);
 827        if (ret < 0) {
 828            error_setg(errp, "Error writing bmap to %s", filename);
 829            goto exit;
 830        }
 831        offset += bmap_size;
 832    }
 833
 834    if (image_type == VDI_TYPE_STATIC) {
 835        ret = blk_truncate(blk, offset + blocks * block_size,
 836                           PREALLOC_MODE_OFF, errp);
 837        if (ret < 0) {
 838            error_prepend(errp, "Failed to statically allocate %s", filename);
 839            goto exit;
 840        }
 841    }
 842
 843exit:
 844    blk_unref(blk);
 845    g_free(bmap);
 846    return ret;
 847}
 848
 849static void vdi_close(BlockDriverState *bs)
 850{
 851    BDRVVdiState *s = bs->opaque;
 852
 853    qemu_vfree(s->bmap);
 854
 855    migrate_del_blocker(s->migration_blocker);
 856    error_free(s->migration_blocker);
 857}
 858
 859static QemuOptsList vdi_create_opts = {
 860    .name = "vdi-create-opts",
 861    .head = QTAILQ_HEAD_INITIALIZER(vdi_create_opts.head),
 862    .desc = {
 863        {
 864            .name = BLOCK_OPT_SIZE,
 865            .type = QEMU_OPT_SIZE,
 866            .help = "Virtual disk size"
 867        },
 868#if defined(CONFIG_VDI_BLOCK_SIZE)
 869        {
 870            .name = BLOCK_OPT_CLUSTER_SIZE,
 871            .type = QEMU_OPT_SIZE,
 872            .help = "VDI cluster (block) size",
 873            .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
 874        },
 875#endif
 876#if defined(CONFIG_VDI_STATIC_IMAGE)
 877        {
 878            .name = BLOCK_OPT_STATIC,
 879            .type = QEMU_OPT_BOOL,
 880            .help = "VDI static (pre-allocated) image",
 881            .def_value_str = "off"
 882        },
 883#endif
 884        /* TODO: An additional option to set UUID values might be useful. */
 885        { /* end of list */ }
 886    }
 887};
 888
 889static BlockDriver bdrv_vdi = {
 890    .format_name = "vdi",
 891    .instance_size = sizeof(BDRVVdiState),
 892    .bdrv_probe = vdi_probe,
 893    .bdrv_open = vdi_open,
 894    .bdrv_close = vdi_close,
 895    .bdrv_reopen_prepare = vdi_reopen_prepare,
 896    .bdrv_child_perm          = bdrv_format_default_perms,
 897    .bdrv_create = vdi_create,
 898    .bdrv_has_zero_init = bdrv_has_zero_init_1,
 899    .bdrv_co_get_block_status = vdi_co_get_block_status,
 900    .bdrv_make_empty = vdi_make_empty,
 901
 902    .bdrv_co_preadv     = vdi_co_preadv,
 903#if defined(CONFIG_VDI_WRITE)
 904    .bdrv_co_pwritev    = vdi_co_pwritev,
 905#endif
 906
 907    .bdrv_get_info = vdi_get_info,
 908
 909    .create_opts = &vdi_create_opts,
 910    .bdrv_check = vdi_check,
 911};
 912
 913static void bdrv_vdi_init(void)
 914{
 915    logout("\n");
 916    bdrv_register(&bdrv_vdi);
 917}
 918
 919block_init(bdrv_vdi_init);
 920