quorum.c 32.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Quorum Block filter
 *
 * Copyright (C) 2012-2014 Nodalink, EURL.
 *
 * Author:
 *   Benoît Canet <benoit.canet@irqsave.net>
 *
 * Based on the design and code of blkverify.c (Copyright (C) 2010 IBM, Corp)
 * and blkmirror.c (Copyright (C) 2011 Red Hat, Inc).
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or later.
 * See the COPYING file in the top-level directory.
 */

P
Peter Maydell 已提交
16
#include "qemu/osdep.h"
17
#include "qemu/cutils.h"
18
#include "block/block_int.h"
19 20
#include "qapi/qmp/qbool.h"
#include "qapi/qmp/qdict.h"
21
#include "qapi/qmp/qerror.h"
22
#include "qapi/qmp/qint.h"
B
Benoît Canet 已提交
23
#include "qapi/qmp/qjson.h"
24 25
#include "qapi/qmp/qlist.h"
#include "qapi/qmp/qstring.h"
W
Wenchao Xia 已提交
26
#include "qapi-event.h"
27
#include "crypto/hash.h"
B
Benoît Canet 已提交
28 29 30

#define HASH_LENGTH 32

31 32
#define QUORUM_OPT_VOTE_THRESHOLD "vote-threshold"
#define QUORUM_OPT_BLKVERIFY      "blkverify"
33
#define QUORUM_OPT_REWRITE        "rewrite-corrupted"
34
#define QUORUM_OPT_READ_PATTERN   "read-pattern"
35

B
Benoît Canet 已提交
36 37
/* This union holds a vote hash value */
typedef union QuorumVoteValue {
38
    uint8_t h[HASH_LENGTH];    /* SHA-256 hash */
B
Benoît Canet 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    int64_t l;                 /* simpler 64 bits hash */
} QuorumVoteValue;

/* A vote item */
typedef struct QuorumVoteItem {
    int index;
    QLIST_ENTRY(QuorumVoteItem) next;
} QuorumVoteItem;

/* this structure is a vote version. A version is the set of votes sharing the
 * same vote value.
 * The set of votes will be tracked with the items field and its cardinality is
 * vote_count.
 */
typedef struct QuorumVoteVersion {
    QuorumVoteValue value;
    int index;
    int vote_count;
    QLIST_HEAD(, QuorumVoteItem) items;
    QLIST_ENTRY(QuorumVoteVersion) next;
} QuorumVoteVersion;

/* this structure holds a group of vote versions together */
typedef struct QuorumVotes {
    QLIST_HEAD(, QuorumVoteVersion) vote_list;
    bool (*compare)(QuorumVoteValue *a, QuorumVoteValue *b);
} QuorumVotes;
66

67 68
/* the following structure holds the state of one quorum instance */
typedef struct BDRVQuorumState {
K
Kevin Wolf 已提交
69
    BdrvChild **children;  /* children BlockDriverStates */
70
    int num_children;      /* children count */
71 72 73
    unsigned next_child_index;  /* the index of the next child that should
                                 * be added
                                 */
74 75 76 77 78 79 80 81 82 83 84
    int threshold;         /* if less than threshold children reads gave the
                            * same result a quorum error occurs.
                            */
    bool is_blkverify;     /* true if the driver is in blkverify mode
                            * Writes are mirrored on two children devices.
                            * On reads the two children devices' contents are
                            * compared and if a difference is spotted its
                            * location is printed and the code aborts.
                            * It is useful to debug other block drivers by
                            * comparing them with a reference one.
                            */
85 86 87
    bool rewrite_corrupted;/* true if the driver must rewrite-on-read corrupted
                            * block if Quorum is reached.
                            */
88 89

    QuorumReadPattern read_pattern;
90 91
} BDRVQuorumState;

92 93 94 95 96 97 98 99
typedef struct QuorumAIOCB QuorumAIOCB;

/* Quorum will create one instance of the following structure per operation it
 * performs on its children.
 * So for each read/write operation coming from the upper layer there will be
 * $children_count QuorumChildRequest.
 */
typedef struct QuorumChildRequest {
100
    BlockDriverState *bs;
101 102 103 104 105 106 107 108 109 110 111 112
    QEMUIOVector qiov;
    uint8_t *buf;
    int ret;
    QuorumAIOCB *parent;
} QuorumChildRequest;

/* Quorum will use the following structure to track progress of each read/write
 * operation received by the upper layer.
 * This structure hold pointers to the QuorumChildRequest structures instances
 * used to do operations on each children and track overall progress.
 */
struct QuorumAIOCB {
113 114
    BlockDriverState *bs;
    Coroutine *co;
115 116 117 118 119 120 121 122 123 124 125

    /* Request metadata */
    uint64_t sector_num;
    int nb_sectors;

    QEMUIOVector *qiov;         /* calling IOV */

    QuorumChildRequest *qcrs;   /* individual child requests */
    int count;                  /* number of completed AIOCB */
    int success_count;          /* number of successfully completed AIOCB */

126 127 128 129
    int rewrite_count;          /* number of replica to rewrite: count down to
                                 * zero once writes are fired
                                 */

B
Benoît Canet 已提交
130 131
    QuorumVotes votes;

132 133
    bool is_read;
    int vote_ret;
134
    int children_read;          /* how many children have been read from */
135
};
136

