]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/ec.c
Update bcachefs sources to 44dc1f2695 bcachefs: Fix stripe_idx_to_delete()
[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 "bset.h"
8 #include "btree_gc.h"
9 #include "btree_update.h"
10 #include "buckets.h"
11 #include "disk_groups.h"
12 #include "ec.h"
13 #include "error.h"
14 #include "io.h"
15 #include "keylist.h"
16 #include "recovery.h"
17 #include "super-io.h"
18 #include "util.h"
19
20 #include <linux/sort.h>
21
22 #ifdef __KERNEL__
23
24 #include <linux/raid/pq.h>
25 #include <linux/raid/xor.h>
26
27 static void raid5_recov(unsigned disks, unsigned failed_idx,
28                         size_t size, void **data)
29 {
30         unsigned i = 2, nr;
31
32         BUG_ON(failed_idx >= disks);
33
34         swap(data[0], data[failed_idx]);
35         memcpy(data[0], data[1], size);
36
37         while (i < disks) {
38                 nr = min_t(unsigned, disks - i, MAX_XOR_BLOCKS);
39                 xor_blocks(nr, size, data[0], data + i);
40                 i += nr;
41         }
42
43         swap(data[0], data[failed_idx]);
44 }
45
46 static void raid_gen(int nd, int np, size_t size, void **v)
47 {
48         if (np >= 1)
49                 raid5_recov(nd + np, nd, size, v);
50         if (np >= 2)
51                 raid6_call.gen_syndrome(nd + np, size, v);
52         BUG_ON(np > 2);
53 }
54
55 static void raid_rec(int nr, int *ir, int nd, int np, size_t size, void **v)
56 {
57         switch (nr) {
58         case 0:
59                 break;
60         case 1:
61                 if (ir[0] < nd + 1)
62                         raid5_recov(nd + 1, ir[0], size, v);
63                 else
64                         raid6_call.gen_syndrome(nd + np, size, v);
65                 break;
66         case 2:
67                 if (ir[1] < nd) {
68                         /* data+data failure. */
69                         raid6_2data_recov(nd + np, size, ir[0], ir[1], v);
70                 } else if (ir[0] < nd) {
71                         /* data + p/q failure */
72
73                         if (ir[1] == nd) /* data + p failure */
74                                 raid6_datap_recov(nd + np, size, ir[0], v);
75                         else { /* data + q failure */
76                                 raid5_recov(nd + 1, ir[0], size, v);
77                                 raid6_call.gen_syndrome(nd + np, size, v);
78                         }
79                 } else {
80                         raid_gen(nd, np, size, v);
81                 }
82                 break;
83         default:
84                 BUG();
85         }
86 }
87
88 #else
89
90 #include <raid/raid.h>
91
92 #endif
93
94 struct ec_bio {
95         struct bch_dev          *ca;
96         struct ec_stripe_buf    *buf;
97         size_t                  idx;
98         struct bio              bio;
99 };
100
101 /* Stripes btree keys: */
102
103 const char *bch2_stripe_invalid(const struct bch_fs *c, struct bkey_s_c k)
104 {
105         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
106
107         if (k.k->p.inode)
108                 return "invalid stripe key";
109
110         if (bkey_val_bytes(k.k) < sizeof(*s))
111                 return "incorrect value size";
112
113         if (bkey_val_bytes(k.k) < sizeof(*s) ||
114             bkey_val_u64s(k.k) < stripe_val_u64s(s))
115                 return "incorrect value size";
116
117         return bch2_bkey_ptrs_invalid(c, k);
118 }
119
120 void bch2_stripe_to_text(struct printbuf *out, struct bch_fs *c,
121                          struct bkey_s_c k)
122 {
123         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
124         unsigned i;
125
126         pr_buf(out, "algo %u sectors %u blocks %u:%u csum %u gran %u",
127                s->algorithm,
128                le16_to_cpu(s->sectors),
129                s->nr_blocks - s->nr_redundant,
130                s->nr_redundant,
131                s->csum_type,
132                1U << s->csum_granularity_bits);
133
134         for (i = 0; i < s->nr_blocks; i++)
135                 pr_buf(out, " %u:%llu:%u", s->ptrs[i].dev,
136                        (u64) s->ptrs[i].offset,
137                        stripe_blockcount_get(s, i));
138
139         bch2_bkey_ptrs_to_text(out, c, k);
140 }
141
142 static int ptr_matches_stripe(struct bch_fs *c,
143                               struct bch_stripe *v,
144                               const struct bch_extent_ptr *ptr)
145 {
146         unsigned i;
147
148         for (i = 0; i < v->nr_blocks - v->nr_redundant; i++) {
149                 const struct bch_extent_ptr *ptr2 = v->ptrs + i;
150
151                 if (ptr->dev == ptr2->dev &&
152                     ptr->gen == ptr2->gen &&
153                     ptr->offset >= ptr2->offset &&
154                     ptr->offset <  ptr2->offset + le16_to_cpu(v->sectors))
155                         return i;
156         }
157
158         return -1;
159 }
160
161 static int extent_matches_stripe(struct bch_fs *c,
162                                  struct bch_stripe *v,
163                                  struct bkey_s_c k)
164 {
165         struct bkey_s_c_extent e;
166         const struct bch_extent_ptr *ptr;
167         int idx;
168
169         if (!bkey_extent_is_data(k.k))
170                 return -1;
171
172         e = bkey_s_c_to_extent(k);
173
174         extent_for_each_ptr(e, ptr) {
175                 idx = ptr_matches_stripe(c, v, ptr);
176                 if (idx >= 0)
177                         return idx;
178         }
179
180         return -1;
181 }
182
183 static bool extent_has_stripe_ptr(struct bkey_s_c k, u64 idx)
184 {
185         struct bkey_s_c_extent e;
186         const union bch_extent_entry *entry;
187
188         if (!bkey_extent_is_data(k.k))
189                 return false;
190
191         e = bkey_s_c_to_extent(k);
192
193         extent_for_each_entry(e, entry)
194                 if (extent_entry_type(entry) ==
195                     BCH_EXTENT_ENTRY_stripe_ptr &&
196                     entry->stripe_ptr.idx == idx)
197                         return true;
198
199         return false;
200 }
201
202 static void ec_stripe_key_init(struct bch_fs *c,
203                                struct bkey_i_stripe *s,
204                                struct open_buckets *blocks,
205                                struct open_buckets *parity,
206                                unsigned stripe_size)
207 {
208         struct open_bucket *ob;
209         unsigned i, u64s;
210
211         bkey_stripe_init(&s->k_i);
212         s->v.sectors                    = cpu_to_le16(stripe_size);
213         s->v.algorithm                  = 0;
214         s->v.nr_blocks                  = parity->nr + blocks->nr;
215         s->v.nr_redundant               = parity->nr;
216         s->v.csum_granularity_bits      = ilog2(c->sb.encoded_extent_max);
217         s->v.csum_type                  = BCH_CSUM_CRC32C;
218         s->v.pad                        = 0;
219
220         open_bucket_for_each(c, blocks, ob, i)
221                 s->v.ptrs[i]                    = ob->ptr;
222
223         open_bucket_for_each(c, parity, ob, i)
224                 s->v.ptrs[blocks->nr + i]       = ob->ptr;
225
226         while ((u64s = stripe_val_u64s(&s->v)) > BKEY_VAL_U64s_MAX) {
227                 BUG_ON(1 << s->v.csum_granularity_bits >=
228                        le16_to_cpu(s->v.sectors) ||
229                        s->v.csum_granularity_bits == U8_MAX);
230                 s->v.csum_granularity_bits++;
231         }
232
233         set_bkey_val_u64s(&s->k, u64s);
234 }
235
236 /* Checksumming: */
237
238 static void ec_generate_checksums(struct ec_stripe_buf *buf)
239 {
240         struct bch_stripe *v = &buf->key.v;
241         unsigned csum_granularity = 1 << v->csum_granularity_bits;
242         unsigned csums_per_device = stripe_csums_per_device(v);
243         unsigned csum_bytes = bch_crc_bytes[v->csum_type];
244         unsigned i, j;
245
246         if (!csum_bytes)
247                 return;
248
249         BUG_ON(buf->offset);
250         BUG_ON(buf->size != le16_to_cpu(v->sectors));
251
252         for (i = 0; i < v->nr_blocks; i++) {
253                 for (j = 0; j < csums_per_device; j++) {
254                         unsigned offset = j << v->csum_granularity_bits;
255                         unsigned len = min(csum_granularity, buf->size - offset);
256
257                         struct bch_csum csum =
258                                 bch2_checksum(NULL, v->csum_type,
259                                               null_nonce(),
260                                               buf->data[i] + (offset << 9),
261                                               len << 9);
262
263                         memcpy(stripe_csum(v, i, j), &csum, csum_bytes);
264                 }
265         }
266 }
267
268 static void ec_validate_checksums(struct bch_fs *c, struct ec_stripe_buf *buf)
269 {
270         struct bch_stripe *v = &buf->key.v;
271         unsigned csum_granularity = 1 << v->csum_granularity_bits;
272         unsigned csum_bytes = bch_crc_bytes[v->csum_type];
273         unsigned i;
274
275         if (!csum_bytes)
276                 return;
277
278         for (i = 0; i < v->nr_blocks; i++) {
279                 unsigned offset = buf->offset;
280                 unsigned end = buf->offset + buf->size;
281
282                 if (!test_bit(i, buf->valid))
283                         continue;
284
285                 while (offset < end) {
286                         unsigned j = offset >> v->csum_granularity_bits;
287                         unsigned len = min(csum_granularity, end - offset);
288                         struct bch_csum csum;
289
290                         BUG_ON(offset & (csum_granularity - 1));
291                         BUG_ON(offset + len != le16_to_cpu(v->sectors) &&
292                                ((offset + len) & (csum_granularity - 1)));
293
294                         csum = bch2_checksum(NULL, v->csum_type,
295                                              null_nonce(),
296                                              buf->data[i] + ((offset - buf->offset) << 9),
297                                              len << 9);
298
299                         if (memcmp(stripe_csum(v, i, j), &csum, csum_bytes)) {
300                                 __bcache_io_error(c,
301                                         "checksum error while doing reconstruct read (%u:%u)",
302                                         i, j);
303                                 clear_bit(i, buf->valid);
304                                 break;
305                         }
306
307                         offset += len;
308                 }
309         }
310 }
311
312 /* Erasure coding: */
313
314 static void ec_generate_ec(struct ec_stripe_buf *buf)
315 {
316         struct bch_stripe *v = &buf->key.v;
317         unsigned nr_data = v->nr_blocks - v->nr_redundant;
318         unsigned bytes = le16_to_cpu(v->sectors) << 9;
319
320         raid_gen(nr_data, v->nr_redundant, bytes, buf->data);
321 }
322
323 static unsigned __ec_nr_failed(struct ec_stripe_buf *buf, unsigned nr)
324 {
325         return nr - bitmap_weight(buf->valid, nr);
326 }
327
328 static unsigned ec_nr_failed(struct ec_stripe_buf *buf)
329 {
330         return __ec_nr_failed(buf, buf->key.v.nr_blocks);
331 }
332
333 static int ec_do_recov(struct bch_fs *c, struct ec_stripe_buf *buf)
334 {
335         struct bch_stripe *v = &buf->key.v;
336         unsigned i, failed[EC_STRIPE_MAX], nr_failed = 0;
337         unsigned nr_data = v->nr_blocks - v->nr_redundant;
338         unsigned bytes = buf->size << 9;
339
340         if (ec_nr_failed(buf) > v->nr_redundant) {
341                 __bcache_io_error(c,
342                         "error doing reconstruct read: unable to read enough blocks");
343                 return -1;
344         }
345
346         for (i = 0; i < nr_data; i++)
347                 if (!test_bit(i, buf->valid))
348                         failed[nr_failed++] = i;
349
350         raid_rec(nr_failed, failed, nr_data, v->nr_redundant, bytes, buf->data);
351         return 0;
352 }
353
354 /* IO: */
355
356 static void ec_block_endio(struct bio *bio)
357 {
358         struct ec_bio *ec_bio = container_of(bio, struct ec_bio, bio);
359         struct bch_dev *ca = ec_bio->ca;
360         struct closure *cl = bio->bi_private;
361
362         if (bch2_dev_io_err_on(bio->bi_status, ca, "erasure coding"))
363                 clear_bit(ec_bio->idx, ec_bio->buf->valid);
364
365         bio_put(&ec_bio->bio);
366         percpu_ref_put(&ca->io_ref);
367         closure_put(cl);
368 }
369
370 static void ec_block_io(struct bch_fs *c, struct ec_stripe_buf *buf,
371                         unsigned rw, unsigned idx, struct closure *cl)
372 {
373         struct bch_stripe *v = &buf->key.v;
374         unsigned offset = 0, bytes = buf->size << 9;
375         struct bch_extent_ptr *ptr = &v->ptrs[idx];
376         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
377
378         if (!bch2_dev_get_ioref(ca, rw)) {
379                 clear_bit(idx, buf->valid);
380                 return;
381         }
382
383         while (offset < bytes) {
384                 unsigned nr_iovecs = min_t(size_t, BIO_MAX_PAGES,
385                                            DIV_ROUND_UP(bytes, PAGE_SIZE));
386                 unsigned b = min_t(size_t, bytes - offset,
387                                    nr_iovecs << PAGE_SHIFT);
388                 struct ec_bio *ec_bio;
389
390                 ec_bio = container_of(bio_alloc_bioset(GFP_KERNEL, nr_iovecs,
391                                                        &c->ec_bioset),
392                                       struct ec_bio, bio);
393
394                 ec_bio->ca                      = ca;
395                 ec_bio->buf                     = buf;
396                 ec_bio->idx                     = idx;
397
398                 bio_set_dev(&ec_bio->bio, ca->disk_sb.bdev);
399                 bio_set_op_attrs(&ec_bio->bio, rw, 0);
400
401                 ec_bio->bio.bi_iter.bi_sector   = ptr->offset + buf->offset + (offset >> 9);
402                 ec_bio->bio.bi_end_io           = ec_block_endio;
403                 ec_bio->bio.bi_private          = cl;
404
405                 bch2_bio_map(&ec_bio->bio, buf->data[idx] + offset, b);
406
407                 closure_get(cl);
408                 percpu_ref_get(&ca->io_ref);
409
410                 submit_bio(&ec_bio->bio);
411
412                 offset += b;
413         }
414
415         percpu_ref_put(&ca->io_ref);
416 }
417
418 /* recovery read path: */
419 int bch2_ec_read_extent(struct bch_fs *c, struct bch_read_bio *rbio)
420 {
421         struct btree_trans trans;
422         struct btree_iter *iter;
423         struct ec_stripe_buf *buf;
424         struct closure cl;
425         struct bkey_s_c k;
426         struct bch_stripe *v;
427         unsigned stripe_idx;
428         unsigned offset, end;
429         unsigned i, nr_data, csum_granularity;
430         int ret = 0, idx;
431
432         closure_init_stack(&cl);
433
434         BUG_ON(!rbio->pick.idx ||
435                rbio->pick.idx - 1 >= rbio->pick.ec_nr);
436
437         stripe_idx = rbio->pick.ec[rbio->pick.idx - 1].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))
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         int ret;
706
707         bch2_trans_init(&trans, c, 0, 0);
708 retry:
709         bch2_trans_begin(&trans);
710
711         /* XXX: start pos hint */
712         for_each_btree_key(&trans, iter, BTREE_ID_EC, POS_MIN,
713                            BTREE_ITER_SLOTS|BTREE_ITER_INTENT, k, ret) {
714                 if (bkey_cmp(k.k->p, POS(0, U32_MAX)) > 0)
715                         break;
716
717                 if (bkey_deleted(k.k))
718                         goto found_slot;
719         }
720
721         if (!ret)
722                 ret = -ENOSPC;
723         goto err;
724 found_slot:
725         ret = ec_stripe_mem_alloc(c, iter);
726         if (ret)
727                 goto err;
728
729         stripe->k.p = iter->pos;
730
731         bch2_trans_update(&trans, BTREE_INSERT_ENTRY(iter, &stripe->k_i));
732
733         ret = bch2_trans_commit(&trans, NULL, NULL,
734                                 BTREE_INSERT_ATOMIC|
735                                 BTREE_INSERT_NOFAIL);
736 err:
737         if (ret == -EINTR)
738                 goto retry;
739         bch2_trans_exit(&trans);
740
741         return ret;
742 }
743
744 static void extent_stripe_ptr_add(struct bkey_s_extent e,
745                                   struct ec_stripe_buf *s,
746                                   struct bch_extent_ptr *ptr,
747                                   unsigned block)
748 {
749         struct bch_extent_stripe_ptr *dst = (void *) ptr;
750         union bch_extent_entry *end = extent_entry_last(e);
751
752         memmove_u64s_up(dst + 1, dst, (u64 *) end - (u64 *) dst);
753         e.k->u64s += sizeof(*dst) / sizeof(u64);
754
755         *dst = (struct bch_extent_stripe_ptr) {
756                 .type = 1 << BCH_EXTENT_ENTRY_stripe_ptr,
757                 .block          = block,
758                 .idx            = s->key.k.p.offset,
759         };
760 }
761
762 static int ec_stripe_update_ptrs(struct bch_fs *c,
763                                  struct ec_stripe_buf *s,
764                                  struct bkey *pos)
765 {
766         struct btree_trans trans;
767         struct btree_iter *iter;
768         struct bkey_s_c k;
769         struct bkey_s_extent e;
770         struct bch_extent_ptr *ptr;
771         BKEY_PADDED(k) tmp;
772         int ret = 0, dev, idx;
773
774         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
775
776         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
777                                    bkey_start_pos(pos),
778                                    BTREE_ITER_INTENT);
779
780         while ((k = bch2_btree_iter_peek(iter)).k &&
781                !(ret = bkey_err(k)) &&
782                bkey_cmp(bkey_start_pos(k.k), pos->p) < 0) {
783                 if (extent_has_stripe_ptr(k, s->key.k.p.offset)) {
784                         bch2_btree_iter_next(iter);
785                         continue;
786                 }
787
788                 idx = extent_matches_stripe(c, &s->key.v, k);
789                 if (idx < 0) {
790                         bch2_btree_iter_next(iter);
791                         continue;
792                 }
793
794                 bch2_btree_iter_set_pos(iter, bkey_start_pos(k.k));
795
796                 dev = s->key.v.ptrs[idx].dev;
797
798                 bkey_reassemble(&tmp.k, k);
799                 e = bkey_i_to_s_extent(&tmp.k);
800
801                 extent_for_each_ptr(e, ptr)
802                         if (ptr->dev != dev)
803                                 ptr->cached = true;
804
805                 ptr = (void *) bch2_extent_has_device(e.c, dev);
806                 BUG_ON(!ptr);
807
808                 extent_stripe_ptr_add(e, s, ptr, idx);
809
810                 bch2_trans_update(&trans, BTREE_INSERT_ENTRY(iter, &tmp.k));
811
812                 ret = bch2_trans_commit(&trans, NULL, NULL,
813                                         BTREE_INSERT_ATOMIC|
814                                         BTREE_INSERT_NOFAIL|
815                                         BTREE_INSERT_USE_RESERVE);
816                 if (ret == -EINTR)
817                         ret = 0;
818                 if (ret)
819                         break;
820         }
821
822         bch2_trans_exit(&trans);
823
824         return ret;
825 }
826
827 /*
828  * data buckets of new stripe all written: create the stripe
829  */
830 static void ec_stripe_create(struct ec_stripe_new *s)
831 {
832         struct bch_fs *c = s->c;
833         struct open_bucket *ob;
834         struct bkey_i *k;
835         struct bch_stripe *v = &s->stripe.key.v;
836         unsigned i, nr_data = v->nr_blocks - v->nr_redundant;
837         struct closure cl;
838         int ret;
839
840         BUG_ON(s->h->s == s);
841
842         closure_init_stack(&cl);
843
844         if (s->err) {
845                 bch_err(c, "error creating stripe: error writing data buckets");
846                 goto err;
847         }
848
849         if (!percpu_ref_tryget(&c->writes))
850                 goto err;
851
852         BUG_ON(bitmap_weight(s->blocks_allocated,
853                              s->blocks.nr) != s->blocks.nr);
854
855         ec_generate_ec(&s->stripe);
856
857         ec_generate_checksums(&s->stripe);
858
859         /* write p/q: */
860         for (i = nr_data; i < v->nr_blocks; i++)
861                 ec_block_io(c, &s->stripe, REQ_OP_WRITE, i, &cl);
862
863         closure_sync(&cl);
864
865         for (i = nr_data; i < v->nr_blocks; i++)
866                 if (!test_bit(i, s->stripe.valid)) {
867                         bch_err(c, "error creating stripe: error writing redundancy buckets");
868                         goto err_put_writes;
869                 }
870
871         mutex_lock(&c->ec_stripe_create_lock);
872
873         ret = ec_stripe_bkey_insert(c, &s->stripe.key);
874         if (ret) {
875                 bch_err(c, "error creating stripe: error creating stripe key");
876                 goto err_unlock;
877         }
878
879         for_each_keylist_key(&s->keys, k) {
880                 ret = ec_stripe_update_ptrs(c, &s->stripe, &k->k);
881                 if (ret)
882                         break;
883         }
884
885 err_unlock:
886         mutex_unlock(&c->ec_stripe_create_lock);
887 err_put_writes:
888         percpu_ref_put(&c->writes);
889 err:
890         open_bucket_for_each(c, &s->blocks, ob, i) {
891                 ob->ec = NULL;
892                 __bch2_open_bucket_put(c, ob);
893         }
894
895         bch2_open_buckets_put(c, &s->parity);
896
897         bch2_keylist_free(&s->keys, s->inline_keys);
898
899         mutex_lock(&s->h->lock);
900         list_del(&s->list);
901         mutex_unlock(&s->h->lock);
902
903         for (i = 0; i < s->stripe.key.v.nr_blocks; i++)
904                 kvpfree(s->stripe.data[i], s->stripe.size << 9);
905         kfree(s);
906 }
907
908 static struct ec_stripe_new *ec_stripe_set_pending(struct ec_stripe_head *h)
909 {
910         struct ec_stripe_new *s = h->s;
911
912         list_add(&s->list, &h->stripes);
913         h->s = NULL;
914
915         return s;
916 }
917
918 static void ec_stripe_new_put(struct ec_stripe_new *s)
919 {
920         BUG_ON(atomic_read(&s->pin) <= 0);
921         if (atomic_dec_and_test(&s->pin))
922                 ec_stripe_create(s);
923 }
924
925 /* have a full bucket - hand it off to be erasure coded: */
926 void bch2_ec_bucket_written(struct bch_fs *c, struct open_bucket *ob)
927 {
928         struct ec_stripe_new *s = ob->ec;
929
930         if (ob->sectors_free)
931                 s->err = -1;
932
933         ec_stripe_new_put(s);
934 }
935
936 void bch2_ec_bucket_cancel(struct bch_fs *c, struct open_bucket *ob)
937 {
938         struct ec_stripe_new *s = ob->ec;
939
940         s->err = -EIO;
941 }
942
943 void *bch2_writepoint_ec_buf(struct bch_fs *c, struct write_point *wp)
944 {
945         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
946         struct bch_dev *ca;
947         unsigned offset;
948
949         if (!ob)
950                 return NULL;
951
952         ca      = bch_dev_bkey_exists(c, ob->ptr.dev);
953         offset  = ca->mi.bucket_size - ob->sectors_free;
954
955         return ob->ec->stripe.data[ob->ec_idx] + (offset << 9);
956 }
957
958 void bch2_ec_add_backpointer(struct bch_fs *c, struct write_point *wp,
959                              struct bpos pos, unsigned sectors)
960 {
961         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
962         struct ec_stripe_new *ec;
963
964         if (!ob)
965                 return;
966
967         ec = ob->ec;
968         mutex_lock(&ec->lock);
969
970         if (bch2_keylist_realloc(&ec->keys, ec->inline_keys,
971                                  ARRAY_SIZE(ec->inline_keys),
972                                  BKEY_U64s)) {
973                 BUG();
974         }
975
976         bkey_init(&ec->keys.top->k);
977         ec->keys.top->k.p       = pos;
978         bch2_key_resize(&ec->keys.top->k, sectors);
979         bch2_keylist_push(&ec->keys);
980
981         mutex_unlock(&ec->lock);
982 }
983
984 static int unsigned_cmp(const void *_l, const void *_r)
985 {
986         unsigned l = *((const unsigned *) _l);
987         unsigned r = *((const unsigned *) _r);
988
989         return cmp_int(l, r);
990 }
991
992 /* pick most common bucket size: */
993 static unsigned pick_blocksize(struct bch_fs *c,
994                                struct bch_devs_mask *devs)
995 {
996         struct bch_dev *ca;
997         unsigned i, nr = 0, sizes[BCH_SB_MEMBERS_MAX];
998         struct {
999                 unsigned nr, size;
1000         } cur = { 0, 0 }, best = { 0, 0 };
1001
1002         for_each_member_device_rcu(ca, c, i, devs)
1003                 sizes[nr++] = ca->mi.bucket_size;
1004
1005         sort(sizes, nr, sizeof(unsigned), unsigned_cmp, NULL);
1006
1007         for (i = 0; i < nr; i++) {
1008                 if (sizes[i] != cur.size) {
1009                         if (cur.nr > best.nr)
1010                                 best = cur;
1011
1012                         cur.nr = 0;
1013                         cur.size = sizes[i];
1014                 }
1015
1016                 cur.nr++;
1017         }
1018
1019         if (cur.nr > best.nr)
1020                 best = cur;
1021
1022         return best.size;
1023 }
1024
1025 int bch2_ec_stripe_new_alloc(struct bch_fs *c, struct ec_stripe_head *h)
1026 {
1027         struct ec_stripe_new *s;
1028         unsigned i;
1029
1030         BUG_ON(h->parity.nr != h->redundancy);
1031         BUG_ON(!h->blocks.nr);
1032         BUG_ON(h->parity.nr + h->blocks.nr > EC_STRIPE_MAX);
1033         lockdep_assert_held(&h->lock);
1034
1035         s = kzalloc(sizeof(*s), GFP_KERNEL);
1036         if (!s)
1037                 return -ENOMEM;
1038
1039         mutex_init(&s->lock);
1040         atomic_set(&s->pin, 1);
1041         s->c            = c;
1042         s->h            = h;
1043         s->blocks       = h->blocks;
1044         s->parity       = h->parity;
1045
1046         memset(&h->blocks, 0, sizeof(h->blocks));
1047         memset(&h->parity, 0, sizeof(h->parity));
1048
1049         bch2_keylist_init(&s->keys, s->inline_keys);
1050
1051         s->stripe.offset        = 0;
1052         s->stripe.size          = h->blocksize;
1053         memset(s->stripe.valid, 0xFF, sizeof(s->stripe.valid));
1054
1055         ec_stripe_key_init(c, &s->stripe.key,
1056                            &s->blocks, &s->parity,
1057                            h->blocksize);
1058
1059         for (i = 0; i < s->stripe.key.v.nr_blocks; i++) {
1060                 s->stripe.data[i] = kvpmalloc(s->stripe.size << 9, GFP_KERNEL);
1061                 if (!s->stripe.data[i])
1062                         goto err;
1063         }
1064
1065         h->s = s;
1066
1067         return 0;
1068 err:
1069         for (i = 0; i < s->stripe.key.v.nr_blocks; i++)
1070                 kvpfree(s->stripe.data[i], s->stripe.size << 9);
1071         kfree(s);
1072         return -ENOMEM;
1073 }
1074
1075 static struct ec_stripe_head *
1076 ec_new_stripe_head_alloc(struct bch_fs *c, unsigned target,
1077                          unsigned algo, unsigned redundancy)
1078 {
1079         struct ec_stripe_head *h;
1080         struct bch_dev *ca;
1081         unsigned i;
1082
1083         h = kzalloc(sizeof(*h), GFP_KERNEL);
1084         if (!h)
1085                 return NULL;
1086
1087         mutex_init(&h->lock);
1088         mutex_lock(&h->lock);
1089         INIT_LIST_HEAD(&h->stripes);
1090
1091         h->target       = target;
1092         h->algo         = algo;
1093         h->redundancy   = redundancy;
1094
1095         rcu_read_lock();
1096         h->devs = target_rw_devs(c, BCH_DATA_USER, target);
1097
1098         for_each_member_device_rcu(ca, c, i, &h->devs)
1099                 if (!ca->mi.durability)
1100                         __clear_bit(i, h->devs.d);
1101
1102         h->blocksize = pick_blocksize(c, &h->devs);
1103
1104         for_each_member_device_rcu(ca, c, i, &h->devs)
1105                 if (ca->mi.bucket_size == h->blocksize)
1106                         h->nr_active_devs++;
1107
1108         rcu_read_unlock();
1109         list_add(&h->list, &c->ec_new_stripe_list);
1110         return h;
1111 }
1112
1113 void bch2_ec_stripe_head_put(struct ec_stripe_head *h)
1114 {
1115         struct ec_stripe_new *s = NULL;
1116
1117         if (h->s &&
1118             bitmap_weight(h->s->blocks_allocated,
1119                           h->s->blocks.nr) == h->s->blocks.nr)
1120                 s = ec_stripe_set_pending(h);
1121
1122         mutex_unlock(&h->lock);
1123
1124         if (s)
1125                 ec_stripe_new_put(s);
1126 }
1127
1128 struct ec_stripe_head *bch2_ec_stripe_head_get(struct bch_fs *c,
1129                                                unsigned target,
1130                                                unsigned algo,
1131                                                unsigned redundancy)
1132 {
1133         struct ec_stripe_head *h;
1134
1135         if (!redundancy)
1136                 return NULL;
1137
1138         mutex_lock(&c->ec_new_stripe_lock);
1139         list_for_each_entry(h, &c->ec_new_stripe_list, list)
1140                 if (h->target           == target &&
1141                     h->algo             == algo &&
1142                     h->redundancy       == redundancy) {
1143                         mutex_lock(&h->lock);
1144                         goto found;
1145                 }
1146
1147         h = ec_new_stripe_head_alloc(c, target, algo, redundancy);
1148 found:
1149         mutex_unlock(&c->ec_new_stripe_lock);
1150         return h;
1151 }
1152
1153 void bch2_ec_stop_dev(struct bch_fs *c, struct bch_dev *ca)
1154 {
1155         struct ec_stripe_head *h;
1156         struct open_bucket *ob;
1157         unsigned i;
1158
1159         mutex_lock(&c->ec_new_stripe_lock);
1160         list_for_each_entry(h, &c->ec_new_stripe_list, list) {
1161                 struct ec_stripe_new *s = NULL;
1162
1163                 mutex_lock(&h->lock);
1164                 bch2_open_buckets_stop_dev(c, ca,
1165                                            &h->blocks,
1166                                            BCH_DATA_USER);
1167                 bch2_open_buckets_stop_dev(c, ca,
1168                                            &h->parity,
1169                                            BCH_DATA_USER);
1170
1171                 if (!h->s)
1172                         goto unlock;
1173
1174                 open_bucket_for_each(c, &h->s->blocks, ob, i)
1175                         if (ob->ptr.dev == ca->dev_idx)
1176                                 goto found;
1177                 open_bucket_for_each(c, &h->s->parity, ob, i)
1178                         if (ob->ptr.dev == ca->dev_idx)
1179                                 goto found;
1180                 goto unlock;
1181 found:
1182                 h->s->err = -1;
1183                 s = ec_stripe_set_pending(h);
1184 unlock:
1185                 mutex_unlock(&h->lock);
1186
1187                 if (s)
1188                         ec_stripe_new_put(s);
1189         }
1190         mutex_unlock(&c->ec_new_stripe_lock);
1191 }
1192
1193 static int __bch2_stripe_write_key(struct btree_trans *trans,
1194                                    struct btree_iter *iter,
1195                                    struct stripe *m,
1196                                    size_t idx,
1197                                    struct bkey_i_stripe *new_key,
1198                                    unsigned flags)
1199 {
1200         struct bch_fs *c = trans->c;
1201         struct bkey_s_c k;
1202         unsigned i;
1203         int ret;
1204
1205         bch2_btree_iter_set_pos(iter, POS(0, idx));
1206
1207         k = bch2_btree_iter_peek_slot(iter);
1208         ret = bkey_err(k);
1209         if (ret)
1210                 return ret;
1211
1212         if (k.k->type != KEY_TYPE_stripe)
1213                 return -EIO;
1214
1215         bkey_reassemble(&new_key->k_i, k);
1216
1217         spin_lock(&c->ec_stripes_heap_lock);
1218
1219         for (i = 0; i < new_key->v.nr_blocks; i++)
1220                 stripe_blockcount_set(&new_key->v, i,
1221                                       m->block_sectors[i]);
1222         m->dirty = false;
1223
1224         spin_unlock(&c->ec_stripes_heap_lock);
1225
1226         bch2_trans_update(trans, BTREE_INSERT_ENTRY(iter, &new_key->k_i));
1227
1228         return bch2_trans_commit(trans, NULL, NULL,
1229                                  BTREE_INSERT_NOFAIL|flags);
1230 }
1231
1232 int bch2_stripes_write(struct bch_fs *c, unsigned flags, bool *wrote)
1233 {
1234         struct btree_trans trans;
1235         struct btree_iter *iter;
1236         struct genradix_iter giter;
1237         struct bkey_i_stripe *new_key;
1238         struct stripe *m;
1239         int ret = 0;
1240
1241         new_key = kmalloc(255 * sizeof(u64), GFP_KERNEL);
1242         BUG_ON(!new_key);
1243
1244         bch2_trans_init(&trans, c, 0, 0);
1245
1246         iter = bch2_trans_get_iter(&trans, BTREE_ID_EC, POS_MIN,
1247                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1248
1249         genradix_for_each(&c->stripes[0], giter, m) {
1250                 if (!m->dirty)
1251                         continue;
1252
1253                 ret = __bch2_stripe_write_key(&trans, iter, m, giter.pos,
1254                                               new_key, flags);
1255                 if (ret)
1256                         break;
1257
1258                 *wrote = true;
1259         }
1260
1261         bch2_trans_exit(&trans);
1262
1263         kfree(new_key);
1264
1265         return ret;
1266 }
1267
1268 int bch2_stripes_read(struct bch_fs *c, struct journal_keys *journal_keys)
1269 {
1270         struct journal_key *i;
1271         struct btree_trans trans;
1272         struct btree_iter *iter;
1273         struct bkey_s_c k;
1274         int ret;
1275
1276         ret = bch2_fs_ec_start(c);
1277         if (ret)
1278                 return ret;
1279
1280         bch2_trans_init(&trans, c, 0, 0);
1281
1282         for_each_btree_key(&trans, iter, BTREE_ID_EC, POS_MIN, 0, k, ret)
1283                 bch2_mark_key(c, k, 0, NULL, 0,
1284                               BCH_BUCKET_MARK_ALLOC_READ|
1285                               BCH_BUCKET_MARK_NOATOMIC);
1286
1287         ret = bch2_trans_exit(&trans) ?: ret;
1288         if (ret) {
1289                 bch_err(c, "error reading stripes: %i", ret);
1290                 return ret;
1291         }
1292
1293         for_each_journal_key(*journal_keys, i)
1294                 if (i->btree_id == BTREE_ID_EC)
1295                         bch2_mark_key(c, bkey_i_to_s_c(i->k),
1296                                       0, NULL, 0,
1297                                       BCH_BUCKET_MARK_ALLOC_READ|
1298                                       BCH_BUCKET_MARK_NOATOMIC);
1299
1300         return 0;
1301 }
1302
1303 int bch2_ec_mem_alloc(struct bch_fs *c, bool gc)
1304 {
1305         struct btree_trans trans;
1306         struct btree_iter *iter;
1307         struct bkey_s_c k;
1308         size_t i, idx = 0;
1309         int ret = 0;
1310
1311         bch2_trans_init(&trans, c, 0, 0);
1312
1313         iter = bch2_trans_get_iter(&trans, BTREE_ID_EC, POS(0, U64_MAX), 0);
1314
1315         k = bch2_btree_iter_prev(iter);
1316         if (!IS_ERR_OR_NULL(k.k))
1317                 idx = k.k->p.offset + 1;
1318         ret = bch2_trans_exit(&trans);
1319         if (ret)
1320                 return ret;
1321
1322         if (!gc &&
1323             !init_heap(&c->ec_stripes_heap, roundup_pow_of_two(idx),
1324                        GFP_KERNEL))
1325                 return -ENOMEM;
1326 #if 0
1327         ret = genradix_prealloc(&c->stripes[gc], idx, GFP_KERNEL);
1328 #else
1329         for (i = 0; i < idx; i++)
1330                 if (!genradix_ptr_alloc(&c->stripes[gc], i, GFP_KERNEL))
1331                         return -ENOMEM;
1332 #endif
1333         return 0;
1334 }
1335
1336 int bch2_fs_ec_start(struct bch_fs *c)
1337 {
1338         return bch2_ec_mem_alloc(c, false);
1339 }
1340
1341 void bch2_fs_ec_exit(struct bch_fs *c)
1342 {
1343         struct ec_stripe_head *h;
1344
1345         while (1) {
1346                 mutex_lock(&c->ec_new_stripe_lock);
1347                 h = list_first_entry_or_null(&c->ec_new_stripe_list,
1348                                              struct ec_stripe_head, list);
1349                 if (h)
1350                         list_del(&h->list);
1351                 mutex_unlock(&c->ec_new_stripe_lock);
1352                 if (!h)
1353                         break;
1354
1355                 BUG_ON(h->s);
1356                 BUG_ON(!list_empty(&h->stripes));
1357                 kfree(h);
1358         }
1359
1360         free_heap(&c->ec_stripes_heap);
1361         genradix_free(&c->stripes[0]);
1362         bioset_exit(&c->ec_bioset);
1363 }
1364
1365 int bch2_fs_ec_init(struct bch_fs *c)
1366 {
1367         INIT_WORK(&c->ec_stripe_delete_work, ec_stripe_delete_work);
1368
1369         return bioset_init(&c->ec_bioset, 1, offsetof(struct ec_bio, bio),
1370                            BIOSET_NEED_BVECS);
1371 }