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