]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/ec.c
Merge pull request #24 from brendon-boldt/new-install-distros
[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 static void ec_stripe_key_init(struct bch_fs *c,
204                                struct bkey_i_stripe *s,
205                                struct open_buckets *blocks,
206                                struct open_buckets *parity,
207                                unsigned stripe_size)
208 {
209         struct open_bucket *ob;
210         unsigned i, u64s;
211
212         bkey_stripe_init(&s->k_i);
213         s->v.sectors                    = cpu_to_le16(stripe_size);
214         s->v.algorithm                  = 0;
215         s->v.nr_blocks                  = parity->nr + blocks->nr;
216         s->v.nr_redundant               = parity->nr;
217         s->v.csum_granularity_bits      = ilog2(c->sb.encoded_extent_max);
218         s->v.csum_type                  = BCH_CSUM_CRC32C;
219         s->v.pad                        = 0;
220
221         open_bucket_for_each(c, blocks, ob, i)
222                 s->v.ptrs[i]                    = ob->ptr;
223
224         open_bucket_for_each(c, parity, ob, i)
225                 s->v.ptrs[blocks->nr + i]       = ob->ptr;
226
227         while ((u64s = stripe_val_u64s(&s->v)) > BKEY_VAL_U64s_MAX) {
228                 BUG_ON(1 << s->v.csum_granularity_bits >=
229                        le16_to_cpu(s->v.sectors) ||
230                        s->v.csum_granularity_bits == U8_MAX);
231                 s->v.csum_granularity_bits++;
232         }
233
234         set_bkey_val_u64s(&s->k, u64s);
235 }
236
237 /* Checksumming: */
238
239 static void ec_generate_checksums(struct ec_stripe_buf *buf)
240 {
241         struct bch_stripe *v = &buf->key.v;
242         unsigned csum_granularity = 1 << v->csum_granularity_bits;
243         unsigned csums_per_device = stripe_csums_per_device(v);
244         unsigned csum_bytes = bch_crc_bytes[v->csum_type];
245         unsigned i, j;
246
247         if (!csum_bytes)
248                 return;
249
250         BUG_ON(buf->offset);
251         BUG_ON(buf->size != le16_to_cpu(v->sectors));
252
253         for (i = 0; i < v->nr_blocks; i++) {
254                 for (j = 0; j < csums_per_device; j++) {
255                         unsigned offset = j << v->csum_granularity_bits;
256                         unsigned len = min(csum_granularity, buf->size - offset);
257
258                         struct bch_csum csum =
259                                 bch2_checksum(NULL, v->csum_type,
260                                               null_nonce(),
261                                               buf->data[i] + (offset << 9),
262                                               len << 9);
263
264                         memcpy(stripe_csum(v, i, j), &csum, csum_bytes);
265                 }
266         }
267 }
268
269 static void ec_validate_checksums(struct bch_fs *c, struct ec_stripe_buf *buf)
270 {
271         struct bch_stripe *v = &buf->key.v;
272         unsigned csum_granularity = 1 << v->csum_granularity_bits;
273         unsigned csum_bytes = bch_crc_bytes[v->csum_type];
274         unsigned i;
275
276         if (!csum_bytes)
277                 return;
278
279         for (i = 0; i < v->nr_blocks; i++) {
280                 unsigned offset = buf->offset;
281                 unsigned end = buf->offset + buf->size;
282
283                 if (!test_bit(i, buf->valid))
284                         continue;
285
286                 while (offset < end) {
287                         unsigned j = offset >> v->csum_granularity_bits;
288                         unsigned len = min(csum_granularity, end - offset);
289                         struct bch_csum csum;
290
291                         BUG_ON(offset & (csum_granularity - 1));
292                         BUG_ON(offset + len != le16_to_cpu(v->sectors) &&
293                                ((offset + len) & (csum_granularity - 1)));
294
295                         csum = bch2_checksum(NULL, v->csum_type,
296                                              null_nonce(),
297                                              buf->data[i] + ((offset - buf->offset) << 9),
298                                              len << 9);
299
300                         if (memcmp(stripe_csum(v, i, j), &csum, csum_bytes)) {
301                                 __bcache_io_error(c,
302                                         "checksum error while doing reconstruct read (%u:%u)",
303                                         i, j);
304                                 clear_bit(i, buf->valid);
305                                 break;
306                         }
307
308                         offset += len;
309                 }
310         }
311 }
312
313 /* Erasure coding: */
314
315 static void ec_generate_ec(struct ec_stripe_buf *buf)
316 {
317         struct bch_stripe *v = &buf->key.v;
318         unsigned nr_data = v->nr_blocks - v->nr_redundant;
319         unsigned bytes = le16_to_cpu(v->sectors) << 9;
320
321         raid_gen(nr_data, v->nr_redundant, bytes, buf->data);
322 }
323
324 static unsigned __ec_nr_failed(struct ec_stripe_buf *buf, unsigned nr)
325 {
326         return nr - bitmap_weight(buf->valid, nr);
327 }
328
329 static unsigned ec_nr_failed(struct ec_stripe_buf *buf)
330 {
331         return __ec_nr_failed(buf, buf->key.v.nr_blocks);
332 }
333
334 static int ec_do_recov(struct bch_fs *c, struct ec_stripe_buf *buf)
335 {
336         struct bch_stripe *v = &buf->key.v;
337         unsigned i, failed[EC_STRIPE_MAX], nr_failed = 0;
338         unsigned nr_data = v->nr_blocks - v->nr_redundant;
339         unsigned bytes = buf->size << 9;
340
341         if (ec_nr_failed(buf) > v->nr_redundant) {
342                 __bcache_io_error(c,
343                         "error doing reconstruct read: unable to read enough blocks");
344                 return -1;
345         }
346
347         for (i = 0; i < nr_data; i++)
348                 if (!test_bit(i, buf->valid))
349                         failed[nr_failed++] = i;
350
351         raid_rec(nr_failed, failed, nr_data, v->nr_redundant, bytes, buf->data);
352         return 0;
353 }
354
355 /* IO: */
356
357 static void ec_block_endio(struct bio *bio)
358 {
359         struct ec_bio *ec_bio = container_of(bio, struct ec_bio, bio);
360         struct bch_dev *ca = ec_bio->ca;
361         struct closure *cl = bio->bi_private;
362
363         if (bch2_dev_io_err_on(bio->bi_status, ca, "erasure coding"))
364                 clear_bit(ec_bio->idx, ec_bio->buf->valid);
365
366         bio_put(&ec_bio->bio);
367         percpu_ref_put(&ca->io_ref);
368         closure_put(cl);
369 }
370
371 static void ec_block_io(struct bch_fs *c, struct ec_stripe_buf *buf,
372                         unsigned rw, unsigned idx, struct closure *cl)
373 {
374         struct bch_stripe *v = &buf->key.v;
375         unsigned offset = 0, bytes = buf->size << 9;
376         struct bch_extent_ptr *ptr = &v->ptrs[idx];
377         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
378
379         if (!bch2_dev_get_ioref(ca, rw)) {
380                 clear_bit(idx, buf->valid);
381                 return;
382         }
383
384         while (offset < bytes) {
385                 unsigned nr_iovecs = min_t(size_t, BIO_MAX_PAGES,
386                                            DIV_ROUND_UP(bytes, PAGE_SIZE));
387                 unsigned b = min_t(size_t, bytes - offset,
388                                    nr_iovecs << PAGE_SHIFT);
389                 struct ec_bio *ec_bio;
390
391                 ec_bio = container_of(bio_alloc_bioset(GFP_KERNEL, nr_iovecs,
392                                                        &c->ec_bioset),
393                                       struct ec_bio, bio);
394
395                 ec_bio->ca                      = ca;
396                 ec_bio->buf                     = buf;
397                 ec_bio->idx                     = idx;
398
399                 bio_set_dev(&ec_bio->bio, ca->disk_sb.bdev);
400                 bio_set_op_attrs(&ec_bio->bio, rw, 0);
401
402                 ec_bio->bio.bi_iter.bi_sector   = ptr->offset + buf->offset + (offset >> 9);
403                 ec_bio->bio.bi_end_io           = ec_block_endio;
404                 ec_bio->bio.bi_private          = cl;
405
406                 bch2_bio_map(&ec_bio->bio, buf->data[idx] + offset, b);
407
408                 closure_get(cl);
409                 percpu_ref_get(&ca->io_ref);
410
411                 submit_bio(&ec_bio->bio);
412
413                 offset += b;
414         }
415
416         percpu_ref_put(&ca->io_ref);
417 }
418
419 /* recovery read path: */
420 int bch2_ec_read_extent(struct bch_fs *c, struct bch_read_bio *rbio)
421 {
422         struct btree_trans trans;
423         struct btree_iter *iter;
424         struct ec_stripe_buf *buf;
425         struct closure cl;
426         struct bkey_s_c k;
427         struct bch_stripe *v;
428         unsigned stripe_idx;
429         unsigned offset, end;
430         unsigned i, nr_data, csum_granularity;
431         int ret = 0, idx;
432
433         closure_init_stack(&cl);
434
435         BUG_ON(!rbio->pick.has_ec);
436
437         stripe_idx = rbio->pick.ec.idx;
438
439         buf = kzalloc(sizeof(*buf), GFP_NOIO);
440         if (!buf)
441                 return -ENOMEM;
442
443         bch2_trans_init(&trans, c, 0, 0);
444
445         iter = bch2_trans_get_iter(&trans, BTREE_ID_EC,
446                                    POS(0, stripe_idx),
447                                    BTREE_ITER_SLOTS);
448         k = bch2_btree_iter_peek_slot(iter);
449         if (bkey_err(k) || k.k->type != KEY_TYPE_stripe) {
450                 __bcache_io_error(c,
451                         "error doing reconstruct read: stripe not found");
452                 kfree(buf);
453                 return bch2_trans_exit(&trans) ?: -EIO;
454         }
455
456         bkey_reassemble(&buf->key.k_i, k);
457         bch2_trans_exit(&trans);
458
459         v = &buf->key.v;
460
461         nr_data = v->nr_blocks - v->nr_redundant;
462
463         idx = ptr_matches_stripe(c, v, &rbio->pick.ptr);
464         BUG_ON(idx < 0);
465
466         csum_granularity = 1U << v->csum_granularity_bits;
467
468         offset  = rbio->bio.bi_iter.bi_sector - v->ptrs[idx].offset;
469         end     = offset + bio_sectors(&rbio->bio);
470
471         BUG_ON(end > le16_to_cpu(v->sectors));
472
473         buf->offset     = round_down(offset, csum_granularity);
474         buf->size       = min_t(unsigned, le16_to_cpu(v->sectors),
475                                 round_up(end, csum_granularity)) - buf->offset;
476
477         for (i = 0; i < v->nr_blocks; i++) {
478                 buf->data[i] = kmalloc(buf->size << 9, GFP_NOIO);
479                 if (!buf->data[i]) {
480                         ret = -ENOMEM;
481                         goto err;
482                 }
483         }
484
485         memset(buf->valid, 0xFF, sizeof(buf->valid));
486
487         for (i = 0; i < v->nr_blocks; i++) {
488                 struct bch_extent_ptr *ptr = v->ptrs + i;
489                 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
490
491                 if (ptr_stale(ca, ptr)) {
492                         __bcache_io_error(c,
493                                           "error doing reconstruct read: stale pointer");
494                         clear_bit(i, buf->valid);
495                         continue;
496                 }
497
498                 ec_block_io(c, buf, REQ_OP_READ, i, &cl);
499         }
500
501         closure_sync(&cl);
502
503         if (ec_nr_failed(buf) > v->nr_redundant) {
504                 __bcache_io_error(c,
505                         "error doing reconstruct read: unable to read enough blocks");
506                 ret = -EIO;
507                 goto err;
508         }
509
510         ec_validate_checksums(c, buf);
511
512         ret = ec_do_recov(c, buf);
513         if (ret)
514                 goto err;
515
516         memcpy_to_bio(&rbio->bio, rbio->bio.bi_iter,
517                       buf->data[idx] + ((offset - buf->offset) << 9));
518 err:
519         for (i = 0; i < v->nr_blocks; i++)
520                 kfree(buf->data[i]);
521         kfree(buf);
522         return ret;
523 }
524
525 /* stripe bucket accounting: */
526
527 static int __ec_stripe_mem_alloc(struct bch_fs *c, size_t idx, gfp_t gfp)
528 {
529         ec_stripes_heap n, *h = &c->ec_stripes_heap;
530
531         if (idx >= h->size) {
532                 if (!init_heap(&n, max(1024UL, roundup_pow_of_two(idx + 1)), gfp))
533                         return -ENOMEM;
534
535                 spin_lock(&c->ec_stripes_heap_lock);
536                 if (n.size > h->size) {
537                         memcpy(n.data, h->data, h->used * sizeof(h->data[0]));
538                         n.used = h->used;
539                         swap(*h, n);
540                 }
541                 spin_unlock(&c->ec_stripes_heap_lock);
542
543                 free_heap(&n);
544         }
545
546         if (!genradix_ptr_alloc(&c->stripes[0], idx, gfp))
547                 return -ENOMEM;
548
549         if (c->gc_pos.phase != GC_PHASE_NOT_RUNNING &&
550             !genradix_ptr_alloc(&c->stripes[1], idx, gfp))
551                 return -ENOMEM;
552
553         return 0;
554 }
555
556 static int ec_stripe_mem_alloc(struct bch_fs *c,
557                                struct btree_iter *iter)
558 {
559         size_t idx = iter->pos.offset;
560         int ret = 0;
561
562         if (!__ec_stripe_mem_alloc(c, idx, GFP_NOWAIT|__GFP_NOWARN))
563                 return ret;
564
565         bch2_trans_unlock(iter->trans);
566         ret = -EINTR;
567
568         if (!__ec_stripe_mem_alloc(c, idx, GFP_KERNEL))
569                 return ret;
570
571         return -ENOMEM;
572 }
573
574 static ssize_t stripe_idx_to_delete(struct bch_fs *c)
575 {
576         ec_stripes_heap *h = &c->ec_stripes_heap;
577
578         return h->used && h->data[0].blocks_nonempty == 0
579                 ? h->data[0].idx : -1;
580 }
581
582 static inline int ec_stripes_heap_cmp(ec_stripes_heap *h,
583                                       struct ec_stripe_heap_entry l,
584                                       struct ec_stripe_heap_entry r)
585 {
586         return ((l.blocks_nonempty > r.blocks_nonempty) -
587                 (l.blocks_nonempty < r.blocks_nonempty));
588 }
589
590 static inline void ec_stripes_heap_set_backpointer(ec_stripes_heap *h,
591                                                    size_t i)
592 {
593         struct bch_fs *c = container_of(h, struct bch_fs, ec_stripes_heap);
594
595         genradix_ptr(&c->stripes[0], h->data[i].idx)->heap_idx = i;
596 }
597
598 static void heap_verify_backpointer(struct bch_fs *c, size_t idx)
599 {
600         ec_stripes_heap *h = &c->ec_stripes_heap;
601         struct stripe *m = genradix_ptr(&c->stripes[0], idx);
602
603         BUG_ON(!m->alive);
604         BUG_ON(m->heap_idx >= h->used);
605         BUG_ON(h->data[m->heap_idx].idx != idx);
606 }
607
608 void bch2_stripes_heap_update(struct bch_fs *c,
609                               struct stripe *m, size_t idx)
610 {
611         ec_stripes_heap *h = &c->ec_stripes_heap;
612         size_t i;
613
614         if (m->alive) {
615                 heap_verify_backpointer(c, idx);
616
617                 h->data[m->heap_idx].blocks_nonempty = m->blocks_nonempty;
618
619                 i = m->heap_idx;
620                 heap_sift_up(h,   i, ec_stripes_heap_cmp,
621                              ec_stripes_heap_set_backpointer);
622                 heap_sift_down(h, i, ec_stripes_heap_cmp,
623                                ec_stripes_heap_set_backpointer);
624
625                 heap_verify_backpointer(c, idx);
626         } else {
627                 bch2_stripes_heap_insert(c, m, idx);
628         }
629
630         if (stripe_idx_to_delete(c) >= 0 &&
631             !percpu_ref_is_dying(&c->writes))
632                 schedule_work(&c->ec_stripe_delete_work);
633 }
634
635 void bch2_stripes_heap_del(struct bch_fs *c,
636                            struct stripe *m, size_t idx)
637 {
638         heap_verify_backpointer(c, idx);
639
640         m->alive = false;
641         heap_del(&c->ec_stripes_heap, m->heap_idx,
642                  ec_stripes_heap_cmp,
643                  ec_stripes_heap_set_backpointer);
644 }
645
646 void bch2_stripes_heap_insert(struct bch_fs *c,
647                               struct stripe *m, size_t idx)
648 {
649         BUG_ON(heap_full(&c->ec_stripes_heap));
650
651         heap_add(&c->ec_stripes_heap, ((struct ec_stripe_heap_entry) {
652                         .idx = idx,
653                         .blocks_nonempty = m->blocks_nonempty,
654                 }),
655                  ec_stripes_heap_cmp,
656                  ec_stripes_heap_set_backpointer);
657         m->alive = true;
658
659         heap_verify_backpointer(c, idx);
660 }
661
662 /* stripe deletion */
663
664 static int ec_stripe_delete(struct bch_fs *c, size_t idx)
665 {
666         return bch2_btree_delete_range(c, BTREE_ID_EC,
667                                        POS(0, idx),
668                                        POS(0, idx + 1),
669                                        NULL);
670 }
671
672 static void ec_stripe_delete_work(struct work_struct *work)
673 {
674         struct bch_fs *c =
675                 container_of(work, struct bch_fs, ec_stripe_delete_work);
676         ssize_t idx;
677
678         down_read(&c->gc_lock);
679         mutex_lock(&c->ec_stripe_create_lock);
680
681         while (1) {
682                 spin_lock(&c->ec_stripes_heap_lock);
683                 idx = stripe_idx_to_delete(c);
684                 spin_unlock(&c->ec_stripes_heap_lock);
685
686                 if (idx < 0)
687                         break;
688
689                 if (ec_stripe_delete(c, idx))
690                         break;
691         }
692
693         mutex_unlock(&c->ec_stripe_create_lock);
694         up_read(&c->gc_lock);
695 }
696
697 /* stripe creation: */
698
699 static int ec_stripe_bkey_insert(struct bch_fs *c,
700                                  struct bkey_i_stripe *stripe)
701 {
702         struct btree_trans trans;
703         struct btree_iter *iter;
704         struct bkey_s_c k;
705         struct bpos start_pos = POS(0, c->ec_stripe_hint);
706         int ret;
707
708         bch2_trans_init(&trans, c, 0, 0);
709 retry:
710         bch2_trans_begin(&trans);
711
712         for_each_btree_key(&trans, iter, BTREE_ID_EC, start_pos,
713                            BTREE_ITER_SLOTS|BTREE_ITER_INTENT, k, ret) {
714                 if (bkey_cmp(k.k->p, POS(0, U32_MAX)) > 0) {
715                         if (start_pos.offset) {
716                                 start_pos = POS_MIN;
717                                 bch2_btree_iter_set_pos(iter, start_pos);
718                                 continue;
719                         }
720
721                         ret = -ENOSPC;
722                         break;
723                 }
724
725                 if (bkey_deleted(k.k))
726                         goto found_slot;
727         }
728
729         goto err;
730 found_slot:
731         start_pos = iter->pos;
732
733         ret = ec_stripe_mem_alloc(c, iter);
734         if (ret)
735                 goto err;
736
737         stripe->k.p = iter->pos;
738
739         bch2_trans_update(&trans, iter, &stripe->k_i);
740
741         ret = bch2_trans_commit(&trans, NULL, NULL,
742                                 BTREE_INSERT_ATOMIC|
743                                 BTREE_INSERT_NOFAIL);
744 err:
745         if (ret == -EINTR)
746                 goto retry;
747
748         c->ec_stripe_hint = ret ? start_pos.offset : start_pos.offset + 1;
749         bch2_trans_exit(&trans);
750
751         return ret;
752 }
753
754 static void extent_stripe_ptr_add(struct bkey_s_extent e,
755                                   struct ec_stripe_buf *s,
756                                   struct bch_extent_ptr *ptr,
757                                   unsigned block)
758 {
759         struct bch_extent_stripe_ptr *dst = (void *) ptr;
760         union bch_extent_entry *end = extent_entry_last(e);
761
762         memmove_u64s_up(dst + 1, dst, (u64 *) end - (u64 *) dst);
763         e.k->u64s += sizeof(*dst) / sizeof(u64);
764
765         *dst = (struct bch_extent_stripe_ptr) {
766                 .type = 1 << BCH_EXTENT_ENTRY_stripe_ptr,
767                 .block          = block,
768                 .idx            = s->key.k.p.offset,
769         };
770 }
771
772 static int ec_stripe_update_ptrs(struct bch_fs *c,
773                                  struct ec_stripe_buf *s,
774                                  struct bkey *pos)
775 {
776         struct btree_trans trans;
777         struct btree_iter *iter;
778         struct bkey_s_c k;
779         struct bkey_s_extent e;
780         struct bkey_on_stack sk;
781         int ret = 0, dev, idx;
782
783         bkey_on_stack_init(&sk);
784         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
785
786         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
787                                    bkey_start_pos(pos),
788                                    BTREE_ITER_INTENT);
789
790         while ((k = bch2_btree_iter_peek(iter)).k &&
791                !(ret = bkey_err(k)) &&
792                bkey_cmp(bkey_start_pos(k.k), pos->p) < 0) {
793                 struct bch_extent_ptr *ptr, *ec_ptr = NULL;
794
795                 if (extent_has_stripe_ptr(k, s->key.k.p.offset)) {
796                         bch2_btree_iter_next(iter);
797                         continue;
798                 }
799
800                 idx = extent_matches_stripe(c, &s->key.v, k);
801                 if (idx < 0) {
802                         bch2_btree_iter_next(iter);
803                         continue;
804                 }
805
806                 bch2_btree_iter_set_pos(iter, bkey_start_pos(k.k));
807
808                 dev = s->key.v.ptrs[idx].dev;
809
810                 bkey_on_stack_reassemble(&sk, c, k);
811                 e = bkey_i_to_s_extent(sk.k);
812
813                 extent_for_each_ptr(e, ptr) {
814                         if (ptr->dev == dev)
815                                 ec_ptr = ptr;
816                         else
817                                 ptr->cached = true;
818                 }
819
820                 extent_stripe_ptr_add(e, s, ec_ptr, idx);
821
822                 bch2_trans_update(&trans, iter, sk.k);
823
824                 ret = bch2_trans_commit(&trans, NULL, NULL,
825                                         BTREE_INSERT_ATOMIC|
826                                         BTREE_INSERT_NOFAIL|
827                                         BTREE_INSERT_USE_RESERVE);
828                 if (ret == -EINTR)
829                         ret = 0;
830                 if (ret)
831                         break;
832         }
833
834         bch2_trans_exit(&trans);
835         bkey_on_stack_exit(&sk, c);
836
837         return ret;
838 }
839
840 /*
841  * data buckets of new stripe all written: create the stripe
842  */
843 static void ec_stripe_create(struct ec_stripe_new *s)
844 {
845         struct bch_fs *c = s->c;
846         struct open_bucket *ob;
847         struct bkey_i *k;
848         struct bch_stripe *v = &s->stripe.key.v;
849         unsigned i, nr_data = v->nr_blocks - v->nr_redundant;
850         struct closure cl;
851         int ret;
852
853         BUG_ON(s->h->s == s);
854
855         closure_init_stack(&cl);
856
857         if (s->err) {
858                 bch_err(c, "error creating stripe: error writing data buckets");
859                 goto err;
860         }
861
862         if (!percpu_ref_tryget(&c->writes))
863                 goto err;
864
865         BUG_ON(bitmap_weight(s->blocks_allocated,
866                              s->blocks.nr) != s->blocks.nr);
867
868         ec_generate_ec(&s->stripe);
869
870         ec_generate_checksums(&s->stripe);
871
872         /* write p/q: */
873         for (i = nr_data; i < v->nr_blocks; i++)
874                 ec_block_io(c, &s->stripe, REQ_OP_WRITE, i, &cl);
875
876         closure_sync(&cl);
877
878         for (i = nr_data; i < v->nr_blocks; i++)
879                 if (!test_bit(i, s->stripe.valid)) {
880                         bch_err(c, "error creating stripe: error writing redundancy buckets");
881                         goto err_put_writes;
882                 }
883
884         mutex_lock(&c->ec_stripe_create_lock);
885
886         ret = ec_stripe_bkey_insert(c, &s->stripe.key);
887         if (ret) {
888                 bch_err(c, "error creating stripe: error creating stripe key");
889                 goto err_unlock;
890         }
891
892         for_each_keylist_key(&s->keys, k) {
893                 ret = ec_stripe_update_ptrs(c, &s->stripe, &k->k);
894                 if (ret)
895                         break;
896         }
897
898 err_unlock:
899         mutex_unlock(&c->ec_stripe_create_lock);
900 err_put_writes:
901         percpu_ref_put(&c->writes);
902 err:
903         open_bucket_for_each(c, &s->blocks, ob, i) {
904                 ob->ec = NULL;
905                 __bch2_open_bucket_put(c, ob);
906         }
907
908         bch2_open_buckets_put(c, &s->parity);
909
910         bch2_keylist_free(&s->keys, s->inline_keys);
911
912         mutex_lock(&s->h->lock);
913         list_del(&s->list);
914         mutex_unlock(&s->h->lock);
915
916         for (i = 0; i < s->stripe.key.v.nr_blocks; i++)
917                 kvpfree(s->stripe.data[i], s->stripe.size << 9);
918         kfree(s);
919 }
920
921 static struct ec_stripe_new *ec_stripe_set_pending(struct ec_stripe_head *h)
922 {
923         struct ec_stripe_new *s = h->s;
924
925         list_add(&s->list, &h->stripes);
926         h->s = NULL;
927
928         return s;
929 }
930
931 static void ec_stripe_new_put(struct ec_stripe_new *s)
932 {
933         BUG_ON(atomic_read(&s->pin) <= 0);
934         if (atomic_dec_and_test(&s->pin))
935                 ec_stripe_create(s);
936 }
937
938 /* have a full bucket - hand it off to be erasure coded: */
939 void bch2_ec_bucket_written(struct bch_fs *c, struct open_bucket *ob)
940 {
941         struct ec_stripe_new *s = ob->ec;
942
943         if (ob->sectors_free)
944                 s->err = -1;
945
946         ec_stripe_new_put(s);
947 }
948
949 void bch2_ec_bucket_cancel(struct bch_fs *c, struct open_bucket *ob)
950 {
951         struct ec_stripe_new *s = ob->ec;
952
953         s->err = -EIO;
954 }
955
956 void *bch2_writepoint_ec_buf(struct bch_fs *c, struct write_point *wp)
957 {
958         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
959         struct bch_dev *ca;
960         unsigned offset;
961
962         if (!ob)
963                 return NULL;
964
965         ca      = bch_dev_bkey_exists(c, ob->ptr.dev);
966         offset  = ca->mi.bucket_size - ob->sectors_free;
967
968         return ob->ec->stripe.data[ob->ec_idx] + (offset << 9);
969 }
970
971 void bch2_ec_add_backpointer(struct bch_fs *c, struct write_point *wp,
972                              struct bpos pos, unsigned sectors)
973 {
974         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
975         struct ec_stripe_new *ec;
976
977         if (!ob)
978                 return;
979
980         ec = ob->ec;
981         mutex_lock(&ec->lock);
982
983         if (bch2_keylist_realloc(&ec->keys, ec->inline_keys,
984                                  ARRAY_SIZE(ec->inline_keys),
985                                  BKEY_U64s)) {
986                 BUG();
987         }
988
989         bkey_init(&ec->keys.top->k);
990         ec->keys.top->k.p       = pos;
991         bch2_key_resize(&ec->keys.top->k, sectors);
992         bch2_keylist_push(&ec->keys);
993
994         mutex_unlock(&ec->lock);
995 }
996
997 static int unsigned_cmp(const void *_l, const void *_r)
998 {
999         unsigned l = *((const unsigned *) _l);
1000         unsigned r = *((const unsigned *) _r);
1001
1002         return cmp_int(l, r);
1003 }
1004
1005 /* pick most common bucket size: */
1006 static unsigned pick_blocksize(struct bch_fs *c,
1007                                struct bch_devs_mask *devs)
1008 {
1009         struct bch_dev *ca;
1010         unsigned i, nr = 0, sizes[BCH_SB_MEMBERS_MAX];
1011         struct {
1012                 unsigned nr, size;
1013         } cur = { 0, 0 }, best = { 0, 0 };
1014
1015         for_each_member_device_rcu(ca, c, i, devs)
1016                 sizes[nr++] = ca->mi.bucket_size;
1017
1018         sort(sizes, nr, sizeof(unsigned), unsigned_cmp, NULL);
1019
1020         for (i = 0; i < nr; i++) {
1021                 if (sizes[i] != cur.size) {
1022                         if (cur.nr > best.nr)
1023                                 best = cur;
1024
1025                         cur.nr = 0;
1026                         cur.size = sizes[i];
1027                 }
1028
1029                 cur.nr++;
1030         }
1031
1032         if (cur.nr > best.nr)
1033                 best = cur;
1034
1035         return best.size;
1036 }
1037
1038 int bch2_ec_stripe_new_alloc(struct bch_fs *c, struct ec_stripe_head *h)
1039 {
1040         struct ec_stripe_new *s;
1041         unsigned i;
1042
1043         BUG_ON(h->parity.nr != h->redundancy);
1044         BUG_ON(!h->blocks.nr);
1045         BUG_ON(h->parity.nr + h->blocks.nr > EC_STRIPE_MAX);
1046         lockdep_assert_held(&h->lock);
1047
1048         s = kzalloc(sizeof(*s), GFP_KERNEL);
1049         if (!s)
1050                 return -ENOMEM;
1051
1052         mutex_init(&s->lock);
1053         atomic_set(&s->pin, 1);
1054         s->c            = c;
1055         s->h            = h;
1056         s->blocks       = h->blocks;
1057         s->parity       = h->parity;
1058
1059         memset(&h->blocks, 0, sizeof(h->blocks));
1060         memset(&h->parity, 0, sizeof(h->parity));
1061
1062         bch2_keylist_init(&s->keys, s->inline_keys);
1063
1064         s->stripe.offset        = 0;
1065         s->stripe.size          = h->blocksize;
1066         memset(s->stripe.valid, 0xFF, sizeof(s->stripe.valid));
1067
1068         ec_stripe_key_init(c, &s->stripe.key,
1069                            &s->blocks, &s->parity,
1070                            h->blocksize);
1071
1072         for (i = 0; i < s->stripe.key.v.nr_blocks; i++) {
1073                 s->stripe.data[i] = kvpmalloc(s->stripe.size << 9, GFP_KERNEL);
1074                 if (!s->stripe.data[i])
1075                         goto err;
1076         }
1077
1078         h->s = s;
1079
1080         return 0;
1081 err:
1082         for (i = 0; i < s->stripe.key.v.nr_blocks; i++)
1083                 kvpfree(s->stripe.data[i], s->stripe.size << 9);
1084         kfree(s);
1085         return -ENOMEM;
1086 }
1087
1088 static struct ec_stripe_head *
1089 ec_new_stripe_head_alloc(struct bch_fs *c, unsigned target,
1090                          unsigned algo, unsigned redundancy)
1091 {
1092         struct ec_stripe_head *h;
1093         struct bch_dev *ca;
1094         unsigned i;
1095
1096         h = kzalloc(sizeof(*h), GFP_KERNEL);
1097         if (!h)
1098                 return NULL;
1099
1100         mutex_init(&h->lock);
1101         mutex_lock(&h->lock);
1102         INIT_LIST_HEAD(&h->stripes);
1103
1104         h->target       = target;
1105         h->algo         = algo;
1106         h->redundancy   = redundancy;
1107
1108         rcu_read_lock();
1109         h->devs = target_rw_devs(c, BCH_DATA_USER, target);
1110
1111         for_each_member_device_rcu(ca, c, i, &h->devs)
1112                 if (!ca->mi.durability)
1113                         __clear_bit(i, h->devs.d);
1114
1115         h->blocksize = pick_blocksize(c, &h->devs);
1116
1117         for_each_member_device_rcu(ca, c, i, &h->devs)
1118                 if (ca->mi.bucket_size == h->blocksize)
1119                         h->nr_active_devs++;
1120
1121         rcu_read_unlock();
1122         list_add(&h->list, &c->ec_new_stripe_list);
1123         return h;
1124 }
1125
1126 void bch2_ec_stripe_head_put(struct ec_stripe_head *h)
1127 {
1128         struct ec_stripe_new *s = NULL;
1129
1130         if (h->s &&
1131             bitmap_weight(h->s->blocks_allocated,
1132                           h->s->blocks.nr) == h->s->blocks.nr)
1133                 s = ec_stripe_set_pending(h);
1134
1135         mutex_unlock(&h->lock);
1136
1137         if (s)
1138                 ec_stripe_new_put(s);
1139 }
1140
1141 struct ec_stripe_head *bch2_ec_stripe_head_get(struct bch_fs *c,
1142                                                unsigned target,
1143                                                unsigned algo,
1144                                                unsigned redundancy)
1145 {
1146         struct ec_stripe_head *h;
1147
1148         if (!redundancy)
1149                 return NULL;
1150
1151         mutex_lock(&c->ec_new_stripe_lock);
1152         list_for_each_entry(h, &c->ec_new_stripe_list, list)
1153                 if (h->target           == target &&
1154                     h->algo             == algo &&
1155                     h->redundancy       == redundancy) {
1156                         mutex_lock(&h->lock);
1157                         goto found;
1158                 }
1159
1160         h = ec_new_stripe_head_alloc(c, target, algo, redundancy);
1161 found:
1162         mutex_unlock(&c->ec_new_stripe_lock);
1163         return h;
1164 }
1165
1166 void bch2_ec_stop_dev(struct bch_fs *c, struct bch_dev *ca)
1167 {
1168         struct ec_stripe_head *h;
1169         struct open_bucket *ob;
1170         unsigned i;
1171
1172         mutex_lock(&c->ec_new_stripe_lock);
1173         list_for_each_entry(h, &c->ec_new_stripe_list, list) {
1174                 struct ec_stripe_new *s = NULL;
1175
1176                 mutex_lock(&h->lock);
1177                 bch2_open_buckets_stop_dev(c, ca, &h->blocks);
1178                 bch2_open_buckets_stop_dev(c, ca, &h->parity);
1179
1180                 if (!h->s)
1181                         goto unlock;
1182
1183                 open_bucket_for_each(c, &h->s->blocks, ob, i)
1184                         if (ob->ptr.dev == ca->dev_idx)
1185                                 goto found;
1186                 open_bucket_for_each(c, &h->s->parity, ob, i)
1187                         if (ob->ptr.dev == ca->dev_idx)
1188                                 goto found;
1189                 goto unlock;
1190 found:
1191                 h->s->err = -1;
1192                 s = ec_stripe_set_pending(h);
1193 unlock:
1194                 mutex_unlock(&h->lock);
1195
1196                 if (s)
1197                         ec_stripe_new_put(s);
1198         }
1199         mutex_unlock(&c->ec_new_stripe_lock);
1200 }
1201
1202 static int __bch2_stripe_write_key(struct btree_trans *trans,
1203                                    struct btree_iter *iter,
1204                                    struct stripe *m,
1205                                    size_t idx,
1206                                    struct bkey_i_stripe *new_key,
1207                                    unsigned flags)
1208 {
1209         struct bch_fs *c = trans->c;
1210         struct bkey_s_c k;
1211         unsigned i;
1212         int ret;
1213
1214         bch2_btree_iter_set_pos(iter, POS(0, idx));
1215
1216         k = bch2_btree_iter_peek_slot(iter);
1217         ret = bkey_err(k);
1218         if (ret)
1219                 return ret;
1220
1221         if (k.k->type != KEY_TYPE_stripe)
1222                 return -EIO;
1223
1224         bkey_reassemble(&new_key->k_i, k);
1225
1226         spin_lock(&c->ec_stripes_heap_lock);
1227
1228         for (i = 0; i < new_key->v.nr_blocks; i++)
1229                 stripe_blockcount_set(&new_key->v, i,
1230                                       m->block_sectors[i]);
1231         m->dirty = false;
1232
1233         spin_unlock(&c->ec_stripes_heap_lock);
1234
1235         bch2_trans_update(trans, iter, &new_key->k_i);
1236
1237         return bch2_trans_commit(trans, NULL, NULL,
1238                                  BTREE_INSERT_NOFAIL|flags);
1239 }
1240
1241 int bch2_stripes_write(struct bch_fs *c, unsigned flags, bool *wrote)
1242 {
1243         struct btree_trans trans;
1244         struct btree_iter *iter;
1245         struct genradix_iter giter;
1246         struct bkey_i_stripe *new_key;
1247         struct stripe *m;
1248         int ret = 0;
1249
1250         new_key = kmalloc(255 * sizeof(u64), GFP_KERNEL);
1251         BUG_ON(!new_key);
1252
1253         bch2_trans_init(&trans, c, 0, 0);
1254
1255         iter = bch2_trans_get_iter(&trans, BTREE_ID_EC, POS_MIN,
1256                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1257
1258         genradix_for_each(&c->stripes[0], giter, m) {
1259                 if (!m->dirty)
1260                         continue;
1261
1262                 ret = __bch2_stripe_write_key(&trans, iter, m, giter.pos,
1263                                               new_key, flags);
1264                 if (ret)
1265                         break;
1266
1267                 *wrote = true;
1268         }
1269
1270         bch2_trans_exit(&trans);
1271
1272         kfree(new_key);
1273
1274         return ret;
1275 }
1276
1277 int bch2_stripes_read(struct bch_fs *c, struct journal_keys *journal_keys)
1278 {
1279         struct btree_trans trans;
1280         struct btree_iter *btree_iter;
1281         struct journal_iter journal_iter;
1282         struct bkey_s_c btree_k, journal_k;
1283         int ret;
1284
1285         ret = bch2_fs_ec_start(c);
1286         if (ret)
1287                 return ret;
1288
1289         bch2_trans_init(&trans, c, 0, 0);
1290
1291         btree_iter      = bch2_trans_get_iter(&trans, BTREE_ID_EC, POS_MIN, 0);
1292         journal_iter    = bch2_journal_iter_init(journal_keys, BTREE_ID_EC);
1293
1294         btree_k         = bch2_btree_iter_peek(btree_iter);
1295         journal_k       = bch2_journal_iter_peek(&journal_iter);
1296
1297         while (1) {
1298                 bool btree;
1299
1300                 if (btree_k.k && journal_k.k) {
1301                         int cmp = bkey_cmp(btree_k.k->p, journal_k.k->p);
1302
1303                         if (!cmp)
1304                                 btree_k = bch2_btree_iter_next(btree_iter);
1305                         btree = cmp < 0;
1306                 } else if (btree_k.k) {
1307                         btree = true;
1308                 } else if (journal_k.k) {
1309                         btree = false;
1310                 } else {
1311                         break;
1312                 }
1313
1314                 bch2_mark_key(c, btree ? btree_k : journal_k,
1315                               0, 0, NULL, 0,
1316                               BCH_BUCKET_MARK_ALLOC_READ|
1317                               BCH_BUCKET_MARK_NOATOMIC);
1318
1319                 if (btree)
1320                         btree_k = bch2_btree_iter_next(btree_iter);
1321                 else
1322                         journal_k = bch2_journal_iter_next(&journal_iter);
1323         }
1324
1325         ret = bch2_trans_exit(&trans) ?: ret;
1326         if (ret) {
1327                 bch_err(c, "error reading stripes: %i", ret);
1328                 return ret;
1329         }
1330
1331         return 0;
1332 }
1333
1334 int bch2_ec_mem_alloc(struct bch_fs *c, bool gc)
1335 {
1336         struct btree_trans trans;
1337         struct btree_iter *iter;
1338         struct bkey_s_c k;
1339         size_t i, idx = 0;
1340         int ret = 0;
1341
1342         bch2_trans_init(&trans, c, 0, 0);
1343
1344         iter = bch2_trans_get_iter(&trans, BTREE_ID_EC, POS(0, U64_MAX), 0);
1345
1346         k = bch2_btree_iter_prev(iter);
1347         if (!IS_ERR_OR_NULL(k.k))
1348                 idx = k.k->p.offset + 1;
1349         ret = bch2_trans_exit(&trans);
1350         if (ret)
1351                 return ret;
1352
1353         if (!idx)
1354                 return 0;
1355
1356         if (!gc &&
1357             !init_heap(&c->ec_stripes_heap, roundup_pow_of_two(idx),
1358                        GFP_KERNEL))
1359                 return -ENOMEM;
1360 #if 0
1361         ret = genradix_prealloc(&c->stripes[gc], idx, GFP_KERNEL);
1362 #else
1363         for (i = 0; i < idx; i++)
1364                 if (!genradix_ptr_alloc(&c->stripes[gc], i, GFP_KERNEL))
1365                         return -ENOMEM;
1366 #endif
1367         return 0;
1368 }
1369
1370 int bch2_fs_ec_start(struct bch_fs *c)
1371 {
1372         return bch2_ec_mem_alloc(c, false);
1373 }
1374
1375 void bch2_fs_ec_exit(struct bch_fs *c)
1376 {
1377         struct ec_stripe_head *h;
1378
1379         while (1) {
1380                 mutex_lock(&c->ec_new_stripe_lock);
1381                 h = list_first_entry_or_null(&c->ec_new_stripe_list,
1382                                              struct ec_stripe_head, list);
1383                 if (h)
1384                         list_del(&h->list);
1385                 mutex_unlock(&c->ec_new_stripe_lock);
1386                 if (!h)
1387                         break;
1388
1389                 BUG_ON(h->s);
1390                 BUG_ON(!list_empty(&h->stripes));
1391                 kfree(h);
1392         }
1393
1394         free_heap(&c->ec_stripes_heap);
1395         genradix_free(&c->stripes[0]);
1396         bioset_exit(&c->ec_bioset);
1397 }
1398
1399 int bch2_fs_ec_init(struct bch_fs *c)
1400 {
1401         INIT_WORK(&c->ec_stripe_delete_work, ec_stripe_delete_work);
1402
1403         return bioset_init(&c->ec_bioset, 1, offsetof(struct ec_bio, bio),
1404                            BIOSET_NEED_BVECS);
1405 }