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