qemu/block/qed.c
<<
>>
Prefs
   1/*
   2 * QEMU Enhanced Disk Format
   3 *
   4 * Copyright IBM, Corp. 2010
   5 *
   6 * Authors:
   7 *  Stefan Hajnoczi   <stefanha@linux.vnet.ibm.com>
   8 *  Anthony Liguori   <aliguori@us.ibm.com>
   9 *
  10 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
  11 * See the COPYING.LIB file in the top-level directory.
  12 *
  13 */
  14
  15#include "qemu/osdep.h"
  16#include "block/qdict.h"
  17#include "qapi/error.h"
  18#include "qemu/timer.h"
  19#include "qemu/bswap.h"
  20#include "qemu/option.h"
  21#include "trace.h"
  22#include "qed.h"
  23#include "sysemu/block-backend.h"
  24#include "qapi/qmp/qdict.h"
  25#include "qapi/qobject-input-visitor.h"
  26#include "qapi/qapi-visit-block-core.h"
  27
  28static QemuOptsList qed_create_opts;
  29
  30static int bdrv_qed_probe(const uint8_t *buf, int buf_size,
  31                          const char *filename)
  32{
  33    const QEDHeader *header = (const QEDHeader *)buf;
  34
  35    if (buf_size < sizeof(*header)) {
  36        return 0;
  37    }
  38    if (le32_to_cpu(header->magic) != QED_MAGIC) {
  39        return 0;
  40    }
  41    return 100;
  42}
  43
  44/**
  45 * Check whether an image format is raw
  46 *
  47 * @fmt:    Backing file format, may be NULL
  48 */
  49static bool qed_fmt_is_raw(const char *fmt)
  50{
  51    return fmt && strcmp(fmt, "raw") == 0;
  52}
  53
  54static void qed_header_le_to_cpu(const QEDHeader *le, QEDHeader *cpu)
  55{
  56    cpu->magic = le32_to_cpu(le->magic);
  57    cpu->cluster_size = le32_to_cpu(le->cluster_size);
  58    cpu->table_size = le32_to_cpu(le->table_size);
  59    cpu->header_size = le32_to_cpu(le->header_size);
  60    cpu->features = le64_to_cpu(le->features);
  61    cpu->compat_features = le64_to_cpu(le->compat_features);
  62    cpu->autoclear_features = le64_to_cpu(le->autoclear_features);
  63    cpu->l1_table_offset = le64_to_cpu(le->l1_table_offset);
  64    cpu->image_size = le64_to_cpu(le->image_size);
  65    cpu->backing_filename_offset = le32_to_cpu(le->backing_filename_offset);
  66    cpu->backing_filename_size = le32_to_cpu(le->backing_filename_size);
  67}
  68
  69static void qed_header_cpu_to_le(const QEDHeader *cpu, QEDHeader *le)
  70{
  71    le->magic = cpu_to_le32(cpu->magic);
  72    le->cluster_size = cpu_to_le32(cpu->cluster_size);
  73    le->table_size = cpu_to_le32(cpu->table_size);
  74    le->header_size = cpu_to_le32(cpu->header_size);
  75    le->features = cpu_to_le64(cpu->features);
  76    le->compat_features = cpu_to_le64(cpu->compat_features);
  77    le->autoclear_features = cpu_to_le64(cpu->autoclear_features);
  78    le->l1_table_offset = cpu_to_le64(cpu->l1_table_offset);
  79    le->image_size = cpu_to_le64(cpu->image_size);
  80    le->backing_filename_offset = cpu_to_le32(cpu->backing_filename_offset);
  81    le->backing_filename_size = cpu_to_le32(cpu->backing_filename_size);
  82}
  83
  84int qed_write_header_sync(BDRVQEDState *s)
  85{
  86    QEDHeader le;
  87    int ret;
  88
  89    qed_header_cpu_to_le(&s->header, &le);
  90    ret = bdrv_pwrite(s->bs->file, 0, &le, sizeof(le));
  91    if (ret != sizeof(le)) {
  92        return ret;
  93    }
  94    return 0;
  95}
  96
  97/**
  98 * Update header in-place (does not rewrite backing filename or other strings)
  99 *
 100 * This function only updates known header fields in-place and does not affect
 101 * extra data after the QED header.
 102 *
 103 * No new allocating reqs can start while this function runs.
 104 */
 105static int coroutine_fn qed_write_header(BDRVQEDState *s)
 106{
 107    /* We must write full sectors for O_DIRECT but cannot necessarily generate
 108     * the data following the header if an unrecognized compat feature is
 109     * active.  Therefore, first read the sectors containing the header, update
 110     * them, and write back.
 111     */
 112
 113    int nsectors = DIV_ROUND_UP(sizeof(QEDHeader), BDRV_SECTOR_SIZE);
 114    size_t len = nsectors * BDRV_SECTOR_SIZE;
 115    uint8_t *buf;
 116    struct iovec iov;
 117    QEMUIOVector qiov;
 118    int ret;
 119
 120    assert(s->allocating_acb || s->allocating_write_reqs_plugged);
 121
 122    buf = qemu_blockalign(s->bs, len);
 123    iov = (struct iovec) {
 124        .iov_base = buf,
 125        .iov_len = len,
 126    };
 127    qemu_iovec_init_external(&qiov, &iov, 1);
 128
 129    ret = bdrv_co_preadv(s->bs->file, 0, qiov.size, &qiov, 0);
 130    if (ret < 0) {
 131        goto out;
 132    }
 133
 134    /* Update header */
 135    qed_header_cpu_to_le(&s->header, (QEDHeader *) buf);
 136
 137    ret = bdrv_co_pwritev(s->bs->file, 0, qiov.size,  &qiov, 0);
 138    if (ret < 0) {
 139        goto out;
 140    }
 141
 142    ret = 0;
 143out:
 144    qemu_vfree(buf);
 145    return ret;
 146}
 147
 148static uint64_t qed_max_image_size(uint32_t cluster_size, uint32_t table_size)
 149{
 150    uint64_t table_entries;
 151    uint64_t l2_size;
 152
 153    table_entries = (table_size * cluster_size) / sizeof(uint64_t);
 154    l2_size = table_entries * cluster_size;
 155
 156    return l2_size * table_entries;
 157}
 158
 159static bool qed_is_cluster_size_valid(uint32_t cluster_size)
 160{
 161    if (cluster_size < QED_MIN_CLUSTER_SIZE ||
 162        cluster_size > QED_MAX_CLUSTER_SIZE) {
 163        return false;
 164    }
 165    if (cluster_size & (cluster_size - 1)) {
 166        return false; /* not power of 2 */
 167    }
 168    return true;
 169}
 170
 171static bool qed_is_table_size_valid(uint32_t table_size)
 172{
 173    if (table_size < QED_MIN_TABLE_SIZE ||
 174        table_size > QED_MAX_TABLE_SIZE) {
 175        return false;
 176    }
 177    if (table_size & (table_size - 1)) {
 178        return false; /* not power of 2 */
 179    }
 180    return true;
 181}
 182
 183static bool qed_is_image_size_valid(uint64_t image_size, uint32_t cluster_size,
 184                                    uint32_t table_size)
 185{
 186    if (image_size % BDRV_SECTOR_SIZE != 0) {
 187        return false; /* not multiple of sector size */
 188    }
 189    if (image_size > qed_max_image_size(cluster_size, table_size)) {
 190        return false; /* image is too large */
 191    }
 192    return true;
 193}
 194
 195/**
 196 * Read a string of known length from the image file
 197 *
 198 * @file:       Image file
 199 * @offset:     File offset to start of string, in bytes
 200 * @n:          String length in bytes
 201 * @buf:        Destination buffer
 202 * @buflen:     Destination buffer length in bytes
 203 * @ret:        0 on success, -errno on failure
 204 *
 205 * The string is NUL-terminated.
 206 */
 207static int qed_read_string(BdrvChild *file, uint64_t offset, size_t n,
 208                           char *buf, size_t buflen)
 209{
 210    int ret;
 211    if (n >= buflen) {
 212        return -EINVAL;
 213    }
 214    ret = bdrv_pread(file, offset, buf, n);
 215    if (ret < 0) {
 216        return ret;
 217    }
 218    buf[n] = '\0';
 219    return 0;
 220}
 221
 222/**
 223 * Allocate new clusters
 224 *
 225 * @s:          QED state
 226 * @n:          Number of contiguous clusters to allocate
 227 * @ret:        Offset of first allocated cluster
 228 *
 229 * This function only produces the offset where the new clusters should be
 230 * written.  It updates BDRVQEDState but does not make any changes to the image
 231 * file.
 232 *
 233 * Called with table_lock held.
 234 */
 235static uint64_t qed_alloc_clusters(BDRVQEDState *s, unsigned int n)
 236{
 237    uint64_t offset = s->file_size;
 238    s->file_size += n * s->header.cluster_size;
 239    return offset;
 240}
 241
 242QEDTable *qed_alloc_table(BDRVQEDState *s)
 243{
 244    /* Honor O_DIRECT memory alignment requirements */
 245    return qemu_blockalign(s->bs,
 246                           s->header.cluster_size * s->header.table_size);
 247}
 248
 249/**
 250 * Allocate a new zeroed L2 table
 251 *
 252 * Called with table_lock held.
 253 */
 254static CachedL2Table *qed_new_l2_table(BDRVQEDState *s)
 255{
 256    CachedL2Table *l2_table = qed_alloc_l2_cache_entry(&s->l2_cache);
 257
 258    l2_table->table = qed_alloc_table(s);
 259    l2_table->offset = qed_alloc_clusters(s, s->header.table_size);
 260
 261    memset(l2_table->table->offsets, 0,
 262           s->header.cluster_size * s->header.table_size);
 263    return l2_table;
 264}
 265
 266static bool qed_plug_allocating_write_reqs(BDRVQEDState *s)
 267{
 268    qemu_co_mutex_lock(&s->table_lock);
 269
 270    /* No reentrancy is allowed.  */
 271    assert(!s->allocating_write_reqs_plugged);
 272    if (s->allocating_acb != NULL) {
 273        /* Another allocating write came concurrently.  This cannot happen
 274         * from bdrv_qed_co_drain_begin, but it can happen when the timer runs.
 275         */
 276        qemu_co_mutex_unlock(&s->table_lock);
 277        return false;
 278    }
 279
 280    s->allocating_write_reqs_plugged = true;
 281    qemu_co_mutex_unlock(&s->table_lock);
 282    return true;
 283}
 284
 285static void qed_unplug_allocating_write_reqs(BDRVQEDState *s)
 286{
 287    qemu_co_mutex_lock(&s->table_lock);
 288    assert(s->allocating_write_reqs_plugged);
 289    s->allocating_write_reqs_plugged = false;
 290    qemu_co_queue_next(&s->allocating_write_reqs);
 291    qemu_co_mutex_unlock(&s->table_lock);
 292}
 293
 294static void coroutine_fn qed_need_check_timer_entry(void *opaque)
 295{
 296    BDRVQEDState *s = opaque;
 297    int ret;
 298
 299    trace_qed_need_check_timer_cb(s);
 300
 301    if (!qed_plug_allocating_write_reqs(s)) {
 302        return;
 303    }
 304
 305    /* Ensure writes are on disk before clearing flag */
 306    ret = bdrv_co_flush(s->bs->file->bs);
 307    if (ret < 0) {
 308        qed_unplug_allocating_write_reqs(s);
 309        return;
 310    }
 311
 312    s->header.features &= ~QED_F_NEED_CHECK;
 313    ret = qed_write_header(s);
 314    (void) ret;
 315
 316    qed_unplug_allocating_write_reqs(s);
 317
 318    ret = bdrv_co_flush(s->bs);
 319    (void) ret;
 320}
 321
 322static void qed_need_check_timer_cb(void *opaque)
 323{
 324    Coroutine *co = qemu_coroutine_create(qed_need_check_timer_entry, opaque);
 325    qemu_coroutine_enter(co);
 326}
 327
 328static void qed_start_need_check_timer(BDRVQEDState *s)
 329{
 330    trace_qed_start_need_check_timer(s);
 331
 332    /* Use QEMU_CLOCK_VIRTUAL so we don't alter the image file while suspended for
 333     * migration.
 334     */
 335    timer_mod(s->need_check_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
 336                   NANOSECONDS_PER_SECOND * QED_NEED_CHECK_TIMEOUT);
 337}
 338
 339/* It's okay to call this multiple times or when no timer is started */
 340static void qed_cancel_need_check_timer(BDRVQEDState *s)
 341{
 342    trace_qed_cancel_need_check_timer(s);
 343    timer_del(s->need_check_timer);
 344}
 345
 346static void bdrv_qed_detach_aio_context(BlockDriverState *bs)
 347{
 348    BDRVQEDState *s = bs->opaque;
 349
 350    qed_cancel_need_check_timer(s);
 351    timer_free(s->need_check_timer);
 352}
 353
 354static void bdrv_qed_attach_aio_context(BlockDriverState *bs,
 355                                        AioContext *new_context)
 356{
 357    BDRVQEDState *s = bs->opaque;
 358
 359    s->need_check_timer = aio_timer_new(new_context,
 360                                        QEMU_CLOCK_VIRTUAL, SCALE_NS,
 361                                        qed_need_check_timer_cb, s);
 362    if (s->header.features & QED_F_NEED_CHECK) {
 363        qed_start_need_check_timer(s);
 364    }
 365}
 366
 367static void coroutine_fn bdrv_qed_co_drain_begin(BlockDriverState *bs)
 368{
 369    BDRVQEDState *s = bs->opaque;
 370
 371    /* Fire the timer immediately in order to start doing I/O as soon as the
 372     * header is flushed.
 373     */
 374    if (s->need_check_timer && timer_pending(s->need_check_timer)) {
 375        qed_cancel_need_check_timer(s);
 376        qed_need_check_timer_entry(s);
 377    }
 378}
 379
 380static void bdrv_qed_init_state(BlockDriverState *bs)
 381{
 382    BDRVQEDState *s = bs->opaque;
 383
 384    memset(s, 0, sizeof(BDRVQEDState));
 385    s->bs = bs;
 386    qemu_co_mutex_init(&s->table_lock);
 387    qemu_co_queue_init(&s->allocating_write_reqs);
 388}
 389
 390/* Called with table_lock held.  */
 391static int coroutine_fn bdrv_qed_do_open(BlockDriverState *bs, QDict *options,
 392                                         int flags, Error **errp)
 393{
 394    BDRVQEDState *s = bs->opaque;
 395    QEDHeader le_header;
 396    int64_t file_size;
 397    int ret;
 398
 399    ret = bdrv_pread(bs->file, 0, &le_header, sizeof(le_header));
 400    if (ret < 0) {
 401        return ret;
 402    }
 403    qed_header_le_to_cpu(&le_header, &s->header);
 404
 405    if (s->header.magic != QED_MAGIC) {
 406        error_setg(errp, "Image not in QED format");
 407        return -EINVAL;
 408    }
 409    if (s->header.features & ~QED_FEATURE_MASK) {
 410        /* image uses unsupported feature bits */
 411        error_setg(errp, "Unsupported QED features: %" PRIx64,
 412                   s->header.features & ~QED_FEATURE_MASK);
 413        return -ENOTSUP;
 414    }
 415    if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
 416        return -EINVAL;
 417    }
 418
 419    /* Round down file size to the last cluster */
 420    file_size = bdrv_getlength(bs->file->bs);
 421    if (file_size < 0) {
 422        return file_size;
 423    }
 424    s->file_size = qed_start_of_cluster(s, file_size);
 425
 426    if (!qed_is_table_size_valid(s->header.table_size)) {
 427        return -EINVAL;
 428    }
 429    if (!qed_is_image_size_valid(s->header.image_size,
 430                                 s->header.cluster_size,
 431                                 s->header.table_size)) {
 432        return -EINVAL;
 433    }
 434    if (!qed_check_table_offset(s, s->header.l1_table_offset)) {
 435        return -EINVAL;
 436    }
 437
 438    s->table_nelems = (s->header.cluster_size * s->header.table_size) /
 439                      sizeof(uint64_t);
 440    s->l2_shift = ctz32(s->header.cluster_size);
 441    s->l2_mask = s->table_nelems - 1;
 442    s->l1_shift = s->l2_shift + ctz32(s->table_nelems);
 443
 444    /* Header size calculation must not overflow uint32_t */
 445    if (s->header.header_size > UINT32_MAX / s->header.cluster_size) {
 446        return -EINVAL;
 447    }
 448
 449    if ((s->header.features & QED_F_BACKING_FILE)) {
 450        if ((uint64_t)s->header.backing_filename_offset +
 451            s->header.backing_filename_size >
 452            s->header.cluster_size * s->header.header_size) {
 453            return -EINVAL;
 454        }
 455
 456        ret = qed_read_string(bs->file, s->header.backing_filename_offset,
 457                              s->header.backing_filename_size, bs->backing_file,
 458                              sizeof(bs->backing_file));
 459        if (ret < 0) {
 460            return ret;
 461        }
 462
 463        if (s->header.features & QED_F_BACKING_FORMAT_NO_PROBE) {
 464            pstrcpy(bs->backing_format, sizeof(bs->backing_format), "raw");
 465        }
 466    }
 467
 468    /* Reset unknown autoclear feature bits.  This is a backwards
 469     * compatibility mechanism that allows images to be opened by older
 470     * programs, which "knock out" unknown feature bits.  When an image is
 471     * opened by a newer program again it can detect that the autoclear
 472     * feature is no longer valid.
 473     */
 474    if ((s->header.autoclear_features & ~QED_AUTOCLEAR_FEATURE_MASK) != 0 &&
 475        !bdrv_is_read_only(bs->file->bs) && !(flags & BDRV_O_INACTIVE)) {
 476        s->header.autoclear_features &= QED_AUTOCLEAR_FEATURE_MASK;
 477
 478        ret = qed_write_header_sync(s);
 479        if (ret) {
 480            return ret;
 481        }
 482
 483        /* From here on only known autoclear feature bits are valid */
 484        bdrv_flush(bs->file->bs);
 485    }
 486
 487    s->l1_table = qed_alloc_table(s);
 488    qed_init_l2_cache(&s->l2_cache);
 489
 490    ret = qed_read_l1_table_sync(s);
 491    if (ret) {
 492        goto out;
 493    }
 494
 495    /* If image was not closed cleanly, check consistency */
 496    if (!(flags & BDRV_O_CHECK) && (s->header.features & QED_F_NEED_CHECK)) {
 497        /* Read-only images cannot be fixed.  There is no risk of corruption
 498         * since write operations are not possible.  Therefore, allow
 499         * potentially inconsistent images to be opened read-only.  This can
 500         * aid data recovery from an otherwise inconsistent image.
 501         */
 502        if (!bdrv_is_read_only(bs->file->bs) &&
 503            !(flags & BDRV_O_INACTIVE)) {
 504            BdrvCheckResult result = {0};
 505
 506            ret = qed_check(s, &result, true);
 507            if (ret) {
 508                goto out;
 509            }
 510        }
 511    }
 512
 513    bdrv_qed_attach_aio_context(bs, bdrv_get_aio_context(bs));
 514
 515out:
 516    if (ret) {
 517        qed_free_l2_cache(&s->l2_cache);
 518        qemu_vfree(s->l1_table);
 519    }
 520    return ret;
 521}
 522
 523typedef struct QEDOpenCo {
 524    BlockDriverState *bs;
 525    QDict *options;
 526    int flags;
 527    Error **errp;
 528    int ret;
 529} QEDOpenCo;
 530
 531static void coroutine_fn bdrv_qed_open_entry(void *opaque)
 532{
 533    QEDOpenCo *qoc = opaque;
 534    BDRVQEDState *s = qoc->bs->opaque;
 535
 536    qemu_co_mutex_lock(&s->table_lock);
 537    qoc->ret = bdrv_qed_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
 538    qemu_co_mutex_unlock(&s->table_lock);
 539}
 540
 541static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
 542                         Error **errp)
 543{
 544    QEDOpenCo qoc = {
 545        .bs = bs,
 546        .options = options,
 547        .flags = flags,
 548        .errp = errp,
 549        .ret = -EINPROGRESS
 550    };
 551
 552    bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
 553                               false, errp);
 554    if (!bs->file) {
 555        return -EINVAL;
 556    }
 557
 558    bdrv_qed_init_state(bs);
 559    if (qemu_in_coroutine()) {
 560        bdrv_qed_open_entry(&qoc);
 561    } else {
 562        qemu_coroutine_enter(qemu_coroutine_create(bdrv_qed_open_entry, &qoc));
 563        BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
 564    }
 565    BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
 566    return qoc.ret;
 567}
 568
 569static void bdrv_qed_refresh_limits(BlockDriverState *bs, Error **errp)
 570{
 571    BDRVQEDState *s = bs->opaque;
 572
 573    bs->bl.pwrite_zeroes_alignment = s->header.cluster_size;
 574}
 575
 576/* We have nothing to do for QED reopen, stubs just return
 577 * success */
 578static int bdrv_qed_reopen_prepare(BDRVReopenState *state,
 579                                   BlockReopenQueue *queue, Error **errp)
 580{
 581    return 0;
 582}
 583
 584static void bdrv_qed_close(BlockDriverState *bs)
 585{
 586    BDRVQEDState *s = bs->opaque;
 587
 588    bdrv_qed_detach_aio_context(bs);
 589
 590    /* Ensure writes reach stable storage */
 591    bdrv_flush(bs->file->bs);
 592
 593    /* Clean shutdown, no check required on next open */
 594    if (s->header.features & QED_F_NEED_CHECK) {
 595        s->header.features &= ~QED_F_NEED_CHECK;
 596        qed_write_header_sync(s);
 597    }
 598
 599    qed_free_l2_cache(&s->l2_cache);
 600    qemu_vfree(s->l1_table);
 601}
 602
 603static int coroutine_fn bdrv_qed_co_create(BlockdevCreateOptions *opts,
 604                                           Error **errp)
 605{
 606    BlockdevCreateOptionsQed *qed_opts;
 607    BlockBackend *blk = NULL;
 608    BlockDriverState *bs = NULL;
 609
 610    QEDHeader header;
 611    QEDHeader le_header;
 612    uint8_t *l1_table = NULL;
 613    size_t l1_size;
 614    int ret = 0;
 615
 616    assert(opts->driver == BLOCKDEV_DRIVER_QED);
 617    qed_opts = &opts->u.qed;
 618
 619    /* Validate options and set default values */
 620    if (!qed_opts->has_cluster_size) {
 621        qed_opts->cluster_size = QED_DEFAULT_CLUSTER_SIZE;
 622    }
 623    if (!qed_opts->has_table_size) {
 624        qed_opts->table_size = QED_DEFAULT_TABLE_SIZE;
 625    }
 626
 627    if (!qed_is_cluster_size_valid(qed_opts->cluster_size)) {
 628        error_setg(errp, "QED cluster size must be within range [%u, %u] "
 629                         "and power of 2",
 630                   QED_MIN_CLUSTER_SIZE, QED_MAX_CLUSTER_SIZE);
 631        return -EINVAL;
 632    }
 633    if (!qed_is_table_size_valid(qed_opts->table_size)) {
 634        error_setg(errp, "QED table size must be within range [%u, %u] "
 635                         "and power of 2",
 636                   QED_MIN_TABLE_SIZE, QED_MAX_TABLE_SIZE);
 637        return -EINVAL;
 638    }
 639    if (!qed_is_image_size_valid(qed_opts->size, qed_opts->cluster_size,
 640                                 qed_opts->table_size))
 641    {
 642        error_setg(errp, "QED image size must be a non-zero multiple of "
 643                         "cluster size and less than %" PRIu64 " bytes",
 644                   qed_max_image_size(qed_opts->cluster_size,
 645                                      qed_opts->table_size));
 646        return -EINVAL;
 647    }
 648
 649    /* Create BlockBackend to write to the image */
 650    bs = bdrv_open_blockdev_ref(qed_opts->file, errp);
 651    if (bs == NULL) {
 652        return -EIO;
 653    }
 654
 655    blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
 656    ret = blk_insert_bs(blk, bs, errp);
 657    if (ret < 0) {
 658        goto out;
 659    }
 660    blk_set_allow_write_beyond_eof(blk, true);
 661
 662    /* Prepare image format */
 663    header = (QEDHeader) {
 664        .magic = QED_MAGIC,
 665        .cluster_size = qed_opts->cluster_size,
 666        .table_size = qed_opts->table_size,
 667        .header_size = 1,
 668        .features = 0,
 669        .compat_features = 0,
 670        .l1_table_offset = qed_opts->cluster_size,
 671        .image_size = qed_opts->size,
 672    };
 673
 674    l1_size = header.cluster_size * header.table_size;
 675
 676    /* File must start empty and grow, check truncate is supported */
 677    ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
 678    if (ret < 0) {
 679        goto out;
 680    }
 681
 682    if (qed_opts->has_backing_file) {
 683        header.features |= QED_F_BACKING_FILE;
 684        header.backing_filename_offset = sizeof(le_header);
 685        header.backing_filename_size = strlen(qed_opts->backing_file);
 686
 687        if (qed_opts->has_backing_fmt) {
 688            const char *backing_fmt = BlockdevDriver_str(qed_opts->backing_fmt);
 689            if (qed_fmt_is_raw(backing_fmt)) {
 690                header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
 691            }
 692        }
 693    }
 694
 695    qed_header_cpu_to_le(&header, &le_header);
 696    ret = blk_pwrite(blk, 0, &le_header, sizeof(le_header), 0);
 697    if (ret < 0) {
 698        goto out;
 699    }
 700    ret = blk_pwrite(blk, sizeof(le_header), qed_opts->backing_file,
 701                     header.backing_filename_size, 0);
 702    if (ret < 0) {
 703        goto out;
 704    }
 705
 706    l1_table = g_malloc0(l1_size);
 707    ret = blk_pwrite(blk, header.l1_table_offset, l1_table, l1_size, 0);
 708    if (ret < 0) {
 709        goto out;
 710    }
 711
 712    ret = 0; /* success */
 713out:
 714    g_free(l1_table);
 715    blk_unref(blk);
 716    bdrv_unref(bs);
 717    return ret;
 718}
 719
 720static int coroutine_fn bdrv_qed_co_create_opts(const char *filename,
 721                                                QemuOpts *opts,
 722                                                Error **errp)
 723{
 724    BlockdevCreateOptions *create_options = NULL;
 725    QDict *qdict;
 726    Visitor *v;
 727    BlockDriverState *bs = NULL;
 728    Error *local_err = NULL;
 729    int ret;
 730
 731    static const QDictRenames opt_renames[] = {
 732        { BLOCK_OPT_BACKING_FILE,       "backing-file" },
 733        { BLOCK_OPT_BACKING_FMT,        "backing-fmt" },
 734        { BLOCK_OPT_CLUSTER_SIZE,       "cluster-size" },
 735        { BLOCK_OPT_TABLE_SIZE,         "table-size" },
 736        { NULL, NULL },
 737    };
 738
 739    /* Parse options and convert legacy syntax */
 740    qdict = qemu_opts_to_qdict_filtered(opts, NULL, &qed_create_opts, true);
 741
 742    if (!qdict_rename_keys(qdict, opt_renames, errp)) {
 743        ret = -EINVAL;
 744        goto fail;
 745    }
 746
 747    /* Create and open the file (protocol layer) */
 748    ret = bdrv_create_file(filename, opts, &local_err);
 749    if (ret < 0) {
 750        error_propagate(errp, local_err);
 751        goto fail;
 752    }
 753
 754    bs = bdrv_open(filename, NULL, NULL,
 755                   BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
 756    if (bs == NULL) {
 757        ret = -EIO;
 758        goto fail;
 759    }
 760
 761    /* Now get the QAPI type BlockdevCreateOptions */
 762    qdict_put_str(qdict, "driver", "qed");
 763    qdict_put_str(qdict, "file", bs->node_name);
 764
 765    v = qobject_input_visitor_new_flat_confused(qdict, errp);
 766    if (!v) {
 767        ret = -EINVAL;
 768        goto fail;
 769    }
 770
 771    visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
 772    visit_free(v);
 773
 774    if (local_err) {
 775        error_propagate(errp, local_err);
 776        ret = -EINVAL;
 777        goto fail;
 778    }
 779
 780    /* Silently round up size */
 781    assert(create_options->driver == BLOCKDEV_DRIVER_QED);
 782    create_options->u.qed.size =
 783        ROUND_UP(create_options->u.qed.size, BDRV_SECTOR_SIZE);
 784
 785    /* Create the qed image (format layer) */
 786    ret = bdrv_qed_co_create(create_options, errp);
 787
 788fail:
 789    qobject_unref(qdict);
 790    bdrv_unref(bs);
 791    qapi_free_BlockdevCreateOptions(create_options);
 792    return ret;
 793}
 794
 795static int coroutine_fn bdrv_qed_co_block_status(BlockDriverState *bs,
 796                                                 bool want_zero,
 797                                                 int64_t pos, int64_t bytes,
 798                                                 int64_t *pnum, int64_t *map,
 799                                                 BlockDriverState **file)
 800{
 801    BDRVQEDState *s = bs->opaque;
 802    size_t len = MIN(bytes, SIZE_MAX);
 803    int status;
 804    QEDRequest request = { .l2_table = NULL };
 805    uint64_t offset;
 806    int ret;
 807
 808    qemu_co_mutex_lock(&s->table_lock);
 809    ret = qed_find_cluster(s, &request, pos, &len, &offset);
 810
 811    *pnum = len;
 812    switch (ret) {
 813    case QED_CLUSTER_FOUND:
 814        *map = offset | qed_offset_into_cluster(s, pos);
 815        status = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
 816        *file = bs->file->bs;
 817        break;
 818    case QED_CLUSTER_ZERO:
 819        status = BDRV_BLOCK_ZERO;
 820        break;
 821    case QED_CLUSTER_L2:
 822    case QED_CLUSTER_L1:
 823        status = 0;
 824        break;
 825    default:
 826        assert(ret < 0);
 827        status = ret;
 828        break;
 829    }
 830
 831    qed_unref_l2_cache_entry(request.l2_table);
 832    qemu_co_mutex_unlock(&s->table_lock);
 833
 834    return status;
 835}
 836
 837static BDRVQEDState *acb_to_s(QEDAIOCB *acb)
 838{
 839    return acb->bs->opaque;
 840}
 841
 842/**
 843 * Read from the backing file or zero-fill if no backing file
 844 *
 845 * @s:              QED state
 846 * @pos:            Byte position in device
 847 * @qiov:           Destination I/O vector
 848 * @backing_qiov:   Possibly shortened copy of qiov, to be allocated here
 849 * @cb:             Completion function
 850 * @opaque:         User data for completion function
 851 *
 852 * This function reads qiov->size bytes starting at pos from the backing file.
 853 * If there is no backing file then zeroes are read.
 854 */
 855static int coroutine_fn qed_read_backing_file(BDRVQEDState *s, uint64_t pos,
 856                                              QEMUIOVector *qiov,
 857                                              QEMUIOVector **backing_qiov)
 858{
 859    uint64_t backing_length = 0;
 860    size_t size;
 861    int ret;
 862
 863    /* If there is a backing file, get its length.  Treat the absence of a
 864     * backing file like a zero length backing file.
 865     */
 866    if (s->bs->backing) {
 867        int64_t l = bdrv_getlength(s->bs->backing->bs);
 868        if (l < 0) {
 869            return l;
 870        }
 871        backing_length = l;
 872    }
 873
 874    /* Zero all sectors if reading beyond the end of the backing file */
 875    if (pos >= backing_length ||
 876        pos + qiov->size > backing_length) {
 877        qemu_iovec_memset(qiov, 0, 0, qiov->size);
 878    }
 879
 880    /* Complete now if there are no backing file sectors to read */
 881    if (pos >= backing_length) {
 882        return 0;
 883    }
 884
 885    /* If the read straddles the end of the backing file, shorten it */
 886    size = MIN((uint64_t)backing_length - pos, qiov->size);
 887
 888    assert(*backing_qiov == NULL);
 889    *backing_qiov = g_new(QEMUIOVector, 1);
 890    qemu_iovec_init(*backing_qiov, qiov->niov);
 891    qemu_iovec_concat(*backing_qiov, qiov, 0, size);
 892
 893    BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING_AIO);
 894    ret = bdrv_co_preadv(s->bs->backing, pos, size, *backing_qiov, 0);
 895    if (ret < 0) {
 896        return ret;
 897    }
 898    return 0;
 899}
 900
 901/**
 902 * Copy data from backing file into the image
 903 *
 904 * @s:          QED state
 905 * @pos:        Byte position in device
 906 * @len:        Number of bytes
 907 * @offset:     Byte offset in image file
 908 */
 909static int coroutine_fn qed_copy_from_backing_file(BDRVQEDState *s,
 910                                                   uint64_t pos, uint64_t len,
 911                                                   uint64_t offset)
 912{
 913    QEMUIOVector qiov;
 914    QEMUIOVector *backing_qiov = NULL;
 915    struct iovec iov;
 916    int ret;
 917
 918    /* Skip copy entirely if there is no work to do */
 919    if (len == 0) {
 920        return 0;
 921    }
 922
 923    iov = (struct iovec) {
 924        .iov_base = qemu_blockalign(s->bs, len),
 925        .iov_len = len,
 926    };
 927    qemu_iovec_init_external(&qiov, &iov, 1);
 928
 929    ret = qed_read_backing_file(s, pos, &qiov, &backing_qiov);
 930
 931    if (backing_qiov) {
 932        qemu_iovec_destroy(backing_qiov);
 933        g_free(backing_qiov);
 934        backing_qiov = NULL;
 935    }
 936
 937    if (ret) {
 938        goto out;
 939    }
 940
 941    BLKDBG_EVENT(s->bs->file, BLKDBG_COW_WRITE);
 942    ret = bdrv_co_pwritev(s->bs->file, offset, qiov.size, &qiov, 0);
 943    if (ret < 0) {
 944        goto out;
 945    }
 946    ret = 0;
 947out:
 948    qemu_vfree(iov.iov_base);
 949    return ret;
 950}
 951
 952/**
 953 * Link one or more contiguous clusters into a table
 954 *
 955 * @s:              QED state
 956 * @table:          L2 table
 957 * @index:          First cluster index
 958 * @n:              Number of contiguous clusters
 959 * @cluster:        First cluster offset
 960 *
 961 * The cluster offset may be an allocated byte offset in the image file, the
 962 * zero cluster marker, or the unallocated cluster marker.
 963 *
 964 * Called with table_lock held.
 965 */
 966static void coroutine_fn qed_update_l2_table(BDRVQEDState *s, QEDTable *table,
 967                                             int index, unsigned int n,
 968                                             uint64_t cluster)
 969{
 970    int i;
 971    for (i = index; i < index + n; i++) {
 972        table->offsets[i] = cluster;
 973        if (!qed_offset_is_unalloc_cluster(cluster) &&
 974            !qed_offset_is_zero_cluster(cluster)) {
 975            cluster += s->header.cluster_size;
 976        }
 977    }
 978}
 979
 980/* Called with table_lock held.  */
 981static void coroutine_fn qed_aio_complete(QEDAIOCB *acb)
 982{
 983    BDRVQEDState *s = acb_to_s(acb);
 984
 985    /* Free resources */
 986    qemu_iovec_destroy(&acb->cur_qiov);
 987    qed_unref_l2_cache_entry(acb->request.l2_table);
 988
 989    /* Free the buffer we may have allocated for zero writes */
 990    if (acb->flags & QED_AIOCB_ZERO) {
 991        qemu_vfree(acb->qiov->iov[0].iov_base);
 992        acb->qiov->iov[0].iov_base = NULL;
 993    }
 994
 995    /* Start next allocating write request waiting behind this one.  Note that
 996     * requests enqueue themselves when they first hit an unallocated cluster
 997     * but they wait until the entire request is finished before waking up the
 998     * next request in the queue.  This ensures that we don't cycle through
 999     * requests multiple times but rather finish one at a time completely.
1000     */
1001    if (acb == s->allocating_acb) {
1002        s->allocating_acb = NULL;
1003        if (!qemu_co_queue_empty(&s->allocating_write_reqs)) {
1004            qemu_co_queue_next(&s->allocating_write_reqs);
1005        } else if (s->header.features & QED_F_NEED_CHECK) {
1006            qed_start_need_check_timer(s);
1007        }
1008    }
1009}
1010
1011/**
1012 * Update L1 table with new L2 table offset and write it out
1013 *
1014 * Called with table_lock held.
1015 */
1016static int coroutine_fn qed_aio_write_l1_update(QEDAIOCB *acb)
1017{
1018    BDRVQEDState *s = acb_to_s(acb);
1019    CachedL2Table *l2_table = acb->request.l2_table;
1020    uint64_t l2_offset = l2_table->offset;
1021    int index, ret;
1022
1023    index = qed_l1_index(s, acb->cur_pos);
1024    s->l1_table->offsets[index] = l2_table->offset;
1025
1026    ret = qed_write_l1_table(s, index, 1);
1027
1028    /* Commit the current L2 table to the cache */
1029    qed_commit_l2_cache_entry(&s->l2_cache, l2_table);
1030
1031    /* This is guaranteed to succeed because we just committed the entry to the
1032     * cache.
1033     */
1034    acb->request.l2_table = qed_find_l2_cache_entry(&s->l2_cache, l2_offset);
1035    assert(acb->request.l2_table != NULL);
1036
1037    return ret;
1038}
1039
1040
1041/**
1042 * Update L2 table with new cluster offsets and write them out
1043 *
1044 * Called with table_lock held.
1045 */
1046static int coroutine_fn qed_aio_write_l2_update(QEDAIOCB *acb, uint64_t offset)
1047{
1048    BDRVQEDState *s = acb_to_s(acb);
1049    bool need_alloc = acb->find_cluster_ret == QED_CLUSTER_L1;
1050    int index, ret;
1051
1052    if (need_alloc) {
1053        qed_unref_l2_cache_entry(acb->request.l2_table);
1054        acb->request.l2_table = qed_new_l2_table(s);
1055    }
1056
1057    index = qed_l2_index(s, acb->cur_pos);
1058    qed_update_l2_table(s, acb->request.l2_table->table, index, acb->cur_nclusters,
1059                         offset);
1060
1061    if (need_alloc) {
1062        /* Write out the whole new L2 table */
1063        ret = qed_write_l2_table(s, &acb->request, 0, s->table_nelems, true);
1064        if (ret) {
1065            return ret;
1066        }
1067        return qed_aio_write_l1_update(acb);
1068    } else {
1069        /* Write out only the updated part of the L2 table */
1070        ret = qed_write_l2_table(s, &acb->request, index, acb->cur_nclusters,
1071                                 false);
1072        if (ret) {
1073            return ret;
1074        }
1075    }
1076    return 0;
1077}
1078
1079/**
1080 * Write data to the image file
1081 *
1082 * Called with table_lock *not* held.
1083 */
1084static int coroutine_fn qed_aio_write_main(QEDAIOCB *acb)
1085{
1086    BDRVQEDState *s = acb_to_s(acb);
1087    uint64_t offset = acb->cur_cluster +
1088                      qed_offset_into_cluster(s, acb->cur_pos);
1089
1090    trace_qed_aio_write_main(s, acb, 0, offset, acb->cur_qiov.size);
1091
1092    BLKDBG_EVENT(s->bs->file, BLKDBG_WRITE_AIO);
1093    return bdrv_co_pwritev(s->bs->file, offset, acb->cur_qiov.size,
1094                           &acb->cur_qiov, 0);
1095}
1096
1097/**
1098 * Populate untouched regions of new data cluster
1099 *
1100 * Called with table_lock held.
1101 */
1102static int coroutine_fn qed_aio_write_cow(QEDAIOCB *acb)
1103{
1104    BDRVQEDState *s = acb_to_s(acb);
1105    uint64_t start, len, offset;
1106    int ret;
1107
1108    qemu_co_mutex_unlock(&s->table_lock);
1109
1110    /* Populate front untouched region of new data cluster */
1111    start = qed_start_of_cluster(s, acb->cur_pos);
1112    len = qed_offset_into_cluster(s, acb->cur_pos);
1113
1114    trace_qed_aio_write_prefill(s, acb, start, len, acb->cur_cluster);
1115    ret = qed_copy_from_backing_file(s, start, len, acb->cur_cluster);
1116    if (ret < 0) {
1117        goto out;
1118    }
1119
1120    /* Populate back untouched region of new data cluster */
1121    start = acb->cur_pos + acb->cur_qiov.size;
1122    len = qed_start_of_cluster(s, start + s->header.cluster_size - 1) - start;
1123    offset = acb->cur_cluster +
1124             qed_offset_into_cluster(s, acb->cur_pos) +
1125             acb->cur_qiov.size;
1126
1127    trace_qed_aio_write_postfill(s, acb, start, len, offset);
1128    ret = qed_copy_from_backing_file(s, start, len, offset);
1129    if (ret < 0) {
1130        goto out;
1131    }
1132
1133    ret = qed_aio_write_main(acb);
1134    if (ret < 0) {
1135        goto out;
1136    }
1137
1138    if (s->bs->backing) {
1139        /*
1140         * Flush new data clusters before updating the L2 table
1141         *
1142         * This flush is necessary when a backing file is in use.  A crash
1143         * during an allocating write could result in empty clusters in the
1144         * image.  If the write only touched a subregion of the cluster,
1145         * then backing image sectors have been lost in the untouched
1146         * region.  The solution is to flush after writing a new data
1147         * cluster and before updating the L2 table.
1148         */
1149        ret = bdrv_co_flush(s->bs->file->bs);
1150    }
1151
1152out:
1153    qemu_co_mutex_lock(&s->table_lock);
1154    return ret;
1155}
1156
1157/**
1158 * Check if the QED_F_NEED_CHECK bit should be set during allocating write
1159 */
1160static bool qed_should_set_need_check(BDRVQEDState *s)
1161{
1162    /* The flush before L2 update path ensures consistency */
1163    if (s->bs->backing) {
1164        return false;
1165    }
1166
1167    return !(s->header.features & QED_F_NEED_CHECK);
1168}
1169
1170/**
1171 * Write new data cluster
1172 *
1173 * @acb:        Write request
1174 * @len:        Length in bytes
1175 *
1176 * This path is taken when writing to previously unallocated clusters.
1177 *
1178 * Called with table_lock held.
1179 */
1180static int coroutine_fn qed_aio_write_alloc(QEDAIOCB *acb, size_t len)
1181{
1182    BDRVQEDState *s = acb_to_s(acb);
1183    int ret;
1184
1185    /* Cancel timer when the first allocating request comes in */
1186    if (s->allocating_acb == NULL) {
1187        qed_cancel_need_check_timer(s);
1188    }
1189
1190    /* Freeze this request if another allocating write is in progress */
1191    if (s->allocating_acb != acb || s->allocating_write_reqs_plugged) {
1192        if (s->allocating_acb != NULL) {
1193            qemu_co_queue_wait(&s->allocating_write_reqs, &s->table_lock);
1194            assert(s->allocating_acb == NULL);
1195        }
1196        s->allocating_acb = acb;
1197        return -EAGAIN; /* start over with looking up table entries */
1198    }
1199
1200    acb->cur_nclusters = qed_bytes_to_clusters(s,
1201            qed_offset_into_cluster(s, acb->cur_pos) + len);
1202    qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1203
1204    if (acb->flags & QED_AIOCB_ZERO) {
1205        /* Skip ahead if the clusters are already zero */
1206        if (acb->find_cluster_ret == QED_CLUSTER_ZERO) {
1207            return 0;
1208        }
1209        acb->cur_cluster = 1;
1210    } else {
1211        acb->cur_cluster = qed_alloc_clusters(s, acb->cur_nclusters);
1212    }
1213
1214    if (qed_should_set_need_check(s)) {
1215        s->header.features |= QED_F_NEED_CHECK;
1216        ret = qed_write_header(s);
1217        if (ret < 0) {
1218            return ret;
1219        }
1220    }
1221
1222    if (!(acb->flags & QED_AIOCB_ZERO)) {
1223        ret = qed_aio_write_cow(acb);
1224        if (ret < 0) {
1225            return ret;
1226        }
1227    }
1228
1229    return qed_aio_write_l2_update(acb, acb->cur_cluster);
1230}
1231
1232/**
1233 * Write data cluster in place
1234 *
1235 * @acb:        Write request
1236 * @offset:     Cluster offset in bytes
1237 * @len:        Length in bytes
1238 *
1239 * This path is taken when writing to already allocated clusters.
1240 *
1241 * Called with table_lock held.
1242 */
1243static int coroutine_fn qed_aio_write_inplace(QEDAIOCB *acb, uint64_t offset,
1244                                              size_t len)
1245{
1246    BDRVQEDState *s = acb_to_s(acb);
1247    int r;
1248
1249    qemu_co_mutex_unlock(&s->table_lock);
1250
1251    /* Allocate buffer for zero writes */
1252    if (acb->flags & QED_AIOCB_ZERO) {
1253        struct iovec *iov = acb->qiov->iov;
1254
1255        if (!iov->iov_base) {
1256            iov->iov_base = qemu_try_blockalign(acb->bs, iov->iov_len);
1257            if (iov->iov_base == NULL) {
1258                r = -ENOMEM;
1259                goto out;
1260            }
1261            memset(iov->iov_base, 0, iov->iov_len);
1262        }
1263    }
1264
1265    /* Calculate the I/O vector */
1266    acb->cur_cluster = offset;
1267    qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1268
1269    /* Do the actual write.  */
1270    r = qed_aio_write_main(acb);
1271out:
1272    qemu_co_mutex_lock(&s->table_lock);
1273    return r;
1274}
1275
1276/**
1277 * Write data cluster
1278 *
1279 * @opaque:     Write request
1280 * @ret:        QED_CLUSTER_FOUND, QED_CLUSTER_L2 or QED_CLUSTER_L1
1281 * @offset:     Cluster offset in bytes
1282 * @len:        Length in bytes
1283 *
1284 * Called with table_lock held.
1285 */
1286static int coroutine_fn qed_aio_write_data(void *opaque, int ret,
1287                                           uint64_t offset, size_t len)
1288{
1289    QEDAIOCB *acb = opaque;
1290
1291    trace_qed_aio_write_data(acb_to_s(acb), acb, ret, offset, len);
1292
1293    acb->find_cluster_ret = ret;
1294
1295    switch (ret) {
1296    case QED_CLUSTER_FOUND:
1297        return qed_aio_write_inplace(acb, offset, len);
1298
1299    case QED_CLUSTER_L2:
1300    case QED_CLUSTER_L1:
1301    case QED_CLUSTER_ZERO:
1302        return qed_aio_write_alloc(acb, len);
1303
1304    default:
1305        g_assert_not_reached();
1306    }
1307}
1308
1309/**
1310 * Read data cluster
1311 *
1312 * @opaque:     Read request
1313 * @ret:        QED_CLUSTER_FOUND, QED_CLUSTER_L2 or QED_CLUSTER_L1
1314 * @offset:     Cluster offset in bytes
1315 * @len:        Length in bytes
1316 *
1317 * Called with table_lock held.
1318 */
1319static int coroutine_fn qed_aio_read_data(void *opaque, int ret,
1320                                          uint64_t offset, size_t len)
1321{
1322    QEDAIOCB *acb = opaque;
1323    BDRVQEDState *s = acb_to_s(acb);
1324    BlockDriverState *bs = acb->bs;
1325    int r;
1326
1327    qemu_co_mutex_unlock(&s->table_lock);
1328
1329    /* Adjust offset into cluster */
1330    offset += qed_offset_into_cluster(s, acb->cur_pos);
1331
1332    trace_qed_aio_read_data(s, acb, ret, offset, len);
1333
1334    qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1335
1336    /* Handle zero cluster and backing file reads, otherwise read
1337     * data cluster directly.
1338     */
1339    if (ret == QED_CLUSTER_ZERO) {
1340        qemu_iovec_memset(&acb->cur_qiov, 0, 0, acb->cur_qiov.size);
1341        r = 0;
1342    } else if (ret != QED_CLUSTER_FOUND) {
1343        r = qed_read_backing_file(s, acb->cur_pos, &acb->cur_qiov,
1344                                  &acb->backing_qiov);
1345    } else {
1346        BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1347        r = bdrv_co_preadv(bs->file, offset, acb->cur_qiov.size,
1348                           &acb->cur_qiov, 0);
1349    }
1350
1351    qemu_co_mutex_lock(&s->table_lock);
1352    return r;
1353}
1354
1355/**
1356 * Begin next I/O or complete the request
1357 */
1358static int coroutine_fn qed_aio_next_io(QEDAIOCB *acb)
1359{
1360    BDRVQEDState *s = acb_to_s(acb);
1361    uint64_t offset;
1362    size_t len;
1363    int ret;
1364
1365    qemu_co_mutex_lock(&s->table_lock);
1366    while (1) {
1367        trace_qed_aio_next_io(s, acb, 0, acb->cur_pos + acb->cur_qiov.size);
1368
1369        if (acb->backing_qiov) {
1370            qemu_iovec_destroy(acb->backing_qiov);
1371            g_free(acb->backing_qiov);
1372            acb->backing_qiov = NULL;
1373        }
1374
1375        acb->qiov_offset += acb->cur_qiov.size;
1376        acb->cur_pos += acb->cur_qiov.size;
1377        qemu_iovec_reset(&acb->cur_qiov);
1378
1379        /* Complete request */
1380        if (acb->cur_pos >= acb->end_pos) {
1381            ret = 0;
1382            break;
1383        }
1384
1385        /* Find next cluster and start I/O */
1386        len = acb->end_pos - acb->cur_pos;
1387        ret = qed_find_cluster(s, &acb->request, acb->cur_pos, &len, &offset);
1388        if (ret < 0) {
1389            break;
1390        }
1391
1392        if (acb->flags & QED_AIOCB_WRITE) {
1393            ret = qed_aio_write_data(acb, ret, offset, len);
1394        } else {
1395            ret = qed_aio_read_data(acb, ret, offset, len);
1396        }
1397
1398        if (ret < 0 && ret != -EAGAIN) {
1399            break;
1400        }
1401    }
1402
1403    trace_qed_aio_complete(s, acb, ret);
1404    qed_aio_complete(acb);
1405    qemu_co_mutex_unlock(&s->table_lock);
1406    return ret;
1407}
1408
1409static int coroutine_fn qed_co_request(BlockDriverState *bs, int64_t sector_num,
1410                                       QEMUIOVector *qiov, int nb_sectors,
1411                                       int flags)
1412{
1413    QEDAIOCB acb = {
1414        .bs         = bs,
1415        .cur_pos    = (uint64_t) sector_num * BDRV_SECTOR_SIZE,
1416        .end_pos    = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE,
1417        .qiov       = qiov,
1418        .flags      = flags,
1419    };
1420    qemu_iovec_init(&acb.cur_qiov, qiov->niov);
1421
1422    trace_qed_aio_setup(bs->opaque, &acb, sector_num, nb_sectors, NULL, flags);
1423
1424    /* Start request */
1425    return qed_aio_next_io(&acb);
1426}
1427
1428static int coroutine_fn bdrv_qed_co_readv(BlockDriverState *bs,
1429                                          int64_t sector_num, int nb_sectors,
1430                                          QEMUIOVector *qiov)
1431{
1432    return qed_co_request(bs, sector_num, qiov, nb_sectors, 0);
1433}
1434
1435static int coroutine_fn bdrv_qed_co_writev(BlockDriverState *bs,
1436                                           int64_t sector_num, int nb_sectors,
1437                                           QEMUIOVector *qiov, int flags)
1438{
1439    assert(!flags);
1440    return qed_co_request(bs, sector_num, qiov, nb_sectors, QED_AIOCB_WRITE);
1441}
1442
1443static int coroutine_fn bdrv_qed_co_pwrite_zeroes(BlockDriverState *bs,
1444                                                  int64_t offset,
1445                                                  int bytes,
1446                                                  BdrvRequestFlags flags)
1447{
1448    BDRVQEDState *s = bs->opaque;
1449    QEMUIOVector qiov;
1450    struct iovec iov;
1451
1452    /* Fall back if the request is not aligned */
1453    if (qed_offset_into_cluster(s, offset) ||
1454        qed_offset_into_cluster(s, bytes)) {
1455        return -ENOTSUP;
1456    }
1457
1458    /* Zero writes start without an I/O buffer.  If a buffer becomes necessary
1459     * then it will be allocated during request processing.
1460     */
1461    iov.iov_base = NULL;
1462    iov.iov_len = bytes;
1463
1464    qemu_iovec_init_external(&qiov, &iov, 1);
1465    return qed_co_request(bs, offset >> BDRV_SECTOR_BITS, &qiov,
1466                          bytes >> BDRV_SECTOR_BITS,
1467                          QED_AIOCB_WRITE | QED_AIOCB_ZERO);
1468}
1469
1470static int coroutine_fn bdrv_qed_co_truncate(BlockDriverState *bs,
1471                                             int64_t offset,
1472                                             PreallocMode prealloc,
1473                                             Error **errp)
1474{
1475    BDRVQEDState *s = bs->opaque;
1476    uint64_t old_image_size;
1477    int ret;
1478
1479    if (prealloc != PREALLOC_MODE_OFF) {
1480        error_setg(errp, "Unsupported preallocation mode '%s'",
1481                   PreallocMode_str(prealloc));
1482        return -ENOTSUP;
1483    }
1484
1485    if (!qed_is_image_size_valid(offset, s->header.cluster_size,
1486                                 s->header.table_size)) {
1487        error_setg(errp, "Invalid image size specified");
1488        return -EINVAL;
1489    }
1490
1491    if ((uint64_t)offset < s->header.image_size) {
1492        error_setg(errp, "Shrinking images is currently not supported");
1493        return -ENOTSUP;
1494    }
1495
1496    old_image_size = s->header.image_size;
1497    s->header.image_size = offset;
1498    ret = qed_write_header_sync(s);
1499    if (ret < 0) {
1500        s->header.image_size = old_image_size;
1501        error_setg_errno(errp, -ret, "Failed to update the image size");
1502    }
1503    return ret;
1504}
1505
1506static int64_t bdrv_qed_getlength(BlockDriverState *bs)
1507{
1508    BDRVQEDState *s = bs->opaque;
1509    return s->header.image_size;
1510}
1511
1512static int bdrv_qed_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1513{
1514    BDRVQEDState *s = bs->opaque;
1515
1516    memset(bdi, 0, sizeof(*bdi));
1517    bdi->cluster_size = s->header.cluster_size;
1518    bdi->is_dirty = s->header.features & QED_F_NEED_CHECK;
1519    bdi->unallocated_blocks_are_zero = true;
1520    return 0;
1521}
1522
1523static int bdrv_qed_change_backing_file(BlockDriverState *bs,
1524                                        const char *backing_file,
1525                                        const char *backing_fmt)
1526{
1527    BDRVQEDState *s = bs->opaque;
1528    QEDHeader new_header, le_header;
1529    void *buffer;
1530    size_t buffer_len, backing_file_len;
1531    int ret;
1532
1533    /* Refuse to set backing filename if unknown compat feature bits are
1534     * active.  If the image uses an unknown compat feature then we may not
1535     * know the layout of data following the header structure and cannot safely
1536     * add a new string.
1537     */
1538    if (backing_file && (s->header.compat_features &
1539                         ~QED_COMPAT_FEATURE_MASK)) {
1540        return -ENOTSUP;
1541    }
1542
1543    memcpy(&new_header, &s->header, sizeof(new_header));
1544
1545    new_header.features &= ~(QED_F_BACKING_FILE |
1546                             QED_F_BACKING_FORMAT_NO_PROBE);
1547
1548    /* Adjust feature flags */
1549    if (backing_file) {
1550        new_header.features |= QED_F_BACKING_FILE;
1551
1552        if (qed_fmt_is_raw(backing_fmt)) {
1553            new_header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
1554        }
1555    }
1556
1557    /* Calculate new header size */
1558    backing_file_len = 0;
1559
1560    if (backing_file) {
1561        backing_file_len = strlen(backing_file);
1562    }
1563
1564    buffer_len = sizeof(new_header);
1565    new_header.backing_filename_offset = buffer_len;
1566    new_header.backing_filename_size = backing_file_len;
1567    buffer_len += backing_file_len;
1568
1569    /* Make sure we can rewrite header without failing */
1570    if (buffer_len > new_header.header_size * new_header.cluster_size) {
1571        return -ENOSPC;
1572    }
1573
1574    /* Prepare new header */
1575    buffer = g_malloc(buffer_len);
1576
1577    qed_header_cpu_to_le(&new_header, &le_header);
1578    memcpy(buffer, &le_header, sizeof(le_header));
1579    buffer_len = sizeof(le_header);
1580
1581    if (backing_file) {
1582        memcpy(buffer + buffer_len, backing_file, backing_file_len);
1583        buffer_len += backing_file_len;
1584    }
1585
1586    /* Write new header */
1587    ret = bdrv_pwrite_sync(bs->file, 0, buffer, buffer_len);
1588    g_free(buffer);
1589    if (ret == 0) {
1590        memcpy(&s->header, &new_header, sizeof(new_header));
1591    }
1592    return ret;
1593}
1594
1595static void coroutine_fn bdrv_qed_co_invalidate_cache(BlockDriverState *bs,
1596                                                      Error **errp)
1597{
1598    BDRVQEDState *s = bs->opaque;
1599    Error *local_err = NULL;
1600    int ret;
1601
1602    bdrv_qed_close(bs);
1603
1604    bdrv_qed_init_state(bs);
1605    qemu_co_mutex_lock(&s->table_lock);
1606    ret = bdrv_qed_do_open(bs, NULL, bs->open_flags, &local_err);
1607    qemu_co_mutex_unlock(&s->table_lock);
1608    if (local_err) {
1609        error_propagate(errp, local_err);
1610        error_prepend(errp, "Could not reopen qed layer: ");
1611        return;
1612    } else if (ret < 0) {
1613        error_setg_errno(errp, -ret, "Could not reopen qed layer");
1614        return;
1615    }
1616}
1617
1618static int bdrv_qed_co_check(BlockDriverState *bs, BdrvCheckResult *result,
1619                             BdrvCheckMode fix)
1620{
1621    BDRVQEDState *s = bs->opaque;
1622    int ret;
1623
1624    qemu_co_mutex_lock(&s->table_lock);
1625    ret = qed_check(s, result, !!fix);
1626    qemu_co_mutex_unlock(&s->table_lock);
1627
1628    return ret;
1629}
1630
1631static QemuOptsList qed_create_opts = {
1632    .name = "qed-create-opts",
1633    .head = QTAILQ_HEAD_INITIALIZER(qed_create_opts.head),
1634    .desc = {
1635        {
1636            .name = BLOCK_OPT_SIZE,
1637            .type = QEMU_OPT_SIZE,
1638            .help = "Virtual disk size"
1639        },
1640        {
1641            .name = BLOCK_OPT_BACKING_FILE,
1642            .type = QEMU_OPT_STRING,
1643            .help = "File name of a base image"
1644        },
1645        {
1646            .name = BLOCK_OPT_BACKING_FMT,
1647            .type = QEMU_OPT_STRING,
1648            .help = "Image format of the base image"
1649        },
1650        {
1651            .name = BLOCK_OPT_CLUSTER_SIZE,
1652            .type = QEMU_OPT_SIZE,
1653            .help = "Cluster size (in bytes)",
1654            .def_value_str = stringify(QED_DEFAULT_CLUSTER_SIZE)
1655        },
1656        {
1657            .name = BLOCK_OPT_TABLE_SIZE,
1658            .type = QEMU_OPT_SIZE,
1659            .help = "L1/L2 table size (in clusters)"
1660        },
1661        { /* end of list */ }
1662    }
1663};
1664
1665static BlockDriver bdrv_qed = {
1666    .format_name              = "qed",
1667    .instance_size            = sizeof(BDRVQEDState),
1668    .create_opts              = &qed_create_opts,
1669    .supports_backing         = true,
1670
1671    .bdrv_probe               = bdrv_qed_probe,
1672    .bdrv_open                = bdrv_qed_open,
1673    .bdrv_close               = bdrv_qed_close,
1674    .bdrv_reopen_prepare      = bdrv_qed_reopen_prepare,
1675    .bdrv_child_perm          = bdrv_format_default_perms,
1676    .bdrv_co_create           = bdrv_qed_co_create,
1677    .bdrv_co_create_opts      = bdrv_qed_co_create_opts,
1678    .bdrv_has_zero_init       = bdrv_has_zero_init_1,
1679    .bdrv_co_block_status     = bdrv_qed_co_block_status,
1680    .bdrv_co_readv            = bdrv_qed_co_readv,
1681    .bdrv_co_writev           = bdrv_qed_co_writev,
1682    .bdrv_co_pwrite_zeroes    = bdrv_qed_co_pwrite_zeroes,
1683    .bdrv_co_truncate         = bdrv_qed_co_truncate,
1684    .bdrv_getlength           = bdrv_qed_getlength,
1685    .bdrv_get_info            = bdrv_qed_get_info,
1686    .bdrv_refresh_limits      = bdrv_qed_refresh_limits,
1687    .bdrv_change_backing_file = bdrv_qed_change_backing_file,
1688    .bdrv_co_invalidate_cache = bdrv_qed_co_invalidate_cache,
1689    .bdrv_co_check            = bdrv_qed_co_check,
1690    .bdrv_detach_aio_context  = bdrv_qed_detach_aio_context,
1691    .bdrv_attach_aio_context  = bdrv_qed_attach_aio_context,
1692    .bdrv_co_drain_begin      = bdrv_qed_co_drain_begin,
1693};
1694
1695static void bdrv_qed_init(void)
1696{
1697    bdrv_register(&bdrv_qed);
1698}
1699
1700block_init(bdrv_qed_init);
1701