137 138 139 140
typedef struct QuorumCo {
    QuorumAIOCB *acb;
    int idx;
} QuorumCo;
141 142 143 144

static void quorum_aio_finalize(QuorumAIOCB *acb)
{
    g_free(acb->qcrs);
145
    g_free(acb);
146 147
}

B
Benoît Canet 已提交
148 149 150 151 152 153 154 155 156 157
static bool quorum_sha256_compare(QuorumVoteValue *a, QuorumVoteValue *b)
{
    return !memcmp(a->h, b->h, HASH_LENGTH);
}

static bool quorum_64bits_compare(QuorumVoteValue *a, QuorumVoteValue *b)
{
    return a->l == b->l;
}

158
static QuorumAIOCB *quorum_aio_get(BlockDriverState *bs,
159 160
                                   QEMUIOVector *qiov,
                                   uint64_t sector_num,
161
                                   int nb_sectors)
162
{
163
    BDRVQuorumState *s = bs->opaque;
164
    QuorumAIOCB *acb = g_new(QuorumAIOCB, 1);
165 166
    int i;

167 168
    acb->co = qemu_coroutine_self();
    acb->bs = bs;
169 170 171 172 173 174
    acb->sector_num = sector_num;
    acb->nb_sectors = nb_sectors;
    acb->qiov = qiov;
    acb->qcrs = g_new0(QuorumChildRequest, s->num_children);
    acb->count = 0;
    acb->success_count = 0;
175
    acb->rewrite_count = 0;
B
Benoît Canet 已提交
176 177
    acb->votes.compare = quorum_sha256_compare;
    QLIST_INIT(&acb->votes.vote_list);
178 179 180 181 182 183 184 185 186 187 188 189
    acb->is_read = false;
    acb->vote_ret = 0;

    for (i = 0; i < s->num_children; i++) {
        acb->qcrs[i].buf = NULL;
        acb->qcrs[i].ret = 0;
        acb->qcrs[i].parent = acb;
    }

    return acb;
}

190 191
static void quorum_report_bad(QuorumOpType type, uint64_t sector_num,
                              int nb_sectors, char *node_name, int ret)
B
Benoît Canet 已提交
192
{
W
Wenchao Xia 已提交
193
    const char *msg = NULL;
194
    if (ret < 0) {
W
Wenchao Xia 已提交
195
        msg = strerror(-ret);
196
    }
197 198 199

    qapi_event_send_quorum_report_bad(type, !!msg, msg, node_name,
                                      sector_num, nb_sectors, &error_abort);
B
Benoît Canet 已提交
200 201 202 203
}

static void quorum_report_failure(QuorumAIOCB *acb)
{
204
    const char *reference = bdrv_get_device_or_node_name(acb->bs);
W
Wenchao Xia 已提交
205 206
    qapi_event_send_quorum_failure(reference, acb->sector_num,
                                   acb->nb_sectors, &error_abort);
B
Benoît Canet 已提交
207 208 209 210 211 212
}

static int quorum_vote_error(QuorumAIOCB *acb);

static bool quorum_has_too_much_io_failed(QuorumAIOCB *acb)
{
213
    BDRVQuorumState *s = acb->bs->opaque;
B
Benoît Canet 已提交
214 215 216 217 218 219 220 221 222 223

    if (acb->success_count < s->threshold) {
        acb->vote_ret = quorum_vote_error(acb);
        quorum_report_failure(acb);
        return true;
    }

    return false;
}

224 225 226 227 228 229
static void quorum_rewrite_aio_cb(void *opaque, int ret)
{
    QuorumAIOCB *acb = opaque;

    /* one less rewrite to do */
    acb->rewrite_count--;
230
    qemu_coroutine_enter_if_inactive(acb->co);
231 232
}

233
static int read_fifo_child(QuorumAIOCB *acb);
234 235 236 237 238 239 240 241 242 243 244 245 246 247

static void quorum_copy_qiov(QEMUIOVector *dest, QEMUIOVector *source)
{
    int i;
    assert(dest->niov == source->niov);
    assert(dest->size == source->size);
    for (i = 0; i < source->niov; i++) {
        assert(dest->iov[i].iov_len == source->iov[i].iov_len);
        memcpy(dest->iov[i].iov_base,
               source->iov[i].iov_base,
               source->iov[i].iov_len);
    }
}

248 249 250 251 252
static void quorum_report_bad_acb(QuorumChildRequest *sacb, int ret)
{
    QuorumAIOCB *acb = sacb->parent;
    QuorumOpType type = acb->is_read ? QUORUM_OP_TYPE_READ : QUORUM_OP_TYPE_WRITE;
    quorum_report_bad(type, acb->sector_num, acb->nb_sectors,
253
                      sacb->bs->node_name, ret);
254 255
}

