]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/ec.c
Update bcachefs sources to 0a9f0fc68a bcachefs: Don't unconditially version_upgrade...
[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_PAGES,
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         iter = bch2_trans_get_iter(&trans, BTREE_ID_stripes, POS(0, idx), BTREE_ITER_SLOTS);
438         k = bch2_btree_iter_peek_slot(iter);
439         ret = bkey_err(k);
440         if (ret)
441                 goto err;
442         if (k.k->type != KEY_TYPE_stripe) {
443                 ret = -ENOENT;
444                 goto err;
445         }
446         bkey_reassemble(&stripe->key.k_i, k);
447 err:
448         bch2_trans_exit(&trans);
449         return ret;
450 }
451
452 /* recovery read path: */
453 int bch2_ec_read_extent(struct bch_fs *c, struct bch_read_bio *rbio)
454 {
455         struct ec_stripe_buf *buf;
456         struct closure cl;
457         struct bch_stripe *v;
458         unsigned i, offset;
459         int ret = 0;
460
461         closure_init_stack(&cl);
462
463         BUG_ON(!rbio->pick.has_ec);
464
465         buf = kzalloc(sizeof(*buf), GFP_NOIO);
466         if (!buf)
467                 return -ENOMEM;
468
469         ret = get_stripe_key(c, rbio->pick.ec.idx, buf);
470         if (ret) {
471                 bch_err_ratelimited(c,
472                         "error doing reconstruct read: error %i looking up stripe", ret);
473                 kfree(buf);
474                 return -EIO;
475         }
476
477         v = &buf->key.v;
478
479         if (!bch2_ptr_matches_stripe(v, rbio->pick)) {
480                 bch_err_ratelimited(c,
481                         "error doing reconstruct read: pointer doesn't match stripe");
482                 ret = -EIO;
483                 goto err;
484         }
485
486         offset = rbio->bio.bi_iter.bi_sector - v->ptrs[rbio->pick.ec.block].offset;
487         if (offset + bio_sectors(&rbio->bio) > le16_to_cpu(v->sectors)) {
488                 bch_err_ratelimited(c,
489                         "error doing reconstruct read: read is bigger than stripe");
490                 ret = -EIO;
491                 goto err;
492         }
493
494         ret = ec_stripe_buf_init(buf, offset, bio_sectors(&rbio->bio));
495         if (ret)
496                 goto err;
497
498         for (i = 0; i < v->nr_blocks; i++)
499                 ec_block_io(c, buf, REQ_OP_READ, i, &cl);
500
501         closure_sync(&cl);
502
503         if (ec_nr_failed(buf) > v->nr_redundant) {
504                 bch_err_ratelimited(c,
505                         "error doing reconstruct read: unable to read enough blocks");
506                 ret = -EIO;
507                 goto err;
508         }
509
510         ec_validate_checksums(c, buf);
511
512         ret = ec_do_recov(c, buf);
513         if (ret)
514                 goto err;
515
516         memcpy_to_bio(&rbio->bio, rbio->bio.bi_iter,
517                       buf->data[rbio->pick.ec.block] + ((offset - buf->offset) << 9));
518 err:
519         ec_stripe_buf_exit(buf);
520         kfree(buf);
521         return ret;
522 }
523
524 /* stripe bucket accounting: */
525
526 static int __ec_stripe_mem_alloc(struct bch_fs *c, size_t idx, gfp_t gfp)
527 {
528         ec_stripes_heap n, *h = &c->ec_stripes_heap;
529
530         if (idx >= h->size) {
531                 if (!init_heap(&n, max(1024UL, roundup_pow_of_two(idx + 1)), gfp))
532                         return -ENOMEM;
533
534                 spin_lock(&c->ec_stripes_heap_lock);
535                 if (n.size > h->size) {
536                         memcpy(n.data, h->data, h->used * sizeof(h->data[0]));
537                         n.used = h->used;
538                         swap(*h, n);
539                 }
540                 spin_unlock(&c->ec_stripes_heap_lock);
541
542                 free_heap(&n);
543         }
544
545         if (!genradix_ptr_alloc(&c->stripes[0], idx, gfp))
546                 return -ENOMEM;
547
548         if (c->gc_pos.phase != GC_PHASE_NOT_RUNNING &&
549             !genradix_ptr_alloc(&c->stripes[1], idx, gfp))
550                 return -ENOMEM;
551
552         return 0;
553 }
554
555 static int ec_stripe_mem_alloc(struct bch_fs *c,
556                                struct btree_iter *iter)
557 {
558         size_t idx = iter->pos.offset;
559         int ret = 0;
560
561         if (!__ec_stripe_mem_alloc(c, idx, GFP_NOWAIT|__GFP_NOWARN))
562                 return ret;
563
564         bch2_trans_unlock(iter->trans);
565         ret = -EINTR;
566
567         if (!__ec_stripe_mem_alloc(c, idx, GFP_KERNEL))
568                 return ret;
569
570         return -ENOMEM;
571 }
572
573 static ssize_t stripe_idx_to_delete(struct bch_fs *c)
574 {
575         ec_stripes_heap *h = &c->ec_stripes_heap;
576
577         return h->used && h->data[0].blocks_nonempty == 0
578                 ? h->data[0].idx : -1;
579 }
580
581 static inline int ec_stripes_heap_cmp(ec_stripes_heap *h,
582                                       struct ec_stripe_heap_entry l,
583                                       struct ec_stripe_heap_entry r)
584 {
585         return ((l.blocks_nonempty > r.blocks_nonempty) -
586                 (l.blocks_nonempty < r.blocks_nonempty));
587 }
588
589 static inline void ec_stripes_heap_set_backpointer(ec_stripes_heap *h,
590                                                    size_t i)
591 {
592         struct bch_fs *c = container_of(h, struct bch_fs, ec_stripes_heap);
593
594         genradix_ptr(&c->stripes[0], h->data[i].idx)->heap_idx = i;
595 }
596
597 static void heap_verify_backpointer(struct bch_fs *c, size_t idx)
598 {
599         ec_stripes_heap *h = &c->ec_stripes_heap;
600         struct stripe *m = genradix_ptr(&c->stripes[0], idx);
601
602         BUG_ON(!m->alive);
603         BUG_ON(m->heap_idx >= h->used);
604         BUG_ON(h->data[m->heap_idx].idx != idx);
605 }
606
607 void bch2_stripes_heap_del(struct bch_fs *c,
608                            struct stripe *m, size_t idx)
609 {
610         if (!m->on_heap)
611                 return;
612
613         m->on_heap = false;
614
615         heap_verify_backpointer(c, idx);
616
617         heap_del(&c->ec_stripes_heap, m->heap_idx,
618                  ec_stripes_heap_cmp,
619                  ec_stripes_heap_set_backpointer);
620 }
621
622 void bch2_stripes_heap_insert(struct bch_fs *c,
623                               struct stripe *m, size_t idx)
624 {
625         if (m->on_heap)
626                 return;
627
628         BUG_ON(heap_full(&c->ec_stripes_heap));
629
630         m->on_heap = true;
631
632         heap_add(&c->ec_stripes_heap, ((struct ec_stripe_heap_entry) {
633                         .idx = idx,
634                         .blocks_nonempty = m->blocks_nonempty,
635                 }),
636                  ec_stripes_heap_cmp,
637                  ec_stripes_heap_set_backpointer);
638
639         heap_verify_backpointer(c, idx);
640 }
641
642 void bch2_stripes_heap_update(struct bch_fs *c,
643                               struct stripe *m, size_t idx)
644 {
645         ec_stripes_heap *h = &c->ec_stripes_heap;
646         size_t i;
647
648         if (!m->on_heap)
649                 return;
650
651         heap_verify_backpointer(c, idx);
652
653         h->data[m->heap_idx].blocks_nonempty = m->blocks_nonempty;
654
655         i = m->heap_idx;
656         heap_sift_up(h,   i, ec_stripes_heap_cmp,
657                      ec_stripes_heap_set_backpointer);
658         heap_sift_down(h, i, ec_stripes_heap_cmp,
659                        ec_stripes_heap_set_backpointer);
660
661         heap_verify_backpointer(c, idx);
662
663         if (stripe_idx_to_delete(c) >= 0 &&
664             !percpu_ref_is_dying(&c->writes))
665                 schedule_work(&c->ec_stripe_delete_work);
666 }
667
668 /* stripe deletion */
669
670 static int ec_stripe_delete(struct bch_fs *c, size_t idx)
671 {
672         return bch2_btree_delete_range(c, BTREE_ID_stripes,
673                                        POS(0, idx),
674                                        POS(0, idx + 1),
675                                        NULL);
676 }
677
678 static void ec_stripe_delete_work(struct work_struct *work)
679 {
680         struct bch_fs *c =
681                 container_of(work, struct bch_fs, ec_stripe_delete_work);
682         ssize_t idx;
683
684         while (1) {
685                 spin_lock(&c->ec_stripes_heap_lock);
686                 idx = stripe_idx_to_delete(c);
687                 if (idx < 0) {
688                         spin_unlock(&c->ec_stripes_heap_lock);
689                         break;
690                 }
691
692                 bch2_stripes_heap_del(c, genradix_ptr(&c->stripes[0], idx), idx);
693                 spin_unlock(&c->ec_stripes_heap_lock);
694
695                 if (ec_stripe_delete(c, idx))
696                         break;
697         }
698 }
699
700 /* stripe creation: */
701
702 static int ec_stripe_bkey_insert(struct bch_fs *c,
703                                  struct bkey_i_stripe *stripe,
704                                  struct disk_reservation *res)
705 {
706         struct btree_trans trans;
707         struct btree_iter *iter;
708         struct bkey_s_c k;
709         struct bpos min_pos = POS(0, 1);
710         struct bpos start_pos = bpos_max(min_pos, POS(0, c->ec_stripe_hint));
711         int ret;
712
713         bch2_trans_init(&trans, c, 0, 0);
714 retry:
715         bch2_trans_begin(&trans);
716
717         for_each_btree_key(&trans, iter, BTREE_ID_stripes, start_pos,
718                            BTREE_ITER_SLOTS|BTREE_ITER_INTENT, k, ret) {
719                 if (bkey_cmp(k.k->p, POS(0, U32_MAX)) > 0) {
720                         if (start_pos.offset) {
721                                 start_pos = min_pos;
722                                 bch2_btree_iter_set_pos(iter, start_pos);
723                                 continue;
724                         }
725
726                         ret = -ENOSPC;
727                         break;
728                 }
729
730                 if (bkey_deleted(k.k))
731                         goto found_slot;
732         }
733
734         goto err;
735 found_slot:
736         start_pos = iter->pos;
737
738         ret = ec_stripe_mem_alloc(c, iter);
739         if (ret)
740                 goto err;
741
742         stripe->k.p = iter->pos;
743
744         bch2_trans_update(&trans, iter, &stripe->k_i, 0);
745
746         ret = bch2_trans_commit(&trans, res, NULL,
747                                 BTREE_INSERT_NOFAIL);
748 err:
749         bch2_trans_iter_put(&trans, iter);
750
751         if (ret == -EINTR)
752                 goto retry;
753
754         c->ec_stripe_hint = ret ? start_pos.offset : start_pos.offset + 1;
755         bch2_trans_exit(&trans);
756
757         return ret;
758 }
759
760 static int ec_stripe_bkey_update(struct btree_trans *trans,
761                                  struct bkey_i_stripe *new)
762 {
763         struct btree_iter *iter;
764         struct bkey_s_c k;
765         const struct bch_stripe *existing;
766         unsigned i;
767         int ret;
768
769         iter = bch2_trans_get_iter(trans, BTREE_ID_stripes,
770                                    new->k.p, BTREE_ITER_INTENT);
771         k = bch2_btree_iter_peek_slot(iter);
772         ret = bkey_err(k);
773         if (ret)
774                 goto err;
775
776         if (!k.k || k.k->type != KEY_TYPE_stripe) {
777                 bch_err(trans->c, "error updating stripe: not found");
778                 ret = -ENOENT;
779                 goto err;
780         }
781
782         existing = bkey_s_c_to_stripe(k).v;
783
784         if (existing->nr_blocks != new->v.nr_blocks) {
785                 bch_err(trans->c, "error updating stripe: nr_blocks does not match");
786                 ret = -EINVAL;
787                 goto err;
788         }
789
790         for (i = 0; i < new->v.nr_blocks; i++)
791                 stripe_blockcount_set(&new->v, i,
792                         stripe_blockcount_get(existing, i));
793
794         bch2_trans_update(trans, iter, &new->k_i, 0);
795 err:
796         bch2_trans_iter_put(trans, iter);
797         return ret;
798 }
799
800 static void extent_stripe_ptr_add(struct bkey_s_extent e,
801                                   struct ec_stripe_buf *s,
802                                   struct bch_extent_ptr *ptr,
803                                   unsigned block)
804 {
805         struct bch_extent_stripe_ptr *dst = (void *) ptr;
806         union bch_extent_entry *end = extent_entry_last(e);
807
808         memmove_u64s_up(dst + 1, dst, (u64 *) end - (u64 *) dst);
809         e.k->u64s += sizeof(*dst) / sizeof(u64);
810
811         *dst = (struct bch_extent_stripe_ptr) {
812                 .type = 1 << BCH_EXTENT_ENTRY_stripe_ptr,
813                 .block          = block,
814                 .redundancy     = s->key.v.nr_redundant,
815                 .idx            = s->key.k.p.offset,
816         };
817 }
818
819 static int ec_stripe_update_ptrs(struct bch_fs *c,
820                                  struct ec_stripe_buf *s,
821                                  struct bkey *pos)
822 {
823         struct btree_trans trans;
824         struct btree_iter *iter;
825         struct bkey_s_c k;
826         struct bkey_s_extent e;
827         struct bkey_buf sk;
828         int ret = 0, dev, block;
829
830         bch2_bkey_buf_init(&sk);
831         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
832
833         /* XXX this doesn't support the reflink btree */
834
835         iter = bch2_trans_get_iter(&trans, BTREE_ID_extents,
836                                    bkey_start_pos(pos),
837                                    BTREE_ITER_INTENT);
838
839         while ((k = bch2_btree_iter_peek(iter)).k &&
840                !(ret = bkey_err(k)) &&
841                bkey_cmp(bkey_start_pos(k.k), pos->p) < 0) {
842                 struct bch_extent_ptr *ptr, *ec_ptr = NULL;
843
844                 if (extent_has_stripe_ptr(k, s->key.k.p.offset)) {
845                         bch2_btree_iter_next(iter);
846                         continue;
847                 }
848
849                 block = bkey_matches_stripe(&s->key.v, k);
850                 if (block < 0) {
851                         bch2_btree_iter_next(iter);
852                         continue;
853                 }
854
855                 dev = s->key.v.ptrs[block].dev;
856
857                 bch2_bkey_buf_reassemble(&sk, c, k);
858                 e = bkey_i_to_s_extent(sk.k);
859
860                 bch2_bkey_drop_ptrs(e.s, ptr, ptr->dev != dev);
861                 ec_ptr = (void *) bch2_bkey_has_device(e.s_c, dev);
862                 BUG_ON(!ec_ptr);
863
864                 extent_stripe_ptr_add(e, s, ec_ptr, block);
865
866                 bch2_btree_iter_set_pos(iter, bkey_start_pos(&sk.k->k));
867                 bch2_trans_update(&trans, iter, sk.k, 0);
868
869                 ret = bch2_trans_commit(&trans, NULL, NULL,
870                                         BTREE_INSERT_NOFAIL);
871                 if (ret == -EINTR)
872                         ret = 0;
873                 if (ret)
874                         break;
875         }
876
877         bch2_trans_exit(&trans);
878         bch2_bkey_buf_exit(&sk, c);
879
880         return ret;
881 }
882
883 /*
884  * data buckets of new stripe all written: create the stripe
885  */
886 static void ec_stripe_create(struct ec_stripe_new *s)
887 {
888         struct bch_fs *c = s->c;
889         struct open_bucket *ob;
890         struct bkey_i *k;
891         struct stripe *m;
892         struct bch_stripe *v = &s->new_stripe.key.v;
893         unsigned i, nr_data = v->nr_blocks - v->nr_redundant;
894         int ret;
895
896         BUG_ON(s->h->s == s);
897
898         closure_sync(&s->iodone);
899
900         if (s->err) {
901                 if (s->err != -EROFS)
902                         bch_err(c, "error creating stripe: error writing data buckets");
903                 goto err;
904         }
905
906         if (s->have_existing_stripe) {
907                 ec_validate_checksums(c, &s->existing_stripe);
908
909                 if (ec_do_recov(c, &s->existing_stripe)) {
910                         bch_err(c, "error creating stripe: error reading existing stripe");
911                         goto err;
912                 }
913
914                 for (i = 0; i < nr_data; i++)
915                         if (stripe_blockcount_get(&s->existing_stripe.key.v, i))
916                                 swap(s->new_stripe.data[i],
917                                      s->existing_stripe.data[i]);
918
919                 ec_stripe_buf_exit(&s->existing_stripe);
920         }
921
922         BUG_ON(!s->allocated);
923
924         if (!percpu_ref_tryget(&c->writes))
925                 goto err;
926
927         ec_generate_ec(&s->new_stripe);
928
929         ec_generate_checksums(&s->new_stripe);
930
931         /* write p/q: */
932         for (i = nr_data; i < v->nr_blocks; i++)
933                 ec_block_io(c, &s->new_stripe, REQ_OP_WRITE, i, &s->iodone);
934         closure_sync(&s->iodone);
935
936         if (ec_nr_failed(&s->new_stripe)) {
937                 bch_err(c, "error creating stripe: error writing redundancy buckets");
938                 goto err_put_writes;
939         }
940
941         ret = s->have_existing_stripe
942                 ? bch2_trans_do(c, &s->res, NULL, BTREE_INSERT_NOFAIL,
943                                 ec_stripe_bkey_update(&trans, &s->new_stripe.key))
944                 : ec_stripe_bkey_insert(c, &s->new_stripe.key, &s->res);
945         if (ret) {
946                 bch_err(c, "error creating stripe: error creating stripe key");
947                 goto err_put_writes;
948         }
949
950         for_each_keylist_key(&s->keys, k) {
951                 ret = ec_stripe_update_ptrs(c, &s->new_stripe, &k->k);
952                 if (ret) {
953                         bch_err(c, "error creating stripe: error %i updating pointers", ret);
954                         break;
955                 }
956         }
957
958         spin_lock(&c->ec_stripes_heap_lock);
959         m = genradix_ptr(&c->stripes[0], s->new_stripe.key.k.p.offset);
960
961         BUG_ON(m->on_heap);
962         bch2_stripes_heap_insert(c, m, s->new_stripe.key.k.p.offset);
963         spin_unlock(&c->ec_stripes_heap_lock);
964 err_put_writes:
965         percpu_ref_put(&c->writes);
966 err:
967         bch2_disk_reservation_put(c, &s->res);
968
969         for (i = 0; i < v->nr_blocks; i++)
970                 if (s->blocks[i]) {
971                         ob = c->open_buckets + s->blocks[i];
972
973                         if (i < nr_data) {
974                                 ob->ec = NULL;
975                                 __bch2_open_bucket_put(c, ob);
976                         } else {
977                                 bch2_open_bucket_put(c, ob);
978                         }
979                 }
980
981         bch2_keylist_free(&s->keys, s->inline_keys);
982
983         ec_stripe_buf_exit(&s->existing_stripe);
984         ec_stripe_buf_exit(&s->new_stripe);
985         closure_debug_destroy(&s->iodone);
986         kfree(s);
987 }
988
989 static void ec_stripe_create_work(struct work_struct *work)
990 {
991         struct bch_fs *c = container_of(work,
992                 struct bch_fs, ec_stripe_create_work);
993         struct ec_stripe_new *s, *n;
994 restart:
995         mutex_lock(&c->ec_stripe_new_lock);
996         list_for_each_entry_safe(s, n, &c->ec_stripe_new_list, list)
997                 if (!atomic_read(&s->pin)) {
998                         list_del(&s->list);
999                         mutex_unlock(&c->ec_stripe_new_lock);
1000                         ec_stripe_create(s);
1001                         goto restart;
1002                 }
1003         mutex_unlock(&c->ec_stripe_new_lock);
1004 }
1005
1006 static void ec_stripe_new_put(struct bch_fs *c, struct ec_stripe_new *s)
1007 {
1008         BUG_ON(atomic_read(&s->pin) <= 0);
1009
1010         if (atomic_dec_and_test(&s->pin)) {
1011                 BUG_ON(!s->pending);
1012                 queue_work(system_long_wq, &c->ec_stripe_create_work);
1013         }
1014 }
1015
1016 static void ec_stripe_set_pending(struct bch_fs *c, struct ec_stripe_head *h)
1017 {
1018         struct ec_stripe_new *s = h->s;
1019
1020         BUG_ON(!s->allocated && !s->err);
1021
1022         h->s            = NULL;
1023         s->pending      = true;
1024
1025         mutex_lock(&c->ec_stripe_new_lock);
1026         list_add(&s->list, &c->ec_stripe_new_list);
1027         mutex_unlock(&c->ec_stripe_new_lock);
1028
1029         ec_stripe_new_put(c, s);
1030 }
1031
1032 /* have a full bucket - hand it off to be erasure coded: */
1033 void bch2_ec_bucket_written(struct bch_fs *c, struct open_bucket *ob)
1034 {
1035         struct ec_stripe_new *s = ob->ec;
1036
1037         if (ob->sectors_free)
1038                 s->err = -1;
1039
1040         ec_stripe_new_put(c, s);
1041 }
1042
1043 void bch2_ec_bucket_cancel(struct bch_fs *c, struct open_bucket *ob)
1044 {
1045         struct ec_stripe_new *s = ob->ec;
1046
1047         s->err = -EIO;
1048 }
1049
1050 void *bch2_writepoint_ec_buf(struct bch_fs *c, struct write_point *wp)
1051 {
1052         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
1053         struct bch_dev *ca;
1054         unsigned offset;
1055
1056         if (!ob)
1057                 return NULL;
1058
1059         ca      = bch_dev_bkey_exists(c, ob->ptr.dev);
1060         offset  = ca->mi.bucket_size - ob->sectors_free;
1061
1062         return ob->ec->new_stripe.data[ob->ec_idx] + (offset << 9);
1063 }
1064
1065 void bch2_ec_add_backpointer(struct bch_fs *c, struct write_point *wp,
1066                              struct bpos pos, unsigned sectors)
1067 {
1068         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
1069         struct ec_stripe_new *ec;
1070
1071         if (!ob)
1072                 return;
1073
1074         ec = ob->ec;
1075         mutex_lock(&ec->lock);
1076
1077         if (bch2_keylist_realloc(&ec->keys, ec->inline_keys,
1078                                  ARRAY_SIZE(ec->inline_keys),
1079                                  BKEY_U64s)) {
1080                 BUG();
1081         }
1082
1083         bkey_init(&ec->keys.top->k);
1084         ec->keys.top->k.p       = pos;
1085         bch2_key_resize(&ec->keys.top->k, sectors);
1086         bch2_keylist_push(&ec->keys);
1087
1088         mutex_unlock(&ec->lock);
1089 }
1090
1091 static int unsigned_cmp(const void *_l, const void *_r)
1092 {
1093         unsigned l = *((const unsigned *) _l);
1094         unsigned r = *((const unsigned *) _r);
1095
1096         return cmp_int(l, r);
1097 }
1098
1099 /* pick most common bucket size: */
1100 static unsigned pick_blocksize(struct bch_fs *c,
1101                                struct bch_devs_mask *devs)
1102 {
1103         struct bch_dev *ca;
1104         unsigned i, nr = 0, sizes[BCH_SB_MEMBERS_MAX];
1105         struct {
1106                 unsigned nr, size;
1107         } cur = { 0, 0 }, best = { 0, 0 };
1108
1109         for_each_member_device_rcu(ca, c, i, devs)
1110                 sizes[nr++] = ca->mi.bucket_size;
1111
1112         sort(sizes, nr, sizeof(unsigned), unsigned_cmp, NULL);
1113
1114         for (i = 0; i < nr; i++) {
1115                 if (sizes[i] != cur.size) {
1116                         if (cur.nr > best.nr)
1117                                 best = cur;
1118
1119                         cur.nr = 0;
1120                         cur.size = sizes[i];
1121                 }
1122
1123                 cur.nr++;
1124         }
1125
1126         if (cur.nr > best.nr)
1127                 best = cur;
1128
1129         return best.size;
1130 }
1131
1132 static bool may_create_new_stripe(struct bch_fs *c)
1133 {
1134         return false;
1135 }
1136
1137 static void ec_stripe_key_init(struct bch_fs *c,
1138                                struct bkey_i_stripe *s,
1139                                unsigned nr_data,
1140                                unsigned nr_parity,
1141                                unsigned stripe_size)
1142 {
1143         unsigned u64s;
1144
1145         bkey_stripe_init(&s->k_i);
1146         s->v.sectors                    = cpu_to_le16(stripe_size);
1147         s->v.algorithm                  = 0;
1148         s->v.nr_blocks                  = nr_data + nr_parity;
1149         s->v.nr_redundant               = nr_parity;
1150         s->v.csum_granularity_bits      = ilog2(c->sb.encoded_extent_max);
1151         s->v.csum_type                  = BCH_CSUM_CRC32C;
1152         s->v.pad                        = 0;
1153
1154         while ((u64s = stripe_val_u64s(&s->v)) > BKEY_VAL_U64s_MAX) {
1155                 BUG_ON(1 << s->v.csum_granularity_bits >=
1156                        le16_to_cpu(s->v.sectors) ||
1157                        s->v.csum_granularity_bits == U8_MAX);
1158                 s->v.csum_granularity_bits++;
1159         }
1160
1161         set_bkey_val_u64s(&s->k, u64s);
1162 }
1163
1164 static int ec_new_stripe_alloc(struct bch_fs *c, struct ec_stripe_head *h)
1165 {
1166         struct ec_stripe_new *s;
1167
1168         lockdep_assert_held(&h->lock);
1169
1170         s = kzalloc(sizeof(*s), GFP_KERNEL);
1171         if (!s)
1172                 return -ENOMEM;
1173
1174         mutex_init(&s->lock);
1175         closure_init(&s->iodone, NULL);
1176         atomic_set(&s->pin, 1);
1177         s->c            = c;
1178         s->h            = h;
1179         s->nr_data      = min_t(unsigned, h->nr_active_devs,
1180                                 BCH_BKEY_PTRS_MAX) - h->redundancy;
1181         s->nr_parity    = h->redundancy;
1182
1183         bch2_keylist_init(&s->keys, s->inline_keys);
1184
1185         ec_stripe_key_init(c, &s->new_stripe.key, s->nr_data,
1186                            s->nr_parity, h->blocksize);
1187
1188         h->s = s;
1189         return 0;
1190 }
1191
1192 static struct ec_stripe_head *
1193 ec_new_stripe_head_alloc(struct bch_fs *c, unsigned target,
1194                          unsigned algo, unsigned redundancy,
1195                          bool copygc)
1196 {
1197         struct ec_stripe_head *h;
1198         struct bch_dev *ca;
1199         unsigned i;
1200
1201         h = kzalloc(sizeof(*h), GFP_KERNEL);
1202         if (!h)
1203                 return NULL;
1204
1205         mutex_init(&h->lock);
1206         mutex_lock(&h->lock);
1207
1208         h->target       = target;
1209         h->algo         = algo;
1210         h->redundancy   = redundancy;
1211         h->copygc       = copygc;
1212
1213         rcu_read_lock();
1214         h->devs = target_rw_devs(c, BCH_DATA_user, target);
1215
1216         for_each_member_device_rcu(ca, c, i, &h->devs)
1217                 if (!ca->mi.durability)
1218                         __clear_bit(i, h->devs.d);
1219
1220         h->blocksize = pick_blocksize(c, &h->devs);
1221
1222         for_each_member_device_rcu(ca, c, i, &h->devs)
1223                 if (ca->mi.bucket_size == h->blocksize)
1224                         h->nr_active_devs++;
1225
1226         rcu_read_unlock();
1227         list_add(&h->list, &c->ec_stripe_head_list);
1228         return h;
1229 }
1230
1231 void bch2_ec_stripe_head_put(struct bch_fs *c, struct ec_stripe_head *h)
1232 {
1233         if (h->s &&
1234             h->s->allocated &&
1235             bitmap_weight(h->s->blocks_allocated,
1236                           h->s->nr_data) == h->s->nr_data)
1237                 ec_stripe_set_pending(c, h);
1238
1239         mutex_unlock(&h->lock);
1240 }
1241
1242 struct ec_stripe_head *__bch2_ec_stripe_head_get(struct bch_fs *c,
1243                                                  unsigned target,
1244                                                  unsigned algo,
1245                                                  unsigned redundancy,
1246                                                  bool copygc)
1247 {
1248         struct ec_stripe_head *h;
1249
1250         if (!redundancy)
1251                 return NULL;
1252
1253         mutex_lock(&c->ec_stripe_head_lock);
1254         list_for_each_entry(h, &c->ec_stripe_head_list, list)
1255                 if (h->target           == target &&
1256                     h->algo             == algo &&
1257                     h->redundancy       == redundancy &&
1258                     h->copygc           == copygc) {
1259                         mutex_lock(&h->lock);
1260                         goto found;
1261                 }
1262
1263         h = ec_new_stripe_head_alloc(c, target, algo, redundancy, copygc);
1264 found:
1265         mutex_unlock(&c->ec_stripe_head_lock);
1266         return h;
1267 }
1268
1269 static enum bucket_alloc_ret
1270 new_stripe_alloc_buckets(struct bch_fs *c, struct ec_stripe_head *h,
1271                          struct closure *cl)
1272 {
1273         struct bch_devs_mask devs = h->devs;
1274         struct open_bucket *ob;
1275         struct open_buckets buckets;
1276         unsigned i, j, nr_have_parity = 0, nr_have_data = 0;
1277         bool have_cache = true;
1278         enum bucket_alloc_ret ret = ALLOC_SUCCESS;
1279
1280         for (i = 0; i < h->s->new_stripe.key.v.nr_blocks; i++) {
1281                 if (test_bit(i, h->s->blocks_gotten)) {
1282                         __clear_bit(h->s->new_stripe.key.v.ptrs[i].dev, devs.d);
1283                         if (i < h->s->nr_data)
1284                                 nr_have_data++;
1285                         else
1286                                 nr_have_parity++;
1287                 }
1288         }
1289
1290         BUG_ON(nr_have_data     > h->s->nr_data);
1291         BUG_ON(nr_have_parity   > h->s->nr_parity);
1292
1293         percpu_down_read(&c->mark_lock);
1294         rcu_read_lock();
1295
1296         buckets.nr = 0;
1297         if (nr_have_parity < h->s->nr_parity) {
1298                 ret = bch2_bucket_alloc_set(c, &buckets,
1299                                             &h->parity_stripe,
1300                                             &devs,
1301                                             h->s->nr_parity,
1302                                             &nr_have_parity,
1303                                             &have_cache,
1304                                             h->copygc
1305                                             ? RESERVE_MOVINGGC
1306                                             : RESERVE_NONE,
1307                                             0,
1308                                             cl);
1309
1310                 open_bucket_for_each(c, &buckets, ob, i) {
1311                         j = find_next_zero_bit(h->s->blocks_gotten,
1312                                                h->s->nr_data + h->s->nr_parity,
1313                                                h->s->nr_data);
1314                         BUG_ON(j >= h->s->nr_data + h->s->nr_parity);
1315
1316                         h->s->blocks[j] = buckets.v[i];
1317                         h->s->new_stripe.key.v.ptrs[j] = ob->ptr;
1318                         __set_bit(j, h->s->blocks_gotten);
1319                 }
1320
1321                 if (ret)
1322                         goto err;
1323         }
1324
1325         buckets.nr = 0;
1326         if (nr_have_data < h->s->nr_data) {
1327                 ret = bch2_bucket_alloc_set(c, &buckets,
1328                                             &h->block_stripe,
1329                                             &devs,
1330                                             h->s->nr_data,
1331                                             &nr_have_data,
1332                                             &have_cache,
1333                                             h->copygc
1334                                             ? RESERVE_MOVINGGC
1335                                             : RESERVE_NONE,
1336                                             0,
1337                                             cl);
1338
1339                 open_bucket_for_each(c, &buckets, ob, i) {
1340                         j = find_next_zero_bit(h->s->blocks_gotten,
1341                                                h->s->nr_data, 0);
1342                         BUG_ON(j >= h->s->nr_data);
1343
1344                         h->s->blocks[j] = buckets.v[i];
1345                         h->s->new_stripe.key.v.ptrs[j] = ob->ptr;
1346                         __set_bit(j, h->s->blocks_gotten);
1347                 }
1348
1349                 if (ret)
1350                         goto err;
1351         }
1352 err:
1353         rcu_read_unlock();
1354         percpu_up_read(&c->mark_lock);
1355         return ret;
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[0], 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->ptr.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[0], iter, m)
1553                 if (m->alive)
1554                         bch2_stripes_heap_insert(c, m, iter.pos);
1555 }
1556
1557 static int __bch2_stripe_write_key(struct btree_trans *trans,
1558                                    struct btree_iter *iter,
1559                                    struct stripe *m,
1560                                    size_t idx,
1561                                    struct bkey_i_stripe *new_key)
1562 {
1563         const struct bch_stripe *v;
1564         struct bkey_s_c k;
1565         unsigned i;
1566         int ret;
1567
1568         bch2_btree_iter_set_pos(iter, POS(0, idx));
1569
1570         k = bch2_btree_iter_peek_slot(iter);
1571         ret = bkey_err(k);
1572         if (ret)
1573                 return ret;
1574
1575         if (k.k->type != KEY_TYPE_stripe)
1576                 return -EIO;
1577
1578         v = bkey_s_c_to_stripe(k).v;
1579         for (i = 0; i < v->nr_blocks; i++)
1580                 if (m->block_sectors[i] != stripe_blockcount_get(v, i))
1581                         goto write;
1582         return 0;
1583 write:
1584         bkey_reassemble(&new_key->k_i, k);
1585
1586         for (i = 0; i < new_key->v.nr_blocks; i++)
1587                 stripe_blockcount_set(&new_key->v, i,
1588                                       m->block_sectors[i]);
1589
1590         bch2_trans_update(trans, iter, &new_key->k_i, 0);
1591         return 0;
1592 }
1593
1594 int bch2_stripes_write(struct bch_fs *c, unsigned flags)
1595 {
1596         struct btree_trans trans;
1597         struct btree_iter *iter;
1598         struct genradix_iter giter;
1599         struct bkey_i_stripe *new_key;
1600         struct stripe *m;
1601         int ret = 0;
1602
1603         new_key = kmalloc(255 * sizeof(u64), GFP_KERNEL);
1604         BUG_ON(!new_key);
1605
1606         bch2_trans_init(&trans, c, 0, 0);
1607
1608         iter = bch2_trans_get_iter(&trans, BTREE_ID_stripes, POS_MIN,
1609                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1610
1611         genradix_for_each(&c->stripes[0], giter, m) {
1612                 if (!m->alive)
1613                         continue;
1614
1615                 ret = __bch2_trans_do(&trans, NULL, NULL,
1616                                       BTREE_INSERT_NOFAIL|flags,
1617                         __bch2_stripe_write_key(&trans, iter, m,
1618                                         giter.pos, new_key));
1619
1620                 if (ret)
1621                         break;
1622         }
1623
1624         bch2_trans_exit(&trans);
1625
1626         kfree(new_key);
1627
1628         return ret;
1629 }
1630
1631 static int bch2_stripes_read_fn(struct bch_fs *c, enum btree_id id,
1632                               unsigned level, struct bkey_s_c k)
1633 {
1634         int ret = 0;
1635
1636         if (k.k->type == KEY_TYPE_stripe) {
1637                 ret = __ec_stripe_mem_alloc(c, k.k->p.offset, GFP_KERNEL) ?:
1638                         bch2_mark_key(c, k, 0, 0, NULL, 0,
1639                                       BTREE_TRIGGER_NOATOMIC);
1640                 if (ret)
1641                         return ret;
1642         }
1643
1644         return ret;
1645 }
1646
1647 int bch2_stripes_read(struct bch_fs *c, struct journal_keys *journal_keys)
1648 {
1649         int ret = bch2_btree_and_journal_walk(c, journal_keys, BTREE_ID_stripes,
1650                                           NULL, bch2_stripes_read_fn);
1651         if (ret)
1652                 bch_err(c, "error reading stripes: %i", ret);
1653
1654         return ret;
1655 }
1656
1657 int bch2_ec_mem_alloc(struct bch_fs *c, bool gc)
1658 {
1659         struct btree_trans trans;
1660         struct btree_iter *iter;
1661         struct bkey_s_c k;
1662         size_t i, idx = 0;
1663         int ret = 0;
1664
1665         bch2_trans_init(&trans, c, 0, 0);
1666         iter = bch2_trans_get_iter(&trans, BTREE_ID_stripes, POS(0, U64_MAX), 0);
1667
1668         k = bch2_btree_iter_prev(iter);
1669         if (!IS_ERR_OR_NULL(k.k))
1670                 idx = k.k->p.offset + 1;
1671
1672         bch2_trans_iter_put(&trans, iter);
1673         ret = bch2_trans_exit(&trans);
1674         if (ret)
1675                 return ret;
1676
1677         if (!idx)
1678                 return 0;
1679
1680         if (!gc &&
1681             !init_heap(&c->ec_stripes_heap, roundup_pow_of_two(idx),
1682                        GFP_KERNEL))
1683                 return -ENOMEM;
1684 #if 0
1685         ret = genradix_prealloc(&c->stripes[gc], idx, GFP_KERNEL);
1686 #else
1687         for (i = 0; i < idx; i++)
1688                 if (!genradix_ptr_alloc(&c->stripes[gc], i, GFP_KERNEL))
1689                         return -ENOMEM;
1690 #endif
1691         return 0;
1692 }
1693
1694 void bch2_stripes_heap_to_text(struct printbuf *out, struct bch_fs *c)
1695 {
1696         ec_stripes_heap *h = &c->ec_stripes_heap;
1697         struct stripe *m;
1698         size_t i;
1699
1700         spin_lock(&c->ec_stripes_heap_lock);
1701         for (i = 0; i < min_t(size_t, h->used, 20); i++) {
1702                 m = genradix_ptr(&c->stripes[0], h->data[i].idx);
1703
1704                 pr_buf(out, "%zu %u/%u+%u\n", h->data[i].idx,
1705                        h->data[i].blocks_nonempty,
1706                        m->nr_blocks - m->nr_redundant,
1707                        m->nr_redundant);
1708         }
1709         spin_unlock(&c->ec_stripes_heap_lock);
1710 }
1711
1712 void bch2_new_stripes_to_text(struct printbuf *out, struct bch_fs *c)
1713 {
1714         struct ec_stripe_head *h;
1715         struct ec_stripe_new *s;
1716
1717         mutex_lock(&c->ec_stripe_head_lock);
1718         list_for_each_entry(h, &c->ec_stripe_head_list, list) {
1719                 pr_buf(out, "target %u algo %u redundancy %u:\n",
1720                        h->target, h->algo, h->redundancy);
1721
1722                 if (h->s)
1723                         pr_buf(out, "\tpending: blocks %u+%u allocated %u\n",
1724                                h->s->nr_data, h->s->nr_parity,
1725                                bitmap_weight(h->s->blocks_allocated,
1726                                              h->s->nr_data));
1727         }
1728         mutex_unlock(&c->ec_stripe_head_lock);
1729
1730         mutex_lock(&c->ec_stripe_new_lock);
1731         list_for_each_entry(s, &c->ec_stripe_new_list, list) {
1732                 pr_buf(out, "\tin flight: blocks %u+%u pin %u\n",
1733                        s->nr_data, s->nr_parity,
1734                        atomic_read(&s->pin));
1735         }
1736         mutex_unlock(&c->ec_stripe_new_lock);
1737 }
1738
1739 void bch2_fs_ec_exit(struct bch_fs *c)
1740 {
1741         struct ec_stripe_head *h;
1742
1743         while (1) {
1744                 mutex_lock(&c->ec_stripe_head_lock);
1745                 h = list_first_entry_or_null(&c->ec_stripe_head_list,
1746                                              struct ec_stripe_head, list);
1747                 if (h)
1748                         list_del(&h->list);
1749                 mutex_unlock(&c->ec_stripe_head_lock);
1750                 if (!h)
1751                         break;
1752
1753                 BUG_ON(h->s);
1754                 kfree(h);
1755         }
1756
1757         BUG_ON(!list_empty(&c->ec_stripe_new_list));
1758
1759         free_heap(&c->ec_stripes_heap);
1760         genradix_free(&c->stripes[0]);
1761         bioset_exit(&c->ec_bioset);
1762 }
1763
1764 int bch2_fs_ec_init(struct bch_fs *c)
1765 {
1766         INIT_WORK(&c->ec_stripe_create_work, ec_stripe_create_work);
1767         INIT_WORK(&c->ec_stripe_delete_work, ec_stripe_delete_work);
1768
1769         return bioset_init(&c->ec_bioset, 1, offsetof(struct ec_bio, bio),
1770                            BIOSET_NEED_BVECS);
1771 }