]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/ec.c
Merge pull request #26 from unquietwiki/master
[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, 0);
740
741         ret = bch2_trans_commit(&trans, NULL, NULL,
742                                 BTREE_INSERT_NOFAIL);
743 err:
744         if (ret == -EINTR)
745                 goto retry;
746
747         c->ec_stripe_hint = ret ? start_pos.offset : start_pos.offset + 1;
748         bch2_trans_exit(&trans);
749
750         return ret;
751 }
752
753 static void extent_stripe_ptr_add(struct bkey_s_extent e,
754                                   struct ec_stripe_buf *s,
755                                   struct bch_extent_ptr *ptr,
756                                   unsigned block)
757 {
758         struct bch_extent_stripe_ptr *dst = (void *) ptr;
759         union bch_extent_entry *end = extent_entry_last(e);
760
761         memmove_u64s_up(dst + 1, dst, (u64 *) end - (u64 *) dst);
762         e.k->u64s += sizeof(*dst) / sizeof(u64);
763
764         *dst = (struct bch_extent_stripe_ptr) {
765                 .type = 1 << BCH_EXTENT_ENTRY_stripe_ptr,
766                 .block          = block,
767                 .idx            = s->key.k.p.offset,
768         };
769 }
770
771 static int ec_stripe_update_ptrs(struct bch_fs *c,
772                                  struct ec_stripe_buf *s,
773                                  struct bkey *pos)
774 {
775         struct btree_trans trans;
776         struct btree_iter *iter;
777         struct bkey_s_c k;
778         struct bkey_s_extent e;
779         struct bkey_on_stack sk;
780         int ret = 0, dev, idx;
781
782         bkey_on_stack_init(&sk);
783         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
784
785         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
786                                    bkey_start_pos(pos),
787                                    BTREE_ITER_INTENT);
788
789         while ((k = bch2_btree_iter_peek(iter)).k &&
790                !(ret = bkey_err(k)) &&
791                bkey_cmp(bkey_start_pos(k.k), pos->p) < 0) {
792                 struct bch_extent_ptr *ptr, *ec_ptr = NULL;
793
794                 if (extent_has_stripe_ptr(k, s->key.k.p.offset)) {
795                         bch2_btree_iter_next(iter);
796                         continue;
797                 }
798
799                 idx = extent_matches_stripe(c, &s->key.v, k);
800                 if (idx < 0) {
801                         bch2_btree_iter_next(iter);
802                         continue;
803                 }
804
805                 bch2_btree_iter_set_pos(iter, bkey_start_pos(k.k));
806
807                 dev = s->key.v.ptrs[idx].dev;
808
809                 bkey_on_stack_reassemble(&sk, c, k);
810                 e = bkey_i_to_s_extent(sk.k);
811
812                 extent_for_each_ptr(e, ptr) {
813                         if (ptr->dev == dev)
814                                 ec_ptr = ptr;
815                         else
816                                 ptr->cached = true;
817                 }
818
819                 extent_stripe_ptr_add(e, s, ec_ptr, idx);
820
821                 bch2_trans_update(&trans, iter, sk.k, 0);
822
823                 ret = bch2_trans_commit(&trans, NULL, NULL,
824                                         BTREE_INSERT_NOFAIL|
825                                         BTREE_INSERT_USE_RESERVE);
826                 if (ret == -EINTR)
827                         ret = 0;
828                 if (ret)
829                         break;
830         }
831
832         bch2_trans_exit(&trans);
833         bkey_on_stack_exit(&sk, c);
834
835         return ret;
836 }
837
838 /*
839  * data buckets of new stripe all written: create the stripe
840  */
841 static void ec_stripe_create(struct ec_stripe_new *s)
842 {
843         struct bch_fs *c = s->c;
844         struct open_bucket *ob;
845         struct bkey_i *k;
846         struct bch_stripe *v = &s->stripe.key.v;
847         unsigned i, nr_data = v->nr_blocks - v->nr_redundant;
848         struct closure cl;
849         int ret;
850
851         BUG_ON(s->h->s == s);
852
853         closure_init_stack(&cl);
854
855         if (s->err) {
856                 bch_err(c, "error creating stripe: error writing data buckets");
857                 goto err;
858         }
859
860         if (!percpu_ref_tryget(&c->writes))
861                 goto err;
862
863         BUG_ON(bitmap_weight(s->blocks_allocated,
864                              s->blocks.nr) != s->blocks.nr);
865
866         ec_generate_ec(&s->stripe);
867
868         ec_generate_checksums(&s->stripe);
869
870         /* write p/q: */
871         for (i = nr_data; i < v->nr_blocks; i++)
872                 ec_block_io(c, &s->stripe, REQ_OP_WRITE, i, &cl);
873
874         closure_sync(&cl);
875
876         for (i = nr_data; i < v->nr_blocks; i++)
877                 if (!test_bit(i, s->stripe.valid)) {
878                         bch_err(c, "error creating stripe: error writing redundancy buckets");
879                         goto err_put_writes;
880                 }
881
882         mutex_lock(&c->ec_stripe_create_lock);
883
884         ret = ec_stripe_bkey_insert(c, &s->stripe.key);
885         if (ret) {
886                 bch_err(c, "error creating stripe: error creating stripe key");
887                 goto err_unlock;
888         }
889
890         for_each_keylist_key(&s->keys, k) {
891                 ret = ec_stripe_update_ptrs(c, &s->stripe, &k->k);
892                 if (ret)
893                         break;
894         }
895
896 err_unlock:
897         mutex_unlock(&c->ec_stripe_create_lock);
898 err_put_writes:
899         percpu_ref_put(&c->writes);
900 err:
901         open_bucket_for_each(c, &s->blocks, ob, i) {
902                 ob->ec = NULL;
903                 __bch2_open_bucket_put(c, ob);
904         }
905
906         bch2_open_buckets_put(c, &s->parity);
907
908         bch2_keylist_free(&s->keys, s->inline_keys);
909
910         mutex_lock(&s->h->lock);
911         list_del(&s->list);
912         mutex_unlock(&s->h->lock);
913
914         for (i = 0; i < s->stripe.key.v.nr_blocks; i++)
915                 kvpfree(s->stripe.data[i], s->stripe.size << 9);
916         kfree(s);
917 }
918
919 static struct ec_stripe_new *ec_stripe_set_pending(struct ec_stripe_head *h)
920 {
921         struct ec_stripe_new *s = h->s;
922
923         list_add(&s->list, &h->stripes);
924         h->s = NULL;
925
926         return s;
927 }
928
929 static void ec_stripe_new_put(struct ec_stripe_new *s)
930 {
931         BUG_ON(atomic_read(&s->pin) <= 0);
932         if (atomic_dec_and_test(&s->pin))
933                 ec_stripe_create(s);
934 }
935
936 /* have a full bucket - hand it off to be erasure coded: */
937 void bch2_ec_bucket_written(struct bch_fs *c, struct open_bucket *ob)
938 {
939         struct ec_stripe_new *s = ob->ec;
940
941         if (ob->sectors_free)
942                 s->err = -1;
943
944         ec_stripe_new_put(s);
945 }
946
947 void bch2_ec_bucket_cancel(struct bch_fs *c, struct open_bucket *ob)
948 {
949         struct ec_stripe_new *s = ob->ec;
950
951         s->err = -EIO;
952 }
953
954 void *bch2_writepoint_ec_buf(struct bch_fs *c, struct write_point *wp)
955 {
956         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
957         struct bch_dev *ca;
958         unsigned offset;
959
960         if (!ob)
961                 return NULL;
962
963         ca      = bch_dev_bkey_exists(c, ob->ptr.dev);
964         offset  = ca->mi.bucket_size - ob->sectors_free;
965
966         return ob->ec->stripe.data[ob->ec_idx] + (offset << 9);
967 }
968
969 void bch2_ec_add_backpointer(struct bch_fs *c, struct write_point *wp,
970                              struct bpos pos, unsigned sectors)
971 {
972         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
973         struct ec_stripe_new *ec;
974
975         if (!ob)
976                 return;
977
978         ec = ob->ec;
979         mutex_lock(&ec->lock);
980
981         if (bch2_keylist_realloc(&ec->keys, ec->inline_keys,
982                                  ARRAY_SIZE(ec->inline_keys),
983                                  BKEY_U64s)) {
984                 BUG();
985         }
986
987         bkey_init(&ec->keys.top->k);
988         ec->keys.top->k.p       = pos;
989         bch2_key_resize(&ec->keys.top->k, sectors);
990         bch2_keylist_push(&ec->keys);
991
992         mutex_unlock(&ec->lock);
993 }
994
995 static int unsigned_cmp(const void *_l, const void *_r)
996 {
997         unsigned l = *((const unsigned *) _l);
998         unsigned r = *((const unsigned *) _r);
999
1000         return cmp_int(l, r);
1001 }
1002
1003 /* pick most common bucket size: */
1004 static unsigned pick_blocksize(struct bch_fs *c,
1005                                struct bch_devs_mask *devs)
1006 {
1007         struct bch_dev *ca;
1008         unsigned i, nr = 0, sizes[BCH_SB_MEMBERS_MAX];
1009         struct {
1010                 unsigned nr, size;
1011         } cur = { 0, 0 }, best = { 0, 0 };
1012
1013         for_each_member_device_rcu(ca, c, i, devs)
1014                 sizes[nr++] = ca->mi.bucket_size;
1015
1016         sort(sizes, nr, sizeof(unsigned), unsigned_cmp, NULL);
1017
1018         for (i = 0; i < nr; i++) {
1019                 if (sizes[i] != cur.size) {
1020                         if (cur.nr > best.nr)
1021                                 best = cur;
1022
1023                         cur.nr = 0;
1024                         cur.size = sizes[i];
1025                 }
1026
1027                 cur.nr++;
1028         }
1029
1030         if (cur.nr > best.nr)
1031                 best = cur;
1032
1033         return best.size;
1034 }
1035
1036 int bch2_ec_stripe_new_alloc(struct bch_fs *c, struct ec_stripe_head *h)
1037 {
1038         struct ec_stripe_new *s;
1039         unsigned i;
1040
1041         BUG_ON(h->parity.nr != h->redundancy);
1042         BUG_ON(!h->blocks.nr);
1043         BUG_ON(h->parity.nr + h->blocks.nr > EC_STRIPE_MAX);
1044         lockdep_assert_held(&h->lock);
1045
1046         s = kzalloc(sizeof(*s), GFP_KERNEL);
1047         if (!s)
1048                 return -ENOMEM;
1049
1050         mutex_init(&s->lock);
1051         atomic_set(&s->pin, 1);
1052         s->c            = c;
1053         s->h            = h;
1054         s->blocks       = h->blocks;
1055         s->parity       = h->parity;
1056
1057         memset(&h->blocks, 0, sizeof(h->blocks));
1058         memset(&h->parity, 0, sizeof(h->parity));
1059
1060         bch2_keylist_init(&s->keys, s->inline_keys);
1061
1062         s->stripe.offset        = 0;
1063         s->stripe.size          = h->blocksize;
1064         memset(s->stripe.valid, 0xFF, sizeof(s->stripe.valid));
1065
1066         ec_stripe_key_init(c, &s->stripe.key,
1067                            &s->blocks, &s->parity,
1068                            h->blocksize);
1069
1070         for (i = 0; i < s->stripe.key.v.nr_blocks; i++) {
1071                 s->stripe.data[i] = kvpmalloc(s->stripe.size << 9, GFP_KERNEL);
1072                 if (!s->stripe.data[i])
1073                         goto err;
1074         }
1075
1076         h->s = s;
1077
1078         return 0;
1079 err:
1080         for (i = 0; i < s->stripe.key.v.nr_blocks; i++)
1081                 kvpfree(s->stripe.data[i], s->stripe.size << 9);
1082         kfree(s);
1083         return -ENOMEM;
1084 }
1085
1086 static struct ec_stripe_head *
1087 ec_new_stripe_head_alloc(struct bch_fs *c, unsigned target,
1088                          unsigned algo, unsigned redundancy)
1089 {
1090         struct ec_stripe_head *h;
1091         struct bch_dev *ca;
1092         unsigned i;
1093
1094         h = kzalloc(sizeof(*h), GFP_KERNEL);
1095         if (!h)
1096                 return NULL;
1097
1098         mutex_init(&h->lock);
1099         mutex_lock(&h->lock);
1100         INIT_LIST_HEAD(&h->stripes);
1101
1102         h->target       = target;
1103         h->algo         = algo;
1104         h->redundancy   = redundancy;
1105
1106         rcu_read_lock();
1107         h->devs = target_rw_devs(c, BCH_DATA_USER, target);
1108
1109         for_each_member_device_rcu(ca, c, i, &h->devs)
1110                 if (!ca->mi.durability)
1111                         __clear_bit(i, h->devs.d);
1112
1113         h->blocksize = pick_blocksize(c, &h->devs);
1114
1115         for_each_member_device_rcu(ca, c, i, &h->devs)
1116                 if (ca->mi.bucket_size == h->blocksize)
1117                         h->nr_active_devs++;
1118
1119         rcu_read_unlock();
1120         list_add(&h->list, &c->ec_new_stripe_list);
1121         return h;
1122 }
1123
1124 void bch2_ec_stripe_head_put(struct ec_stripe_head *h)
1125 {
1126         struct ec_stripe_new *s = NULL;
1127
1128         if (h->s &&
1129             bitmap_weight(h->s->blocks_allocated,
1130                           h->s->blocks.nr) == h->s->blocks.nr)
1131                 s = ec_stripe_set_pending(h);
1132
1133         mutex_unlock(&h->lock);
1134
1135         if (s)
1136                 ec_stripe_new_put(s);
1137 }
1138
1139 struct ec_stripe_head *bch2_ec_stripe_head_get(struct bch_fs *c,
1140                                                unsigned target,
1141                                                unsigned algo,
1142                                                unsigned redundancy)
1143 {
1144         struct ec_stripe_head *h;
1145
1146         if (!redundancy)
1147                 return NULL;
1148
1149         mutex_lock(&c->ec_new_stripe_lock);
1150         list_for_each_entry(h, &c->ec_new_stripe_list, list)
1151                 if (h->target           == target &&
1152                     h->algo             == algo &&
1153                     h->redundancy       == redundancy) {
1154                         mutex_lock(&h->lock);
1155                         goto found;
1156                 }
1157
1158         h = ec_new_stripe_head_alloc(c, target, algo, redundancy);
1159 found:
1160         mutex_unlock(&c->ec_new_stripe_lock);
1161         return h;
1162 }
1163
1164 void bch2_ec_stop_dev(struct bch_fs *c, struct bch_dev *ca)
1165 {
1166         struct ec_stripe_head *h;
1167         struct open_bucket *ob;
1168         unsigned i;
1169
1170         mutex_lock(&c->ec_new_stripe_lock);
1171         list_for_each_entry(h, &c->ec_new_stripe_list, list) {
1172                 struct ec_stripe_new *s = NULL;
1173
1174                 mutex_lock(&h->lock);
1175                 bch2_open_buckets_stop_dev(c, ca, &h->blocks);
1176                 bch2_open_buckets_stop_dev(c, ca, &h->parity);
1177
1178                 if (!h->s)
1179                         goto unlock;
1180
1181                 open_bucket_for_each(c, &h->s->blocks, ob, i)
1182                         if (ob->ptr.dev == ca->dev_idx)
1183                                 goto found;
1184                 open_bucket_for_each(c, &h->s->parity, ob, i)
1185                         if (ob->ptr.dev == ca->dev_idx)
1186                                 goto found;
1187                 goto unlock;
1188 found:
1189                 h->s->err = -1;
1190                 s = ec_stripe_set_pending(h);
1191 unlock:
1192                 mutex_unlock(&h->lock);
1193
1194                 if (s)
1195                         ec_stripe_new_put(s);
1196         }
1197         mutex_unlock(&c->ec_new_stripe_lock);
1198 }
1199
1200 static int __bch2_stripe_write_key(struct btree_trans *trans,
1201                                    struct btree_iter *iter,
1202                                    struct stripe *m,
1203                                    size_t idx,
1204                                    struct bkey_i_stripe *new_key,
1205                                    unsigned flags)
1206 {
1207         struct bch_fs *c = trans->c;
1208         struct bkey_s_c k;
1209         unsigned i;
1210         int ret;
1211
1212         bch2_btree_iter_set_pos(iter, POS(0, idx));
1213
1214         k = bch2_btree_iter_peek_slot(iter);
1215         ret = bkey_err(k);
1216         if (ret)
1217                 return ret;
1218
1219         if (k.k->type != KEY_TYPE_stripe)
1220                 return -EIO;
1221
1222         bkey_reassemble(&new_key->k_i, k);
1223
1224         spin_lock(&c->ec_stripes_heap_lock);
1225
1226         for (i = 0; i < new_key->v.nr_blocks; i++)
1227                 stripe_blockcount_set(&new_key->v, i,
1228                                       m->block_sectors[i]);
1229         m->dirty = false;
1230
1231         spin_unlock(&c->ec_stripes_heap_lock);
1232
1233         bch2_trans_update(trans, iter, &new_key->k_i, 0);
1234
1235         return bch2_trans_commit(trans, NULL, NULL,
1236                                  BTREE_INSERT_NOFAIL|flags);
1237 }
1238
1239 int bch2_stripes_write(struct bch_fs *c, unsigned flags, bool *wrote)
1240 {
1241         struct btree_trans trans;
1242         struct btree_iter *iter;
1243         struct genradix_iter giter;
1244         struct bkey_i_stripe *new_key;
1245         struct stripe *m;
1246         int ret = 0;
1247
1248         new_key = kmalloc(255 * sizeof(u64), GFP_KERNEL);
1249         BUG_ON(!new_key);
1250
1251         bch2_trans_init(&trans, c, 0, 0);
1252
1253         iter = bch2_trans_get_iter(&trans, BTREE_ID_EC, POS_MIN,
1254                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1255
1256         genradix_for_each(&c->stripes[0], giter, m) {
1257                 if (!m->dirty)
1258                         continue;
1259
1260                 do {
1261                         bch2_trans_reset(&trans, TRANS_RESET_MEM);
1262
1263                         ret = __bch2_stripe_write_key(&trans, iter, m,
1264                                         giter.pos, new_key, flags);
1265                 } while (ret == -EINTR);
1266
1267                 if (ret)
1268                         break;
1269
1270                 *wrote = true;
1271         }
1272
1273         bch2_trans_exit(&trans);
1274
1275         kfree(new_key);
1276
1277         return ret;
1278 }
1279
1280 int bch2_stripes_read(struct bch_fs *c, struct journal_keys *journal_keys)
1281 {
1282         struct btree_trans trans;
1283         struct btree_and_journal_iter iter;
1284         struct bkey_s_c k;
1285         int ret;
1286
1287         ret = bch2_fs_ec_start(c);
1288         if (ret)
1289                 return ret;
1290
1291         bch2_trans_init(&trans, c, 0, 0);
1292
1293         bch2_btree_and_journal_iter_init(&iter, &trans, journal_keys,
1294                                          BTREE_ID_EC, POS_MIN);
1295
1296
1297         while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
1298                 bch2_mark_key(c, k, 0, 0, NULL, 0,
1299                               BTREE_TRIGGER_ALLOC_READ|
1300                               BTREE_TRIGGER_NOATOMIC);
1301
1302                 bch2_btree_and_journal_iter_advance(&iter);
1303         }
1304
1305         ret = bch2_trans_exit(&trans) ?: ret;
1306         if (ret) {
1307                 bch_err(c, "error reading stripes: %i", ret);
1308                 return ret;
1309         }
1310
1311         return 0;
1312 }
1313
1314 int bch2_ec_mem_alloc(struct bch_fs *c, bool gc)
1315 {
1316         struct btree_trans trans;
1317         struct btree_iter *iter;
1318         struct bkey_s_c k;
1319         size_t i, idx = 0;
1320         int ret = 0;
1321
1322         bch2_trans_init(&trans, c, 0, 0);
1323
1324         iter = bch2_trans_get_iter(&trans, BTREE_ID_EC, POS(0, U64_MAX), 0);
1325
1326         k = bch2_btree_iter_prev(iter);
1327         if (!IS_ERR_OR_NULL(k.k))
1328                 idx = k.k->p.offset + 1;
1329         ret = bch2_trans_exit(&trans);
1330         if (ret)
1331                 return ret;
1332
1333         if (!idx)
1334                 return 0;
1335
1336         if (!gc &&
1337             !init_heap(&c->ec_stripes_heap, roundup_pow_of_two(idx),
1338                        GFP_KERNEL))
1339                 return -ENOMEM;
1340 #if 0
1341         ret = genradix_prealloc(&c->stripes[gc], idx, GFP_KERNEL);
1342 #else
1343         for (i = 0; i < idx; i++)
1344                 if (!genradix_ptr_alloc(&c->stripes[gc], i, GFP_KERNEL))
1345                         return -ENOMEM;
1346 #endif
1347         return 0;
1348 }
1349
1350 int bch2_fs_ec_start(struct bch_fs *c)
1351 {
1352         return bch2_ec_mem_alloc(c, false);
1353 }
1354
1355 void bch2_fs_ec_exit(struct bch_fs *c)
1356 {
1357         struct ec_stripe_head *h;
1358
1359         while (1) {
1360                 mutex_lock(&c->ec_new_stripe_lock);
1361                 h = list_first_entry_or_null(&c->ec_new_stripe_list,
1362                                              struct ec_stripe_head, list);
1363                 if (h)
1364                         list_del(&h->list);
1365                 mutex_unlock(&c->ec_new_stripe_lock);
1366                 if (!h)
1367                         break;
1368
1369                 BUG_ON(h->s);
1370                 BUG_ON(!list_empty(&h->stripes));
1371                 kfree(h);
1372         }
1373
1374         free_heap(&c->ec_stripes_heap);
1375         genradix_free(&c->stripes[0]);
1376         bioset_exit(&c->ec_bioset);
1377 }
1378
1379 int bch2_fs_ec_init(struct bch_fs *c)
1380 {
1381         INIT_WORK(&c->ec_stripe_delete_work, ec_stripe_delete_work);
1382
1383         return bioset_init(&c->ec_bioset, 1, offsetof(struct ec_bio, bio),
1384                            BIOSET_NEED_BVECS);
1385 }