256
static int quorum_fifo_aio_cb(void *opaque, int ret)
257 258 259
{
    QuorumChildRequest *sacb = opaque;
    QuorumAIOCB *acb = sacb->parent;
260
    BDRVQuorumState *s = acb->bs->opaque;
261

262 263 264 265
    assert(acb->is_read && s->read_pattern == QUORUM_READ_PATTERN_FIFO);

    if (ret < 0) {
        quorum_report_bad_acb(sacb, ret);
266

267
        /* We try to read next child in FIFO order if we fail to read */
268
        if (acb->children_read < s->num_children) {
269
            return read_fifo_child(acb);
270 271 272
        }
    }

273 274 275
    acb->vote_ret = ret;

    /* FIXME: rewrite failed children if acb->children_read > 1? */
276

277
    return ret;
278 279
}

B
Benoît Canet 已提交
280 281 282 283 284 285 286 287 288 289 290 291
static void quorum_report_bad_versions(BDRVQuorumState *s,
                                       QuorumAIOCB *acb,
                                       QuorumVoteValue *value)
{
    QuorumVoteVersion *version;
    QuorumVoteItem *item;

    QLIST_FOREACH(version, &acb->votes.vote_list, next) {
        if (acb->votes.compare(&version->value, value)) {
            continue;
        }
        QLIST_FOREACH(item, &version->items, next) {
292 293 294
            quorum_report_bad(QUORUM_OP_TYPE_READ, acb->sector_num,
                              acb->nb_sectors,
                              s->children[item->index]->bs->node_name, 0);
B
Benoît Canet 已提交
295 296 297 298
        }
    }
}

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
static bool quorum_rewrite_bad_versions(BDRVQuorumState *s, QuorumAIOCB *acb,
                                        QuorumVoteValue *value)
{
    QuorumVoteVersion *version;
    QuorumVoteItem *item;
    int count = 0;

    /* first count the number of bad versions: done first to avoid concurrency
     * issues.
     */
    QLIST_FOREACH(version, &acb->votes.vote_list, next) {
        if (acb->votes.compare(&version->value, value)) {
            continue;
        }
        QLIST_FOREACH(item, &version->items, next) {
            count++;
        }
    }

    /* quorum_rewrite_aio_cb will count down this to zero */
    acb->rewrite_count = count;

    /* now fire the correcting rewrites */
    QLIST_FOREACH(version, &acb->votes.vote_list, next) {
        if (acb->votes.compare(&version->value, value)) {
            continue;
        }
        QLIST_FOREACH(item, &version->items, next) {
327
            bdrv_aio_writev(s->children[item->index], acb->sector_num,
K
Kevin Wolf 已提交
328 329
                            acb->qiov, acb->nb_sectors, quorum_rewrite_aio_cb,
                            acb);
330 331 332 333 334 335 336
        }
    }

    /* return true if any rewrite is done else false */
    return count;
}

B
Benoît Canet 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
static void quorum_count_vote(QuorumVotes *votes,
                              QuorumVoteValue *value,
                              int index)
{
    QuorumVoteVersion *v = NULL, *version = NULL;
    QuorumVoteItem *item;

    /* look if we have something with this hash */
    QLIST_FOREACH(v, &votes->vote_list, next) {
        if (votes->compare(&v->value, value)) {
            version = v;
            break;
        }
    }

    /* It's a version not yet in the list add it */
    if (!version) {
        version = g_new0(QuorumVoteVersion, 1);
        QLIST_INIT(&version->items);
        memcpy(&version->value, value, sizeof(version->value));
        version->index = index;
        version->vote_count = 0;
        QLIST_INSERT_HEAD(&votes->vote_list, version, next);
    }

    version->vote_count++;

    item = g_new0(QuorumVoteItem, 1);
    item->index = index;
    QLIST_INSERT_HEAD(&version->items, item, next);
}

static void quorum_free_vote_list(QuorumVotes *votes)
{
    QuorumVoteVersion *version, *next_version;
    QuorumVoteItem *item, *next_item;

    QLIST_FOREACH_SAFE(version, &votes->vote_list, next, next_version) {
        QLIST_REMOVE(version, next);
        QLIST_FOREACH_SAFE(item, &version->items, next, next_item) {
            QLIST_REMOVE(item, next);
            g_free(item);
        }
        g_free(version);
    }
}

static int quorum_compute_hash(QuorumAIOCB *acb, int i, QuorumVoteValue *hash)
{
    QEMUIOVector *qiov = &acb->qcrs[i].qiov;
387 388
    size_t len = sizeof(hash->h);
    uint8_t *data = hash->h;
B
Benoît Canet 已提交
389

390 391 392 393 394 395 396 397
    /* XXX - would be nice if we could pass in the Error **
     * and propagate that back, but this quorum code is
     * restricted to just errno values currently */
    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,
                            qiov->iov, qiov->niov,
                            &data, &len,
                            NULL) < 0) {
        return -EINVAL;
B
Benoît Canet 已提交
398 399
    }

400
    return 0;
B
Benoît Canet 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
}

static QuorumVoteVersion *quorum_get_vote_winner(QuorumVotes *votes)
{
    int max = 0;
    QuorumVoteVersion *candidate, *winner = NULL;

    QLIST_FOREACH(candidate, &votes->vote_list, next) {
        if (candidate->vote_count > max) {
            max = candidate->vote_count;
            winner = candidate;
        }
    }

    return winner;
}

