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