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