/* qemu_iovec_compare is handy for blkverify mode because it returns the first
 * differing byte location. Yet it is handcoded to compare vectors one byte
 * after another so it does not benefit from the libc SIMD optimizations.
 * quorum_iovec_compare is written for speed and should be used in the non
 * blkverify mode of quorum.
 */
static bool quorum_iovec_compare(QEMUIOVector *a, QEMUIOVector *b)
{
    int i;
    int result;

    assert(a->niov == b->niov);
    for (i = 0; i < a->niov; i++) {
        assert(a->iov[i].iov_len == b->iov[i].iov_len);
        result = memcmp(a->iov[i].iov_base,
                        b->iov[i].iov_base,
                        a->iov[i].iov_len);
        if (result) {
            return false;
        }
    }

    return true;
}

static void GCC_FMT_ATTR(2, 3) quorum_err(QuorumAIOCB *acb,
                                          const char *fmt, ...)
{
    va_list ap;

    va_start(ap, fmt);
    fprintf(stderr, "quorum: sector_num=%" PRId64 " nb_sectors=%d ",
            acb->sector_num, acb->nb_sectors);
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
    va_end(ap);
    exit(1);
}

static bool quorum_compare(QuorumAIOCB *acb,
                           QEMUIOVector *a,
                           QEMUIOVector *b)
{
461
    BDRVQuorumState *s = acb->bs->opaque;
B
Benoît Canet 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    ssize_t offset;

    /* This driver will replace blkverify in this particular case */
    if (s->is_blkverify) {
        offset = qemu_iovec_compare(a, b);
        if (offset != -1) {
            quorum_err(acb, "contents mismatch in sector %" PRId64,
                       acb->sector_num +
                       (uint64_t)(offset / BDRV_SECTOR_SIZE));
        }
        return true;
    }

    return quorum_iovec_compare(a, b);
}

/* Do a vote to get the error code */
static int quorum_vote_error(QuorumAIOCB *acb)
{
481
    BDRVQuorumState *s = acb->bs->opaque;
B
Benoît Canet 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    QuorumVoteVersion *winner = NULL;
    QuorumVotes error_votes;
    QuorumVoteValue result_value;
    int i, ret = 0;
    bool error = false;

    QLIST_INIT(&error_votes.vote_list);
    error_votes.compare = quorum_64bits_compare;

    for (i = 0; i < s->num_children; i++) {
        ret = acb->qcrs[i].ret;
        if (ret) {
            error = true;
            result_value.l = ret;
            quorum_count_vote(&error_votes, &result_value, i);
        }
    }

    if (error) {
        winner = quorum_get_vote_winner(&error_votes);
        ret = winner->value.l;
    }

    quorum_free_vote_list(&error_votes);

    return ret;
}

K
Kevin Wolf 已提交
510
static void quorum_vote(QuorumAIOCB *acb)
B
Benoît Canet 已提交
511 512 513 514
{
    bool quorum = true;
    int i, j, ret;
    QuorumVoteValue hash;
515
    BDRVQuorumState *s = acb->bs->opaque;
B
Benoît Canet 已提交
516 517 518
    QuorumVoteVersion *winner;

    if (quorum_has_too_much_io_failed(acb)) {
K
Kevin Wolf 已提交
519
        return;
B
Benoît Canet 已提交
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    }

    /* get the index of the first successful read */
    for (i = 0; i < s->num_children; i++) {
        if (!acb->qcrs[i].ret) {
            break;
        }
    }

    assert(i < s->num_children);

    /* compare this read with all other successful reads stopping at quorum
     * failure
     */
    for (j = i + 1; j < s->num_children; j++) {
        if (acb->qcrs[j].ret) {
            continue;
        }
        quorum = quorum_compare(acb, &acb->qcrs[i].qiov, &acb->qcrs[j].qiov);
        if (!quorum) {
            break;
       }
    }

    /* Every successful read agrees */
    if (quorum) {
        quorum_copy_qiov(acb->qiov, &acb->qcrs[i].qiov);
K
Kevin Wolf 已提交
547
        return;
B
Benoît Canet 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    }

    /* compute hashes for each successful read, also store indexes */
    for (i = 0; i < s->num_children; i++) {
        if (acb->qcrs[i].ret) {
            continue;
        }
        ret = quorum_compute_hash(acb, i, &hash);
        /* if ever the hash computation failed */
        if (ret < 0) {
            acb->vote_ret = ret;
            goto free_exit;
        }
        quorum_count_vote(&acb->votes, &hash, i);
    }

    /* vote to select the most represented version */
    winner = quorum_get_vote_winner(&acb->votes);

    /* if the winner count is smaller than threshold the read fails */
    if (winner->vote_count < s->threshold) {
        quorum_report_failure(acb);
        acb->vote_ret = -EIO;
        goto free_exit;
    }

    /* we have a winner: copy it */
    quorum_copy_qiov(acb->qiov, &acb->qcrs[winner->index].qiov);

    /* some versions are bad print them */
    quorum_report_bad_versions(s, acb, &winner->value);

580 581
    /* corruption correction is enabled */
    if (s->rewrite_corrupted) {
K
Kevin Wolf 已提交
582
        quorum_rewrite_bad_versions(s, acb, &winner->value);
583 584
    }

B
Benoît Canet 已提交
585 586 587 588 589
free_exit:
    /* free lists */
    quorum_free_vote_list(&acb->votes);
}

