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