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