590
static void read_quorum_children_entry(void *opaque)
B
Benoît Canet 已提交
591
{
592 593 594 595
    QuorumCo *co = opaque;
    QuorumAIOCB *acb = co->acb;
    BDRVQuorumState *s = acb->bs->opaque;
    int i = co->idx;
K
Kevin Wolf 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608
    QuorumChildRequest *sacb = &acb->qcrs[i];

    sacb->bs = s->children[i]->bs;
    sacb->ret = bdrv_co_preadv(s->children[i],
                               acb->sector_num * BDRV_SECTOR_SIZE,
                               acb->nb_sectors * BDRV_SECTOR_SIZE,
                               &acb->qcrs[i].qiov, 0);

    if (sacb->ret == 0) {
        acb->success_count++;
    } else {
        quorum_report_bad_acb(sacb, sacb->ret);
    }
609

K
Kevin Wolf 已提交
610 611 612 613 614 615 616 617
    acb->count++;
    assert(acb->count <= s->num_children);
    assert(acb->success_count <= s->num_children);

    /* Wake up the caller after the last read */
    if (acb->count == s->num_children) {
        qemu_coroutine_enter_if_inactive(acb->co);
    }
618 619 620 621 622 623
}

static int read_quorum_children(QuorumAIOCB *acb)
{
    BDRVQuorumState *s = acb->bs->opaque;
    int i, ret;
B
Benoît Canet 已提交
624

625
    acb->children_read = s->num_children;
B
Benoît Canet 已提交
626
    for (i = 0; i < s->num_children; i++) {
K
Kevin Wolf 已提交
627
        acb->qcrs[i].buf = qemu_blockalign(s->children[i]->bs, acb->qiov->size);
628 629
        qemu_iovec_init(&acb->qcrs[i].qiov, acb->qiov->niov);
        qemu_iovec_clone(&acb->qcrs[i].qiov, acb->qiov, acb->qcrs[i].buf);
B
Benoît Canet 已提交
630 631 632
    }

    for (i = 0; i < s->num_children; i++) {
633 634 635 636 637 638 639 640
        Coroutine *co;
        QuorumCo data = {
            .acb = acb,
            .idx = i,
        };

        co = qemu_coroutine_create(read_quorum_children_entry, &data);
        qemu_coroutine_enter(co);
B
Benoît Canet 已提交
641 642
    }

K
Kevin Wolf 已提交
643 644 645 646 647 648 649 650 651 652 653 654
    while (acb->count < s->num_children) {
        qemu_coroutine_yield();
    }

    /* Do the vote on read */
    quorum_vote(acb);
    for (i = 0; i < s->num_children; i++) {
        qemu_vfree(acb->qcrs[i].buf);
        qemu_iovec_destroy(&acb->qcrs[i].qiov);
    }

    while (acb->rewrite_count) {
655 656 657 658 659 660
        qemu_coroutine_yield();
    }

    ret = acb->vote_ret;

    return ret;
B
Benoît Canet 已提交
661 662
}

663
static int read_fifo_child(QuorumAIOCB *acb)
664
{
665
    BDRVQuorumState *s = acb->bs->opaque;
666
    int n = acb->children_read++;
667
    int ret;
668

669 670 671 672
    acb->qcrs[n].bs = s->children[n]->bs;
    ret = bdrv_co_preadv(s->children[n], acb->sector_num * BDRV_SECTOR_SIZE,
                         acb->nb_sectors * BDRV_SECTOR_SIZE, acb->qiov, 0);
    ret = quorum_fifo_aio_cb(&acb->qcrs[n], ret);
673

674
    return ret;
675 676
}

677 678 679
static int quorum_co_readv(BlockDriverState *bs,
                           int64_t sector_num, int nb_sectors,
                           QEMUIOVector *qiov)
680 681
{
    BDRVQuorumState *s = bs->opaque;
682 683 684
    QuorumAIOCB *acb = quorum_aio_get(bs, qiov, sector_num, nb_sectors);
    int ret;

685
    acb->is_read = true;
686
    acb->children_read = 0;
687 688

    if (s->read_pattern == QUORUM_READ_PATTERN_QUORUM) {
689 690 691
        ret = read_quorum_children(acb);
    } else {
        ret = read_fifo_child(acb);
692
    }
693 694
    quorum_aio_finalize(acb);

695 696
    return ret;
}
697

698 699 700 701 702 703
static void write_quorum_entry(void *opaque)
{
    QuorumCo *co = opaque;
    QuorumAIOCB *acb = co->acb;
    BDRVQuorumState *s = acb->bs->opaque;
    int i = co->idx;
K
Kevin Wolf 已提交
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    QuorumChildRequest *sacb = &acb->qcrs[i];

    sacb->bs = s->children[i]->bs;
    sacb->ret = bdrv_co_pwritev(s->children[i],
                                acb->sector_num * BDRV_SECTOR_SIZE,
                                acb->nb_sectors * BDRV_SECTOR_SIZE,
                                acb->qiov, 0);
    if (sacb->ret == 0) {
        acb->success_count++;
    } else {
        quorum_report_bad_acb(sacb, sacb->ret);
    }
    acb->count++;
    assert(acb->count <= s->num_children);
    assert(acb->success_count <= s->num_children);
719

K
Kevin Wolf 已提交
720 721 722 723
    /* Wake up the caller after the last write */
    if (acb->count == s->num_children) {
        qemu_coroutine_enter_if_inactive(acb->co);
    }
724 725
}

