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