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