726 727 728
static int quorum_co_writev(BlockDriverState *bs,
                            int64_t sector_num, int nb_sectors,
                            QEMUIOVector *qiov)
729 730
{
    BDRVQuorumState *s = bs->opaque;
731 732
    QuorumAIOCB *acb = quorum_aio_get(bs, qiov, sector_num, nb_sectors);
    int i, ret;
733 734

    for (i = 0; i < s->num_children; i++) {
735 736 737 738 739 740 741 742
        Coroutine *co;
        QuorumCo data = {
            .acb = acb,
            .idx = i,
        };

        co = qemu_coroutine_create(write_quorum_entry, &data);
        qemu_coroutine_enter(co);
743 744
    }

K
Kevin Wolf 已提交
745
    while (acb->count < s->num_children) {
746 747 748
        qemu_coroutine_yield();
    }

K
Kevin Wolf 已提交
749 750
    quorum_has_too_much_io_failed(acb);

751
    ret = acb->vote_ret;
752
    quorum_aio_finalize(acb);
753 754

    return ret;
755 756
}

B
Benoît Canet 已提交
757 758 759 760 761 762 763
static int64_t quorum_getlength(BlockDriverState *bs)
{
    BDRVQuorumState *s = bs->opaque;
    int64_t result;
    int i;

    /* check that all file have the same length */
K
Kevin Wolf 已提交
764
    result = bdrv_getlength(s->children[0]->bs);
B
Benoît Canet 已提交
765 766 767 768
    if (result < 0) {
        return result;
    }
    for (i = 1; i < s->num_children; i++) {
K
Kevin Wolf 已提交
769
        int64_t value = bdrv_getlength(s->children[i]->bs);
B
Benoît Canet 已提交
770 771 772 773 774 775 776 777 778 779 780
        if (value < 0) {
            return value;
        }
        if (value != result) {
            return -EIO;
        }
    }

    return result;
}

B
Benoît Canet 已提交
781 782 783 784 785 786 787 788
static coroutine_fn int quorum_co_flush(BlockDriverState *bs)
{
    BDRVQuorumState *s = bs->opaque;
    QuorumVoteVersion *winner = NULL;
    QuorumVotes error_votes;
    QuorumVoteValue result_value;
    int i;
    int result = 0;
789
    int success_count = 0;
B
Benoît Canet 已提交
790 791 792 793 794

    QLIST_INIT(&error_votes.vote_list);
    error_votes.compare = quorum_64bits_compare;

    for (i = 0; i < s->num_children; i++) {
K
Kevin Wolf 已提交
795
        result = bdrv_co_flush(s->children[i]->bs);
796 797 798 799 800 801 802 803 804
        if (result) {
            quorum_report_bad(QUORUM_OP_TYPE_FLUSH, 0,
                              bdrv_nb_sectors(s->children[i]->bs),
                              s->children[i]->bs->node_name, result);
            result_value.l = result;
            quorum_count_vote(&error_votes, &result_value, i);
        } else {
            success_count++;
        }
B
Benoît Canet 已提交
805 806
    }

807 808 809 810 811 812
    if (success_count >= s->threshold) {
        result = 0;
    } else {
        winner = quorum_get_vote_winner(&error_votes);
        result = winner->value.l;
    }
B
Benoît Canet 已提交
813 814 815 816 817
    quorum_free_vote_list(&error_votes);

    return result;
}

818 819 820 821 822 823 824
static bool quorum_recurse_is_first_non_filter(BlockDriverState *bs,
                                               BlockDriverState *candidate)
{
    BDRVQuorumState *s = bs->opaque;
    int i;

    for (i = 0; i < s->num_children; i++) {
K
Kevin Wolf 已提交
825
        bool perm = bdrv_recurse_is_first_non_filter(s->children[i]->bs,
826 827 828 829 830 831 832 833 834
                                                     candidate);
        if (perm) {
            return true;
        }
    }

    return false;
}

835 836 837 838
static int quorum_valid_threshold(int threshold, int num_children, Error **errp)
{

    if (threshold < 1) {
839 840
        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
                   "vote-threshold", "value >= 1");
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
        return -ERANGE;
    }

    if (threshold > num_children) {
        error_setg(errp, "threshold may not exceed children count");
        return -ERANGE;
    }

    return 0;
}

static QemuOptsList quorum_runtime_opts = {
    .name = "quorum",
    .head = QTAILQ_HEAD_INITIALIZER(quorum_runtime_opts.head),
    .desc = {
        {
            .name = QUORUM_OPT_VOTE_THRESHOLD,
            .type = QEMU_OPT_NUMBER,
            .help = "The number of vote needed for reaching quorum",
        },
        {
            .name = QUORUM_OPT_BLKVERIFY,
            .type = QEMU_OPT_BOOL,
            .help = "Trigger block verify mode if set",
        },
866 867 868 869 870
        {
            .name = QUORUM_OPT_REWRITE,
            .type = QEMU_OPT_BOOL,
            .help = "Rewrite corrupted block on read quorum",
        },
871 872 873 874 875
        {
            .name = QUORUM_OPT_READ_PATTERN,
            .type = QEMU_OPT_STRING,
            .help = "Allowed pattern: quorum, fifo. Quorum is default",
        },
876 877 878 879
        { /* end of list */ }
    },
};

