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