]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/ec.c
Update bcachefs sources to fad6d13aa5 fixup! bcachefs: Add persistent counters
[bcachefs-tools-debian] / libbcachefs / ec.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 /* erasure coding */
4
5 #include "bcachefs.h"
6 #include "alloc_foreground.h"
7 #include "bkey_buf.h"
8 #include "bset.h"
9 #include "btree_gc.h"
10 #include "btree_update.h"
11 #include "buckets.h"
12 #include "disk_groups.h"
13 #include "ec.h"
14 #include "error.h"
15 #include "io.h"
16 #include "keylist.h"
17 #include "recovery.h"
18 #include "replicas.h"
19 #include "super-io.h"
20 #include "util.h"
21
22 #include <linux/sort.h>
23
24 #ifdef __KERNEL__
25
26 #include <linux/raid/pq.h>
27 #include <linux/raid/xor.h>
28
29 static void raid5_recov(unsigned disks, unsigned failed_idx,
30                         size_t size, void **data)
31 {
32         unsigned i = 2, nr;
33
34         BUG_ON(failed_idx >= disks);
35
36         swap(data[0], data[failed_idx]);
37         memcpy(data[0], data[1], size);
38
39         while (i < disks) {
40                 nr = min_t(unsigned, disks - i, MAX_XOR_BLOCKS);
41                 xor_blocks(nr, size, data[0], data + i);
42                 i += nr;
43         }
44
45         swap(data[0], data[failed_idx]);
46 }
47
48 static void raid_gen(int nd, int np, size_t size, void **v)
49 {
50         if (np >= 1)
51                 raid5_recov(nd + np, nd, size, v);
52         if (np >= 2)
53                 raid6_call.gen_syndrome(nd + np, size, v);
54         BUG_ON(np > 2);
55 }
56
57 static void raid_rec(int nr, int *ir, int nd, int np, size_t size, void **v)
58 {
59         switch (nr) {
60         case 0:
61                 break;
62         case 1:
63                 if (ir[0] < nd + 1)
64                         raid5_recov(nd + 1, ir[0], size, v);
65                 else
66                         raid6_call.gen_syndrome(nd + np, size, v);
67                 break;
68         case 2:
69                 if (ir[1] < nd) {
70                         /* data+data failure. */
71                         raid6_2data_recov(nd + np, size, ir[0], ir[1], v);
72                 } else if (ir[0] < nd) {
73                         /* data + p/q failure */
74
75                         if (ir[1] == nd) /* data + p failure */
76                                 raid6_datap_recov(nd + np, size, ir[0], v);
77                         else { /* data + q failure */
78                                 raid5_recov(nd + 1, ir[0], size, v);
79                                 raid6_call.gen_syndrome(nd + np, size, v);
80                         }
81                 } else {
82                         raid_gen(nd, np, size, v);
83                 }
84                 break;
85         default:
86                 BUG();
87         }
88 }
89
90 #else
91
92 #include <raid/raid.h>
93
94 #endif
95
96 struct ec_bio {
97         struct bch_dev          *ca;
98         struct ec_stripe_buf    *buf;
99         size_t                  idx;
100         struct bio              bio;
101 };
102
103 /* Stripes btree keys: */
104
105 int bch2_stripe_invalid(const struct bch_fs *c, struct bkey_s_c k,
106                         int rw, struct printbuf *err)
107 {
108         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
109
110         if (!bkey_cmp(k.k->p, POS_MIN)) {
111                 pr_buf(err, "stripe at POS_MIN");
112                 return -EINVAL;
113         }
114
115         if (k.k->p.inode) {
116                 pr_buf(err, "nonzero inode field");
117                 return -EINVAL;
118         }
119
120         if (bkey_val_bytes(k.k) < sizeof(*s)) {
121                 pr_buf(err, "incorrect value size (%zu < %zu)",
122                        bkey_val_bytes(k.k), sizeof(*s));
123                 return -EINVAL;
124         }
125
126         if (bkey_val_u64s(k.k) < stripe_val_u64s(s)) {
127                 pr_buf(err, "incorrect value size (%zu < %u)",
128                        bkey_val_u64s(k.k), stripe_val_u64s(s));
129                 return -EINVAL;
130         }
131
132         return bch2_bkey_ptrs_invalid(c, k, rw, err);
133 }
134
135 void bch2_stripe_to_text(struct printbuf *out, struct bch_fs *c,
136                          struct bkey_s_c k)
137 {
138         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
139         unsigned i;
140
141         pr_buf(out, "algo %u sectors %u blocks %u:%u csum %u gran %u",
142                s->algorithm,
143                le16_to_cpu(s->sectors),
144                s->nr_blocks - s->nr_redundant,
145                s->nr_redundant,
146                s->csum_type,
147                1U << s->csum_granularity_bits);
148
149         for (i = 0; i < s->nr_blocks; i++)
150                 pr_buf(out, " %u:%llu:%u", s->ptrs[i].dev,
151                        (u64) s->ptrs[i].offset,
152                        stripe_blockcount_get(s, i));
153 }
154
155 /* returns blocknr in stripe that we matched: */
156 static const struct bch_extent_ptr *bkey_matches_stripe(struct bch_stripe *s,
157                                                 struct bkey_s_c k, unsigned *block)
158 {
159         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
160         const struct bch_extent_ptr *ptr;
161         unsigned i, nr_data = s->nr_blocks - s->nr_redundant;
162
163         bkey_for_each_ptr(ptrs, ptr)
164                 for (i = 0; i < nr_data; i++)
165                         if (__bch2_ptr_matches_stripe(&s->ptrs[i], ptr,
166                                                       le16_to_cpu(s->sectors))) {
167                                 *block = i;
168                                 return ptr;
169                         }
170
171         return NULL;
172 }
173
174 static bool extent_has_stripe_ptr(struct bkey_s_c k, u64 idx)
175 {
176         switch (k.k->type) {
177         case KEY_TYPE_extent: {
178                 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
179                 const union bch_extent_entry *entry;
180
181                 extent_for_each_entry(e, entry)
182                         if (extent_entry_type(entry) ==
183                             BCH_EXTENT_ENTRY_stripe_ptr &&
184                             entry->stripe_ptr.idx == idx)
185                                 return true;
186
187                 break;
188         }
189         }
190
191         return false;
192 }
193
194 /* Stripe bufs: */
195
196 static void ec_stripe_buf_exit(struct ec_stripe_buf *buf)
197 {
198         unsigned i;
199
200         for (i = 0; i < buf->key.v.nr_blocks; i++) {
201                 kvpfree(buf->data[i], buf->size << 9);
202                 buf->data[i] = NULL;
203         }
204 }
205
206 static int ec_stripe_buf_init(struct ec_stripe_buf *buf,
207                                unsigned offset, unsigned size)
208 {
209         struct bch_stripe *v = &buf->key.v;
210         unsigned csum_granularity = 1U << v->csum_granularity_bits;
211         unsigned end = offset + size;
212         unsigned i;
213
214         BUG_ON(end > le16_to_cpu(v->sectors));
215
216         offset  = round_down(offset, csum_granularity);
217         end     = min_t(unsigned, le16_to_cpu(v->sectors),
218                         round_up(end, csum_granularity));
219
220         buf->offset     = offset;
221         buf->size       = end - offset;
222
223         memset(buf->valid, 0xFF, sizeof(buf->valid));
224
225         for (i = 0; i < buf->key.v.nr_blocks; i++) {
226                 buf->data[i] = kvpmalloc(buf->size << 9, GFP_KERNEL);
227                 if (!buf->data[i])
228                         goto err;
229         }
230
231         return 0;
232 err:
233         ec_stripe_buf_exit(buf);
234         return -ENOMEM;
235 }
236
237 /* Checksumming: */
238
239 static struct bch_csum ec_block_checksum(struct ec_stripe_buf *buf,
240                                          unsigned block, unsigned offset)
241 {
242         struct bch_stripe *v = &buf->key.v;
243         unsigned csum_granularity = 1 << v->csum_granularity_bits;
244         unsigned end = buf->offset + buf->size;
245         unsigned len = min(csum_granularity, end - offset);
246
247         BUG_ON(offset >= end);
248         BUG_ON(offset <  buf->offset);
249         BUG_ON(offset & (csum_granularity - 1));
250         BUG_ON(offset + len != le16_to_cpu(v->sectors) &&
251                (len & (csum_granularity - 1)));
252
253         return bch2_checksum(NULL, v->csum_type,
254                              null_nonce(),
255                              buf->data[block] + ((offset - buf->offset) << 9),
256                              len << 9);
257 }
258
259 static void ec_generate_checksums(struct ec_stripe_buf *buf)
260 {
261         struct bch_stripe *v = &buf->key.v;
262         unsigned i, j, csums_per_device = stripe_csums_per_device(v);
263
264         if (!v->csum_type)
265                 return;
266
267         BUG_ON(buf->offset);
268         BUG_ON(buf->size != le16_to_cpu(v->sectors));
269
270         for (i = 0; i < v->nr_blocks; i++)
271                 for (j = 0; j < csums_per_device; j++)
272                         stripe_csum_set(v, i, j,
273                                 ec_block_checksum(buf, i, j << v->csum_granularity_bits));
274 }
275
276 static void ec_validate_checksums(struct bch_fs *c, struct ec_stripe_buf *buf)
277 {
278         struct bch_stripe *v = &buf->key.v;
279         unsigned csum_granularity = 1 << v->csum_granularity_bits;
280         unsigned i;
281
282         if (!v->csum_type)
283                 return;
284
285         for (i = 0; i < v->nr_blocks; i++) {
286                 unsigned offset = buf->offset;
287                 unsigned end = buf->offset + buf->size;
288
289                 if (!test_bit(i, buf->valid))
290                         continue;
291
292                 while (offset < end) {
293                         unsigned j = offset >> v->csum_granularity_bits;
294                         unsigned len = min(csum_granularity, end - offset);
295                         struct bch_csum want = stripe_csum_get(v, i, j);
296                         struct bch_csum got = ec_block_checksum(buf, i, offset);
297
298                         if (bch2_crc_cmp(want, got)) {
299                                 struct printbuf buf2 = PRINTBUF;
300
301                                 bch2_bkey_val_to_text(&buf2, c, bkey_i_to_s_c(&buf->key.k_i));
302
303                                 bch_err_ratelimited(c,
304                                         "stripe checksum error for %ps at %u:%u: csum type %u, expected %llx got %llx\n%s",
305                                         (void *) _RET_IP_, i, j, v->csum_type,
306                                         want.lo, got.lo, buf2.buf);
307                                 printbuf_exit(&buf2);
308                                 clear_bit(i, buf->valid);
309                                 break;
310                         }
311
312                         offset += len;
313                 }
314         }
315 }
316
317 /* Erasure coding: */
318
319 static void ec_generate_ec(struct ec_stripe_buf *buf)
320 {
321         struct bch_stripe *v = &buf->key.v;
322         unsigned nr_data = v->nr_blocks - v->nr_redundant;
323         unsigned bytes = le16_to_cpu(v->sectors) << 9;
324
325         raid_gen(nr_data, v->nr_redundant, bytes, buf->data);
326 }
327
328 static unsigned ec_nr_failed(struct ec_stripe_buf *buf)
329 {
330         return buf->key.v.nr_blocks -
331                 bitmap_weight(buf->valid, buf->key.v.nr_blocks);
332 }
333
334 static int ec_do_recov(struct bch_fs *c, struct ec_stripe_buf *buf)
335 {
336         struct bch_stripe *v = &buf->key.v;
337         unsigned i, failed[BCH_BKEY_PTRS_MAX], nr_failed = 0;
338         unsigned nr_data = v->nr_blocks - v->nr_redundant;
339         unsigned bytes = buf->size << 9;
340
341         if (ec_nr_failed(buf) > v->nr_redundant) {
342                 bch_err_ratelimited(c,
343                         "error doing reconstruct read: unable to read enough blocks");
344                 return -1;
345         }
346
347         for (i = 0; i < nr_data; i++)
348                 if (!test_bit(i, buf->valid))
349                         failed[nr_failed++] = i;
350
351         raid_rec(nr_failed, failed, nr_data, v->nr_redundant, bytes, buf->data);
352         return 0;
353 }
354
355 /* IO: */
356
357 static void ec_block_endio(struct bio *bio)
358 {
359         struct ec_bio *ec_bio = container_of(bio, struct ec_bio, bio);
360         struct bch_stripe *v = &ec_bio->buf->key.v;
361         struct bch_extent_ptr *ptr = &v->ptrs[ec_bio->idx];
362         struct bch_dev *ca = ec_bio->ca;
363         struct closure *cl = bio->bi_private;
364
365         if (bch2_dev_io_err_on(bio->bi_status, ca, "erasure coding %s error: %s",
366                                bio_data_dir(bio) ? "write" : "read",
367                                bch2_blk_status_to_str(bio->bi_status)))
368                 clear_bit(ec_bio->idx, ec_bio->buf->valid);
369
370         if (ptr_stale(ca, ptr)) {
371                 bch_err_ratelimited(ca->fs,
372                                     "error %s stripe: stale pointer after io",
373                                     bio_data_dir(bio) == READ ? "reading from" : "writing to");
374                 clear_bit(ec_bio->idx, ec_bio->buf->valid);
375         }
376
377         bio_put(&ec_bio->bio);
378         percpu_ref_put(&ca->io_ref);
379         closure_put(cl);
380 }
381
382 static void ec_block_io(struct bch_fs *c, struct ec_stripe_buf *buf,
383                         unsigned rw, unsigned idx, struct closure *cl)
384 {
385         struct bch_stripe *v = &buf->key.v;
386         unsigned offset = 0, bytes = buf->size << 9;
387         struct bch_extent_ptr *ptr = &v->ptrs[idx];
388         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
389         enum bch_data_type data_type = idx < buf->key.v.nr_blocks - buf->key.v.nr_redundant
390                 ? BCH_DATA_user
391                 : BCH_DATA_parity;
392
393         if (ptr_stale(ca, ptr)) {
394                 bch_err_ratelimited(c,
395                                     "error %s stripe: stale pointer",
396                                     rw == READ ? "reading from" : "writing to");
397                 clear_bit(idx, buf->valid);
398                 return;
399         }
400
401         if (!bch2_dev_get_ioref(ca, rw)) {
402                 clear_bit(idx, buf->valid);
403                 return;
404         }
405
406         this_cpu_add(ca->io_done->sectors[rw][data_type], buf->size);
407
408         while (offset < bytes) {
409                 unsigned nr_iovecs = min_t(size_t, BIO_MAX_VECS,
410                                            DIV_ROUND_UP(bytes, PAGE_SIZE));
411                 unsigned b = min_t(size_t, bytes - offset,
412                                    nr_iovecs << PAGE_SHIFT);
413                 struct ec_bio *ec_bio;
414
415                 ec_bio = container_of(bio_alloc_bioset(ca->disk_sb.bdev,
416                                                        nr_iovecs,
417                                                        rw,
418                                                        GFP_KERNEL,
419                                                        &c->ec_bioset),
420                                       struct ec_bio, bio);
421
422                 ec_bio->ca                      = ca;
423                 ec_bio->buf                     = buf;
424                 ec_bio->idx                     = idx;
425
426                 ec_bio->bio.bi_iter.bi_sector   = ptr->offset + buf->offset + (offset >> 9);
427                 ec_bio->bio.bi_end_io           = ec_block_endio;
428                 ec_bio->bio.bi_private          = cl;
429
430                 bch2_bio_map(&ec_bio->bio, buf->data[idx] + offset, b);
431
432                 closure_get(cl);
433                 percpu_ref_get(&ca->io_ref);
434
435                 submit_bio(&ec_bio->bio);
436
437                 offset += b;
438         }
439
440         percpu_ref_put(&ca->io_ref);
441 }
442
443 static int get_stripe_key(struct bch_fs *c, u64 idx, struct ec_stripe_buf *stripe)
444 {
445         struct btree_trans trans;
446         struct btree_iter iter;
447         struct bkey_s_c k;
448         int ret;
449
450         bch2_trans_init(&trans, c, 0, 0);
451         bch2_trans_iter_init(&trans, &iter, BTREE_ID_stripes,
452                              POS(0, idx), BTREE_ITER_SLOTS);
453         k = bch2_btree_iter_peek_slot(&iter);
454         ret = bkey_err(k);
455         if (ret)
456                 goto err;
457         if (k.k->type != KEY_TYPE_stripe) {
458                 ret = -ENOENT;
459                 goto err;
460         }
461         bkey_reassemble(&stripe->key.k_i, k);
462 err:
463         bch2_trans_iter_exit(&trans, &iter);
464         bch2_trans_exit(&trans);
465         return ret;
466 }
467
468 /* recovery read path: */
469 int bch2_ec_read_extent(struct bch_fs *c, struct bch_read_bio *rbio)
470 {
471         struct ec_stripe_buf *buf;
472         struct closure cl;
473         struct bch_stripe *v;
474         unsigned i, offset;
475         int ret = 0;
476
477         closure_init_stack(&cl);
478
479         BUG_ON(!rbio->pick.has_ec);
480
481         buf = kzalloc(sizeof(*buf), GFP_NOIO);
482         if (!buf)
483                 return -ENOMEM;
484
485         ret = get_stripe_key(c, rbio->pick.ec.idx, buf);
486         if (ret) {
487                 bch_err_ratelimited(c,
488                         "error doing reconstruct read: error %i looking up stripe", ret);
489                 kfree(buf);
490                 return -EIO;
491         }
492
493         v = &buf->key.v;
494
495         if (!bch2_ptr_matches_stripe(v, rbio->pick)) {
496                 bch_err_ratelimited(c,
497                         "error doing reconstruct read: pointer doesn't match stripe");
498                 ret = -EIO;
499                 goto err;
500         }
501
502         offset = rbio->bio.bi_iter.bi_sector - v->ptrs[rbio->pick.ec.block].offset;
503         if (offset + bio_sectors(&rbio->bio) > le16_to_cpu(v->sectors)) {
504                 bch_err_ratelimited(c,
505                         "error doing reconstruct read: read is bigger than stripe");
506                 ret = -EIO;
507                 goto err;
508         }
509
510         ret = ec_stripe_buf_init(buf, offset, bio_sectors(&rbio->bio));
511         if (ret)
512                 goto err;
513
514         for (i = 0; i < v->nr_blocks; i++)
515                 ec_block_io(c, buf, REQ_OP_READ, i, &cl);
516
517         closure_sync(&cl);
518
519         if (ec_nr_failed(buf) > v->nr_redundant) {
520                 bch_err_ratelimited(c,
521                         "error doing reconstruct read: unable to read enough blocks");
522                 ret = -EIO;
523                 goto err;
524         }
525
526         ec_validate_checksums(c, buf);
527
528         ret = ec_do_recov(c, buf);
529         if (ret)
530                 goto err;
531
532         memcpy_to_bio(&rbio->bio, rbio->bio.bi_iter,
533                       buf->data[rbio->pick.ec.block] + ((offset - buf->offset) << 9));
534 err:
535         ec_stripe_buf_exit(buf);
536         kfree(buf);
537         return ret;
538 }
539
540 /* stripe bucket accounting: */
541
542 static int __ec_stripe_mem_alloc(struct bch_fs *c, size_t idx, gfp_t gfp)
543 {
544         ec_stripes_heap n, *h = &c->ec_stripes_heap;
545
546         if (idx >= h->size) {
547                 if (!init_heap(&n, max(1024UL, roundup_pow_of_two(idx + 1)), gfp))
548                         return -ENOMEM;
549
550                 spin_lock(&c->ec_stripes_heap_lock);
551                 if (n.size > h->size) {
552                         memcpy(n.data, h->data, h->used * sizeof(h->data[0]));
553                         n.used = h->used;
554                         swap(*h, n);
555                 }
556                 spin_unlock(&c->ec_stripes_heap_lock);
557
558                 free_heap(&n);
559         }
560
561         if (!genradix_ptr_alloc(&c->stripes, idx, gfp))
562                 return -ENOMEM;
563
564         if (c->gc_pos.phase != GC_PHASE_NOT_RUNNING &&
565             !genradix_ptr_alloc(&c->gc_stripes, idx, gfp))
566                 return -ENOMEM;
567
568         return 0;
569 }
570
571 static int ec_stripe_mem_alloc(struct btree_trans *trans,
572                                struct btree_iter *iter)
573 {
574         size_t idx = iter->pos.offset;
575         int ret = 0;
576
577         if (!__ec_stripe_mem_alloc(trans->c, idx, GFP_NOWAIT|__GFP_NOWARN))
578                 return ret;
579
580         bch2_trans_unlock(trans);
581         ret = -EINTR;
582
583         if (!__ec_stripe_mem_alloc(trans->c, idx, GFP_KERNEL))
584                 return ret;
585
586         return -ENOMEM;
587 }
588
589 static ssize_t stripe_idx_to_delete(struct bch_fs *c)
590 {
591         ec_stripes_heap *h = &c->ec_stripes_heap;
592
593         return h->used && h->data[0].blocks_nonempty == 0
594                 ? h->data[0].idx : -1;
595 }
596
597 static inline int ec_stripes_heap_cmp(ec_stripes_heap *h,
598                                       struct ec_stripe_heap_entry l,
599                                       struct ec_stripe_heap_entry r)
600 {
601         return ((l.blocks_nonempty > r.blocks_nonempty) -
602                 (l.blocks_nonempty < r.blocks_nonempty));
603 }
604
605 static inline void ec_stripes_heap_set_backpointer(ec_stripes_heap *h,
606                                                    size_t i)
607 {
608         struct bch_fs *c = container_of(h, struct bch_fs, ec_stripes_heap);
609
610         genradix_ptr(&c->stripes, h->data[i].idx)->heap_idx = i;
611 }
612
613 static void heap_verify_backpointer(struct bch_fs *c, size_t idx)
614 {
615         ec_stripes_heap *h = &c->ec_stripes_heap;
616         struct stripe *m = genradix_ptr(&c->stripes, idx);
617
618         BUG_ON(!m->alive);
619         BUG_ON(m->heap_idx >= h->used);
620         BUG_ON(h->data[m->heap_idx].idx != idx);
621 }
622
623 void bch2_stripes_heap_del(struct bch_fs *c,
624                            struct stripe *m, size_t idx)
625 {
626         if (!m->on_heap)
627                 return;
628
629         m->on_heap = false;
630
631         heap_verify_backpointer(c, idx);
632
633         heap_del(&c->ec_stripes_heap, m->heap_idx,
634                  ec_stripes_heap_cmp,
635                  ec_stripes_heap_set_backpointer);
636 }
637
638 void bch2_stripes_heap_insert(struct bch_fs *c,
639                               struct stripe *m, size_t idx)
640 {
641         if (m->on_heap)
642                 return;
643
644         BUG_ON(heap_full(&c->ec_stripes_heap));
645
646         m->on_heap = true;
647
648         heap_add(&c->ec_stripes_heap, ((struct ec_stripe_heap_entry) {
649                         .idx = idx,
650                         .blocks_nonempty = m->blocks_nonempty,
651                 }),
652                  ec_stripes_heap_cmp,
653                  ec_stripes_heap_set_backpointer);
654
655         heap_verify_backpointer(c, idx);
656 }
657
658 void bch2_stripes_heap_update(struct bch_fs *c,
659                               struct stripe *m, size_t idx)
660 {
661         ec_stripes_heap *h = &c->ec_stripes_heap;
662         size_t i;
663
664         if (!m->on_heap)
665                 return;
666
667         heap_verify_backpointer(c, idx);
668
669         h->data[m->heap_idx].blocks_nonempty = m->blocks_nonempty;
670
671         i = m->heap_idx;
672         heap_sift_up(h,   i, ec_stripes_heap_cmp,
673                      ec_stripes_heap_set_backpointer);
674         heap_sift_down(h, i, ec_stripes_heap_cmp,
675                        ec_stripes_heap_set_backpointer);
676
677         heap_verify_backpointer(c, idx);
678
679         if (stripe_idx_to_delete(c) >= 0 &&
680             !percpu_ref_is_dying(&c->writes))
681                 schedule_work(&c->ec_stripe_delete_work);
682 }
683
684 /* stripe deletion */
685
686 static int ec_stripe_delete(struct bch_fs *c, size_t idx)
687 {
688         return bch2_btree_delete_range(c, BTREE_ID_stripes,
689                                        POS(0, idx),
690                                        POS(0, idx + 1),
691                                        0, NULL);
692 }
693
694 static void ec_stripe_delete_work(struct work_struct *work)
695 {
696         struct bch_fs *c =
697                 container_of(work, struct bch_fs, ec_stripe_delete_work);
698         ssize_t idx;
699
700         while (1) {
701                 spin_lock(&c->ec_stripes_heap_lock);
702                 idx = stripe_idx_to_delete(c);
703                 if (idx < 0) {
704                         spin_unlock(&c->ec_stripes_heap_lock);
705                         break;
706                 }
707
708                 bch2_stripes_heap_del(c, genradix_ptr(&c->stripes, idx), idx);
709                 spin_unlock(&c->ec_stripes_heap_lock);
710
711                 if (ec_stripe_delete(c, idx))
712                         break;
713         }
714 }
715
716 /* stripe creation: */
717
718 static int ec_stripe_bkey_insert(struct btree_trans *trans,
719                                  struct bkey_i_stripe *stripe,
720                                  struct disk_reservation *res)
721 {
722         struct bch_fs *c = trans->c;
723         struct btree_iter iter;
724         struct bkey_s_c k;
725         struct bpos min_pos = POS(0, 1);
726         struct bpos start_pos = bpos_max(min_pos, POS(0, c->ec_stripe_hint));
727         int ret;
728
729         for_each_btree_key(trans, iter, BTREE_ID_stripes, start_pos,
730                            BTREE_ITER_SLOTS|BTREE_ITER_INTENT, k, ret) {
731                 if (bkey_cmp(k.k->p, POS(0, U32_MAX)) > 0) {
732                         if (start_pos.offset) {
733                                 start_pos = min_pos;
734                                 bch2_btree_iter_set_pos(&iter, start_pos);
735                                 continue;
736                         }
737
738                         ret = -ENOSPC;
739                         break;
740                 }
741
742                 if (bkey_deleted(k.k))
743                         goto found_slot;
744         }
745
746         goto err;
747 found_slot:
748         start_pos = iter.pos;
749
750         ret = ec_stripe_mem_alloc(trans, &iter);
751         if (ret)
752                 goto err;
753
754         stripe->k.p = iter.pos;
755
756         ret = bch2_trans_update(trans, &iter, &stripe->k_i, 0);
757
758         c->ec_stripe_hint = start_pos.offset;
759 err:
760         bch2_trans_iter_exit(trans, &iter);
761
762         return ret;
763 }
764
765 static int ec_stripe_bkey_update(struct btree_trans *trans,
766                                  struct bkey_i_stripe *new,
767                                  struct disk_reservation *res)
768 {
769         struct btree_iter iter;
770         struct bkey_s_c k;
771         const struct bch_stripe *existing;
772         unsigned i;
773         int ret;
774
775         bch2_trans_iter_init(trans, &iter, BTREE_ID_stripes,
776                              new->k.p, BTREE_ITER_INTENT);
777         k = bch2_btree_iter_peek_slot(&iter);
778         ret = bkey_err(k);
779         if (ret)
780                 goto err;
781
782         if (!k.k || k.k->type != KEY_TYPE_stripe) {
783                 bch_err(trans->c, "error updating stripe: not found");
784                 ret = -ENOENT;
785                 goto err;
786         }
787
788         existing = bkey_s_c_to_stripe(k).v;
789
790         if (existing->nr_blocks != new->v.nr_blocks) {
791                 bch_err(trans->c, "error updating stripe: nr_blocks does not match");
792                 ret = -EINVAL;
793                 goto err;
794         }
795
796         for (i = 0; i < new->v.nr_blocks; i++)
797                 stripe_blockcount_set(&new->v, i,
798                         stripe_blockcount_get(existing, i));
799
800         ret = bch2_trans_update(trans, &iter, &new->k_i, 0);
801 err:
802         bch2_trans_iter_exit(trans, &iter);
803         return ret;
804 }
805
806 static void extent_stripe_ptr_add(struct bkey_s_extent e,
807                                   struct ec_stripe_buf *s,
808                                   struct bch_extent_ptr *ptr,
809                                   unsigned block)
810 {
811         struct bch_extent_stripe_ptr *dst = (void *) ptr;
812         union bch_extent_entry *end = extent_entry_last(e);
813
814         memmove_u64s_up(dst + 1, dst, (u64 *) end - (u64 *) dst);
815         e.k->u64s += sizeof(*dst) / sizeof(u64);
816
817         *dst = (struct bch_extent_stripe_ptr) {
818                 .type = 1 << BCH_EXTENT_ENTRY_stripe_ptr,
819                 .block          = block,
820                 .redundancy     = s->key.v.nr_redundant,
821                 .idx            = s->key.k.p.offset,
822         };
823 }
824
825 static int ec_stripe_update_ptrs(struct bch_fs *c,
826                                  struct ec_stripe_buf *s,
827                                  struct bkey *pos)
828 {
829         struct btree_trans trans;
830         struct btree_iter iter;
831         struct bkey_s_c k;
832         struct bkey_s_extent e;
833         struct bkey_buf sk;
834         struct bpos next_pos;
835         int ret = 0, dev, block;
836
837         bch2_bkey_buf_init(&sk);
838         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
839
840         /* XXX this doesn't support the reflink btree */
841
842         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
843                              bkey_start_pos(pos),
844                              BTREE_ITER_INTENT);
845 retry:
846         while (bch2_trans_begin(&trans),
847                (k = bch2_btree_iter_peek(&iter)).k &&
848                !(ret = bkey_err(k)) &&
849                bkey_cmp(bkey_start_pos(k.k), pos->p) < 0) {
850                 const struct bch_extent_ptr *ptr_c;
851                 struct bch_extent_ptr *ptr, *ec_ptr = NULL;
852
853                 if (extent_has_stripe_ptr(k, s->key.k.p.offset)) {
854                         bch2_btree_iter_advance(&iter);
855                         continue;
856                 }
857
858                 ptr_c = bkey_matches_stripe(&s->key.v, k, &block);
859                 /*
860                  * It doesn't generally make sense to erasure code cached ptrs:
861                  * XXX: should we be incrementing a counter?
862                  */
863                 if (!ptr_c || ptr_c->cached) {
864                         bch2_btree_iter_advance(&iter);
865                         continue;
866                 }
867
868                 dev = s->key.v.ptrs[block].dev;
869
870                 bch2_bkey_buf_reassemble(&sk, c, k);
871                 e = bkey_i_to_s_extent(sk.k);
872
873                 bch2_bkey_drop_ptrs(e.s, ptr, ptr->dev != dev);
874                 ec_ptr = (void *) bch2_bkey_has_device(e.s_c, dev);
875                 BUG_ON(!ec_ptr);
876
877                 extent_stripe_ptr_add(e, s, ec_ptr, block);
878
879                 bch2_btree_iter_set_pos(&iter, bkey_start_pos(&sk.k->k));
880                 next_pos = sk.k->k.p;
881
882                 ret   = bch2_btree_iter_traverse(&iter) ?:
883                         bch2_trans_update(&trans, &iter, sk.k, 0) ?:
884                         bch2_trans_commit(&trans, NULL, NULL,
885                                         BTREE_INSERT_NOFAIL);
886                 if (!ret)
887                         bch2_btree_iter_set_pos(&iter, next_pos);
888                 if (ret)
889                         break;
890         }
891         if (ret == -EINTR)
892                 goto retry;
893         bch2_trans_iter_exit(&trans, &iter);
894
895         bch2_trans_exit(&trans);
896         bch2_bkey_buf_exit(&sk, c);
897
898         return ret;
899 }
900
901 /*
902  * data buckets of new stripe all written: create the stripe
903  */
904 static void ec_stripe_create(struct ec_stripe_new *s)
905 {
906         struct bch_fs *c = s->c;
907         struct open_bucket *ob;
908         struct bkey_i *k;
909         struct stripe *m;
910         struct bch_stripe *v = &s->new_stripe.key.v;
911         unsigned i, nr_data = v->nr_blocks - v->nr_redundant;
912         int ret;
913
914         BUG_ON(s->h->s == s);
915
916         closure_sync(&s->iodone);
917
918         if (s->err) {
919                 if (s->err != -EROFS)
920                         bch_err(c, "error creating stripe: error writing data buckets");
921                 goto err;
922         }
923
924         if (s->have_existing_stripe) {
925                 ec_validate_checksums(c, &s->existing_stripe);
926
927                 if (ec_do_recov(c, &s->existing_stripe)) {
928                         bch_err(c, "error creating stripe: error reading existing stripe");
929                         goto err;
930                 }
931
932                 for (i = 0; i < nr_data; i++)
933                         if (stripe_blockcount_get(&s->existing_stripe.key.v, i))
934                                 swap(s->new_stripe.data[i],
935                                      s->existing_stripe.data[i]);
936
937                 ec_stripe_buf_exit(&s->existing_stripe);
938         }
939
940         BUG_ON(!s->allocated);
941
942         if (!percpu_ref_tryget(&c->writes))
943                 goto err;
944
945         ec_generate_ec(&s->new_stripe);
946
947         ec_generate_checksums(&s->new_stripe);
948
949         /* write p/q: */
950         for (i = nr_data; i < v->nr_blocks; i++)
951                 ec_block_io(c, &s->new_stripe, REQ_OP_WRITE, i, &s->iodone);
952         closure_sync(&s->iodone);
953
954         if (ec_nr_failed(&s->new_stripe)) {
955                 bch_err(c, "error creating stripe: error writing redundancy buckets");
956                 goto err_put_writes;
957         }
958
959         ret = bch2_trans_do(c, &s->res, NULL, BTREE_INSERT_NOFAIL,
960                             s->have_existing_stripe
961                             ? ec_stripe_bkey_update(&trans, &s->new_stripe.key, &s->res)
962                             : ec_stripe_bkey_insert(&trans, &s->new_stripe.key, &s->res));
963         if (ret) {
964                 bch_err(c, "error creating stripe: error creating stripe key");
965                 goto err_put_writes;
966         }
967
968         for_each_keylist_key(&s->keys, k) {
969                 ret = ec_stripe_update_ptrs(c, &s->new_stripe, &k->k);
970                 if (ret) {
971                         bch_err(c, "error creating stripe: error %i updating pointers", ret);
972                         break;
973                 }
974         }
975
976         spin_lock(&c->ec_stripes_heap_lock);
977         m = genradix_ptr(&c->stripes, s->new_stripe.key.k.p.offset);
978
979         BUG_ON(m->on_heap);
980         bch2_stripes_heap_insert(c, m, s->new_stripe.key.k.p.offset);
981         spin_unlock(&c->ec_stripes_heap_lock);
982 err_put_writes:
983         percpu_ref_put(&c->writes);
984 err:
985         bch2_disk_reservation_put(c, &s->res);
986
987         for (i = 0; i < v->nr_blocks; i++)
988                 if (s->blocks[i]) {
989                         ob = c->open_buckets + s->blocks[i];
990
991                         if (i < nr_data) {
992                                 ob->ec = NULL;
993                                 __bch2_open_bucket_put(c, ob);
994                         } else {
995                                 bch2_open_bucket_put(c, ob);
996                         }
997                 }
998
999         bch2_keylist_free(&s->keys, s->inline_keys);
1000
1001         ec_stripe_buf_exit(&s->existing_stripe);
1002         ec_stripe_buf_exit(&s->new_stripe);
1003         closure_debug_destroy(&s->iodone);
1004         kfree(s);
1005 }
1006
1007 static void ec_stripe_create_work(struct work_struct *work)
1008 {
1009         struct bch_fs *c = container_of(work,
1010                 struct bch_fs, ec_stripe_create_work);
1011         struct ec_stripe_new *s, *n;
1012 restart:
1013         mutex_lock(&c->ec_stripe_new_lock);
1014         list_for_each_entry_safe(s, n, &c->ec_stripe_new_list, list)
1015                 if (!atomic_read(&s->pin)) {
1016                         list_del(&s->list);
1017                         mutex_unlock(&c->ec_stripe_new_lock);
1018                         ec_stripe_create(s);
1019                         goto restart;
1020                 }
1021         mutex_unlock(&c->ec_stripe_new_lock);
1022 }
1023
1024 static void ec_stripe_new_put(struct bch_fs *c, struct ec_stripe_new *s)
1025 {
1026         BUG_ON(atomic_read(&s->pin) <= 0);
1027
1028         if (atomic_dec_and_test(&s->pin)) {
1029                 BUG_ON(!s->pending);
1030                 queue_work(system_long_wq, &c->ec_stripe_create_work);
1031         }
1032 }
1033
1034 static void ec_stripe_set_pending(struct bch_fs *c, struct ec_stripe_head *h)
1035 {
1036         struct ec_stripe_new *s = h->s;
1037
1038         BUG_ON(!s->allocated && !s->err);
1039
1040         h->s            = NULL;
1041         s->pending      = true;
1042
1043         mutex_lock(&c->ec_stripe_new_lock);
1044         list_add(&s->list, &c->ec_stripe_new_list);
1045         mutex_unlock(&c->ec_stripe_new_lock);
1046
1047         ec_stripe_new_put(c, s);
1048 }
1049
1050 /* have a full bucket - hand it off to be erasure coded: */
1051 void bch2_ec_bucket_written(struct bch_fs *c, struct open_bucket *ob)
1052 {
1053         struct ec_stripe_new *s = ob->ec;
1054
1055         if (ob->sectors_free)
1056                 s->err = -1;
1057
1058         ec_stripe_new_put(c, s);
1059 }
1060
1061 void bch2_ec_bucket_cancel(struct bch_fs *c, struct open_bucket *ob)
1062 {
1063         struct ec_stripe_new *s = ob->ec;
1064
1065         s->err = -EIO;
1066 }
1067
1068 void *bch2_writepoint_ec_buf(struct bch_fs *c, struct write_point *wp)
1069 {
1070         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
1071         struct bch_dev *ca;
1072         unsigned offset;
1073
1074         if (!ob)
1075                 return NULL;
1076
1077         ca      = bch_dev_bkey_exists(c, ob->dev);
1078         offset  = ca->mi.bucket_size - ob->sectors_free;
1079
1080         return ob->ec->new_stripe.data[ob->ec_idx] + (offset << 9);
1081 }
1082
1083 void bch2_ob_add_backpointer(struct bch_fs *c, struct open_bucket *ob,
1084                              struct bkey *k)
1085 {
1086         struct ec_stripe_new *ec = ob->ec;
1087
1088         if (!ec)
1089                 return;
1090
1091         mutex_lock(&ec->lock);
1092
1093         if (bch2_keylist_realloc(&ec->keys, ec->inline_keys,
1094                                  ARRAY_SIZE(ec->inline_keys),
1095                                  BKEY_U64s)) {
1096                 BUG();
1097         }
1098
1099         bkey_init(&ec->keys.top->k);
1100         ec->keys.top->k.p       = k->p;
1101         ec->keys.top->k.size    = k->size;
1102         bch2_keylist_push(&ec->keys);
1103
1104         mutex_unlock(&ec->lock);
1105 }
1106
1107 static int unsigned_cmp(const void *_l, const void *_r)
1108 {
1109         unsigned l = *((const unsigned *) _l);
1110         unsigned r = *((const unsigned *) _r);
1111
1112         return cmp_int(l, r);
1113 }
1114
1115 /* pick most common bucket size: */
1116 static unsigned pick_blocksize(struct bch_fs *c,
1117                                struct bch_devs_mask *devs)
1118 {
1119         struct bch_dev *ca;
1120         unsigned i, nr = 0, sizes[BCH_SB_MEMBERS_MAX];
1121         struct {
1122                 unsigned nr, size;
1123         } cur = { 0, 0 }, best = { 0, 0 };
1124
1125         for_each_member_device_rcu(ca, c, i, devs)
1126                 sizes[nr++] = ca->mi.bucket_size;
1127
1128         sort(sizes, nr, sizeof(unsigned), unsigned_cmp, NULL);
1129
1130         for (i = 0; i < nr; i++) {
1131                 if (sizes[i] != cur.size) {
1132                         if (cur.nr > best.nr)
1133                                 best = cur;
1134
1135                         cur.nr = 0;
1136                         cur.size = sizes[i];
1137                 }
1138
1139                 cur.nr++;
1140         }
1141
1142         if (cur.nr > best.nr)
1143                 best = cur;
1144
1145         return best.size;
1146 }
1147
1148 static bool may_create_new_stripe(struct bch_fs *c)
1149 {
1150         return false;
1151 }
1152
1153 static void ec_stripe_key_init(struct bch_fs *c,
1154                                struct bkey_i_stripe *s,
1155                                unsigned nr_data,
1156                                unsigned nr_parity,
1157                                unsigned stripe_size)
1158 {
1159         unsigned u64s;
1160
1161         bkey_stripe_init(&s->k_i);
1162         s->v.sectors                    = cpu_to_le16(stripe_size);
1163         s->v.algorithm                  = 0;
1164         s->v.nr_blocks                  = nr_data + nr_parity;
1165         s->v.nr_redundant               = nr_parity;
1166         s->v.csum_granularity_bits      = ilog2(c->opts.encoded_extent_max >> 9);
1167         s->v.csum_type                  = BCH_CSUM_crc32c;
1168         s->v.pad                        = 0;
1169
1170         while ((u64s = stripe_val_u64s(&s->v)) > BKEY_VAL_U64s_MAX) {
1171                 BUG_ON(1 << s->v.csum_granularity_bits >=
1172                        le16_to_cpu(s->v.sectors) ||
1173                        s->v.csum_granularity_bits == U8_MAX);
1174                 s->v.csum_granularity_bits++;
1175         }
1176
1177         set_bkey_val_u64s(&s->k, u64s);
1178 }
1179
1180 static int ec_new_stripe_alloc(struct bch_fs *c, struct ec_stripe_head *h)
1181 {
1182         struct ec_stripe_new *s;
1183
1184         lockdep_assert_held(&h->lock);
1185
1186         s = kzalloc(sizeof(*s), GFP_KERNEL);
1187         if (!s)
1188                 return -ENOMEM;
1189
1190         mutex_init(&s->lock);
1191         closure_init(&s->iodone, NULL);
1192         atomic_set(&s->pin, 1);
1193         s->c            = c;
1194         s->h            = h;
1195         s->nr_data      = min_t(unsigned, h->nr_active_devs,
1196                                 BCH_BKEY_PTRS_MAX) - h->redundancy;
1197         s->nr_parity    = h->redundancy;
1198
1199         bch2_keylist_init(&s->keys, s->inline_keys);
1200
1201         ec_stripe_key_init(c, &s->new_stripe.key, s->nr_data,
1202                            s->nr_parity, h->blocksize);
1203
1204         h->s = s;
1205         return 0;
1206 }
1207
1208 static struct ec_stripe_head *
1209 ec_new_stripe_head_alloc(struct bch_fs *c, unsigned target,
1210                          unsigned algo, unsigned redundancy,
1211                          bool copygc)
1212 {
1213         struct ec_stripe_head *h;
1214         struct bch_dev *ca;
1215         unsigned i;
1216
1217         h = kzalloc(sizeof(*h), GFP_KERNEL);
1218         if (!h)
1219                 return NULL;
1220
1221         mutex_init(&h->lock);
1222         mutex_lock(&h->lock);
1223
1224         h->target       = target;
1225         h->algo         = algo;
1226         h->redundancy   = redundancy;
1227         h->copygc       = copygc;
1228
1229         rcu_read_lock();
1230         h->devs = target_rw_devs(c, BCH_DATA_user, target);
1231
1232         for_each_member_device_rcu(ca, c, i, &h->devs)
1233                 if (!ca->mi.durability)
1234                         __clear_bit(i, h->devs.d);
1235
1236         h->blocksize = pick_blocksize(c, &h->devs);
1237
1238         for_each_member_device_rcu(ca, c, i, &h->devs)
1239                 if (ca->mi.bucket_size == h->blocksize)
1240                         h->nr_active_devs++;
1241
1242         rcu_read_unlock();
1243         list_add(&h->list, &c->ec_stripe_head_list);
1244         return h;
1245 }
1246
1247 void bch2_ec_stripe_head_put(struct bch_fs *c, struct ec_stripe_head *h)
1248 {
1249         if (h->s &&
1250             h->s->allocated &&
1251             bitmap_weight(h->s->blocks_allocated,
1252                           h->s->nr_data) == h->s->nr_data)
1253                 ec_stripe_set_pending(c, h);
1254
1255         mutex_unlock(&h->lock);
1256 }
1257
1258 struct ec_stripe_head *__bch2_ec_stripe_head_get(struct bch_fs *c,
1259                                                  unsigned target,
1260                                                  unsigned algo,
1261                                                  unsigned redundancy,
1262                                                  bool copygc)
1263 {
1264         struct ec_stripe_head *h;
1265
1266         if (!redundancy)
1267                 return NULL;
1268
1269         mutex_lock(&c->ec_stripe_head_lock);
1270         list_for_each_entry(h, &c->ec_stripe_head_list, list)
1271                 if (h->target           == target &&
1272                     h->algo             == algo &&
1273                     h->redundancy       == redundancy &&
1274                     h->copygc           == copygc) {
1275                         mutex_lock(&h->lock);
1276                         goto found;
1277                 }
1278
1279         h = ec_new_stripe_head_alloc(c, target, algo, redundancy, copygc);
1280 found:
1281         mutex_unlock(&c->ec_stripe_head_lock);
1282         return h;
1283 }
1284
1285 static int new_stripe_alloc_buckets(struct bch_fs *c, struct ec_stripe_head *h,
1286                                     struct closure *cl)
1287 {
1288         struct bch_devs_mask devs = h->devs;
1289         struct open_bucket *ob;
1290         struct open_buckets buckets;
1291         unsigned i, j, nr_have_parity = 0, nr_have_data = 0;
1292         bool have_cache = true;
1293         int ret = 0;
1294
1295         for (i = 0; i < h->s->new_stripe.key.v.nr_blocks; i++) {
1296                 if (test_bit(i, h->s->blocks_gotten)) {
1297                         __clear_bit(h->s->new_stripe.key.v.ptrs[i].dev, devs.d);
1298                         if (i < h->s->nr_data)
1299                                 nr_have_data++;
1300                         else
1301                                 nr_have_parity++;
1302                 }
1303         }
1304
1305         BUG_ON(nr_have_data     > h->s->nr_data);
1306         BUG_ON(nr_have_parity   > h->s->nr_parity);
1307
1308         buckets.nr = 0;
1309         if (nr_have_parity < h->s->nr_parity) {
1310                 ret = bch2_bucket_alloc_set(c, &buckets,
1311                                             &h->parity_stripe,
1312                                             &devs,
1313                                             h->s->nr_parity,
1314                                             &nr_have_parity,
1315                                             &have_cache,
1316                                             h->copygc
1317                                             ? RESERVE_movinggc
1318                                             : RESERVE_none,
1319                                             0,
1320                                             cl);
1321
1322                 open_bucket_for_each(c, &buckets, ob, i) {
1323                         j = find_next_zero_bit(h->s->blocks_gotten,
1324                                                h->s->nr_data + h->s->nr_parity,
1325                                                h->s->nr_data);
1326                         BUG_ON(j >= h->s->nr_data + h->s->nr_parity);
1327
1328                         h->s->blocks[j] = buckets.v[i];
1329                         h->s->new_stripe.key.v.ptrs[j] = bch2_ob_ptr(c, ob);
1330                         __set_bit(j, h->s->blocks_gotten);
1331                 }
1332
1333                 if (ret)
1334                         return ret;
1335         }
1336
1337         buckets.nr = 0;
1338         if (nr_have_data < h->s->nr_data) {
1339                 ret = bch2_bucket_alloc_set(c, &buckets,
1340                                             &h->block_stripe,
1341                                             &devs,
1342                                             h->s->nr_data,
1343                                             &nr_have_data,
1344                                             &have_cache,
1345                                             h->copygc
1346                                             ? RESERVE_movinggc
1347                                             : RESERVE_none,
1348                                             0,
1349                                             cl);
1350
1351                 open_bucket_for_each(c, &buckets, ob, i) {
1352                         j = find_next_zero_bit(h->s->blocks_gotten,
1353                                                h->s->nr_data, 0);
1354                         BUG_ON(j >= h->s->nr_data);
1355
1356                         h->s->blocks[j] = buckets.v[i];
1357                         h->s->new_stripe.key.v.ptrs[j] = bch2_ob_ptr(c, ob);
1358                         __set_bit(j, h->s->blocks_gotten);
1359                 }
1360
1361                 if (ret)
1362                         return ret;
1363         }
1364
1365         return 0;
1366 }
1367
1368 /* XXX: doesn't obey target: */
1369 static s64 get_existing_stripe(struct bch_fs *c,
1370                                struct ec_stripe_head *head)
1371 {
1372         ec_stripes_heap *h = &c->ec_stripes_heap;
1373         struct stripe *m;
1374         size_t heap_idx;
1375         u64 stripe_idx;
1376         s64 ret = -1;
1377
1378         if (may_create_new_stripe(c))
1379                 return -1;
1380
1381         spin_lock(&c->ec_stripes_heap_lock);
1382         for (heap_idx = 0; heap_idx < h->used; heap_idx++) {
1383                 /* No blocks worth reusing, stripe will just be deleted: */
1384                 if (!h->data[heap_idx].blocks_nonempty)
1385                         continue;
1386
1387                 stripe_idx = h->data[heap_idx].idx;
1388                 m = genradix_ptr(&c->stripes, stripe_idx);
1389
1390                 if (m->algorithm        == head->algo &&
1391                     m->nr_redundant     == head->redundancy &&
1392                     m->sectors          == head->blocksize &&
1393                     m->blocks_nonempty  < m->nr_blocks - m->nr_redundant) {
1394                         bch2_stripes_heap_del(c, m, stripe_idx);
1395                         ret = stripe_idx;
1396                         break;
1397                 }
1398         }
1399         spin_unlock(&c->ec_stripes_heap_lock);
1400         return ret;
1401 }
1402
1403 static int __bch2_ec_stripe_head_reuse(struct bch_fs *c,
1404                                                    struct ec_stripe_head *h)
1405 {
1406         unsigned i;
1407         s64 idx;
1408         int ret;
1409
1410         idx = get_existing_stripe(c, h);
1411         if (idx < 0) {
1412                 bch_err(c, "failed to find an existing stripe");
1413                 return -ENOSPC;
1414         }
1415
1416         h->s->have_existing_stripe = true;
1417         ret = get_stripe_key(c, idx, &h->s->existing_stripe);
1418         if (ret) {
1419                 bch2_fs_fatal_error(c, "error reading stripe key: %i", ret);
1420                 return ret;
1421         }
1422
1423         if (ec_stripe_buf_init(&h->s->existing_stripe, 0, h->blocksize)) {
1424                 /*
1425                  * this is a problem: we have deleted from the
1426                  * stripes heap already
1427                  */
1428                 BUG();
1429         }
1430
1431         BUG_ON(h->s->existing_stripe.size != h->blocksize);
1432         BUG_ON(h->s->existing_stripe.size != h->s->existing_stripe.key.v.sectors);
1433
1434         for (i = 0; i < h->s->existing_stripe.key.v.nr_blocks; i++) {
1435                 if (stripe_blockcount_get(&h->s->existing_stripe.key.v, i)) {
1436                         __set_bit(i, h->s->blocks_gotten);
1437                         __set_bit(i, h->s->blocks_allocated);
1438                 }
1439
1440                 ec_block_io(c, &h->s->existing_stripe, READ, i, &h->s->iodone);
1441         }
1442
1443         bkey_copy(&h->s->new_stripe.key.k_i,
1444                         &h->s->existing_stripe.key.k_i);
1445
1446         return 0;
1447 }
1448
1449 static int __bch2_ec_stripe_head_reserve(struct bch_fs *c,
1450                                                         struct ec_stripe_head *h)
1451 {
1452         int ret;
1453
1454         ret = bch2_disk_reservation_get(c, &h->s->res,
1455                         h->blocksize,
1456                         h->s->nr_parity, 0);
1457
1458         if (ret) {
1459                 /*
1460                  * This means we need to wait for copygc to
1461                  * empty out buckets from existing stripes:
1462                  */
1463                 bch_err(c, "failed to reserve stripe");
1464         }
1465
1466         return ret;
1467 }
1468
1469 struct ec_stripe_head *bch2_ec_stripe_head_get(struct bch_fs *c,
1470                                                unsigned target,
1471                                                unsigned algo,
1472                                                unsigned redundancy,
1473                                                bool copygc,
1474                                                struct closure *cl)
1475 {
1476         struct ec_stripe_head *h;
1477         int ret;
1478         bool needs_stripe_new;
1479
1480         h = __bch2_ec_stripe_head_get(c, target, algo, redundancy, copygc);
1481         if (!h) {
1482                 bch_err(c, "no stripe head");
1483                 return NULL;
1484         }
1485
1486         needs_stripe_new = !h->s;
1487         if (needs_stripe_new) {
1488                 if (ec_new_stripe_alloc(c, h)) {
1489                         ret = -ENOMEM;
1490                         bch_err(c, "failed to allocate new stripe");
1491                         goto err;
1492                 }
1493
1494                 if (ec_stripe_buf_init(&h->s->new_stripe, 0, h->blocksize))
1495                         BUG();
1496         }
1497
1498         /*
1499          * Try reserve a new stripe before reusing an
1500          * existing stripe. This will prevent unnecessary
1501          * read amplification during write oriented workloads.
1502          */
1503         ret = 0;
1504         if (!h->s->allocated && !h->s->res.sectors && !h->s->have_existing_stripe)
1505                 ret = __bch2_ec_stripe_head_reserve(c, h);
1506         if (ret && needs_stripe_new)
1507                 ret = __bch2_ec_stripe_head_reuse(c, h);
1508         if (ret)
1509                 goto err;
1510
1511         if (!h->s->allocated) {
1512                 ret = new_stripe_alloc_buckets(c, h, cl);
1513                 if (ret)
1514                         goto err;
1515
1516                 h->s->allocated = true;
1517         }
1518
1519         return h;
1520
1521 err:
1522         bch2_ec_stripe_head_put(c, h);
1523         return ERR_PTR(ret);
1524 }
1525
1526 void bch2_ec_stop_dev(struct bch_fs *c, struct bch_dev *ca)
1527 {
1528         struct ec_stripe_head *h;
1529         struct open_bucket *ob;
1530         unsigned i;
1531
1532         mutex_lock(&c->ec_stripe_head_lock);
1533         list_for_each_entry(h, &c->ec_stripe_head_list, list) {
1534
1535                 mutex_lock(&h->lock);
1536                 if (!h->s)
1537                         goto unlock;
1538
1539                 for (i = 0; i < h->s->new_stripe.key.v.nr_blocks; i++) {
1540                         if (!h->s->blocks[i])
1541                                 continue;
1542
1543                         ob = c->open_buckets + h->s->blocks[i];
1544                         if (ob->dev == ca->dev_idx)
1545                                 goto found;
1546                 }
1547                 goto unlock;
1548 found:
1549                 h->s->err = -EROFS;
1550                 ec_stripe_set_pending(c, h);
1551 unlock:
1552                 mutex_unlock(&h->lock);
1553         }
1554         mutex_unlock(&c->ec_stripe_head_lock);
1555 }
1556
1557 void bch2_stripes_heap_start(struct bch_fs *c)
1558 {
1559         struct genradix_iter iter;
1560         struct stripe *m;
1561
1562         genradix_for_each(&c->stripes, iter, m)
1563                 if (m->alive)
1564                         bch2_stripes_heap_insert(c, m, iter.pos);
1565 }
1566
1567 int bch2_stripes_read(struct bch_fs *c)
1568 {
1569         struct btree_trans trans;
1570         struct btree_iter iter;
1571         struct bkey_s_c k;
1572         const struct bch_stripe *s;
1573         struct stripe *m;
1574         unsigned i;
1575         int ret;
1576
1577         bch2_trans_init(&trans, c, 0, 0);
1578
1579         for_each_btree_key(&trans, iter, BTREE_ID_stripes, POS_MIN,
1580                            BTREE_ITER_PREFETCH, k, ret) {
1581                 if (k.k->type != KEY_TYPE_stripe)
1582                         continue;
1583
1584                 ret = __ec_stripe_mem_alloc(c, k.k->p.offset, GFP_KERNEL);
1585                 if (ret)
1586                         break;
1587
1588                 s = bkey_s_c_to_stripe(k).v;
1589
1590                 m = genradix_ptr(&c->stripes, k.k->p.offset);
1591                 m->alive        = true;
1592                 m->sectors      = le16_to_cpu(s->sectors);
1593                 m->algorithm    = s->algorithm;
1594                 m->nr_blocks    = s->nr_blocks;
1595                 m->nr_redundant = s->nr_redundant;
1596                 m->blocks_nonempty = 0;
1597
1598                 for (i = 0; i < s->nr_blocks; i++)
1599                         m->blocks_nonempty += !!stripe_blockcount_get(s, i);
1600
1601                 spin_lock(&c->ec_stripes_heap_lock);
1602                 bch2_stripes_heap_update(c, m, k.k->p.offset);
1603                 spin_unlock(&c->ec_stripes_heap_lock);
1604         }
1605         bch2_trans_iter_exit(&trans, &iter);
1606
1607         bch2_trans_exit(&trans);
1608
1609         if (ret)
1610                 bch_err(c, "error reading stripes: %i", ret);
1611
1612         return ret;
1613 }
1614
1615 void bch2_stripes_heap_to_text(struct printbuf *out, struct bch_fs *c)
1616 {
1617         ec_stripes_heap *h = &c->ec_stripes_heap;
1618         struct stripe *m;
1619         size_t i;
1620
1621         spin_lock(&c->ec_stripes_heap_lock);
1622         for (i = 0; i < min_t(size_t, h->used, 20); i++) {
1623                 m = genradix_ptr(&c->stripes, h->data[i].idx);
1624
1625                 pr_buf(out, "%zu %u/%u+%u\n", h->data[i].idx,
1626                        h->data[i].blocks_nonempty,
1627                        m->nr_blocks - m->nr_redundant,
1628                        m->nr_redundant);
1629         }
1630         spin_unlock(&c->ec_stripes_heap_lock);
1631 }
1632
1633 void bch2_new_stripes_to_text(struct printbuf *out, struct bch_fs *c)
1634 {
1635         struct ec_stripe_head *h;
1636         struct ec_stripe_new *s;
1637
1638         mutex_lock(&c->ec_stripe_head_lock);
1639         list_for_each_entry(h, &c->ec_stripe_head_list, list) {
1640                 pr_buf(out, "target %u algo %u redundancy %u:\n",
1641                        h->target, h->algo, h->redundancy);
1642
1643                 if (h->s)
1644                         pr_buf(out, "\tpending: blocks %u+%u allocated %u\n",
1645                                h->s->nr_data, h->s->nr_parity,
1646                                bitmap_weight(h->s->blocks_allocated,
1647                                              h->s->nr_data));
1648         }
1649         mutex_unlock(&c->ec_stripe_head_lock);
1650
1651         mutex_lock(&c->ec_stripe_new_lock);
1652         list_for_each_entry(s, &c->ec_stripe_new_list, list) {
1653                 pr_buf(out, "\tin flight: blocks %u+%u pin %u\n",
1654                        s->nr_data, s->nr_parity,
1655                        atomic_read(&s->pin));
1656         }
1657         mutex_unlock(&c->ec_stripe_new_lock);
1658 }
1659
1660 void bch2_fs_ec_exit(struct bch_fs *c)
1661 {
1662         struct ec_stripe_head *h;
1663
1664         while (1) {
1665                 mutex_lock(&c->ec_stripe_head_lock);
1666                 h = list_first_entry_or_null(&c->ec_stripe_head_list,
1667                                              struct ec_stripe_head, list);
1668                 if (h)
1669                         list_del(&h->list);
1670                 mutex_unlock(&c->ec_stripe_head_lock);
1671                 if (!h)
1672                         break;
1673
1674                 BUG_ON(h->s);
1675                 kfree(h);
1676         }
1677
1678         BUG_ON(!list_empty(&c->ec_stripe_new_list));
1679
1680         free_heap(&c->ec_stripes_heap);
1681         genradix_free(&c->stripes);
1682         bioset_exit(&c->ec_bioset);
1683 }
1684
1685 void bch2_fs_ec_init_early(struct bch_fs *c)
1686 {
1687         INIT_WORK(&c->ec_stripe_create_work, ec_stripe_create_work);
1688         INIT_WORK(&c->ec_stripe_delete_work, ec_stripe_delete_work);
1689 }
1690
1691 int bch2_fs_ec_init(struct bch_fs *c)
1692 {
1693         return bioset_init(&c->ec_bioset, 1, offsetof(struct ec_bio, bio),
1694                            BIOSET_NEED_BVECS);
1695 }