880 881 882 883 884 885 886 887 888
static int parse_read_pattern(const char *opt)
{
    int i;

    if (!opt) {
        /* Set quorum as default */
        return QUORUM_READ_PATTERN_QUORUM;
    }

889
    for (i = 0; i < QUORUM_READ_PATTERN__MAX; i++) {
890 891 892 893 894 895 896 897
        if (!strcmp(opt, QuorumReadPattern_lookup[i])) {
            return i;
        }
    }

    return -EINVAL;
}

898 899 900 901 902
static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
                       Error **errp)
{
    BDRVQuorumState *s = bs->opaque;
    Error *local_err = NULL;
903
    QemuOpts *opts = NULL;
904 905 906 907 908 909
    bool *opened;
    int i;
    int ret = 0;

    qdict_flatten(options);

K
Kevin Wolf 已提交
910 911 912 913
    /* count how many different children are present */
    s->num_children = qdict_array_entries(options, "children.");
    if (s->num_children < 0) {
        error_setg(&local_err, "Option children is not a valid array");
M
Max Reitz 已提交
914 915 916
        ret = -EINVAL;
        goto exit;
    }
917
    if (s->num_children < 1) {
918
        error_setg(&local_err,
919
                   "Number of provided children must be 1 or more");
920 921 922 923 924 925
        ret = -EINVAL;
        goto exit;
    }

    opts = qemu_opts_create(&quorum_runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
926
    if (local_err) {
927 928 929 930 931
        ret = -EINVAL;
        goto exit;
    }

    s->threshold = qemu_opt_get_number(opts, QUORUM_OPT_VOTE_THRESHOLD, 0);
932 933 934 935 936 937
    /* and validate it against s->num_children */
    ret = quorum_valid_threshold(s->threshold, s->num_children, &local_err);
    if (ret < 0) {
        goto exit;
    }

938
    ret = parse_read_pattern(qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN));
939
    if (ret < 0) {
940
        error_setg(&local_err, "Please set read-pattern as fifo or quorum");
941 942
        goto exit;
    }
943
    s->read_pattern = ret;
944

945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
    if (s->read_pattern == QUORUM_READ_PATTERN_QUORUM) {
        /* is the driver in blkverify mode */
        if (qemu_opt_get_bool(opts, QUORUM_OPT_BLKVERIFY, false) &&
            s->num_children == 2 && s->threshold == 2) {
            s->is_blkverify = true;
        } else if (qemu_opt_get_bool(opts, QUORUM_OPT_BLKVERIFY, false)) {
            fprintf(stderr, "blkverify mode is set by setting blkverify=on "
                    "and using two files with vote_threshold=2\n");
        }

        s->rewrite_corrupted = qemu_opt_get_bool(opts, QUORUM_OPT_REWRITE,
                                                 false);
        if (s->rewrite_corrupted && s->is_blkverify) {
            error_setg(&local_err,
                       "rewrite-corrupted=on cannot be used with blkverify=on");
            ret = -EINVAL;
            goto exit;
        }
963 964
    }

K
Kevin Wolf 已提交
965 966
    /* allocate the children array */
    s->children = g_new0(BdrvChild *, s->num_children);
967 968
    opened = g_new0(bool, s->num_children);

K
Kevin Wolf 已提交
969 970 971 972
    for (i = 0; i < s->num_children; i++) {
        char indexstr[32];
        ret = snprintf(indexstr, 32, "children.%d", i);
        assert(ret < 32);
M
Max Reitz 已提交
973

K
Kevin Wolf 已提交
974 975 976 977
        s->children[i] = bdrv_open_child(NULL, options, indexstr, bs,
                                         &child_format, false, &local_err);
        if (local_err) {
            ret = -EINVAL;
M
Max Reitz 已提交
978
            goto close_exit;
979
        }
K
Kevin Wolf 已提交
980

M
Max Reitz 已提交
981
        opened[i] = true;
982
    }
983
    s->next_child_index = s->num_children;
984 985 986 987 988 989 990 991 992 993

    g_free(opened);
    goto exit;

close_exit:
    /* cleanup on error */
    for (i = 0; i < s->num_children; i++) {
        if (!opened[i]) {
            continue;
        }
K
Kevin Wolf 已提交
994
        bdrv_unref_child(bs, s->children[i]);
995
    }
K
Kevin Wolf 已提交
996
    g_free(s->children);
997 998
    g_free(opened);
exit:
999
    qemu_opts_del(opts);
1000
    /* propagate error */
1001
    error_propagate(errp, local_err);
1002 1003 1004 1005 1006 1007 1008 1009 1010
    return ret;
}

