]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/ec.c
Update bcachefs sources to 70b5fb5daf bcachefs: Fix error reporting from bch2_journal...
[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 "super-io.h"
19 #include "util.h"
20
21 #include <linux/sort.h>
22
23 #ifdef __KERNEL__
24
25 #include <linux/raid/pq.h>
26 #include <linux/raid/xor.h>
27
28 static void raid5_recov(unsigned disks, unsigned failed_idx,
29                         size_t size, void **data)
30 {
31         unsigned i = 2, nr;
32
33         BUG_ON(failed_idx >= disks);
34
35         swap(data[0], data[failed_idx]);
36         memcpy(data[0], data[1], size);
37
38         while (i < disks) {
39                 nr = min_t(unsigned, disks - i, MAX_XOR_BLOCKS);
40                 xor_blocks(nr, size, data[0], data + i);
41                 i += nr;
42         }
43
44         swap(data[0], data[failed_idx]);
45 }
46
47 static void raid_gen(int nd, int np, size_t size, void **v)
48 {
49         if (np >= 1)
50                 raid5_recov(nd + np, nd, size, v);
51         if (np >= 2)
52                 raid6_call.gen_syndrome(nd + np, size, v);
53         BUG_ON(np > 2);
54 }
55
56 static void raid_rec(int nr, int *ir, int nd, int np, size_t size, void **v)
57 {
58         switch (nr) {
59         case 0:
60                 break;
61         case 1:
62                 if (ir[0] < nd + 1)
63                         raid5_recov(nd + 1, ir[0], size, v);
64                 else
65                         raid6_call.gen_syndrome(nd + np, size, v);
66                 break;
67         case 2:
68                 if (ir[1] < nd) {
69                         /* data+data failure. */
70                         raid6_2data_recov(nd + np, size, ir[0], ir[1], v);
71                 } else if (ir[0] < nd) {
72                         /* data + p/q failure */
73
74                         if (ir[1] == nd) /* data + p failure */
75                                 raid6_datap_recov(nd + np, size, ir[0], v);
76                         else { /* data + q failure */
77                                 raid5_recov(nd + 1, ir[0], size, v);
78                                 raid6_call.gen_syndrome(nd + np, size, v);
79                         }
80                 } else {
81                         raid_gen(nd, np, size, v);
82                 }
83                 break;
84         default:
85                 BUG();
86         }
87 }
88
89 #else
90
91 #include <raid/raid.h>
92
93 #endif
94
95 struct ec_bio {
96         struct bch_dev          *ca;
97         struct ec_stripe_buf    *buf;
98         size_t                  idx;
99         struct bio              bio;
100 };
101
102 /* Stripes btree keys: */
103
104 const char *bch2_stripe_invalid(const struct bch_fs *c, struct bkey_s_c k)
105 {
106         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
107
108         if (!bkey_cmp(k.k->p, POS_MIN))
109                 return "stripe at pos 0";
110
111         if (k.k->p.inode)
112                 return "invalid stripe key";
113
114         if (bkey_val_bytes(k.k) < sizeof(*s))
115                 return "incorrect value size";
116
117         if (bkey_val_bytes(k.k) < sizeof(*s) ||
118             bkey_val_u64s(k.k) < stripe_val_u64s(s))
119                 return "incorrect value size";
120
121         return bch2_bkey_ptrs_invalid(c, k);
122 }
123
124 void bch2_stripe_to_text(struct printbuf *out, struct bch_fs *c,
125                          struct bkey_s_c k)
126 {
127         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
128         unsigned i;
129
130         pr_buf(out, "algo %u sectors %u blocks %u:%u csum %u gran %u",
131                s->algorithm,
132                le16_to_cpu(s->sectors),
133                s->nr_blocks - s->nr_redundant,
134                s->nr_redundant,
135                s->csum_type,
136                1U << s->csum_granularity_bits);
137
138         for (i = 0; i < s->nr_blocks; i++)
139                 pr_buf(out, " %u:%llu:%u", s->ptrs[i].dev,
140                        (u64) s->ptrs[i].offset,
141                        stripe_blockcount_get(s, i));
142 }
143
144 /* returns blocknr in stripe that we matched: */
145 static int bkey_matches_stripe(struct bch_stripe *s,
146                                struct bkey_s_c k)
147 {
148         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
149         const struct bch_extent_ptr *ptr;
150         unsigned i, nr_data = s->nr_blocks - s->nr_redundant;
151
152         bkey_for_each_ptr(ptrs, ptr)
153                 for (i = 0; i < nr_data; i++)
154                         if (__bch2_ptr_matches_stripe(&s->ptrs[i], ptr,
155                                                       le16_to_cpu(s->sectors)))
156                                 return i;
157
158         return -1;
159 }
160
161 static bool extent_has_stripe_ptr(struct bkey_s_c k, u64 idx)
162 {
163         switch (k.k->type) {
164         case KEY_TYPE_extent: {
165                 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
166                 const union bch_extent_entry *entry;
167
168                 extent_for_each_entry(e, entry)
169                         if (extent_entry_type(entry) ==
170                             BCH_EXTENT_ENTRY_stripe_ptr &&
171                             entry->stripe_ptr.idx == idx)
172                                 return true;
173
174                 break;
175         }
176         }
177
178         return false;
179 }
180
181 /* Stripe bufs: */
182
183 static void ec_stripe_buf_exit(struct ec_stripe_buf *buf)
184 {
185         unsigned i;
186
187         for (i = 0; i < buf->key.v.nr_blocks; i++) {
188                 kvpfree(buf->data[i], buf->size << 9);
189                 buf->data[i] = NULL;
190         }
191 }
192
193 static int ec_stripe_buf_init(struct ec_stripe_buf *buf,
194                                unsigned offset, unsigned size)
195 {
196         struct bch_stripe *v = &buf->key.v;
197         unsigned csum_granularity = 1U << v->csum_granularity_bits;
198         unsigned end = offset + size;
199         unsigned i;
200
201         BUG_ON(end > le16_to_cpu(v->sectors));
202
203         offset  = round_down(offset, csum_granularity);
204         end     = min_t(unsigned, le16_to_cpu(v->sectors),
205                         round_up(end, csum_granularity));
206
207         buf->offset     = offset;
208         buf->size       = end - offset;
209
210         memset(buf->valid, 0xFF, sizeof(buf->valid));
211
212         for (i = 0; i < buf->key.v.nr_blocks; i++) {
213                 buf->data[i] = kvpmalloc(buf->size << 9, GFP_KERNEL);
214                 if (!buf->data[i])
215                         goto err;
216         }
217
218         return 0;
219 err:
220         ec_stripe_buf_exit(buf);
221         return -ENOMEM;
222 }
223
224 /* Checksumming: */
225
226 static struct bch_csum ec_block_checksum(struct ec_stripe_buf *buf,
227                                          unsigned block, unsigned offset)
228 {
229         struct bch_stripe *v = &buf->key.v;
230         unsigned csum_granularity = 1 << v->csum_granularity_bits;
231         unsigned end = buf->offset + buf->size;
232         unsigned len = min(csum_granularity, end - offset);
233
234         BUG_ON(offset >= end);
235         BUG_ON(offset <  buf->offset);
236         BUG_ON(offset & (csum_granularity - 1));
237         BUG_ON(offset + len != le16_to_cpu(v->sectors) &&
238                (len & (csum_granularity - 1)));
239
240         return bch2_checksum(NULL, v->csum_type,
241                              null_nonce(),
242                              buf->data[block] + ((offset - buf->offset) << 9),
243                              len << 9);
244 }
245
246 static void ec_generate_checksums(struct ec_stripe_buf *buf)
247 {
248         struct bch_stripe *v = &buf->key.v;
249         unsigned i, j, csums_per_device = stripe_csums_per_device(v);
250
251         if (!v->csum_type)
252                 return;
253
254         BUG_ON(buf->offset);
255         BUG_ON(buf->size != le16_to_cpu(v->sectors));
256
257         for (i = 0; i < v->nr_blocks; i++)
258                 for (j = 0; j < csums_per_device; j++)
259                         stripe_csum_set(v, i, j,
260                                 ec_block_checksum(buf, i, j << v->csum_granularity_bits));
261 }
262
263 static void ec_validate_checksums(struct bch_fs *c, struct ec_stripe_buf *buf)
264 {
265         struct bch_stripe *v = &buf->key.v;
266         unsigned csum_granularity = 1 << v->csum_granularity_bits;
267         unsigned i;
268
269         if (!v->csum_type)
270                 return;
271
272         for (i = 0; i < v->nr_blocks; i++) {
273                 unsigned offset = buf->offset;
274                 unsigned end = buf->offset + buf->size;
275
276                 if (!test_bit(i, buf->valid))
277                         continue;
278
279                 while (offset < end) {
280                         unsigned j = offset >> v->csum_granularity_bits;
281                         unsigned len = min(csum_granularity, end - offset);
282                         struct bch_csum want = stripe_csum_get(v, i, j);
283                         struct bch_csum got = ec_block_checksum(buf, i, offset);
284
285                         if (bch2_crc_cmp(want, got)) {
286                                 char buf2[200];
287
288                                 bch2_bkey_val_to_text(&PBUF(buf2), c, bkey_i_to_s_c(&buf->key.k_i));
289
290                                 bch_err_ratelimited(c,
291                                         "stripe checksum error for %ps at %u:%u: csum type %u, expected %llx got %llx\n%s",
292                                         (void *) _RET_IP_, i, j, v->csum_type,
293                                         want.lo, got.lo, buf2);
294                                 clear_bit(i, buf->valid);
295                                 break;
296                         }
297
298                         offset += len;
299                 }
300         }
301 }
302
303 /* Erasure coding: */
304
305 static void ec_generate_ec(struct ec_stripe_buf *buf)
306 {
307         struct bch_stripe *v = &buf->key.v;
308         unsigned nr_data = v->nr_blocks - v->nr_redundant;
309         unsigned bytes = le16_to_cpu(v->sectors) << 9;
310
311         raid_gen(nr_data, v->nr_redundant, bytes, buf->data);
312 }
313
314 static unsigned ec_nr_failed(struct ec_stripe_buf *buf)
315 {
316         return buf->key.v.nr_blocks -
317                 bitmap_weight(buf->valid, buf->key.v.nr_blocks);
318 }
319
320 static int ec_do_recov(struct bch_fs *c, struct ec_stripe_buf *buf)
321 {
322         struct bch_stripe *v = &buf->key.v;
323         unsigned i, failed[BCH_BKEY_PTRS_MAX], nr_failed = 0;
324         unsigned nr_data = v->nr_blocks - v->nr_redundant;
325         unsigned bytes = buf->size << 9;
326
327         if (ec_nr_failed(buf) > v->nr_redundant) {
328                 bch_err_ratelimited(c,
329                         "error doing reconstruct read: unable to read enough blocks");
330                 return -1;
331         }
332
333         for (i = 0; i < nr_data; i++)
334                 if (!test_bit(i, buf->valid))
335                         failed[nr_failed++] = i;
336
337         raid_rec(nr_failed, failed, nr_data, v->nr_redundant, bytes, buf->data);
338         return 0;
339 }
340
341 /* IO: */
342
343 static void ec_block_endio(struct bio *bio)
344 {
345         struct ec_bio *ec_bio = container_of(bio, struct ec_bio, bio);
346         struct bch_stripe *v = &ec_bio->buf->key.v;
347         struct bch_extent_ptr *ptr = &v->ptrs[ec_bio->idx];
348         struct bch_dev *ca = ec_bio->ca;
349         struct closure *cl = bio->bi_private;
350
351         if (bch2_dev_io_err_on(bio->bi_status, ca, "erasure coding %s error: %s",
352                                bio_data_dir(bio) ? "write" : "read",
353                                bch2_blk_status_to_str(bio->bi_status)))
354                 clear_bit(ec_bio->idx, ec_bio->buf->valid);
355
356         if (ptr_stale(ca, ptr)) {
357                 bch_err_ratelimited(ca->fs,
358                                     "error %s stripe: stale pointer after io",
359                                     bio_data_dir(bio) == READ ? "reading from" : "writing to");
360                 clear_bit(ec_bio->idx, ec_bio->buf->valid);
361         }
362
363         bio_put(&ec_bio->bio);
364         percpu_ref_put(&ca->io_ref);
365         closure_put(cl);
366 }
367
368 static void ec_block_io(struct bch_fs *c, struct ec_stripe_buf *buf,
369                         unsigned rw, unsigned idx, struct closure *cl)
370 {
371         struct bch_stripe *v = &buf->key.v;
372         unsigned offset = 0, bytes = buf->size << 9;
373         struct bch_extent_ptr *ptr = &v->ptrs[idx];
374         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
375         enum bch_data_type data_type = idx < buf->key.v.nr_blocks - buf->key.v.nr_redundant
376                 ? BCH_DATA_user
377                 : BCH_DATA_parity;
378
379         if (ptr_stale(ca, ptr)) {
380                 bch_err_ratelimited(c,
381                                     "error %s stripe: stale pointer",
382                                     rw == READ ? "reading from" : "writing to");
383                 clear_bit(idx, buf->valid);
384                 return;
385         }
386
387         if (!bch2_dev_get_ioref(ca, rw)) {
388                 clear_bit(idx, buf->valid);
389                 return;
390         }
391
392         this_cpu_add(ca->io_done->sectors[rw][data_type], buf->size);
393
394         while (offset < bytes) {
395                 unsigned nr_iovecs = min_t(size_t, BIO_MAX_VECS,
396                                            DIV_ROUND_UP(bytes, PAGE_SIZE));
397                 unsigned b = min_t(size_t, bytes - offset,
398                                    nr_iovecs << PAGE_SHIFT);
399                 struct ec_bio *ec_bio;
400
401                 ec_bio = container_of(bio_alloc_bioset(GFP_KERNEL, nr_iovecs,
402                                                        &c->ec_bioset),
403                                       struct ec_bio, bio);
404
405                 ec_bio->ca                      = ca;
406                 ec_bio->buf                     = buf;
407                 ec_bio->idx                     = idx;
408
409                 bio_set_dev(&ec_bio->bio, ca->disk_sb.bdev);
410                 bio_set_op_attrs(&ec_bio->bio, rw, 0);
411
412                 ec_bio->bio.bi_iter.bi_sector   = ptr->offset + buf->offset + (offset >> 9);
413                 ec_bio->bio.bi_end_io           = ec_block_endio;
414                 ec_bio->bio.bi_private          = cl;
415
416                 bch2_bio_map(&ec_bio->bio, buf->data[idx] + offset, b);
417
418                 closure_get(cl);
419                 percpu_ref_get(&ca->io_ref);
420
421                 submit_bio(&ec_bio->bio);
422
423                 offset += b;
424         }
425
426         percpu_ref_put(&ca->io_ref);
427 }
428
429 static int get_stripe_key(struct bch_fs *c, u64 idx, struct ec_stripe_buf *stripe)
430 {
431         struct btree_trans trans;
432         struct btree_iter iter;
433         struct bkey_s_c k;
434         int ret;
435
436         bch2_trans_init(&trans, c, 0, 0);
437         bch2_trans_iter_init(&trans, &iter, BTREE_ID_stripes,
438                              POS(0, idx), BTREE_ITER_SLOTS);
439         k = bch2_btree_iter_peek_slot(&iter);
440         ret = bkey_err(k);
441         if (ret)
442                 goto err;
443         if (k.k->type != KEY_TYPE_stripe) {
444                 ret = -ENOENT;
445                 goto err;
446         }
447         bkey_reassemble(&stripe->key.k_i, k);
448 err:
449         bch2_trans_iter_exit(&trans, &iter);
450         bch2_trans_exit(&trans);
451         return ret;
452 }
453
454 /* recovery read path: */
455 int bch2_ec_read_extent(struct bch_fs *c, struct bch_read_bio *rbio)
456 {
457         struct ec_stripe_buf *buf;
458         struct closure cl;
459         struct bch_stripe *v;
460         unsigned i, offset;
461         int ret = 0;
462
463         closure_init_stack(&cl);
464
465         BUG_ON(!rbio->pick.has_ec);
466
467         buf = kzalloc(sizeof(*buf), GFP_NOIO);
468         if (!buf)
469                 return -ENOMEM;
470
471         ret = get_stripe_key(c, rbio->pick.ec.idx, buf);
472         if (ret) {
473                 bch_err_ratelimited(c,
474                         "error doing reconstruct read: error %i looking up stripe", ret);
475                 kfree(buf);
476                 return -EIO;
477         }
478
479         v = &buf->key.v;
480
481         if (!bch2_ptr_matches_stripe(v, rbio->pick)) {
482                 bch_err_ratelimited(c,
483                         "error doing reconstruct read: pointer doesn't match stripe");
484                 ret = -EIO;
485                 goto err;
486         }
487
488         offset = rbio->bio.bi_iter.bi_sector - v->ptrs[rbio->pick.ec.block].offset;
489         if (offset + bio_sectors(&rbio->bio) > le16_to_cpu(v->sectors)) {
490                 bch_err_ratelimited(c,
491                         "error doing reconstruct read: read is bigger than stripe");
492                 ret = -EIO;
493                 goto err;
494         }
495
496         ret = ec_stripe_buf_init(buf, offset, bio_sectors(&rbio->bio));
497         if (ret)
498                 goto err;
499
500         for (i = 0; i < v->nr_blocks; i++)
501                 ec_block_io(c, buf, REQ_OP_READ, i, &cl);
502
503         closure_sync(&cl);
504
505         if (ec_nr_failed(buf) > v->nr_redundant) {
506                 bch_err_ratelimited(c,
507                         "error doing reconstruct read: unable to read enough blocks");
508                 ret = -EIO;
509                 goto err;
510         }
511
512         ec_validate_checksums(c, buf);
513
514         ret = ec_do_recov(c, buf);
515         if (ret)
516                 goto err;
517
518         memcpy_to_bio(&rbio->bio, rbio->bio.bi_iter,
519                       buf->data[rbio->pick.ec.block] + ((offset - buf->offset) << 9));
520 err:
521         ec_stripe_buf_exit(buf);
522         kfree(buf);
523         return ret;
524 }
525
526 /* stripe bucket accounting: */
527
528 static int __ec_stripe_mem_alloc(struct bch_fs *c, size_t idx, gfp_t gfp)
529 {
530         ec_stripes_heap n, *h = &c->ec_stripes_heap;
531
532         if (idx >= h->size) {
533                 if (!init_heap(&n, max(1024UL, roundup_pow_of_two(idx + 1)), gfp))
534                         return -ENOMEM;
535
536                 spin_lock(&c->ec_stripes_heap_lock);
537                 if (n.size > h->size) {
538                         memcpy(n.data, h->data, h->used * sizeof(h->data[0]));
539                         n.used = h->used;
540                         swap(*h, n);
541                 }
542                 spin_unlock(&c->ec_stripes_heap_lock);
543
544                 free_heap(&n);
545         }
546
547         if (!genradix_ptr_alloc(&c->stripes[0], idx, gfp))
548                 return -ENOMEM;
549
550         if (c->gc_pos.phase != GC_PHASE_NOT_RUNNING &&
551             !genradix_ptr_alloc(&c->stripes[1], idx, gfp))
552                 return -ENOMEM;
553
554         return 0;
555 }
556
557 static int ec_stripe_mem_alloc(struct btree_trans *trans,
558                                struct btree_iter *iter)
559 {
560         size_t idx = iter->pos.offset;
561         int ret = 0;
562
563         if (!__ec_stripe_mem_alloc(trans->c, idx, GFP_NOWAIT|__GFP_NOWARN))
564                 return ret;
565
566         bch2_trans_unlock(trans);
567         ret = -EINTR;
568
569         if (!__ec_stripe_mem_alloc(trans->c, idx, GFP_KERNEL))
570                 return ret;
571
572         return -ENOMEM;
573 }
574
575 static ssize_t stripe_idx_to_delete(struct bch_fs *c)
576 {
577         ec_stripes_heap *h = &c->ec_stripes_heap;
578
579         return h->used && h->data[0].blocks_nonempty == 0
580                 ? h->data[0].idx : -1;
581 }
582
583 static inline int ec_stripes_heap_cmp(ec_stripes_heap *h,
584                                       struct ec_stripe_heap_entry l,
585                                       struct ec_stripe_heap_entry r)
586 {
587         return ((l.blocks_nonempty > r.blocks_nonempty) -
588                 (l.blocks_nonempty < r.blocks_nonempty));
589 }
590
591 static inline void ec_stripes_heap_set_backpointer(ec_stripes_heap *h,
592                                                    size_t i)
593 {
594         struct bch_fs *c = container_of(h, struct bch_fs, ec_stripes_heap);
595
596         genradix_ptr(&c->stripes[0], h->data[i].idx)->heap_idx = i;
597 }
598
599 static void heap_verify_backpointer(struct bch_fs *c, size_t idx)
600 {
601         ec_stripes_heap *h = &c->ec_stripes_heap;
602         struct stripe *m = genradix_ptr(&c->stripes[0], idx);
603
604         BUG_ON(!m->alive);
605         BUG_ON(m->heap_idx >= h->used);
606         BUG_ON(h->data[m->heap_idx].idx != idx);
607 }
608
609 void bch2_stripes_heap_del(struct bch_fs *c,
610                            struct stripe *m, size_t idx)
611 {
612         if (!m->on_heap)
613                 return;
614
615         m->on_heap = false;
616
617         heap_verify_backpointer(c, idx);
618
619         heap_del(&c->ec_stripes_heap, m->heap_idx,
620                  ec_stripes_heap_cmp,
621                  ec_stripes_heap_set_backpointer);
622 }
623
624 void bch2_stripes_heap_insert(struct bch_fs *c,
625                               struct stripe *m, size_t idx)
626 {
627         if (m->on_heap)
628                 return;
629
630         BUG_ON(heap_full(&c->ec_stripes_heap));
631
632         m->on_heap = true;
633
634         heap_add(&c->ec_stripes_heap, ((struct ec_stripe_heap_entry) {
635                         .idx = idx,
636                         .blocks_nonempty = m->blocks_nonempty,
637                 }),
638                  ec_stripes_heap_cmp,
639                  ec_stripes_heap_set_backpointer);
640
641         heap_verify_backpointer(c, idx);
642 }
643
644 void bch2_stripes_heap_update(struct bch_fs *c,
645                               struct stripe *m, size_t idx)
646 {
647         ec_stripes_heap *h = &c->ec_stripes_heap;
648         size_t i;
649
650         if (!m->on_heap)
651                 return;
652
653         heap_verify_backpointer(c, idx);
654
655         h->data[m->heap_idx].blocks_nonempty = m->blocks_nonempty;
656
657         i = m->heap_idx;
658         heap_sift_up(h,   i, ec_stripes_heap_cmp,
659                      ec_stripes_heap_set_backpointer);
660         heap_sift_down(h, i, ec_stripes_heap_cmp,
661                        ec_stripes_heap_set_backpointer);
662
663         heap_verify_backpointer(c, idx);
664
665         if (stripe_idx_to_delete(c) >= 0 &&
666             !percpu_ref_is_dying(&c->writes))
667                 schedule_work(&c->ec_stripe_delete_work);
668 }
669
670 /* stripe deletion */
671
672 static int ec_stripe_delete(struct bch_fs *c, size_t idx)
673 {
674         return bch2_btree_delete_range(c, BTREE_ID_stripes,
675                                        POS(0, idx),
676                                        POS(0, idx + 1),
677                                        NULL);
678 }
679
680 static void ec_stripe_delete_work(struct work_struct *work)
681 {
682         struct bch_fs *c =
683                 container_of(work, struct bch_fs, ec_stripe_delete_work);
684         ssize_t idx;
685
686         while (1) {
687                 spin_lock(&c->ec_stripes_heap_lock);
688                 idx = stripe_idx_to_delete(c);
689                 if (idx < 0) {
690                         spin_unlock(&c->ec_stripes_heap_lock);
691                         break;
692                 }
693
694                 bch2_stripes_heap_del(c, genradix_ptr(&c->stripes[0], idx), idx);
695                 spin_unlock(&c->ec_stripes_heap_lock);
696
697                 if (ec_stripe_delete(c, idx))
698                         break;
699         }
700 }
701
702 /* stripe creation: */
703
704 static int ec_stripe_bkey_insert(struct bch_fs *c,
705                                  struct bkey_i_stripe *stripe,
706                                  struct disk_reservation *res)
707 {
708         struct btree_trans trans;
709         struct btree_iter iter;
710         struct bkey_s_c k;
711         struct bpos min_pos = POS(0, 1);
712         struct bpos start_pos = bpos_max(min_pos, POS(0, c->ec_stripe_hint));
713         int ret;
714
715         bch2_trans_init(&trans, c, 0, 0);
716 retry:
717         bch2_trans_begin(&trans);
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                 bch2_trans_commit(&trans, res, NULL,
748                                 BTREE_INSERT_NOFAIL);
749 err:
750         bch2_trans_iter_exit(&trans, &iter);
751
752         if (ret == -EINTR)
753                 goto retry;
754
755         c->ec_stripe_hint = ret ? start_pos.offset : start_pos.offset + 1;
756         bch2_trans_exit(&trans);
757
758         return ret;
759 }
760
761 static int ec_stripe_bkey_update(struct btree_trans *trans,
762                                  struct bkey_i_stripe *new)
763 {
764         struct btree_iter iter;
765         struct bkey_s_c k;
766         const struct bch_stripe *existing;
767         unsigned i;
768         int ret;
769
770         bch2_trans_iter_init(trans, &iter, BTREE_ID_stripes,
771                              new->k.p, BTREE_ITER_INTENT);
772         k = bch2_btree_iter_peek_slot(&iter);
773         ret = bkey_err(k);
774         if (ret)
775                 goto err;
776
777         if (!k.k || k.k->type != KEY_TYPE_stripe) {
778                 bch_err(trans->c, "error updating stripe: not found");
779                 ret = -ENOENT;
780                 goto err;
781         }
782
783         existing = bkey_s_c_to_stripe(k).v;
784
785         if (existing->nr_blocks != new->v.nr_blocks) {
786                 bch_err(trans->c, "error updating stripe: nr_blocks does not match");
787                 ret = -EINVAL;
788                 goto err;
789         }
790
791         for (i = 0; i < new->v.nr_blocks; i++)
792                 stripe_blockcount_set(&new->v, i,
793                         stripe_blockcount_get(existing, i));
794
795         ret = bch2_trans_update(trans, &iter, &new->k_i, 0);
796 err:
797         bch2_trans_iter_exit(trans, &iter);
798         return ret;
799 }
800
801 static void extent_stripe_ptr_add(struct bkey_s_extent e,
802                                   struct ec_stripe_buf *s,
803                                   struct bch_extent_ptr *ptr,
804                                   unsigned block)
805 {
806         struct bch_extent_stripe_ptr *dst = (void *) ptr;
807         union bch_extent_entry *end = extent_entry_last(e);
808
809         memmove_u64s_up(dst + 1, dst, (u64 *) end - (u64 *) dst);
810         e.k->u64s += sizeof(*dst) / sizeof(u64);
811
812         *dst = (struct bch_extent_stripe_ptr) {
813                 .type = 1 << BCH_EXTENT_ENTRY_stripe_ptr,
814                 .block          = block,
815                 .redundancy     = s->key.v.nr_redundant,
816                 .idx            = s->key.k.p.offset,
817         };
818 }
819
820 static int ec_stripe_update_ptrs(struct bch_fs *c,
821                                  struct ec_stripe_buf *s,
822                                  struct bkey *pos)
823 {
824         struct btree_trans trans;
825         struct btree_iter iter;
826         struct bkey_s_c k;
827         struct bkey_s_extent e;
828         struct bkey_buf sk;
829         struct bpos next_pos;
830         int ret = 0, dev, block;
831
832         bch2_bkey_buf_init(&sk);
833         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
834
835         /* XXX this doesn't support the reflink btree */
836
837         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
838                              bkey_start_pos(pos),
839                              BTREE_ITER_INTENT);
840 retry:
841         while (bch2_trans_begin(&trans),
842                (k = bch2_btree_iter_peek(&iter)).k &&
843                !(ret = bkey_err(k)) &&
844                bkey_cmp(bkey_start_pos(k.k), pos->p) < 0) {
845                 struct bch_extent_ptr *ptr, *ec_ptr = NULL;
846
847                 if (extent_has_stripe_ptr(k, s->key.k.p.offset)) {
848                         bch2_btree_iter_advance(&iter);
849                         continue;
850                 }
851
852                 block = bkey_matches_stripe(&s->key.v, k);
853                 if (block < 0) {
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 = s->have_existing_stripe
950                 ? bch2_trans_do(c, &s->res, NULL, BTREE_INSERT_NOFAIL,
951                                 ec_stripe_bkey_update(&trans, &s->new_stripe.key))
952                 : ec_stripe_bkey_insert(c, &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[0], 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->ptr.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->sb.encoded_extent_max);
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 enum bucket_alloc_ret
1276 new_stripe_alloc_buckets(struct bch_fs *c, struct ec_stripe_head *h,
1277                          struct closure *cl)
1278 {
1279         struct bch_devs_mask devs = h->devs;
1280         struct open_bucket *ob;
1281         struct open_buckets buckets;
1282         unsigned i, j, nr_have_parity = 0, nr_have_data = 0;
1283         bool have_cache = true;
1284         enum bucket_alloc_ret ret = ALLOC_SUCCESS;
1285
1286         for (i = 0; i < h->s->new_stripe.key.v.nr_blocks; i++) {
1287                 if (test_bit(i, h->s->blocks_gotten)) {
1288                         __clear_bit(h->s->new_stripe.key.v.ptrs[i].dev, devs.d);
1289                         if (i < h->s->nr_data)
1290                                 nr_have_data++;
1291                         else
1292                                 nr_have_parity++;
1293                 }
1294         }
1295
1296         BUG_ON(nr_have_data     > h->s->nr_data);
1297         BUG_ON(nr_have_parity   > h->s->nr_parity);
1298
1299         percpu_down_read(&c->mark_lock);
1300         rcu_read_lock();
1301
1302         buckets.nr = 0;
1303         if (nr_have_parity < h->s->nr_parity) {
1304                 ret = bch2_bucket_alloc_set(c, &buckets,
1305                                             &h->parity_stripe,
1306                                             &devs,
1307                                             h->s->nr_parity,
1308                                             &nr_have_parity,
1309                                             &have_cache,
1310                                             h->copygc
1311                                             ? RESERVE_MOVINGGC
1312                                             : RESERVE_NONE,
1313                                             0,
1314                                             cl);
1315
1316                 open_bucket_for_each(c, &buckets, ob, i) {
1317                         j = find_next_zero_bit(h->s->blocks_gotten,
1318                                                h->s->nr_data + h->s->nr_parity,
1319                                                h->s->nr_data);
1320                         BUG_ON(j >= h->s->nr_data + h->s->nr_parity);
1321
1322                         h->s->blocks[j] = buckets.v[i];
1323                         h->s->new_stripe.key.v.ptrs[j] = ob->ptr;
1324                         __set_bit(j, h->s->blocks_gotten);
1325                 }
1326
1327                 if (ret)
1328                         goto err;
1329         }
1330
1331         buckets.nr = 0;
1332         if (nr_have_data < h->s->nr_data) {
1333                 ret = bch2_bucket_alloc_set(c, &buckets,
1334                                             &h->block_stripe,
1335                                             &devs,
1336                                             h->s->nr_data,
1337                                             &nr_have_data,
1338                                             &have_cache,
1339                                             h->copygc
1340                                             ? RESERVE_MOVINGGC
1341                                             : RESERVE_NONE,
1342                                             0,
1343                                             cl);
1344
1345                 open_bucket_for_each(c, &buckets, ob, i) {
1346                         j = find_next_zero_bit(h->s->blocks_gotten,
1347                                                h->s->nr_data, 0);
1348                         BUG_ON(j >= h->s->nr_data);
1349
1350                         h->s->blocks[j] = buckets.v[i];
1351                         h->s->new_stripe.key.v.ptrs[j] = ob->ptr;
1352                         __set_bit(j, h->s->blocks_gotten);
1353                 }
1354
1355                 if (ret)
1356                         goto err;
1357         }
1358 err:
1359         rcu_read_unlock();
1360         percpu_up_read(&c->mark_lock);
1361         return ret;
1362 }
1363
1364 /* XXX: doesn't obey target: */
1365 static s64 get_existing_stripe(struct bch_fs *c,
1366                                struct ec_stripe_head *head)
1367 {
1368         ec_stripes_heap *h = &c->ec_stripes_heap;
1369         struct stripe *m;
1370         size_t heap_idx;
1371         u64 stripe_idx;
1372         s64 ret = -1;
1373
1374         if (may_create_new_stripe(c))
1375                 return -1;
1376
1377         spin_lock(&c->ec_stripes_heap_lock);
1378         for (heap_idx = 0; heap_idx < h->used; heap_idx++) {
1379                 /* No blocks worth reusing, stripe will just be deleted: */
1380                 if (!h->data[heap_idx].blocks_nonempty)
1381                         continue;
1382
1383                 stripe_idx = h->data[heap_idx].idx;
1384                 m = genradix_ptr(&c->stripes[0], stripe_idx);
1385
1386                 if (m->algorithm        == head->algo &&
1387                     m->nr_redundant     == head->redundancy &&
1388                     m->sectors          == head->blocksize &&
1389                     m->blocks_nonempty  < m->nr_blocks - m->nr_redundant) {
1390                         bch2_stripes_heap_del(c, m, stripe_idx);
1391                         ret = stripe_idx;
1392                         break;
1393                 }
1394         }
1395         spin_unlock(&c->ec_stripes_heap_lock);
1396         return ret;
1397 }
1398
1399 static int __bch2_ec_stripe_head_reuse(struct bch_fs *c,
1400                                                    struct ec_stripe_head *h)
1401 {
1402         unsigned i;
1403         s64 idx;
1404         int ret;
1405
1406         idx = get_existing_stripe(c, h);
1407         if (idx < 0) {
1408                 bch_err(c, "failed to find an existing stripe");
1409                 return -ENOSPC;
1410         }
1411
1412         h->s->have_existing_stripe = true;
1413         ret = get_stripe_key(c, idx, &h->s->existing_stripe);
1414         if (ret) {
1415                 bch2_fs_fatal_error(c, "error reading stripe key: %i", ret);
1416                 return ret;
1417         }
1418
1419         if (ec_stripe_buf_init(&h->s->existing_stripe, 0, h->blocksize)) {
1420                 /*
1421                  * this is a problem: we have deleted from the
1422                  * stripes heap already
1423                  */
1424                 BUG();
1425         }
1426
1427         BUG_ON(h->s->existing_stripe.size != h->blocksize);
1428         BUG_ON(h->s->existing_stripe.size != h->s->existing_stripe.key.v.sectors);
1429
1430         for (i = 0; i < h->s->existing_stripe.key.v.nr_blocks; i++) {
1431                 if (stripe_blockcount_get(&h->s->existing_stripe.key.v, i)) {
1432                         __set_bit(i, h->s->blocks_gotten);
1433                         __set_bit(i, h->s->blocks_allocated);
1434                 }
1435
1436                 ec_block_io(c, &h->s->existing_stripe, READ, i, &h->s->iodone);
1437         }
1438
1439         bkey_copy(&h->s->new_stripe.key.k_i,
1440                         &h->s->existing_stripe.key.k_i);
1441
1442         return 0;
1443 }
1444
1445 static int __bch2_ec_stripe_head_reserve(struct bch_fs *c,
1446                                                         struct ec_stripe_head *h)
1447 {
1448         int ret;
1449
1450         ret = bch2_disk_reservation_get(c, &h->s->res,
1451                         h->blocksize,
1452                         h->s->nr_parity, 0);
1453
1454         if (ret) {
1455                 /*
1456                  * This means we need to wait for copygc to
1457                  * empty out buckets from existing stripes:
1458                  */
1459                 bch_err(c, "failed to reserve stripe");
1460         }
1461
1462         return ret;
1463 }
1464
1465 struct ec_stripe_head *bch2_ec_stripe_head_get(struct bch_fs *c,
1466                                                unsigned target,
1467                                                unsigned algo,
1468                                                unsigned redundancy,
1469                                                bool copygc,
1470                                                struct closure *cl)
1471 {
1472         struct ec_stripe_head *h;
1473         int ret;
1474         bool needs_stripe_new;
1475
1476         h = __bch2_ec_stripe_head_get(c, target, algo, redundancy, copygc);
1477         if (!h) {
1478                 bch_err(c, "no stripe head");
1479                 return NULL;
1480         }
1481
1482         needs_stripe_new = !h->s;
1483         if (needs_stripe_new) {
1484                 if (ec_new_stripe_alloc(c, h)) {
1485                         ret = -ENOMEM;
1486                         bch_err(c, "failed to allocate new stripe");
1487                         goto err;
1488                 }
1489
1490                 if (ec_stripe_buf_init(&h->s->new_stripe, 0, h->blocksize))
1491                         BUG();
1492         }
1493
1494         /*
1495          * Try reserve a new stripe before reusing an
1496          * existing stripe. This will prevent unnecessary
1497          * read amplification during write oriented workloads.
1498          */
1499         ret = 0;
1500         if (!h->s->allocated && !h->s->res.sectors && !h->s->have_existing_stripe)
1501                 ret = __bch2_ec_stripe_head_reserve(c, h);
1502         if (ret && needs_stripe_new)
1503                 ret = __bch2_ec_stripe_head_reuse(c, h);
1504         if (ret)
1505                 goto err;
1506
1507         if (!h->s->allocated) {
1508                 ret = new_stripe_alloc_buckets(c, h, cl);
1509                 if (ret)
1510                         goto err;
1511
1512                 h->s->allocated = true;
1513         }
1514
1515         return h;
1516
1517 err:
1518         bch2_ec_stripe_head_put(c, h);
1519         return ERR_PTR(-ret);
1520 }
1521
1522 void bch2_ec_stop_dev(struct bch_fs *c, struct bch_dev *ca)
1523 {
1524         struct ec_stripe_head *h;
1525         struct open_bucket *ob;
1526         unsigned i;
1527
1528         mutex_lock(&c->ec_stripe_head_lock);
1529         list_for_each_entry(h, &c->ec_stripe_head_list, list) {
1530
1531                 mutex_lock(&h->lock);
1532                 if (!h->s)
1533                         goto unlock;
1534
1535                 for (i = 0; i < h->s->new_stripe.key.v.nr_blocks; i++) {
1536                         if (!h->s->blocks[i])
1537                                 continue;
1538
1539                         ob = c->open_buckets + h->s->blocks[i];
1540                         if (ob->ptr.dev == ca->dev_idx)
1541                                 goto found;
1542                 }
1543                 goto unlock;
1544 found:
1545                 h->s->err = -EROFS;
1546                 ec_stripe_set_pending(c, h);
1547 unlock:
1548                 mutex_unlock(&h->lock);
1549         }
1550         mutex_unlock(&c->ec_stripe_head_lock);
1551 }
1552
1553 void bch2_stripes_heap_start(struct bch_fs *c)
1554 {
1555         struct genradix_iter iter;
1556         struct stripe *m;
1557
1558         genradix_for_each(&c->stripes[0], iter, m)
1559                 if (m->alive)
1560                         bch2_stripes_heap_insert(c, m, iter.pos);
1561 }
1562
1563 static int __bch2_stripe_write_key(struct btree_trans *trans,
1564                                    struct btree_iter *iter,
1565                                    struct stripe *m,
1566                                    size_t idx,
1567                                    struct bkey_i_stripe *new_key)
1568 {
1569         const struct bch_stripe *v;
1570         struct bkey_s_c k;
1571         unsigned i;
1572         int ret;
1573
1574         bch2_btree_iter_set_pos(iter, POS(0, idx));
1575
1576         k = bch2_btree_iter_peek_slot(iter);
1577         ret = bkey_err(k);
1578         if (ret)
1579                 return ret;
1580
1581         if (k.k->type != KEY_TYPE_stripe)
1582                 return -EIO;
1583
1584         v = bkey_s_c_to_stripe(k).v;
1585         for (i = 0; i < v->nr_blocks; i++)
1586                 if (m->block_sectors[i] != stripe_blockcount_get(v, i))
1587                         goto write;
1588         return 0;
1589 write:
1590         bkey_reassemble(&new_key->k_i, k);
1591
1592         for (i = 0; i < new_key->v.nr_blocks; i++)
1593                 stripe_blockcount_set(&new_key->v, i,
1594                                       m->block_sectors[i]);
1595
1596         return bch2_trans_update(trans, iter, &new_key->k_i, 0);
1597 }
1598
1599 int bch2_stripes_write(struct bch_fs *c, unsigned flags)
1600 {
1601         struct btree_trans trans;
1602         struct btree_iter iter;
1603         struct genradix_iter giter;
1604         struct bkey_i_stripe *new_key;
1605         struct stripe *m;
1606         int ret = 0;
1607
1608         new_key = kmalloc(255 * sizeof(u64), GFP_KERNEL);
1609         BUG_ON(!new_key);
1610
1611         bch2_trans_init(&trans, c, 0, 0);
1612
1613         bch2_trans_iter_init(&trans, &iter, BTREE_ID_stripes, POS_MIN,
1614                              BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1615
1616         genradix_for_each(&c->stripes[0], giter, m) {
1617                 if (!m->alive)
1618                         continue;
1619
1620                 ret = __bch2_trans_do(&trans, NULL, NULL,
1621                                       BTREE_INSERT_NOFAIL|flags,
1622                         __bch2_stripe_write_key(&trans, &iter, m,
1623                                         giter.pos, new_key));
1624
1625                 if (ret)
1626                         break;
1627         }
1628         bch2_trans_iter_exit(&trans, &iter);
1629
1630         bch2_trans_exit(&trans);
1631
1632         kfree(new_key);
1633
1634         return ret;
1635 }
1636
1637 static int bch2_stripes_read_fn(struct btree_trans *trans, struct bkey_s_c k)
1638 {
1639         struct bch_fs *c = trans->c;
1640         int ret = 0;
1641
1642         if (k.k->type == KEY_TYPE_stripe)
1643                 ret = __ec_stripe_mem_alloc(c, k.k->p.offset, GFP_KERNEL) ?:
1644                         bch2_mark_key(trans, k,
1645                                       BTREE_TRIGGER_NOATOMIC);
1646
1647         return ret;
1648 }
1649
1650 int bch2_stripes_read(struct bch_fs *c)
1651 {
1652         struct btree_trans trans;
1653         int ret;
1654
1655         bch2_trans_init(&trans, c, 0, 0);
1656         ret = bch2_btree_and_journal_walk(&trans, BTREE_ID_stripes,
1657                                           bch2_stripes_read_fn);
1658         bch2_trans_exit(&trans);
1659         if (ret)
1660                 bch_err(c, "error reading stripes: %i", ret);
1661
1662         return ret;
1663 }
1664
1665 int bch2_ec_mem_alloc(struct bch_fs *c, bool gc)
1666 {
1667         struct btree_trans trans;
1668         struct btree_iter iter;
1669         struct bkey_s_c k;
1670         size_t i, idx = 0;
1671         int ret = 0;
1672
1673         bch2_trans_init(&trans, c, 0, 0);
1674         bch2_trans_iter_init(&trans, &iter, BTREE_ID_stripes, POS(0, U64_MAX), 0);
1675
1676         k = bch2_btree_iter_prev(&iter);
1677         ret = bkey_err(k);
1678         if (!ret && k.k)
1679                 idx = k.k->p.offset + 1;
1680
1681         bch2_trans_iter_exit(&trans, &iter);
1682         bch2_trans_exit(&trans);
1683         if (ret)
1684                 return ret;
1685
1686         if (!idx)
1687                 return 0;
1688
1689         if (!gc &&
1690             !init_heap(&c->ec_stripes_heap, roundup_pow_of_two(idx),
1691                        GFP_KERNEL))
1692                 return -ENOMEM;
1693 #if 0
1694         ret = genradix_prealloc(&c->stripes[gc], idx, GFP_KERNEL);
1695 #else
1696         for (i = 0; i < idx; i++)
1697                 if (!genradix_ptr_alloc(&c->stripes[gc], i, GFP_KERNEL))
1698                         return -ENOMEM;
1699 #endif
1700         return 0;
1701 }
1702
1703 void bch2_stripes_heap_to_text(struct printbuf *out, struct bch_fs *c)
1704 {
1705         ec_stripes_heap *h = &c->ec_stripes_heap;
1706         struct stripe *m;
1707         size_t i;
1708
1709         spin_lock(&c->ec_stripes_heap_lock);
1710         for (i = 0; i < min_t(size_t, h->used, 20); i++) {
1711                 m = genradix_ptr(&c->stripes[0], h->data[i].idx);
1712
1713                 pr_buf(out, "%zu %u/%u+%u\n", h->data[i].idx,
1714                        h->data[i].blocks_nonempty,
1715                        m->nr_blocks - m->nr_redundant,
1716                        m->nr_redundant);
1717         }
1718         spin_unlock(&c->ec_stripes_heap_lock);
1719 }
1720
1721 void bch2_new_stripes_to_text(struct printbuf *out, struct bch_fs *c)
1722 {
1723         struct ec_stripe_head *h;
1724         struct ec_stripe_new *s;
1725
1726         mutex_lock(&c->ec_stripe_head_lock);
1727         list_for_each_entry(h, &c->ec_stripe_head_list, list) {
1728                 pr_buf(out, "target %u algo %u redundancy %u:\n",
1729                        h->target, h->algo, h->redundancy);
1730
1731                 if (h->s)
1732                         pr_buf(out, "\tpending: blocks %u+%u allocated %u\n",
1733                                h->s->nr_data, h->s->nr_parity,
1734                                bitmap_weight(h->s->blocks_allocated,
1735                                              h->s->nr_data));
1736         }
1737         mutex_unlock(&c->ec_stripe_head_lock);
1738
1739         mutex_lock(&c->ec_stripe_new_lock);
1740         list_for_each_entry(s, &c->ec_stripe_new_list, list) {
1741                 pr_buf(out, "\tin flight: blocks %u+%u pin %u\n",
1742                        s->nr_data, s->nr_parity,
1743                        atomic_read(&s->pin));
1744         }
1745         mutex_unlock(&c->ec_stripe_new_lock);
1746 }
1747
1748 void bch2_fs_ec_exit(struct bch_fs *c)
1749 {
1750         struct ec_stripe_head *h;
1751
1752         while (1) {
1753                 mutex_lock(&c->ec_stripe_head_lock);
1754                 h = list_first_entry_or_null(&c->ec_stripe_head_list,
1755                                              struct ec_stripe_head, list);
1756                 if (h)
1757                         list_del(&h->list);
1758                 mutex_unlock(&c->ec_stripe_head_lock);
1759                 if (!h)
1760                         break;
1761
1762                 BUG_ON(h->s);
1763                 kfree(h);
1764         }
1765
1766         BUG_ON(!list_empty(&c->ec_stripe_new_list));
1767
1768         free_heap(&c->ec_stripes_heap);
1769         genradix_free(&c->stripes[0]);
1770         bioset_exit(&c->ec_bioset);
1771 }
1772
1773 int bch2_fs_ec_init(struct bch_fs *c)
1774 {
1775         INIT_WORK(&c->ec_stripe_create_work, ec_stripe_create_work);
1776         INIT_WORK(&c->ec_stripe_delete_work, ec_stripe_delete_work);
1777
1778         return bioset_init(&c->ec_bioset, 1, offsetof(struct ec_bio, bio),
1779                            BIOSET_NEED_BVECS);
1780 }