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