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