xref: /openbmc/qemu/block/quorum.c (revision 7d405b2f)
1 /*
2  * Quorum Block filter
3  *
4  * Copyright (C) 2012-2014 Nodalink, EURL.
5  *
6  * Author:
7  *   Benoît Canet <benoit.canet@irqsave.net>
8  *
9  * Based on the design and code of blkverify.c (Copyright (C) 2010 IBM, Corp)
10  * and blkmirror.c (Copyright (C) 2011 Red Hat, Inc).
11  *
12  * This work is licensed under the terms of the GNU GPL, version 2 or later.
13  * See the COPYING file in the top-level directory.
14  */
15 
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/option.h"
19 #include "block/block_int.h"
20 #include "qapi/error.h"
21 #include "qapi/qapi-events-block.h"
22 #include "qapi/qmp/qdict.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qapi/qmp/qlist.h"
25 #include "qapi/qmp/qstring.h"
26 #include "crypto/hash.h"
27 
28 #define HASH_LENGTH 32
29 
30 #define QUORUM_OPT_VOTE_THRESHOLD "vote-threshold"
31 #define QUORUM_OPT_BLKVERIFY      "blkverify"
32 #define QUORUM_OPT_REWRITE        "rewrite-corrupted"
33 #define QUORUM_OPT_READ_PATTERN   "read-pattern"
34 
35 /* This union holds a vote hash value */
36 typedef union QuorumVoteValue {
37     uint8_t h[HASH_LENGTH];    /* SHA-256 hash */
38     int64_t l;                 /* simpler 64 bits hash */
39 } QuorumVoteValue;
40 
41 /* A vote item */
42 typedef struct QuorumVoteItem {
43     int index;
44     QLIST_ENTRY(QuorumVoteItem) next;
45 } QuorumVoteItem;
46 
47 /* this structure is a vote version. A version is the set of votes sharing the
48  * same vote value.
49  * The set of votes will be tracked with the items field and its cardinality is
50  * vote_count.
51  */
52 typedef struct QuorumVoteVersion {
53     QuorumVoteValue value;
54     int index;
55     int vote_count;
56     QLIST_HEAD(, QuorumVoteItem) items;
57     QLIST_ENTRY(QuorumVoteVersion) next;
58 } QuorumVoteVersion;
59 
60 /* this structure holds a group of vote versions together */
61 typedef struct QuorumVotes {
62     QLIST_HEAD(, QuorumVoteVersion) vote_list;
63     bool (*compare)(QuorumVoteValue *a, QuorumVoteValue *b);
64 } QuorumVotes;
65 
66 /* the following structure holds the state of one quorum instance */
67 typedef struct BDRVQuorumState {
68     BdrvChild **children;  /* children BlockDriverStates */
69     int num_children;      /* children count */
70     unsigned next_child_index;  /* the index of the next child that should
71                                  * be added
72                                  */
73     int threshold;         /* if less than threshold children reads gave the
74                             * same result a quorum error occurs.
75                             */
76     bool is_blkverify;     /* true if the driver is in blkverify mode
77                             * Writes are mirrored on two children devices.
78                             * On reads the two children devices' contents are
79                             * compared and if a difference is spotted its
80                             * location is printed and the code aborts.
81                             * It is useful to debug other block drivers by
82                             * comparing them with a reference one.
83                             */
84     bool rewrite_corrupted;/* true if the driver must rewrite-on-read corrupted
85                             * block if Quorum is reached.
86                             */
87 
88     QuorumReadPattern read_pattern;
89 } BDRVQuorumState;
90 
91 typedef struct QuorumAIOCB QuorumAIOCB;
92 
93 /* Quorum will create one instance of the following structure per operation it
94  * performs on its children.
95  * So for each read/write operation coming from the upper layer there will be
96  * $children_count QuorumChildRequest.
97  */
98 typedef struct QuorumChildRequest {
99     BlockDriverState *bs;
100     QEMUIOVector qiov;
101     uint8_t *buf;
102     int ret;
103     QuorumAIOCB *parent;
104 } QuorumChildRequest;
105 
106 /* Quorum will use the following structure to track progress of each read/write
107  * operation received by the upper layer.
108  * This structure hold pointers to the QuorumChildRequest structures instances
109  * used to do operations on each children and track overall progress.
110  */
111 struct QuorumAIOCB {
112     BlockDriverState *bs;
113     Coroutine *co;
114 
115     /* Request metadata */
116     uint64_t offset;
117     uint64_t bytes;
118     int flags;
119 
120     QEMUIOVector *qiov;         /* calling IOV */
121 
122     QuorumChildRequest *qcrs;   /* individual child requests */
123     int count;                  /* number of completed AIOCB */
124     int success_count;          /* number of successfully completed AIOCB */
125 
126     int rewrite_count;          /* number of replica to rewrite: count down to
127                                  * zero once writes are fired
128                                  */
129 
130     QuorumVotes votes;
131 
132     bool is_read;
133     int vote_ret;
134     int children_read;          /* how many children have been read from */
135 };
136 
137 typedef struct QuorumCo {
138     QuorumAIOCB *acb;
139     int idx;
140 } QuorumCo;
141 
142 static void quorum_aio_finalize(QuorumAIOCB *acb)
143 {
144     g_free(acb->qcrs);
145     g_free(acb);
146 }
147 
148 static bool quorum_sha256_compare(QuorumVoteValue *a, QuorumVoteValue *b)
149 {
150     return !memcmp(a->h, b->h, HASH_LENGTH);
151 }
152 
153 static bool quorum_64bits_compare(QuorumVoteValue *a, QuorumVoteValue *b)
154 {
155     return a->l == b->l;
156 }
157 
158 static QuorumAIOCB *quorum_aio_get(BlockDriverState *bs,
159                                    QEMUIOVector *qiov,
160                                    uint64_t offset,
161                                    uint64_t bytes,
162                                    int flags)
163 {
164     BDRVQuorumState *s = bs->opaque;
165     QuorumAIOCB *acb = g_new(QuorumAIOCB, 1);
166     int i;
167 
168     *acb = (QuorumAIOCB) {
169         .co                 = qemu_coroutine_self(),
170         .bs                 = bs,
171         .offset             = offset,
172         .bytes              = bytes,
173         .flags              = flags,
174         .qiov               = qiov,
175         .votes.compare      = quorum_sha256_compare,
176         .votes.vote_list    = QLIST_HEAD_INITIALIZER(acb.votes.vote_list),
177     };
178 
179     acb->qcrs = g_new0(QuorumChildRequest, s->num_children);
180     for (i = 0; i < s->num_children; i++) {
181         acb->qcrs[i].buf = NULL;
182         acb->qcrs[i].ret = 0;
183         acb->qcrs[i].parent = acb;
184     }
185 
186     return acb;
187 }
188 
189 static void quorum_report_bad(QuorumOpType type, uint64_t offset,
190                               uint64_t bytes, char *node_name, int ret)
191 {
192     const char *msg = NULL;
193     int64_t start_sector = offset / BDRV_SECTOR_SIZE;
194     int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
195 
196     if (ret < 0) {
197         msg = strerror(-ret);
198     }
199 
200     qapi_event_send_quorum_report_bad(type, !!msg, msg, node_name, start_sector,
201                                       end_sector - start_sector, &error_abort);
202 }
203 
204 static void quorum_report_failure(QuorumAIOCB *acb)
205 {
206     const char *reference = bdrv_get_device_or_node_name(acb->bs);
207     int64_t start_sector = acb->offset / BDRV_SECTOR_SIZE;
208     int64_t end_sector = DIV_ROUND_UP(acb->offset + acb->bytes,
209                                       BDRV_SECTOR_SIZE);
210 
211     qapi_event_send_quorum_failure(reference, start_sector,
212                                    end_sector - start_sector, &error_abort);
213 }
214 
215 static int quorum_vote_error(QuorumAIOCB *acb);
216 
217 static bool quorum_has_too_much_io_failed(QuorumAIOCB *acb)
218 {
219     BDRVQuorumState *s = acb->bs->opaque;
220 
221     if (acb->success_count < s->threshold) {
222         acb->vote_ret = quorum_vote_error(acb);
223         quorum_report_failure(acb);
224         return true;
225     }
226 
227     return false;
228 }
229 
230 static int read_fifo_child(QuorumAIOCB *acb);
231 
232 static void quorum_copy_qiov(QEMUIOVector *dest, QEMUIOVector *source)
233 {
234     int i;
235     assert(dest->niov == source->niov);
236     assert(dest->size == source->size);
237     for (i = 0; i < source->niov; i++) {
238         assert(dest->iov[i].iov_len == source->iov[i].iov_len);
239         memcpy(dest->iov[i].iov_base,
240                source->iov[i].iov_base,
241                source->iov[i].iov_len);
242     }
243 }
244 
245 static void quorum_report_bad_acb(QuorumChildRequest *sacb, int ret)
246 {
247     QuorumAIOCB *acb = sacb->parent;
248     QuorumOpType type = acb->is_read ? QUORUM_OP_TYPE_READ : QUORUM_OP_TYPE_WRITE;
249     quorum_report_bad(type, acb->offset, acb->bytes, sacb->bs->node_name, ret);
250 }
251 
252 static void quorum_report_bad_versions(BDRVQuorumState *s,
253                                        QuorumAIOCB *acb,
254                                        QuorumVoteValue *value)
255 {
256     QuorumVoteVersion *version;
257     QuorumVoteItem *item;
258 
259     QLIST_FOREACH(version, &acb->votes.vote_list, next) {
260         if (acb->votes.compare(&version->value, value)) {
261             continue;
262         }
263         QLIST_FOREACH(item, &version->items, next) {
264             quorum_report_bad(QUORUM_OP_TYPE_READ, acb->offset, acb->bytes,
265                               s->children[item->index]->bs->node_name, 0);
266         }
267     }
268 }
269 
270 static void quorum_rewrite_entry(void *opaque)
271 {
272     QuorumCo *co = opaque;
273     QuorumAIOCB *acb = co->acb;
274     BDRVQuorumState *s = acb->bs->opaque;
275 
276     /* Ignore any errors, it's just a correction attempt for already
277      * corrupted data.
278      * Mask out BDRV_REQ_WRITE_UNCHANGED because this overwrites the
279      * area with different data from the other children. */
280     bdrv_co_pwritev(s->children[co->idx], acb->offset, acb->bytes,
281                     acb->qiov, acb->flags & ~BDRV_REQ_WRITE_UNCHANGED);
282 
283     /* Wake up the caller after the last rewrite */
284     acb->rewrite_count--;
285     if (!acb->rewrite_count) {
286         qemu_coroutine_enter_if_inactive(acb->co);
287     }
288 }
289 
290 static bool quorum_rewrite_bad_versions(QuorumAIOCB *acb,
291                                         QuorumVoteValue *value)
292 {
293     QuorumVoteVersion *version;
294     QuorumVoteItem *item;
295     int count = 0;
296 
297     /* first count the number of bad versions: done first to avoid concurrency
298      * issues.
299      */
300     QLIST_FOREACH(version, &acb->votes.vote_list, next) {
301         if (acb->votes.compare(&version->value, value)) {
302             continue;
303         }
304         QLIST_FOREACH(item, &version->items, next) {
305             count++;
306         }
307     }
308 
309     /* quorum_rewrite_entry will count down this to zero */
310     acb->rewrite_count = count;
311 
312     /* now fire the correcting rewrites */
313     QLIST_FOREACH(version, &acb->votes.vote_list, next) {
314         if (acb->votes.compare(&version->value, value)) {
315             continue;
316         }
317         QLIST_FOREACH(item, &version->items, next) {
318             Coroutine *co;
319             QuorumCo data = {
320                 .acb = acb,
321                 .idx = item->index,
322             };
323 
324             co = qemu_coroutine_create(quorum_rewrite_entry, &data);
325             qemu_coroutine_enter(co);
326         }
327     }
328 
329     /* return true if any rewrite is done else false */
330     return count;
331 }
332 
333 static void quorum_count_vote(QuorumVotes *votes,
334                               QuorumVoteValue *value,
335                               int index)
336 {
337     QuorumVoteVersion *v = NULL, *version = NULL;
338     QuorumVoteItem *item;
339 
340     /* look if we have something with this hash */
341     QLIST_FOREACH(v, &votes->vote_list, next) {
342         if (votes->compare(&v->value, value)) {
343             version = v;
344             break;
345         }
346     }
347 
348     /* It's a version not yet in the list add it */
349     if (!version) {
350         version = g_new0(QuorumVoteVersion, 1);
351         QLIST_INIT(&version->items);
352         memcpy(&version->value, value, sizeof(version->value));
353         version->index = index;
354         version->vote_count = 0;
355         QLIST_INSERT_HEAD(&votes->vote_list, version, next);
356     }
357 
358     version->vote_count++;
359 
360     item = g_new0(QuorumVoteItem, 1);
361     item->index = index;
362     QLIST_INSERT_HEAD(&version->items, item, next);
363 }
364 
365 static void quorum_free_vote_list(QuorumVotes *votes)
366 {
367     QuorumVoteVersion *version, *next_version;
368     QuorumVoteItem *item, *next_item;
369 
370     QLIST_FOREACH_SAFE(version, &votes->vote_list, next, next_version) {
371         QLIST_REMOVE(version, next);
372         QLIST_FOREACH_SAFE(item, &version->items, next, next_item) {
373             QLIST_REMOVE(item, next);
374             g_free(item);
375         }
376         g_free(version);
377     }
378 }
379 
380 static int quorum_compute_hash(QuorumAIOCB *acb, int i, QuorumVoteValue *hash)
381 {
382     QEMUIOVector *qiov = &acb->qcrs[i].qiov;
383     size_t len = sizeof(hash->h);
384     uint8_t *data = hash->h;
385 
386     /* XXX - would be nice if we could pass in the Error **
387      * and propagate that back, but this quorum code is
388      * restricted to just errno values currently */
389     if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,
390                             qiov->iov, qiov->niov,
391                             &data, &len,
392                             NULL) < 0) {
393         return -EINVAL;
394     }
395 
396     return 0;
397 }
398 
399 static QuorumVoteVersion *quorum_get_vote_winner(QuorumVotes *votes)
400 {
401     int max = 0;
402     QuorumVoteVersion *candidate, *winner = NULL;
403 
404     QLIST_FOREACH(candidate, &votes->vote_list, next) {
405         if (candidate->vote_count > max) {
406             max = candidate->vote_count;
407             winner = candidate;
408         }
409     }
410 
411     return winner;
412 }
413 
414 /* qemu_iovec_compare is handy for blkverify mode because it returns the first
415  * differing byte location. Yet it is handcoded to compare vectors one byte
416  * after another so it does not benefit from the libc SIMD optimizations.
417  * quorum_iovec_compare is written for speed and should be used in the non
418  * blkverify mode of quorum.
419  */
420 static bool quorum_iovec_compare(QEMUIOVector *a, QEMUIOVector *b)
421 {
422     int i;
423     int result;
424 
425     assert(a->niov == b->niov);
426     for (i = 0; i < a->niov; i++) {
427         assert(a->iov[i].iov_len == b->iov[i].iov_len);
428         result = memcmp(a->iov[i].iov_base,
429                         b->iov[i].iov_base,
430                         a->iov[i].iov_len);
431         if (result) {
432             return false;
433         }
434     }
435 
436     return true;
437 }
438 
439 static void GCC_FMT_ATTR(2, 3) quorum_err(QuorumAIOCB *acb,
440                                           const char *fmt, ...)
441 {
442     va_list ap;
443 
444     va_start(ap, fmt);
445     fprintf(stderr, "quorum: offset=%" PRIu64 " bytes=%" PRIu64 " ",
446             acb->offset, acb->bytes);
447     vfprintf(stderr, fmt, ap);
448     fprintf(stderr, "\n");
449     va_end(ap);
450     exit(1);
451 }
452 
453 static bool quorum_compare(QuorumAIOCB *acb,
454                            QEMUIOVector *a,
455                            QEMUIOVector *b)
456 {
457     BDRVQuorumState *s = acb->bs->opaque;
458     ssize_t offset;
459 
460     /* This driver will replace blkverify in this particular case */
461     if (s->is_blkverify) {
462         offset = qemu_iovec_compare(a, b);
463         if (offset != -1) {
464             quorum_err(acb, "contents mismatch at offset %" PRIu64,
465                        acb->offset + offset);
466         }
467         return true;
468     }
469 
470     return quorum_iovec_compare(a, b);
471 }
472 
473 /* Do a vote to get the error code */
474 static int quorum_vote_error(QuorumAIOCB *acb)
475 {
476     BDRVQuorumState *s = acb->bs->opaque;
477     QuorumVoteVersion *winner = NULL;
478     QuorumVotes error_votes;
479     QuorumVoteValue result_value;
480     int i, ret = 0;
481     bool error = false;
482 
483     QLIST_INIT(&error_votes.vote_list);
484     error_votes.compare = quorum_64bits_compare;
485 
486     for (i = 0; i < s->num_children; i++) {
487         ret = acb->qcrs[i].ret;
488         if (ret) {
489             error = true;
490             result_value.l = ret;
491             quorum_count_vote(&error_votes, &result_value, i);
492         }
493     }
494 
495     if (error) {
496         winner = quorum_get_vote_winner(&error_votes);
497         ret = winner->value.l;
498     }
499 
500     quorum_free_vote_list(&error_votes);
501 
502     return ret;
503 }
504 
505 static void quorum_vote(QuorumAIOCB *acb)
506 {
507     bool quorum = true;
508     int i, j, ret;
509     QuorumVoteValue hash;
510     BDRVQuorumState *s = acb->bs->opaque;
511     QuorumVoteVersion *winner;
512 
513     if (quorum_has_too_much_io_failed(acb)) {
514         return;
515     }
516 
517     /* get the index of the first successful read */
518     for (i = 0; i < s->num_children; i++) {
519         if (!acb->qcrs[i].ret) {
520             break;
521         }
522     }
523 
524     assert(i < s->num_children);
525 
526     /* compare this read with all other successful reads stopping at quorum
527      * failure
528      */
529     for (j = i + 1; j < s->num_children; j++) {
530         if (acb->qcrs[j].ret) {
531             continue;
532         }
533         quorum = quorum_compare(acb, &acb->qcrs[i].qiov, &acb->qcrs[j].qiov);
534         if (!quorum) {
535             break;
536        }
537     }
538 
539     /* Every successful read agrees */
540     if (quorum) {
541         quorum_copy_qiov(acb->qiov, &acb->qcrs[i].qiov);
542         return;
543     }
544 
545     /* compute hashes for each successful read, also store indexes */
546     for (i = 0; i < s->num_children; i++) {
547         if (acb->qcrs[i].ret) {
548             continue;
549         }
550         ret = quorum_compute_hash(acb, i, &hash);
551         /* if ever the hash computation failed */
552         if (ret < 0) {
553             acb->vote_ret = ret;
554             goto free_exit;
555         }
556         quorum_count_vote(&acb->votes, &hash, i);
557     }
558 
559     /* vote to select the most represented version */
560     winner = quorum_get_vote_winner(&acb->votes);
561 
562     /* if the winner count is smaller than threshold the read fails */
563     if (winner->vote_count < s->threshold) {
564         quorum_report_failure(acb);
565         acb->vote_ret = -EIO;
566         goto free_exit;
567     }
568 
569     /* we have a winner: copy it */
570     quorum_copy_qiov(acb->qiov, &acb->qcrs[winner->index].qiov);
571 
572     /* some versions are bad print them */
573     quorum_report_bad_versions(s, acb, &winner->value);
574 
575     /* corruption correction is enabled */
576     if (s->rewrite_corrupted) {
577         quorum_rewrite_bad_versions(acb, &winner->value);
578     }
579 
580 free_exit:
581     /* free lists */
582     quorum_free_vote_list(&acb->votes);
583 }
584 
585 static void read_quorum_children_entry(void *opaque)
586 {
587     QuorumCo *co = opaque;
588     QuorumAIOCB *acb = co->acb;
589     BDRVQuorumState *s = acb->bs->opaque;
590     int i = co->idx;
591     QuorumChildRequest *sacb = &acb->qcrs[i];
592 
593     sacb->bs = s->children[i]->bs;
594     sacb->ret = bdrv_co_preadv(s->children[i], acb->offset, acb->bytes,
595                                &acb->qcrs[i].qiov, 0);
596 
597     if (sacb->ret == 0) {
598         acb->success_count++;
599     } else {
600         quorum_report_bad_acb(sacb, sacb->ret);
601     }
602 
603     acb->count++;
604     assert(acb->count <= s->num_children);
605     assert(acb->success_count <= s->num_children);
606 
607     /* Wake up the caller after the last read */
608     if (acb->count == s->num_children) {
609         qemu_coroutine_enter_if_inactive(acb->co);
610     }
611 }
612 
613 static int read_quorum_children(QuorumAIOCB *acb)
614 {
615     BDRVQuorumState *s = acb->bs->opaque;
616     int i;
617 
618     acb->children_read = s->num_children;
619     for (i = 0; i < s->num_children; i++) {
620         acb->qcrs[i].buf = qemu_blockalign(s->children[i]->bs, acb->qiov->size);
621         qemu_iovec_init(&acb->qcrs[i].qiov, acb->qiov->niov);
622         qemu_iovec_clone(&acb->qcrs[i].qiov, acb->qiov, acb->qcrs[i].buf);
623     }
624 
625     for (i = 0; i < s->num_children; i++) {
626         Coroutine *co;
627         QuorumCo data = {
628             .acb = acb,
629             .idx = i,
630         };
631 
632         co = qemu_coroutine_create(read_quorum_children_entry, &data);
633         qemu_coroutine_enter(co);
634     }
635 
636     while (acb->count < s->num_children) {
637         qemu_coroutine_yield();
638     }
639 
640     /* Do the vote on read */
641     quorum_vote(acb);
642     for (i = 0; i < s->num_children; i++) {
643         qemu_vfree(acb->qcrs[i].buf);
644         qemu_iovec_destroy(&acb->qcrs[i].qiov);
645     }
646 
647     while (acb->rewrite_count) {
648         qemu_coroutine_yield();
649     }
650 
651     return acb->vote_ret;
652 }
653 
654 static int read_fifo_child(QuorumAIOCB *acb)
655 {
656     BDRVQuorumState *s = acb->bs->opaque;
657     int n, ret;
658 
659     /* We try to read the next child in FIFO order if we failed to read */
660     do {
661         n = acb->children_read++;
662         acb->qcrs[n].bs = s->children[n]->bs;
663         ret = bdrv_co_preadv(s->children[n], acb->offset, acb->bytes,
664                              acb->qiov, 0);
665         if (ret < 0) {
666             quorum_report_bad_acb(&acb->qcrs[n], ret);
667         }
668     } while (ret < 0 && acb->children_read < s->num_children);
669 
670     /* FIXME: rewrite failed children if acb->children_read > 1? */
671 
672     return ret;
673 }
674 
675 static int quorum_co_preadv(BlockDriverState *bs, uint64_t offset,
676                             uint64_t bytes, QEMUIOVector *qiov, int flags)
677 {
678     BDRVQuorumState *s = bs->opaque;
679     QuorumAIOCB *acb = quorum_aio_get(bs, qiov, offset, bytes, flags);
680     int ret;
681 
682     acb->is_read = true;
683     acb->children_read = 0;
684 
685     if (s->read_pattern == QUORUM_READ_PATTERN_QUORUM) {
686         ret = read_quorum_children(acb);
687     } else {
688         ret = read_fifo_child(acb);
689     }
690     quorum_aio_finalize(acb);
691 
692     return ret;
693 }
694 
695 static void write_quorum_entry(void *opaque)
696 {
697     QuorumCo *co = opaque;
698     QuorumAIOCB *acb = co->acb;
699     BDRVQuorumState *s = acb->bs->opaque;
700     int i = co->idx;
701     QuorumChildRequest *sacb = &acb->qcrs[i];
702 
703     sacb->bs = s->children[i]->bs;
704     sacb->ret = bdrv_co_pwritev(s->children[i], acb->offset, acb->bytes,
705                                 acb->qiov, acb->flags);
706     if (sacb->ret == 0) {
707         acb->success_count++;
708     } else {
709         quorum_report_bad_acb(sacb, sacb->ret);
710     }
711     acb->count++;
712     assert(acb->count <= s->num_children);
713     assert(acb->success_count <= s->num_children);
714 
715     /* Wake up the caller after the last write */
716     if (acb->count == s->num_children) {
717         qemu_coroutine_enter_if_inactive(acb->co);
718     }
719 }
720 
721 static int quorum_co_pwritev(BlockDriverState *bs, uint64_t offset,
722                              uint64_t bytes, QEMUIOVector *qiov, int flags)
723 {
724     BDRVQuorumState *s = bs->opaque;
725     QuorumAIOCB *acb = quorum_aio_get(bs, qiov, offset, bytes, flags);
726     int i, ret;
727 
728     for (i = 0; i < s->num_children; i++) {
729         Coroutine *co;
730         QuorumCo data = {
731             .acb = acb,
732             .idx = i,
733         };
734 
735         co = qemu_coroutine_create(write_quorum_entry, &data);
736         qemu_coroutine_enter(co);
737     }
738 
739     while (acb->count < s->num_children) {
740         qemu_coroutine_yield();
741     }
742 
743     quorum_has_too_much_io_failed(acb);
744 
745     ret = acb->vote_ret;
746     quorum_aio_finalize(acb);
747 
748     return ret;
749 }
750 
751 static int64_t quorum_getlength(BlockDriverState *bs)
752 {
753     BDRVQuorumState *s = bs->opaque;
754     int64_t result;
755     int i;
756 
757     /* check that all file have the same length */
758     result = bdrv_getlength(s->children[0]->bs);
759     if (result < 0) {
760         return result;
761     }
762     for (i = 1; i < s->num_children; i++) {
763         int64_t value = bdrv_getlength(s->children[i]->bs);
764         if (value < 0) {
765             return value;
766         }
767         if (value != result) {
768             return -EIO;
769         }
770     }
771 
772     return result;
773 }
774 
775 static coroutine_fn int quorum_co_flush(BlockDriverState *bs)
776 {
777     BDRVQuorumState *s = bs->opaque;
778     QuorumVoteVersion *winner = NULL;
779     QuorumVotes error_votes;
780     QuorumVoteValue result_value;
781     int i;
782     int result = 0;
783     int success_count = 0;
784 
785     QLIST_INIT(&error_votes.vote_list);
786     error_votes.compare = quorum_64bits_compare;
787 
788     for (i = 0; i < s->num_children; i++) {
789         result = bdrv_co_flush(s->children[i]->bs);
790         if (result) {
791             quorum_report_bad(QUORUM_OP_TYPE_FLUSH, 0, 0,
792                               s->children[i]->bs->node_name, result);
793             result_value.l = result;
794             quorum_count_vote(&error_votes, &result_value, i);
795         } else {
796             success_count++;
797         }
798     }
799 
800     if (success_count >= s->threshold) {
801         result = 0;
802     } else {
803         winner = quorum_get_vote_winner(&error_votes);
804         result = winner->value.l;
805     }
806     quorum_free_vote_list(&error_votes);
807 
808     return result;
809 }
810 
811 static bool quorum_recurse_is_first_non_filter(BlockDriverState *bs,
812                                                BlockDriverState *candidate)
813 {
814     BDRVQuorumState *s = bs->opaque;
815     int i;
816 
817     for (i = 0; i < s->num_children; i++) {
818         bool perm = bdrv_recurse_is_first_non_filter(s->children[i]->bs,
819                                                      candidate);
820         if (perm) {
821             return true;
822         }
823     }
824 
825     return false;
826 }
827 
828 static int quorum_valid_threshold(int threshold, int num_children, Error **errp)
829 {
830 
831     if (threshold < 1) {
832         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
833                    "vote-threshold", "value >= 1");
834         return -ERANGE;
835     }
836 
837     if (threshold > num_children) {
838         error_setg(errp, "threshold may not exceed children count");
839         return -ERANGE;
840     }
841 
842     return 0;
843 }
844 
845 static QemuOptsList quorum_runtime_opts = {
846     .name = "quorum",
847     .head = QTAILQ_HEAD_INITIALIZER(quorum_runtime_opts.head),
848     .desc = {
849         {
850             .name = QUORUM_OPT_VOTE_THRESHOLD,
851             .type = QEMU_OPT_NUMBER,
852             .help = "The number of vote needed for reaching quorum",
853         },
854         {
855             .name = QUORUM_OPT_BLKVERIFY,
856             .type = QEMU_OPT_BOOL,
857             .help = "Trigger block verify mode if set",
858         },
859         {
860             .name = QUORUM_OPT_REWRITE,
861             .type = QEMU_OPT_BOOL,
862             .help = "Rewrite corrupted block on read quorum",
863         },
864         {
865             .name = QUORUM_OPT_READ_PATTERN,
866             .type = QEMU_OPT_STRING,
867             .help = "Allowed pattern: quorum, fifo. Quorum is default",
868         },
869         { /* end of list */ }
870     },
871 };
872 
873 static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
874                        Error **errp)
875 {
876     BDRVQuorumState *s = bs->opaque;
877     Error *local_err = NULL;
878     QemuOpts *opts = NULL;
879     const char *pattern_str;
880     bool *opened;
881     int i;
882     int ret = 0;
883 
884     qdict_flatten(options);
885 
886     /* count how many different children are present */
887     s->num_children = qdict_array_entries(options, "children.");
888     if (s->num_children < 0) {
889         error_setg(&local_err, "Option children is not a valid array");
890         ret = -EINVAL;
891         goto exit;
892     }
893     if (s->num_children < 1) {
894         error_setg(&local_err,
895                    "Number of provided children must be 1 or more");
896         ret = -EINVAL;
897         goto exit;
898     }
899 
900     opts = qemu_opts_create(&quorum_runtime_opts, NULL, 0, &error_abort);
901     qemu_opts_absorb_qdict(opts, options, &local_err);
902     if (local_err) {
903         ret = -EINVAL;
904         goto exit;
905     }
906 
907     s->threshold = qemu_opt_get_number(opts, QUORUM_OPT_VOTE_THRESHOLD, 0);
908     /* and validate it against s->num_children */
909     ret = quorum_valid_threshold(s->threshold, s->num_children, &local_err);
910     if (ret < 0) {
911         goto exit;
912     }
913 
914     pattern_str = qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN);
915     if (!pattern_str) {
916         ret = QUORUM_READ_PATTERN_QUORUM;
917     } else {
918         ret = qapi_enum_parse(&QuorumReadPattern_lookup, pattern_str,
919                               -EINVAL, NULL);
920     }
921     if (ret < 0) {
922         error_setg(&local_err, "Please set read-pattern as fifo or quorum");
923         goto exit;
924     }
925     s->read_pattern = ret;
926 
927     if (s->read_pattern == QUORUM_READ_PATTERN_QUORUM) {
928         /* is the driver in blkverify mode */
929         if (qemu_opt_get_bool(opts, QUORUM_OPT_BLKVERIFY, false) &&
930             s->num_children == 2 && s->threshold == 2) {
931             s->is_blkverify = true;
932         } else if (qemu_opt_get_bool(opts, QUORUM_OPT_BLKVERIFY, false)) {
933             fprintf(stderr, "blkverify mode is set by setting blkverify=on "
934                     "and using two files with vote_threshold=2\n");
935         }
936 
937         s->rewrite_corrupted = qemu_opt_get_bool(opts, QUORUM_OPT_REWRITE,
938                                                  false);
939         if (s->rewrite_corrupted && s->is_blkverify) {
940             error_setg(&local_err,
941                        "rewrite-corrupted=on cannot be used with blkverify=on");
942             ret = -EINVAL;
943             goto exit;
944         }
945     }
946 
947     /* allocate the children array */
948     s->children = g_new0(BdrvChild *, s->num_children);
949     opened = g_new0(bool, s->num_children);
950 
951     for (i = 0; i < s->num_children; i++) {
952         char indexstr[32];
953         ret = snprintf(indexstr, 32, "children.%d", i);
954         assert(ret < 32);
955 
956         s->children[i] = bdrv_open_child(NULL, options, indexstr, bs,
957                                          &child_format, false, &local_err);
958         if (local_err) {
959             ret = -EINVAL;
960             goto close_exit;
961         }
962 
963         opened[i] = true;
964     }
965     s->next_child_index = s->num_children;
966 
967     bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
968 
969     g_free(opened);
970     goto exit;
971 
972 close_exit:
973     /* cleanup on error */
974     for (i = 0; i < s->num_children; i++) {
975         if (!opened[i]) {
976             continue;
977         }
978         bdrv_unref_child(bs, s->children[i]);
979     }
980     g_free(s->children);
981     g_free(opened);
982 exit:
983     qemu_opts_del(opts);
984     /* propagate error */
985     error_propagate(errp, local_err);
986     return ret;
987 }
988 
989 static void quorum_close(BlockDriverState *bs)
990 {
991     BDRVQuorumState *s = bs->opaque;
992     int i;
993 
994     for (i = 0; i < s->num_children; i++) {
995         bdrv_unref_child(bs, s->children[i]);
996     }
997 
998     g_free(s->children);
999 }
1000 
1001 static void quorum_add_child(BlockDriverState *bs, BlockDriverState *child_bs,
1002                              Error **errp)
1003 {
1004     BDRVQuorumState *s = bs->opaque;
1005     BdrvChild *child;
1006     char indexstr[32];
1007     int ret;
1008 
1009     assert(s->num_children <= INT_MAX / sizeof(BdrvChild *));
1010     if (s->num_children == INT_MAX / sizeof(BdrvChild *) ||
1011         s->next_child_index == UINT_MAX) {
1012         error_setg(errp, "Too many children");
1013         return;
1014     }
1015 
1016     ret = snprintf(indexstr, 32, "children.%u", s->next_child_index);
1017     if (ret < 0 || ret >= 32) {
1018         error_setg(errp, "cannot generate child name");
1019         return;
1020     }
1021     s->next_child_index++;
1022 
1023     bdrv_drained_begin(bs);
1024 
1025     /* We can safely add the child now */
1026     bdrv_ref(child_bs);
1027 
1028     child = bdrv_attach_child(bs, child_bs, indexstr, &child_format, errp);
1029     if (child == NULL) {
1030         s->next_child_index--;
1031         bdrv_unref(child_bs);
1032         goto out;
1033     }
1034     s->children = g_renew(BdrvChild *, s->children, s->num_children + 1);
1035     s->children[s->num_children++] = child;
1036 
1037 out:
1038     bdrv_drained_end(bs);
1039 }
1040 
1041 static void quorum_del_child(BlockDriverState *bs, BdrvChild *child,
1042                              Error **errp)
1043 {
1044     BDRVQuorumState *s = bs->opaque;
1045     int i;
1046 
1047     for (i = 0; i < s->num_children; i++) {
1048         if (s->children[i] == child) {
1049             break;
1050         }
1051     }
1052 
1053     /* we have checked it in bdrv_del_child() */
1054     assert(i < s->num_children);
1055 
1056     if (s->num_children <= s->threshold) {
1057         error_setg(errp,
1058             "The number of children cannot be lower than the vote threshold %d",
1059             s->threshold);
1060         return;
1061     }
1062 
1063     bdrv_drained_begin(bs);
1064 
1065     /* We can safely remove this child now */
1066     memmove(&s->children[i], &s->children[i + 1],
1067             (s->num_children - i - 1) * sizeof(BdrvChild *));
1068     s->children = g_renew(BdrvChild *, s->children, --s->num_children);
1069     bdrv_unref_child(bs, child);
1070 
1071     bdrv_drained_end(bs);
1072 }
1073 
1074 static void quorum_refresh_filename(BlockDriverState *bs, QDict *options)
1075 {
1076     BDRVQuorumState *s = bs->opaque;
1077     QDict *opts;
1078     QList *children;
1079     int i;
1080 
1081     for (i = 0; i < s->num_children; i++) {
1082         bdrv_refresh_filename(s->children[i]->bs);
1083         if (!s->children[i]->bs->full_open_options) {
1084             return;
1085         }
1086     }
1087 
1088     children = qlist_new();
1089     for (i = 0; i < s->num_children; i++) {
1090         qlist_append(children,
1091                      qobject_ref(s->children[i]->bs->full_open_options));
1092     }
1093 
1094     opts = qdict_new();
1095     qdict_put_str(opts, "driver", "quorum");
1096     qdict_put_int(opts, QUORUM_OPT_VOTE_THRESHOLD, s->threshold);
1097     qdict_put_bool(opts, QUORUM_OPT_BLKVERIFY, s->is_blkverify);
1098     qdict_put_bool(opts, QUORUM_OPT_REWRITE, s->rewrite_corrupted);
1099     qdict_put(opts, "children", children);
1100 
1101     bs->full_open_options = opts;
1102 }
1103 
1104 static BlockDriver bdrv_quorum = {
1105     .format_name                        = "quorum",
1106 
1107     .instance_size                      = sizeof(BDRVQuorumState),
1108 
1109     .bdrv_open                          = quorum_open,
1110     .bdrv_close                         = quorum_close,
1111     .bdrv_refresh_filename              = quorum_refresh_filename,
1112 
1113     .bdrv_co_flush_to_disk              = quorum_co_flush,
1114 
1115     .bdrv_getlength                     = quorum_getlength,
1116 
1117     .bdrv_co_preadv                     = quorum_co_preadv,
1118     .bdrv_co_pwritev                    = quorum_co_pwritev,
1119 
1120     .bdrv_add_child                     = quorum_add_child,
1121     .bdrv_del_child                     = quorum_del_child,
1122 
1123     .bdrv_child_perm                    = bdrv_filter_default_perms,
1124 
1125     .is_filter                          = true,
1126     .bdrv_recurse_is_first_non_filter   = quorum_recurse_is_first_non_filter,
1127 };
1128 
1129 static void bdrv_quorum_init(void)
1130 {
1131     if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA256)) {
1132         /* SHA256 hash support is required for quorum device */
1133         return;
1134     }
1135     bdrv_register(&bdrv_quorum);
1136 }
1137 
1138 block_init(bdrv_quorum_init);
1139