static void quorum_close(BlockDriverState *bs)
{
    BDRVQuorumState *s = bs->opaque;
    int i;

    for (i = 0; i < s->num_children; i++) {
K
Kevin Wolf 已提交
1011
        bdrv_unref_child(bs, s->children[i]);
1012 1013
    }

K
Kevin Wolf 已提交
1014
    g_free(s->children);
1015 1016
}

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
static void quorum_add_child(BlockDriverState *bs, BlockDriverState *child_bs,
                             Error **errp)
{
    BDRVQuorumState *s = bs->opaque;
    BdrvChild *child;
    char indexstr[32];
    int ret;

    assert(s->num_children <= INT_MAX / sizeof(BdrvChild *));
    if (s->num_children == INT_MAX / sizeof(BdrvChild *) ||
        s->next_child_index == UINT_MAX) {
        error_setg(errp, "Too many children");
        return;
    }

    ret = snprintf(indexstr, 32, "children.%u", s->next_child_index);
    if (ret < 0 || ret >= 32) {
        error_setg(errp, "cannot generate child name");
        return;
    }
    s->next_child_index++;

    bdrv_drained_begin(bs);

    /* We can safely add the child now */
    bdrv_ref(child_bs);
    child = bdrv_attach_child(bs, child_bs, indexstr, &child_format);
    s->children = g_renew(BdrvChild *, s->children, s->num_children + 1);
    s->children[s->num_children++] = child;

    bdrv_drained_end(bs);
}

static void quorum_del_child(BlockDriverState *bs, BdrvChild *child,
                             Error **errp)
{
    BDRVQuorumState *s = bs->opaque;
    int i;

    for (i = 0; i < s->num_children; i++) {
        if (s->children[i] == child) {
            break;
        }
    }

    /* we have checked it in bdrv_del_child() */
    assert(i < s->num_children);

    if (s->num_children <= s->threshold) {
        error_setg(errp,
            "The number of children cannot be lower than the vote threshold %d",
            s->threshold);
        return;
    }

    bdrv_drained_begin(bs);

    /* We can safely remove this child now */
    memmove(&s->children[i], &s->children[i + 1],
            (s->num_children - i - 1) * sizeof(BdrvChild *));
    s->children = g_renew(BdrvChild *, s->children, --s->num_children);
    bdrv_unref_child(bs, child);

    bdrv_drained_end(bs);
}

1083
static void quorum_refresh_filename(BlockDriverState *bs, QDict *options)
1084 1085 1086 1087 1088 1089 1090
{
    BDRVQuorumState *s = bs->opaque;
    QDict *opts;
    QList *children;
    int i;

    for (i = 0; i < s->num_children; i++) {
K
Kevin Wolf 已提交
1091 1092
        bdrv_refresh_filename(s->children[i]->bs);
        if (!s->children[i]->bs->full_open_options) {
1093 1094 1095 1096 1097 1098
            return;
        }
    }

    children = qlist_new();
    for (i = 0; i < s->num_children; i++) {
K
Kevin Wolf 已提交
1099 1100 1101
        QINCREF(s->children[i]->bs->full_open_options);
        qlist_append_obj(children,
                         QOBJECT(s->children[i]->bs->full_open_options));
1102 1103 1104 1105 1106 1107 1108
    }

    opts = qdict_new();
    qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str("quorum")));
    qdict_put_obj(opts, QUORUM_OPT_VOTE_THRESHOLD,
                  QOBJECT(qint_from_int(s->threshold)));
    qdict_put_obj(opts, QUORUM_OPT_BLKVERIFY,
E
Eric Blake 已提交
1109
                  QOBJECT(qbool_from_bool(s->is_blkverify)));
1110
    qdict_put_obj(opts, QUORUM_OPT_REWRITE,
E
Eric Blake 已提交
1111
                  QOBJECT(qbool_from_bool(s->rewrite_corrupted)));
1112 1113 1114 1115 1116
    qdict_put_obj(opts, "children", QOBJECT(children));

    bs->full_open_options = opts;
}

1117
static BlockDriver bdrv_quorum = {
1118 1119 1120 1121
    .format_name                        = "quorum",
    .protocol_name                      = "quorum",

    .instance_size                      = sizeof(BDRVQuorumState),
1122

1123 1124
    .bdrv_file_open                     = quorum_open,
    .bdrv_close                         = quorum_close,
1125
    .bdrv_refresh_filename              = quorum_refresh_filename,
1126

1127
    .bdrv_co_flush_to_disk              = quorum_co_flush,
1128

1129
    .bdrv_getlength                     = quorum_getlength,
B
Benoît Canet 已提交
1130

1131 1132
    .bdrv_co_readv                      = quorum_co_readv,
    .bdrv_co_writev                     = quorum_co_writev,
B
Benoît Canet 已提交
1133

1134 1135 1136
    .bdrv_add_child                     = quorum_add_child,
    .bdrv_del_child                     = quorum_del_child,

1137 1138
    .is_filter                          = true,
    .bdrv_recurse_is_first_non_filter   = quorum_recurse_is_first_non_filter,
1139 1140 1141 1142
};

static void bdrv_quorum_init(void)
{
1143 1144 1145 1146
    if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA256)) {
        /* SHA256 hash support is required for quorum device */
        return;
    }
1147 1148 1149 1150
    bdrv_register(&bdrv_quorum);
}

block_init(bdrv_quorum_init);