]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/ec.c
Update bcachefs sources to 72405e7ff8 bcachefs: Fix bch2_check_extents_to_backpointers()
[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 "backpointers.h"
8 #include "bkey_buf.h"
9 #include "bset.h"
10 #include "btree_gc.h"
11 #include "btree_update.h"
12 #include "btree_write_buffer.h"
13 #include "buckets.h"
14 #include "disk_groups.h"
15 #include "ec.h"
16 #include "error.h"
17 #include "io.h"
18 #include "keylist.h"
19 #include "recovery.h"
20 #include "replicas.h"
21 #include "super-io.h"
22 #include "util.h"
23
24 #include <linux/sort.h>
25
26 #ifdef __KERNEL__
27
28 #include <linux/raid/pq.h>
29 #include <linux/raid/xor.h>
30
31 static void raid5_recov(unsigned disks, unsigned failed_idx,
32                         size_t size, void **data)
33 {
34         unsigned i = 2, nr;
35
36         BUG_ON(failed_idx >= disks);
37
38         swap(data[0], data[failed_idx]);
39         memcpy(data[0], data[1], size);
40
41         while (i < disks) {
42                 nr = min_t(unsigned, disks - i, MAX_XOR_BLOCKS);
43                 xor_blocks(nr, size, data[0], data + i);
44                 i += nr;
45         }
46
47         swap(data[0], data[failed_idx]);
48 }
49
50 static void raid_gen(int nd, int np, size_t size, void **v)
51 {
52         if (np >= 1)
53                 raid5_recov(nd + np, nd, size, v);
54         if (np >= 2)
55                 raid6_call.gen_syndrome(nd + np, size, v);
56         BUG_ON(np > 2);
57 }
58
59 static void raid_rec(int nr, int *ir, int nd, int np, size_t size, void **v)
60 {
61         switch (nr) {
62         case 0:
63                 break;
64         case 1:
65                 if (ir[0] < nd + 1)
66                         raid5_recov(nd + 1, ir[0], size, v);
67                 else
68                         raid6_call.gen_syndrome(nd + np, size, v);
69                 break;
70         case 2:
71                 if (ir[1] < nd) {
72                         /* data+data failure. */
73                         raid6_2data_recov(nd + np, size, ir[0], ir[1], v);
74                 } else if (ir[0] < nd) {
75                         /* data + p/q failure */
76
77                         if (ir[1] == nd) /* data + p failure */
78                                 raid6_datap_recov(nd + np, size, ir[0], v);
79                         else { /* data + q failure */
80                                 raid5_recov(nd + 1, ir[0], size, v);
81                                 raid6_call.gen_syndrome(nd + np, size, v);
82                         }
83                 } else {
84                         raid_gen(nd, np, size, v);
85                 }
86                 break;
87         default:
88                 BUG();
89         }
90 }
91
92 #else
93
94 #include <raid/raid.h>
95
96 #endif
97
98 struct ec_bio {
99         struct bch_dev          *ca;
100         struct ec_stripe_buf    *buf;
101         size_t                  idx;
102         struct bio              bio;
103 };
104
105 /* Stripes btree keys: */
106
107 int bch2_stripe_invalid(const struct bch_fs *c, struct bkey_s_c k,
108                         unsigned flags, struct printbuf *err)
109 {
110         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
111
112         if (bkey_eq(k.k->p, POS_MIN)) {
113                 prt_printf(err, "stripe at POS_MIN");
114                 return -BCH_ERR_invalid_bkey;
115         }
116
117         if (k.k->p.inode) {
118                 prt_printf(err, "nonzero inode field");
119                 return -BCH_ERR_invalid_bkey;
120         }
121
122         if (bkey_val_bytes(k.k) < sizeof(*s)) {
123                 prt_printf(err, "incorrect value size (%zu < %zu)",
124                        bkey_val_bytes(k.k), sizeof(*s));
125                 return -BCH_ERR_invalid_bkey;
126         }
127
128         if (bkey_val_u64s(k.k) < stripe_val_u64s(s)) {
129                 prt_printf(err, "incorrect value size (%zu < %u)",
130                        bkey_val_u64s(k.k), stripe_val_u64s(s));
131                 return -BCH_ERR_invalid_bkey;
132         }
133
134         return bch2_bkey_ptrs_invalid(c, k, flags, err);
135 }
136
137 void bch2_stripe_to_text(struct printbuf *out, struct bch_fs *c,
138                          struct bkey_s_c k)
139 {
140         const struct bch_stripe *s = bkey_s_c_to_stripe(k).v;
141         unsigned i, nr_data = s->nr_blocks - s->nr_redundant;
142
143         prt_printf(out, "algo %u sectors %u blocks %u:%u csum %u gran %u",
144                s->algorithm,
145                le16_to_cpu(s->sectors),
146                nr_data,
147                s->nr_redundant,
148                s->csum_type,
149                1U << s->csum_granularity_bits);
150
151         for (i = 0; i < s->nr_blocks; i++) {
152                 const struct bch_extent_ptr *ptr = s->ptrs + i;
153                 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
154                 u32 offset;
155                 u64 b = sector_to_bucket_and_offset(ca, ptr->offset, &offset);
156
157                 prt_printf(out, " %u:%llu:%u", ptr->dev, b, offset);
158                 if (i < nr_data)
159                         prt_printf(out, "#%u", stripe_blockcount_get(s, i));
160                 if (ptr_stale(ca, ptr))
161                         prt_printf(out, " stale");
162         }
163 }
164
165 /* returns blocknr in stripe that we matched: */
166 static const struct bch_extent_ptr *bkey_matches_stripe(struct bch_stripe *s,
167                                                 struct bkey_s_c k, unsigned *block)
168 {
169         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
170         const struct bch_extent_ptr *ptr;
171         unsigned i, nr_data = s->nr_blocks - s->nr_redundant;
172
173         bkey_for_each_ptr(ptrs, ptr)
174                 for (i = 0; i < nr_data; i++)
175                         if (__bch2_ptr_matches_stripe(&s->ptrs[i], ptr,
176                                                       le16_to_cpu(s->sectors))) {
177                                 *block = i;
178                                 return ptr;
179                         }
180
181         return NULL;
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 /* Stripe bufs: */
205
206 static void ec_stripe_buf_exit(struct ec_stripe_buf *buf)
207 {
208         unsigned i;
209
210         for (i = 0; i < buf->key.v.nr_blocks; i++) {
211                 kvpfree(buf->data[i], buf->size << 9);
212                 buf->data[i] = NULL;
213         }
214 }
215
216 /* XXX: this is a non-mempoolified memory allocation: */
217 static int ec_stripe_buf_init(struct ec_stripe_buf *buf,
218                               unsigned offset, unsigned size)
219 {
220         struct bch_stripe *v = &buf->key.v;
221         unsigned csum_granularity = 1U << v->csum_granularity_bits;
222         unsigned end = offset + size;
223         unsigned i;
224
225         BUG_ON(end > le16_to_cpu(v->sectors));
226
227         offset  = round_down(offset, csum_granularity);
228         end     = min_t(unsigned, le16_to_cpu(v->sectors),
229                         round_up(end, csum_granularity));
230
231         buf->offset     = offset;
232         buf->size       = end - offset;
233
234         memset(buf->valid, 0xFF, sizeof(buf->valid));
235
236         for (i = 0; i < buf->key.v.nr_blocks; i++) {
237                 buf->data[i] = kvpmalloc(buf->size << 9, GFP_KERNEL);
238                 if (!buf->data[i])
239                         goto err;
240         }
241
242         return 0;
243 err:
244         ec_stripe_buf_exit(buf);
245         return -BCH_ERR_ENOMEM_stripe_buf;
246 }
247
248 /* Checksumming: */
249
250 static struct bch_csum ec_block_checksum(struct ec_stripe_buf *buf,
251                                          unsigned block, unsigned offset)
252 {
253         struct bch_stripe *v = &buf->key.v;
254         unsigned csum_granularity = 1 << v->csum_granularity_bits;
255         unsigned end = buf->offset + buf->size;
256         unsigned len = min(csum_granularity, end - offset);
257
258         BUG_ON(offset >= end);
259         BUG_ON(offset <  buf->offset);
260         BUG_ON(offset & (csum_granularity - 1));
261         BUG_ON(offset + len != le16_to_cpu(v->sectors) &&
262                (len & (csum_granularity - 1)));
263
264         return bch2_checksum(NULL, v->csum_type,
265                              null_nonce(),
266                              buf->data[block] + ((offset - buf->offset) << 9),
267                              len << 9);
268 }
269
270 static void ec_generate_checksums(struct ec_stripe_buf *buf)
271 {
272         struct bch_stripe *v = &buf->key.v;
273         unsigned i, j, csums_per_device = stripe_csums_per_device(v);
274
275         if (!v->csum_type)
276                 return;
277
278         BUG_ON(buf->offset);
279         BUG_ON(buf->size != le16_to_cpu(v->sectors));
280
281         for (i = 0; i < v->nr_blocks; i++)
282                 for (j = 0; j < csums_per_device; j++)
283                         stripe_csum_set(v, i, j,
284                                 ec_block_checksum(buf, i, j << v->csum_granularity_bits));
285 }
286
287 static void ec_validate_checksums(struct bch_fs *c, struct ec_stripe_buf *buf)
288 {
289         struct bch_stripe *v = &buf->key.v;
290         unsigned csum_granularity = 1 << v->csum_granularity_bits;
291         unsigned i;
292
293         if (!v->csum_type)
294                 return;
295
296         for (i = 0; i < v->nr_blocks; i++) {
297                 unsigned offset = buf->offset;
298                 unsigned end = buf->offset + buf->size;
299
300                 if (!test_bit(i, buf->valid))
301                         continue;
302
303                 while (offset < end) {
304                         unsigned j = offset >> v->csum_granularity_bits;
305                         unsigned len = min(csum_granularity, end - offset);
306                         struct bch_csum want = stripe_csum_get(v, i, j);
307                         struct bch_csum got = ec_block_checksum(buf, i, offset);
308
309                         if (bch2_crc_cmp(want, got)) {
310                                 struct printbuf buf2 = PRINTBUF;
311
312                                 bch2_bkey_val_to_text(&buf2, c, bkey_i_to_s_c(&buf->key.k_i));
313
314                                 bch_err_ratelimited(c,
315                                         "stripe checksum error for %ps at %u:%u: csum type %u, expected %llx got %llx\n%s",
316                                         (void *) _RET_IP_, i, j, v->csum_type,
317                                         want.lo, got.lo, buf2.buf);
318                                 printbuf_exit(&buf2);
319                                 clear_bit(i, buf->valid);
320                                 break;
321                         }
322
323                         offset += len;
324                 }
325         }
326 }
327
328 /* Erasure coding: */
329
330 static void ec_generate_ec(struct ec_stripe_buf *buf)
331 {
332         struct bch_stripe *v = &buf->key.v;
333         unsigned nr_data = v->nr_blocks - v->nr_redundant;
334         unsigned bytes = le16_to_cpu(v->sectors) << 9;
335
336         raid_gen(nr_data, v->nr_redundant, bytes, buf->data);
337 }
338
339 static unsigned ec_nr_failed(struct ec_stripe_buf *buf)
340 {
341         return buf->key.v.nr_blocks -
342                 bitmap_weight(buf->valid, buf->key.v.nr_blocks);
343 }
344
345 static int ec_do_recov(struct bch_fs *c, struct ec_stripe_buf *buf)
346 {
347         struct bch_stripe *v = &buf->key.v;
348         unsigned i, failed[BCH_BKEY_PTRS_MAX], nr_failed = 0;
349         unsigned nr_data = v->nr_blocks - v->nr_redundant;
350         unsigned bytes = buf->size << 9;
351
352         if (ec_nr_failed(buf) > v->nr_redundant) {
353                 bch_err_ratelimited(c,
354                         "error doing reconstruct read: unable to read enough blocks");
355                 return -1;
356         }
357
358         for (i = 0; i < nr_data; i++)
359                 if (!test_bit(i, buf->valid))
360                         failed[nr_failed++] = i;
361
362         raid_rec(nr_failed, failed, nr_data, v->nr_redundant, bytes, buf->data);
363         return 0;
364 }
365
366 /* IO: */
367
368 static void ec_block_endio(struct bio *bio)
369 {
370         struct ec_bio *ec_bio = container_of(bio, struct ec_bio, bio);
371         struct bch_stripe *v = &ec_bio->buf->key.v;
372         struct bch_extent_ptr *ptr = &v->ptrs[ec_bio->idx];
373         struct bch_dev *ca = ec_bio->ca;
374         struct closure *cl = bio->bi_private;
375
376         if (bch2_dev_io_err_on(bio->bi_status, ca, "erasure coding %s error: %s",
377                                bio_data_dir(bio) ? "write" : "read",
378                                bch2_blk_status_to_str(bio->bi_status)))
379                 clear_bit(ec_bio->idx, ec_bio->buf->valid);
380
381         if (ptr_stale(ca, ptr)) {
382                 bch_err_ratelimited(ca->fs,
383                                     "error %s stripe: stale pointer after io",
384                                     bio_data_dir(bio) == READ ? "reading from" : "writing to");
385                 clear_bit(ec_bio->idx, ec_bio->buf->valid);
386         }
387
388         bio_put(&ec_bio->bio);
389         percpu_ref_put(&ca->io_ref);
390         closure_put(cl);
391 }
392
393 static void ec_block_io(struct bch_fs *c, struct ec_stripe_buf *buf,
394                         unsigned rw, unsigned idx, struct closure *cl)
395 {
396         struct bch_stripe *v = &buf->key.v;
397         unsigned offset = 0, bytes = buf->size << 9;
398         struct bch_extent_ptr *ptr = &v->ptrs[idx];
399         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
400         enum bch_data_type data_type = idx < buf->key.v.nr_blocks - buf->key.v.nr_redundant
401                 ? BCH_DATA_user
402                 : BCH_DATA_parity;
403
404         if (ptr_stale(ca, ptr)) {
405                 bch_err_ratelimited(c,
406                                     "error %s stripe: stale pointer",
407                                     rw == READ ? "reading from" : "writing to");
408                 clear_bit(idx, buf->valid);
409                 return;
410         }
411
412         if (!bch2_dev_get_ioref(ca, rw)) {
413                 clear_bit(idx, buf->valid);
414                 return;
415         }
416
417         this_cpu_add(ca->io_done->sectors[rw][data_type], buf->size);
418
419         while (offset < bytes) {
420                 unsigned nr_iovecs = min_t(size_t, BIO_MAX_VECS,
421                                            DIV_ROUND_UP(bytes, PAGE_SIZE));
422                 unsigned b = min_t(size_t, bytes - offset,
423                                    nr_iovecs << PAGE_SHIFT);
424                 struct ec_bio *ec_bio;
425
426                 ec_bio = container_of(bio_alloc_bioset(ca->disk_sb.bdev,
427                                                        nr_iovecs,
428                                                        rw,
429                                                        GFP_KERNEL,
430                                                        &c->ec_bioset),
431                                       struct ec_bio, bio);
432
433                 ec_bio->ca                      = ca;
434                 ec_bio->buf                     = buf;
435                 ec_bio->idx                     = idx;
436
437                 ec_bio->bio.bi_iter.bi_sector   = ptr->offset + buf->offset + (offset >> 9);
438                 ec_bio->bio.bi_end_io           = ec_block_endio;
439                 ec_bio->bio.bi_private          = cl;
440
441                 bch2_bio_map(&ec_bio->bio, buf->data[idx] + offset, b);
442
443                 closure_get(cl);
444                 percpu_ref_get(&ca->io_ref);
445
446                 submit_bio(&ec_bio->bio);
447
448                 offset += b;
449         }
450
451         percpu_ref_put(&ca->io_ref);
452 }
453
454 static int get_stripe_key_trans(struct btree_trans *trans, u64 idx,
455                                 struct ec_stripe_buf *stripe)
456 {
457         struct btree_iter iter;
458         struct bkey_s_c k;
459         int ret;
460
461         bch2_trans_iter_init(trans, &iter, BTREE_ID_stripes,
462                              POS(0, idx), BTREE_ITER_SLOTS);
463         k = bch2_btree_iter_peek_slot(&iter);
464         ret = bkey_err(k);
465         if (ret)
466                 goto err;
467         if (k.k->type != KEY_TYPE_stripe) {
468                 ret = -ENOENT;
469                 goto err;
470         }
471         bkey_reassemble(&stripe->key.k_i, k);
472 err:
473         bch2_trans_iter_exit(trans, &iter);
474         return ret;
475 }
476
477 static int get_stripe_key(struct bch_fs *c, u64 idx, struct ec_stripe_buf *stripe)
478 {
479         return bch2_trans_run(c, get_stripe_key_trans(&trans, idx, stripe));
480 }
481
482 /* recovery read path: */
483 int bch2_ec_read_extent(struct bch_fs *c, struct bch_read_bio *rbio)
484 {
485         struct ec_stripe_buf *buf;
486         struct closure cl;
487         struct bch_stripe *v;
488         unsigned i, offset;
489         int ret = 0;
490
491         closure_init_stack(&cl);
492
493         BUG_ON(!rbio->pick.has_ec);
494
495         buf = kzalloc(sizeof(*buf), GFP_NOIO);
496         if (!buf)
497                 return -ENOMEM;
498
499         ret = get_stripe_key(c, rbio->pick.ec.idx, buf);
500         if (ret) {
501                 bch_err_ratelimited(c,
502                         "error doing reconstruct read: error %i looking up stripe", ret);
503                 kfree(buf);
504                 return -EIO;
505         }
506
507         v = &buf->key.v;
508
509         if (!bch2_ptr_matches_stripe(v, rbio->pick)) {
510                 bch_err_ratelimited(c,
511                         "error doing reconstruct read: pointer doesn't match stripe");
512                 ret = -EIO;
513                 goto err;
514         }
515
516         offset = rbio->bio.bi_iter.bi_sector - v->ptrs[rbio->pick.ec.block].offset;
517         if (offset + bio_sectors(&rbio->bio) > le16_to_cpu(v->sectors)) {
518                 bch_err_ratelimited(c,
519                         "error doing reconstruct read: read is bigger than stripe");
520                 ret = -EIO;
521                 goto err;
522         }
523
524         ret = ec_stripe_buf_init(buf, offset, bio_sectors(&rbio->bio));
525         if (ret)
526                 goto err;
527
528         for (i = 0; i < v->nr_blocks; i++)
529                 ec_block_io(c, buf, REQ_OP_READ, i, &cl);
530
531         closure_sync(&cl);
532
533         if (ec_nr_failed(buf) > v->nr_redundant) {
534                 bch_err_ratelimited(c,
535                         "error doing reconstruct read: unable to read enough blocks");
536                 ret = -EIO;
537                 goto err;
538         }
539
540         ec_validate_checksums(c, buf);
541
542         ret = ec_do_recov(c, buf);
543         if (ret)
544                 goto err;
545
546         memcpy_to_bio(&rbio->bio, rbio->bio.bi_iter,
547                       buf->data[rbio->pick.ec.block] + ((offset - buf->offset) << 9));
548 err:
549         ec_stripe_buf_exit(buf);
550         kfree(buf);
551         return ret;
552 }
553
554 /* stripe bucket accounting: */
555
556 static int __ec_stripe_mem_alloc(struct bch_fs *c, size_t idx, gfp_t gfp)
557 {
558         ec_stripes_heap n, *h = &c->ec_stripes_heap;
559
560         if (idx >= h->size) {
561                 if (!init_heap(&n, max(1024UL, roundup_pow_of_two(idx + 1)), gfp))
562                         return -ENOMEM;
563
564                 mutex_lock(&c->ec_stripes_heap_lock);
565                 if (n.size > h->size) {
566                         memcpy(n.data, h->data, h->used * sizeof(h->data[0]));
567                         n.used = h->used;
568                         swap(*h, n);
569                 }
570                 mutex_unlock(&c->ec_stripes_heap_lock);
571
572                 free_heap(&n);
573         }
574
575         if (!genradix_ptr_alloc(&c->stripes, idx, gfp))
576                 return -ENOMEM;
577
578         if (c->gc_pos.phase != GC_PHASE_NOT_RUNNING &&
579             !genradix_ptr_alloc(&c->gc_stripes, idx, gfp))
580                 return -ENOMEM;
581
582         return 0;
583 }
584
585 static int ec_stripe_mem_alloc(struct btree_trans *trans,
586                                struct btree_iter *iter)
587 {
588         size_t idx = iter->pos.offset;
589
590         if (!__ec_stripe_mem_alloc(trans->c, idx, GFP_NOWAIT|__GFP_NOWARN))
591                 return 0;
592
593         bch2_trans_unlock(trans);
594
595         return   __ec_stripe_mem_alloc(trans->c, idx, GFP_KERNEL) ?:
596                 bch2_trans_relock(trans);
597 }
598
599 /*
600  * Hash table of open stripes:
601  * Stripes that are being created or modified are kept in a hash table, so that
602  * stripe deletion can skip them.
603  */
604
605 static bool __bch2_stripe_is_open(struct bch_fs *c, u64 idx)
606 {
607         unsigned hash = hash_64(idx, ilog2(ARRAY_SIZE(c->ec_stripes_new)));
608         struct ec_stripe_new *s;
609
610         hlist_for_each_entry(s, &c->ec_stripes_new[hash], hash)
611                 if (s->idx == idx)
612                         return true;
613         return false;
614 }
615
616 static bool bch2_stripe_is_open(struct bch_fs *c, u64 idx)
617 {
618         bool ret = false;
619
620         spin_lock(&c->ec_stripes_new_lock);
621         ret = __bch2_stripe_is_open(c, idx);
622         spin_unlock(&c->ec_stripes_new_lock);
623
624         return ret;
625 }
626
627 static bool bch2_try_open_stripe(struct bch_fs *c,
628                                  struct ec_stripe_new *s,
629                                  u64 idx)
630 {
631         bool ret;
632
633         spin_lock(&c->ec_stripes_new_lock);
634         ret = !__bch2_stripe_is_open(c, idx);
635         if (ret) {
636                 unsigned hash = hash_64(idx, ilog2(ARRAY_SIZE(c->ec_stripes_new)));
637
638                 s->idx = idx;
639                 hlist_add_head(&s->hash, &c->ec_stripes_new[hash]);
640         }
641         spin_unlock(&c->ec_stripes_new_lock);
642
643         return ret;
644 }
645
646 static void bch2_stripe_close(struct bch_fs *c, struct ec_stripe_new *s)
647 {
648         BUG_ON(!s->idx);
649
650         spin_lock(&c->ec_stripes_new_lock);
651         hlist_del_init(&s->hash);
652         spin_unlock(&c->ec_stripes_new_lock);
653
654         s->idx = 0;
655 }
656
657 /* Heap of all existing stripes, ordered by blocks_nonempty */
658
659 static u64 stripe_idx_to_delete(struct bch_fs *c)
660 {
661         ec_stripes_heap *h = &c->ec_stripes_heap;
662
663         lockdep_assert_held(&c->ec_stripes_heap_lock);
664
665         if (h->used &&
666             h->data[0].blocks_nonempty == 0 &&
667             !bch2_stripe_is_open(c, h->data[0].idx))
668                 return h->data[0].idx;
669
670         return 0;
671 }
672
673 static inline int ec_stripes_heap_cmp(ec_stripes_heap *h,
674                                       struct ec_stripe_heap_entry l,
675                                       struct ec_stripe_heap_entry r)
676 {
677         return ((l.blocks_nonempty > r.blocks_nonempty) -
678                 (l.blocks_nonempty < r.blocks_nonempty));
679 }
680
681 static inline void ec_stripes_heap_set_backpointer(ec_stripes_heap *h,
682                                                    size_t i)
683 {
684         struct bch_fs *c = container_of(h, struct bch_fs, ec_stripes_heap);
685
686         genradix_ptr(&c->stripes, h->data[i].idx)->heap_idx = i;
687 }
688
689 static void heap_verify_backpointer(struct bch_fs *c, size_t idx)
690 {
691         ec_stripes_heap *h = &c->ec_stripes_heap;
692         struct stripe *m = genradix_ptr(&c->stripes, idx);
693
694         BUG_ON(m->heap_idx >= h->used);
695         BUG_ON(h->data[m->heap_idx].idx != idx);
696 }
697
698 void bch2_stripes_heap_del(struct bch_fs *c,
699                            struct stripe *m, size_t idx)
700 {
701         mutex_lock(&c->ec_stripes_heap_lock);
702         heap_verify_backpointer(c, idx);
703
704         heap_del(&c->ec_stripes_heap, m->heap_idx,
705                  ec_stripes_heap_cmp,
706                  ec_stripes_heap_set_backpointer);
707         mutex_unlock(&c->ec_stripes_heap_lock);
708 }
709
710 void bch2_stripes_heap_insert(struct bch_fs *c,
711                               struct stripe *m, size_t idx)
712 {
713         mutex_lock(&c->ec_stripes_heap_lock);
714         BUG_ON(heap_full(&c->ec_stripes_heap));
715
716         heap_add(&c->ec_stripes_heap, ((struct ec_stripe_heap_entry) {
717                         .idx = idx,
718                         .blocks_nonempty = m->blocks_nonempty,
719                 }),
720                  ec_stripes_heap_cmp,
721                  ec_stripes_heap_set_backpointer);
722
723         heap_verify_backpointer(c, idx);
724         mutex_unlock(&c->ec_stripes_heap_lock);
725 }
726
727 void bch2_stripes_heap_update(struct bch_fs *c,
728                               struct stripe *m, size_t idx)
729 {
730         ec_stripes_heap *h = &c->ec_stripes_heap;
731         bool do_deletes;
732         size_t i;
733
734         mutex_lock(&c->ec_stripes_heap_lock);
735         heap_verify_backpointer(c, idx);
736
737         h->data[m->heap_idx].blocks_nonempty = m->blocks_nonempty;
738
739         i = m->heap_idx;
740         heap_sift_up(h,   i, ec_stripes_heap_cmp,
741                      ec_stripes_heap_set_backpointer);
742         heap_sift_down(h, i, ec_stripes_heap_cmp,
743                        ec_stripes_heap_set_backpointer);
744
745         heap_verify_backpointer(c, idx);
746
747         do_deletes = stripe_idx_to_delete(c) != 0;
748         mutex_unlock(&c->ec_stripes_heap_lock);
749
750         if (do_deletes)
751                 bch2_do_stripe_deletes(c);
752 }
753
754 /* stripe deletion */
755
756 static int ec_stripe_delete(struct btree_trans *trans, u64 idx)
757 {
758         struct bch_fs *c = trans->c;
759         struct btree_iter iter;
760         struct bkey_s_c k;
761         struct bkey_s_c_stripe s;
762         int ret;
763
764         bch2_trans_iter_init(trans, &iter, BTREE_ID_stripes, POS(0, idx),
765                              BTREE_ITER_INTENT);
766         k = bch2_btree_iter_peek_slot(&iter);
767         ret = bkey_err(k);
768         if (ret)
769                 goto err;
770
771         if (k.k->type != KEY_TYPE_stripe) {
772                 bch2_fs_inconsistent(c, "attempting to delete nonexistent stripe %llu", idx);
773                 ret = -EINVAL;
774                 goto err;
775         }
776
777         s = bkey_s_c_to_stripe(k);
778         for (unsigned i = 0; i < s.v->nr_blocks; i++)
779                 if (stripe_blockcount_get(s.v, i)) {
780                         struct printbuf buf = PRINTBUF;
781
782                         bch2_bkey_val_to_text(&buf, c, k);
783                         bch2_fs_inconsistent(c, "attempting to delete nonempty stripe %s", buf.buf);
784                         printbuf_exit(&buf);
785                         ret = -EINVAL;
786                         goto err;
787                 }
788
789         ret = bch2_btree_delete_at(trans, &iter, 0);
790 err:
791         bch2_trans_iter_exit(trans, &iter);
792         return ret;
793 }
794
795 static void ec_stripe_delete_work(struct work_struct *work)
796 {
797         struct bch_fs *c =
798                 container_of(work, struct bch_fs, ec_stripe_delete_work);
799         struct btree_trans trans;
800         int ret;
801         u64 idx;
802
803         bch2_trans_init(&trans, c, 0, 0);
804
805         while (1) {
806                 mutex_lock(&c->ec_stripes_heap_lock);
807                 idx = stripe_idx_to_delete(c);
808                 mutex_unlock(&c->ec_stripes_heap_lock);
809
810                 if (!idx)
811                         break;
812
813                 ret = commit_do(&trans, NULL, NULL, BTREE_INSERT_NOFAIL,
814                                 ec_stripe_delete(&trans, idx));
815                 if (ret) {
816                         bch_err(c, "%s: err %s", __func__, bch2_err_str(ret));
817                         break;
818                 }
819         }
820
821         bch2_trans_exit(&trans);
822
823         bch2_write_ref_put(c, BCH_WRITE_REF_stripe_delete);
824 }
825
826 void bch2_do_stripe_deletes(struct bch_fs *c)
827 {
828         if (bch2_write_ref_tryget(c, BCH_WRITE_REF_stripe_delete) &&
829             !schedule_work(&c->ec_stripe_delete_work))
830                 bch2_write_ref_put(c, BCH_WRITE_REF_stripe_delete);
831 }
832
833 /* stripe creation: */
834
835 static int ec_stripe_key_update(struct btree_trans *trans,
836                                 struct bkey_i_stripe *new,
837                                 bool create)
838 {
839         struct bch_fs *c = trans->c;
840         struct btree_iter iter;
841         struct bkey_s_c k;
842         int ret;
843
844         bch2_trans_iter_init(trans, &iter, BTREE_ID_stripes,
845                              new->k.p, BTREE_ITER_INTENT);
846         k = bch2_btree_iter_peek_slot(&iter);
847         ret = bkey_err(k);
848         if (ret)
849                 goto err;
850
851         if (k.k->type != (create ? KEY_TYPE_deleted : KEY_TYPE_stripe)) {
852                 bch2_fs_inconsistent(c, "error %s stripe: got existing key type %s",
853                                      create ? "creating" : "updating",
854                                      bch2_bkey_types[k.k->type]);
855                 ret = -EINVAL;
856                 goto err;
857         }
858
859         if (k.k->type == KEY_TYPE_stripe) {
860                 const struct bch_stripe *old = bkey_s_c_to_stripe(k).v;
861                 unsigned i;
862
863                 if (old->nr_blocks != new->v.nr_blocks) {
864                         bch_err(c, "error updating stripe: nr_blocks does not match");
865                         ret = -EINVAL;
866                         goto err;
867                 }
868
869                 for (i = 0; i < new->v.nr_blocks; i++) {
870                         unsigned v = stripe_blockcount_get(old, i);
871
872                         BUG_ON(v &&
873                                (old->ptrs[i].dev != new->v.ptrs[i].dev ||
874                                 old->ptrs[i].gen != new->v.ptrs[i].gen ||
875                                 old->ptrs[i].offset != new->v.ptrs[i].offset));
876
877                         stripe_blockcount_set(&new->v, i, v);
878                 }
879         }
880
881         ret = bch2_trans_update(trans, &iter, &new->k_i, 0);
882 err:
883         bch2_trans_iter_exit(trans, &iter);
884         return ret;
885 }
886
887 static int ec_stripe_update_extent(struct btree_trans *trans,
888                                    struct bpos bucket, u8 gen,
889                                    struct ec_stripe_buf *s,
890                                    u64 *bp_offset)
891 {
892         struct bch_fs *c = trans->c;
893         struct bch_backpointer bp;
894         struct btree_iter iter;
895         struct bkey_s_c k;
896         const struct bch_extent_ptr *ptr_c;
897         struct bch_extent_ptr *ptr, *ec_ptr = NULL;
898         struct bch_extent_stripe_ptr stripe_ptr;
899         struct bkey_i *n;
900         int ret, dev, block;
901
902         ret = bch2_get_next_backpointer(trans, bucket, gen,
903                                 bp_offset, &bp, BTREE_ITER_CACHED);
904         if (ret)
905                 return ret;
906         if (*bp_offset == U64_MAX)
907                 return 0;
908
909         if (bp.level) {
910                 struct printbuf buf = PRINTBUF;
911                 struct btree_iter node_iter;
912                 struct btree *b;
913
914                 b = bch2_backpointer_get_node(trans, &node_iter, bucket, *bp_offset, bp);
915                 bch2_trans_iter_exit(trans, &node_iter);
916
917                 if (!b)
918                         return 0;
919
920                 prt_printf(&buf, "found btree node in erasure coded bucket: b=%px\n", b);
921                 bch2_backpointer_to_text(&buf, &bp);
922
923                 bch2_fs_inconsistent(c, "%s", buf.buf);
924                 printbuf_exit(&buf);
925                 return -EIO;
926         }
927
928         k = bch2_backpointer_get_key(trans, &iter, bucket, *bp_offset, bp);
929         ret = bkey_err(k);
930         if (ret)
931                 return ret;
932         if (!k.k) {
933                 /*
934                  * extent no longer exists - we could flush the btree
935                  * write buffer and retry to verify, but no need:
936                  */
937                 return 0;
938         }
939
940         if (extent_has_stripe_ptr(k, s->key.k.p.offset))
941                 goto out;
942
943         ptr_c = bkey_matches_stripe(&s->key.v, k, &block);
944         /*
945          * It doesn't generally make sense to erasure code cached ptrs:
946          * XXX: should we be incrementing a counter?
947          */
948         if (!ptr_c || ptr_c->cached)
949                 goto out;
950
951         dev = s->key.v.ptrs[block].dev;
952
953         n = bch2_trans_kmalloc(trans, bkey_bytes(k.k) + sizeof(stripe_ptr));
954         ret = PTR_ERR_OR_ZERO(n);
955         if (ret)
956                 goto out;
957
958         bkey_reassemble(n, k);
959
960         bch2_bkey_drop_ptrs(bkey_i_to_s(n), ptr, ptr->dev != dev);
961         ec_ptr = bch2_bkey_has_device(bkey_i_to_s(n), dev);
962         BUG_ON(!ec_ptr);
963
964         stripe_ptr = (struct bch_extent_stripe_ptr) {
965                 .type = 1 << BCH_EXTENT_ENTRY_stripe_ptr,
966                 .block          = block,
967                 .redundancy     = s->key.v.nr_redundant,
968                 .idx            = s->key.k.p.offset,
969         };
970
971         __extent_entry_insert(n,
972                         (union bch_extent_entry *) ec_ptr,
973                         (union bch_extent_entry *) &stripe_ptr);
974
975         ret = bch2_trans_update(trans, &iter, n, 0);
976 out:
977         bch2_trans_iter_exit(trans, &iter);
978         return ret;
979 }
980
981 static int ec_stripe_update_bucket(struct btree_trans *trans, struct ec_stripe_buf *s,
982                                    unsigned block)
983 {
984         struct bch_fs *c = trans->c;
985         struct bch_extent_ptr bucket = s->key.v.ptrs[block];
986         struct bpos bucket_pos = PTR_BUCKET_POS(c, &bucket);
987         u64 bp_offset = 0;
988         int ret = 0;
989
990         while (1) {
991                 ret = commit_do(trans, NULL, NULL,
992                                 BTREE_INSERT_NOCHECK_RW|
993                                 BTREE_INSERT_NOFAIL,
994                         ec_stripe_update_extent(trans, bucket_pos, bucket.gen,
995                                                 s, &bp_offset));
996                 if (ret)
997                         break;
998                 if (bp_offset == U64_MAX)
999                         break;
1000
1001                 bp_offset++;
1002         }
1003
1004         return ret;
1005 }
1006
1007 static int ec_stripe_update_extents(struct bch_fs *c, struct ec_stripe_buf *s)
1008 {
1009         struct btree_trans trans;
1010         struct bch_stripe *v = &s->key.v;
1011         unsigned i, nr_data = v->nr_blocks - v->nr_redundant;
1012         int ret = 0;
1013
1014         bch2_trans_init(&trans, c, 0, 0);
1015
1016         ret = bch2_btree_write_buffer_flush(&trans);
1017         if (ret)
1018                 goto err;
1019
1020         for (i = 0; i < nr_data; i++) {
1021                 ret = ec_stripe_update_bucket(&trans, s, i);
1022                 if (ret)
1023                         break;
1024         }
1025 err:
1026         bch2_trans_exit(&trans);
1027
1028         return ret;
1029 }
1030
1031 static void zero_out_rest_of_ec_bucket(struct bch_fs *c,
1032                                        struct ec_stripe_new *s,
1033                                        unsigned block,
1034                                        struct open_bucket *ob)
1035 {
1036         struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
1037         unsigned offset = ca->mi.bucket_size - ob->sectors_free;
1038         int ret;
1039
1040         if (!bch2_dev_get_ioref(ca, WRITE)) {
1041                 s->err = -EROFS;
1042                 return;
1043         }
1044
1045         memset(s->new_stripe.data[block] + (offset << 9),
1046                0,
1047                ob->sectors_free << 9);
1048
1049         ret = blkdev_issue_zeroout(ca->disk_sb.bdev,
1050                         ob->bucket * ca->mi.bucket_size + offset,
1051                         ob->sectors_free,
1052                         GFP_KERNEL, 0);
1053
1054         percpu_ref_put(&ca->io_ref);
1055
1056         if (ret)
1057                 s->err = ret;
1058 }
1059
1060 void bch2_ec_stripe_new_free(struct bch_fs *c, struct ec_stripe_new *s)
1061 {
1062         if (s->idx)
1063                 bch2_stripe_close(c, s);
1064         kfree(s);
1065 }
1066
1067 /*
1068  * data buckets of new stripe all written: create the stripe
1069  */
1070 static void ec_stripe_create(struct ec_stripe_new *s)
1071 {
1072         struct bch_fs *c = s->c;
1073         struct open_bucket *ob;
1074         struct bch_stripe *v = &s->new_stripe.key.v;
1075         unsigned i, nr_data = v->nr_blocks - v->nr_redundant;
1076         int ret;
1077
1078         BUG_ON(s->h->s == s);
1079
1080         closure_sync(&s->iodone);
1081
1082         if (!s->err) {
1083                 for (i = 0; i < nr_data; i++)
1084                         if (s->blocks[i]) {
1085                                 ob = c->open_buckets + s->blocks[i];
1086
1087                                 if (ob->sectors_free)
1088                                         zero_out_rest_of_ec_bucket(c, s, i, ob);
1089                         }
1090         }
1091
1092         if (s->err) {
1093                 if (!bch2_err_matches(s->err, EROFS))
1094                         bch_err(c, "error creating stripe: error writing data buckets");
1095                 goto err;
1096         }
1097
1098         if (s->have_existing_stripe) {
1099                 ec_validate_checksums(c, &s->existing_stripe);
1100
1101                 if (ec_do_recov(c, &s->existing_stripe)) {
1102                         bch_err(c, "error creating stripe: error reading existing stripe");
1103                         goto err;
1104                 }
1105
1106                 for (i = 0; i < nr_data; i++)
1107                         if (stripe_blockcount_get(&s->existing_stripe.key.v, i))
1108                                 swap(s->new_stripe.data[i],
1109                                      s->existing_stripe.data[i]);
1110
1111                 ec_stripe_buf_exit(&s->existing_stripe);
1112         }
1113
1114         BUG_ON(!s->allocated);
1115         BUG_ON(!s->idx);
1116
1117         ec_generate_ec(&s->new_stripe);
1118
1119         ec_generate_checksums(&s->new_stripe);
1120
1121         /* write p/q: */
1122         for (i = nr_data; i < v->nr_blocks; i++)
1123                 ec_block_io(c, &s->new_stripe, REQ_OP_WRITE, i, &s->iodone);
1124         closure_sync(&s->iodone);
1125
1126         if (ec_nr_failed(&s->new_stripe)) {
1127                 bch_err(c, "error creating stripe: error writing redundancy buckets");
1128                 goto err;
1129         }
1130
1131         ret = bch2_trans_do(c, &s->res, NULL,
1132                             BTREE_INSERT_NOCHECK_RW|
1133                             BTREE_INSERT_NOFAIL,
1134                             ec_stripe_key_update(&trans, &s->new_stripe.key,
1135                                                  !s->have_existing_stripe));
1136         if (ret) {
1137                 bch_err(c, "error creating stripe: error creating stripe key");
1138                 goto err;
1139         }
1140
1141         ret = ec_stripe_update_extents(c, &s->new_stripe);
1142         if (ret) {
1143                 bch_err(c, "error creating stripe: error updating pointers: %s",
1144                         bch2_err_str(ret));
1145                 goto err;
1146         }
1147 err:
1148         bch2_disk_reservation_put(c, &s->res);
1149
1150         for (i = 0; i < v->nr_blocks; i++)
1151                 if (s->blocks[i]) {
1152                         ob = c->open_buckets + s->blocks[i];
1153
1154                         if (i < nr_data) {
1155                                 ob->ec = NULL;
1156                                 __bch2_open_bucket_put(c, ob);
1157                         } else {
1158                                 bch2_open_bucket_put(c, ob);
1159                         }
1160                 }
1161
1162         mutex_lock(&c->ec_stripe_new_lock);
1163         list_del(&s->list);
1164         mutex_unlock(&c->ec_stripe_new_lock);
1165
1166         ec_stripe_buf_exit(&s->existing_stripe);
1167         ec_stripe_buf_exit(&s->new_stripe);
1168         closure_debug_destroy(&s->iodone);
1169
1170         ec_stripe_new_put(c, s, STRIPE_REF_stripe);
1171 }
1172
1173 static struct ec_stripe_new *get_pending_stripe(struct bch_fs *c)
1174 {
1175         struct ec_stripe_new *s;
1176
1177         mutex_lock(&c->ec_stripe_new_lock);
1178         list_for_each_entry(s, &c->ec_stripe_new_list, list)
1179                 if (!atomic_read(&s->ref[STRIPE_REF_io]))
1180                         goto out;
1181         s = NULL;
1182 out:
1183         mutex_unlock(&c->ec_stripe_new_lock);
1184
1185         return s;
1186 }
1187
1188 static void ec_stripe_create_work(struct work_struct *work)
1189 {
1190         struct bch_fs *c = container_of(work,
1191                 struct bch_fs, ec_stripe_create_work);
1192         struct ec_stripe_new *s;
1193
1194         while ((s = get_pending_stripe(c)))
1195                 ec_stripe_create(s);
1196
1197         bch2_write_ref_put(c, BCH_WRITE_REF_stripe_create);
1198 }
1199
1200 void bch2_ec_do_stripe_creates(struct bch_fs *c)
1201 {
1202         bch2_write_ref_get(c, BCH_WRITE_REF_stripe_create);
1203
1204         if (!queue_work(system_long_wq, &c->ec_stripe_create_work))
1205                 bch2_write_ref_put(c, BCH_WRITE_REF_stripe_create);
1206 }
1207
1208 static void ec_stripe_set_pending(struct bch_fs *c, struct ec_stripe_head *h)
1209 {
1210         struct ec_stripe_new *s = h->s;
1211
1212         BUG_ON(!s->allocated && !s->err);
1213
1214         h->s            = NULL;
1215         s->pending      = true;
1216
1217         mutex_lock(&c->ec_stripe_new_lock);
1218         list_add(&s->list, &c->ec_stripe_new_list);
1219         mutex_unlock(&c->ec_stripe_new_lock);
1220
1221         ec_stripe_new_put(c, s, STRIPE_REF_io);
1222 }
1223
1224 void bch2_ec_bucket_cancel(struct bch_fs *c, struct open_bucket *ob)
1225 {
1226         struct ec_stripe_new *s = ob->ec;
1227
1228         s->err = -EIO;
1229 }
1230
1231 void *bch2_writepoint_ec_buf(struct bch_fs *c, struct write_point *wp)
1232 {
1233         struct open_bucket *ob = ec_open_bucket(c, &wp->ptrs);
1234         struct bch_dev *ca;
1235         unsigned offset;
1236
1237         if (!ob)
1238                 return NULL;
1239
1240         BUG_ON(!ob->ec->new_stripe.data[ob->ec_idx]);
1241
1242         ca      = bch_dev_bkey_exists(c, ob->dev);
1243         offset  = ca->mi.bucket_size - ob->sectors_free;
1244
1245         return ob->ec->new_stripe.data[ob->ec_idx] + (offset << 9);
1246 }
1247
1248 static int unsigned_cmp(const void *_l, const void *_r)
1249 {
1250         unsigned l = *((const unsigned *) _l);
1251         unsigned r = *((const unsigned *) _r);
1252
1253         return cmp_int(l, r);
1254 }
1255
1256 /* pick most common bucket size: */
1257 static unsigned pick_blocksize(struct bch_fs *c,
1258                                struct bch_devs_mask *devs)
1259 {
1260         struct bch_dev *ca;
1261         unsigned i, nr = 0, sizes[BCH_SB_MEMBERS_MAX];
1262         struct {
1263                 unsigned nr, size;
1264         } cur = { 0, 0 }, best = { 0, 0 };
1265
1266         for_each_member_device_rcu(ca, c, i, devs)
1267                 sizes[nr++] = ca->mi.bucket_size;
1268
1269         sort(sizes, nr, sizeof(unsigned), unsigned_cmp, NULL);
1270
1271         for (i = 0; i < nr; i++) {
1272                 if (sizes[i] != cur.size) {
1273                         if (cur.nr > best.nr)
1274                                 best = cur;
1275
1276                         cur.nr = 0;
1277                         cur.size = sizes[i];
1278                 }
1279
1280                 cur.nr++;
1281         }
1282
1283         if (cur.nr > best.nr)
1284                 best = cur;
1285
1286         return best.size;
1287 }
1288
1289 static bool may_create_new_stripe(struct bch_fs *c)
1290 {
1291         return false;
1292 }
1293
1294 static void ec_stripe_key_init(struct bch_fs *c,
1295                                struct bkey_i_stripe *s,
1296                                unsigned nr_data,
1297                                unsigned nr_parity,
1298                                unsigned stripe_size)
1299 {
1300         unsigned u64s;
1301
1302         bkey_stripe_init(&s->k_i);
1303         s->v.sectors                    = cpu_to_le16(stripe_size);
1304         s->v.algorithm                  = 0;
1305         s->v.nr_blocks                  = nr_data + nr_parity;
1306         s->v.nr_redundant               = nr_parity;
1307         s->v.csum_granularity_bits      = ilog2(c->opts.encoded_extent_max >> 9);
1308         s->v.csum_type                  = BCH_CSUM_crc32c;
1309         s->v.pad                        = 0;
1310
1311         while ((u64s = stripe_val_u64s(&s->v)) > BKEY_VAL_U64s_MAX) {
1312                 BUG_ON(1 << s->v.csum_granularity_bits >=
1313                        le16_to_cpu(s->v.sectors) ||
1314                        s->v.csum_granularity_bits == U8_MAX);
1315                 s->v.csum_granularity_bits++;
1316         }
1317
1318         set_bkey_val_u64s(&s->k, u64s);
1319 }
1320
1321 static int ec_new_stripe_alloc(struct bch_fs *c, struct ec_stripe_head *h)
1322 {
1323         struct ec_stripe_new *s;
1324
1325         lockdep_assert_held(&h->lock);
1326
1327         s = kzalloc(sizeof(*s), GFP_KERNEL);
1328         if (!s)
1329                 return -ENOMEM;
1330
1331         mutex_init(&s->lock);
1332         closure_init(&s->iodone, NULL);
1333         atomic_set(&s->ref[STRIPE_REF_stripe], 1);
1334         atomic_set(&s->ref[STRIPE_REF_io], 1);
1335         s->c            = c;
1336         s->h            = h;
1337         s->nr_data      = min_t(unsigned, h->nr_active_devs,
1338                                 BCH_BKEY_PTRS_MAX) - h->redundancy;
1339         s->nr_parity    = h->redundancy;
1340
1341         ec_stripe_key_init(c, &s->new_stripe.key, s->nr_data,
1342                            s->nr_parity, h->blocksize);
1343
1344         h->s = s;
1345         return 0;
1346 }
1347
1348 static struct ec_stripe_head *
1349 ec_new_stripe_head_alloc(struct bch_fs *c, unsigned target,
1350                          unsigned algo, unsigned redundancy,
1351                          enum alloc_reserve reserve)
1352 {
1353         struct ec_stripe_head *h;
1354         struct bch_dev *ca;
1355         unsigned i;
1356
1357         h = kzalloc(sizeof(*h), GFP_KERNEL);
1358         if (!h)
1359                 return NULL;
1360
1361         mutex_init(&h->lock);
1362         BUG_ON(!mutex_trylock(&h->lock));
1363
1364         h->target       = target;
1365         h->algo         = algo;
1366         h->redundancy   = redundancy;
1367         h->reserve      = reserve;
1368
1369         rcu_read_lock();
1370         h->devs = target_rw_devs(c, BCH_DATA_user, target);
1371
1372         for_each_member_device_rcu(ca, c, i, &h->devs)
1373                 if (!ca->mi.durability)
1374                         __clear_bit(i, h->devs.d);
1375
1376         h->blocksize = pick_blocksize(c, &h->devs);
1377
1378         for_each_member_device_rcu(ca, c, i, &h->devs)
1379                 if (ca->mi.bucket_size == h->blocksize)
1380                         h->nr_active_devs++;
1381
1382         rcu_read_unlock();
1383         list_add(&h->list, &c->ec_stripe_head_list);
1384         return h;
1385 }
1386
1387 void bch2_ec_stripe_head_put(struct bch_fs *c, struct ec_stripe_head *h)
1388 {
1389         if (h->s &&
1390             h->s->allocated &&
1391             bitmap_weight(h->s->blocks_allocated,
1392                           h->s->nr_data) == h->s->nr_data)
1393                 ec_stripe_set_pending(c, h);
1394
1395         mutex_unlock(&h->lock);
1396 }
1397
1398 struct ec_stripe_head *__bch2_ec_stripe_head_get(struct btree_trans *trans,
1399                                                  unsigned target,
1400                                                  unsigned algo,
1401                                                  unsigned redundancy,
1402                                                  enum alloc_reserve reserve)
1403 {
1404         struct bch_fs *c = trans->c;
1405         struct ec_stripe_head *h;
1406         int ret;
1407
1408         if (!redundancy)
1409                 return NULL;
1410
1411         ret = bch2_trans_mutex_lock(trans, &c->ec_stripe_head_lock);
1412         if (ret)
1413                 return ERR_PTR(ret);
1414
1415         if (test_bit(BCH_FS_GOING_RO, &c->flags)) {
1416                 h = ERR_PTR(-EROFS);
1417                 goto found;
1418         }
1419
1420         list_for_each_entry(h, &c->ec_stripe_head_list, list)
1421                 if (h->target           == target &&
1422                     h->algo             == algo &&
1423                     h->redundancy       == redundancy &&
1424                     h->reserve          == reserve) {
1425                         ret = bch2_trans_mutex_lock(trans, &h->lock);
1426                         if (ret)
1427                                 h = ERR_PTR(ret);
1428                         goto found;
1429                 }
1430
1431         h = ec_new_stripe_head_alloc(c, target, algo, redundancy, reserve);
1432 found:
1433         mutex_unlock(&c->ec_stripe_head_lock);
1434         return h;
1435 }
1436
1437 static int new_stripe_alloc_buckets(struct btree_trans *trans, struct ec_stripe_head *h,
1438                                     enum alloc_reserve reserve, struct closure *cl)
1439 {
1440         struct bch_fs *c = trans->c;
1441         struct bch_devs_mask devs = h->devs;
1442         struct open_bucket *ob;
1443         struct open_buckets buckets;
1444         unsigned i, j, nr_have_parity = 0, nr_have_data = 0;
1445         bool have_cache = true;
1446         int ret = 0;
1447
1448         BUG_ON(h->s->new_stripe.key.v.nr_blocks         != h->s->nr_data + h->s->nr_parity);
1449         BUG_ON(h->s->new_stripe.key.v.nr_redundant      != h->s->nr_parity);
1450
1451         for_each_set_bit(i, h->s->blocks_gotten, h->s->new_stripe.key.v.nr_blocks) {
1452                 __clear_bit(h->s->new_stripe.key.v.ptrs[i].dev, devs.d);
1453                 if (i < h->s->nr_data)
1454                         nr_have_data++;
1455                 else
1456                         nr_have_parity++;
1457         }
1458
1459         BUG_ON(nr_have_data     > h->s->nr_data);
1460         BUG_ON(nr_have_parity   > h->s->nr_parity);
1461
1462         buckets.nr = 0;
1463         if (nr_have_parity < h->s->nr_parity) {
1464                 ret = bch2_bucket_alloc_set_trans(trans, &buckets,
1465                                             &h->parity_stripe,
1466                                             &devs,
1467                                             h->s->nr_parity,
1468                                             &nr_have_parity,
1469                                             &have_cache, 0,
1470                                             BCH_DATA_parity,
1471                                             reserve,
1472                                             cl);
1473
1474                 open_bucket_for_each(c, &buckets, ob, i) {
1475                         j = find_next_zero_bit(h->s->blocks_gotten,
1476                                                h->s->nr_data + h->s->nr_parity,
1477                                                h->s->nr_data);
1478                         BUG_ON(j >= h->s->nr_data + h->s->nr_parity);
1479
1480                         h->s->blocks[j] = buckets.v[i];
1481                         h->s->new_stripe.key.v.ptrs[j] = bch2_ob_ptr(c, ob);
1482                         __set_bit(j, h->s->blocks_gotten);
1483                 }
1484
1485                 if (ret)
1486                         return ret;
1487         }
1488
1489         buckets.nr = 0;
1490         if (nr_have_data < h->s->nr_data) {
1491                 ret = bch2_bucket_alloc_set_trans(trans, &buckets,
1492                                             &h->block_stripe,
1493                                             &devs,
1494                                             h->s->nr_data,
1495                                             &nr_have_data,
1496                                             &have_cache, 0,
1497                                             BCH_DATA_user,
1498                                             reserve,
1499                                             cl);
1500
1501                 open_bucket_for_each(c, &buckets, ob, i) {
1502                         j = find_next_zero_bit(h->s->blocks_gotten,
1503                                                h->s->nr_data, 0);
1504                         BUG_ON(j >= h->s->nr_data);
1505
1506                         h->s->blocks[j] = buckets.v[i];
1507                         h->s->new_stripe.key.v.ptrs[j] = bch2_ob_ptr(c, ob);
1508                         __set_bit(j, h->s->blocks_gotten);
1509                 }
1510
1511                 if (ret)
1512                         return ret;
1513         }
1514
1515         return 0;
1516 }
1517
1518 /* XXX: doesn't obey target: */
1519 static s64 get_existing_stripe(struct bch_fs *c,
1520                                struct ec_stripe_head *head)
1521 {
1522         ec_stripes_heap *h = &c->ec_stripes_heap;
1523         struct stripe *m;
1524         size_t heap_idx;
1525         u64 stripe_idx;
1526         s64 ret = -1;
1527
1528         if (may_create_new_stripe(c))
1529                 return -1;
1530
1531         mutex_lock(&c->ec_stripes_heap_lock);
1532         for (heap_idx = 0; heap_idx < h->used; heap_idx++) {
1533                 /* No blocks worth reusing, stripe will just be deleted: */
1534                 if (!h->data[heap_idx].blocks_nonempty)
1535                         continue;
1536
1537                 stripe_idx = h->data[heap_idx].idx;
1538
1539                 m = genradix_ptr(&c->stripes, stripe_idx);
1540
1541                 if (m->algorithm        == head->algo &&
1542                     m->nr_redundant     == head->redundancy &&
1543                     m->sectors          == head->blocksize &&
1544                     m->blocks_nonempty  < m->nr_blocks - m->nr_redundant &&
1545                     bch2_try_open_stripe(c, head->s, stripe_idx)) {
1546                         ret = stripe_idx;
1547                         break;
1548                 }
1549         }
1550         mutex_unlock(&c->ec_stripes_heap_lock);
1551         return ret;
1552 }
1553
1554 static int __bch2_ec_stripe_head_reuse(struct btree_trans *trans, struct ec_stripe_head *h)
1555 {
1556         struct bch_fs *c = trans->c;
1557         unsigned i;
1558         s64 idx;
1559         int ret;
1560
1561         /*
1562          * If we can't allocate a new stripe, and there's no stripes with empty
1563          * blocks for us to reuse, that means we have to wait on copygc:
1564          */
1565         idx = get_existing_stripe(c, h);
1566         if (idx < 0)
1567                 return -BCH_ERR_stripe_alloc_blocked;
1568
1569         ret = get_stripe_key_trans(trans, idx, &h->s->existing_stripe);
1570         if (ret) {
1571                 bch2_stripe_close(c, h->s);
1572                 if (!bch2_err_matches(ret, BCH_ERR_transaction_restart))
1573                         bch2_fs_fatal_error(c, "error reading stripe key: %s", bch2_err_str(ret));
1574                 return ret;
1575         }
1576
1577         BUG_ON(h->s->existing_stripe.key.v.nr_redundant != h->s->nr_parity);
1578         h->s->nr_data = h->s->existing_stripe.key.v.nr_blocks -
1579                 h->s->existing_stripe.key.v.nr_redundant;
1580
1581         ret = ec_stripe_buf_init(&h->s->existing_stripe, 0, h->blocksize);
1582         if (ret) {
1583                 bch2_stripe_close(c, h->s);
1584                 return ret;
1585         }
1586
1587         BUG_ON(h->s->existing_stripe.size != h->blocksize);
1588         BUG_ON(h->s->existing_stripe.size != h->s->existing_stripe.key.v.sectors);
1589
1590         /*
1591          * Free buckets we initially allocated - they might conflict with
1592          * blocks from the stripe we're reusing:
1593          */
1594         for_each_set_bit(i, h->s->blocks_gotten, h->s->new_stripe.key.v.nr_blocks) {
1595                 bch2_open_bucket_put(c, c->open_buckets + h->s->blocks[i]);
1596                 h->s->blocks[i] = 0;
1597         }
1598         memset(h->s->blocks_gotten, 0, sizeof(h->s->blocks_gotten));
1599         memset(h->s->blocks_allocated, 0, sizeof(h->s->blocks_allocated));
1600
1601         for (i = 0; i < h->s->existing_stripe.key.v.nr_blocks; i++) {
1602                 if (stripe_blockcount_get(&h->s->existing_stripe.key.v, i)) {
1603                         __set_bit(i, h->s->blocks_gotten);
1604                         __set_bit(i, h->s->blocks_allocated);
1605                 }
1606
1607                 ec_block_io(c, &h->s->existing_stripe, READ, i, &h->s->iodone);
1608         }
1609
1610         bkey_copy(&h->s->new_stripe.key.k_i, &h->s->existing_stripe.key.k_i);
1611         h->s->have_existing_stripe = true;
1612
1613         return 0;
1614 }
1615
1616 static int __bch2_ec_stripe_head_reserve(struct btree_trans *trans, struct ec_stripe_head *h)
1617 {
1618         struct bch_fs *c = trans->c;
1619         struct btree_iter iter;
1620         struct bkey_s_c k;
1621         struct bpos min_pos = POS(0, 1);
1622         struct bpos start_pos = bpos_max(min_pos, POS(0, c->ec_stripe_hint));
1623         int ret;
1624
1625         if (!h->s->res.sectors) {
1626                 ret = bch2_disk_reservation_get(c, &h->s->res,
1627                                         h->blocksize,
1628                                         h->s->nr_parity,
1629                                         BCH_DISK_RESERVATION_NOFAIL);
1630                 if (ret)
1631                         return ret;
1632         }
1633
1634         for_each_btree_key_norestart(trans, iter, BTREE_ID_stripes, start_pos,
1635                            BTREE_ITER_SLOTS|BTREE_ITER_INTENT, k, ret) {
1636                 if (bkey_gt(k.k->p, POS(0, U32_MAX))) {
1637                         if (start_pos.offset) {
1638                                 start_pos = min_pos;
1639                                 bch2_btree_iter_set_pos(&iter, start_pos);
1640                                 continue;
1641                         }
1642
1643                         ret = -BCH_ERR_ENOSPC_stripe_create;
1644                         break;
1645                 }
1646
1647                 if (bkey_deleted(k.k) &&
1648                     bch2_try_open_stripe(c, h->s, k.k->p.offset))
1649                         break;
1650         }
1651
1652         c->ec_stripe_hint = iter.pos.offset;
1653
1654         if (ret)
1655                 goto err;
1656
1657         ret = ec_stripe_mem_alloc(trans, &iter);
1658         if (ret) {
1659                 bch2_stripe_close(c, h->s);
1660                 goto err;
1661         }
1662
1663         h->s->new_stripe.key.k.p = iter.pos;
1664 out:
1665         bch2_trans_iter_exit(trans, &iter);
1666         return ret;
1667 err:
1668         bch2_disk_reservation_put(c, &h->s->res);
1669         goto out;
1670 }
1671
1672 struct ec_stripe_head *bch2_ec_stripe_head_get(struct btree_trans *trans,
1673                                                unsigned target,
1674                                                unsigned algo,
1675                                                unsigned redundancy,
1676                                                enum alloc_reserve reserve,
1677                                                struct closure *cl)
1678 {
1679         struct bch_fs *c = trans->c;
1680         struct ec_stripe_head *h;
1681         bool waiting = false;
1682         int ret;
1683
1684         h = __bch2_ec_stripe_head_get(trans, target, algo, redundancy, reserve);
1685         if (!h)
1686                 bch_err(c, "no stripe head");
1687         if (IS_ERR_OR_NULL(h))
1688                 return h;
1689
1690         if (!h->s) {
1691                 if (ec_new_stripe_alloc(c, h)) {
1692                         ret = -ENOMEM;
1693                         bch_err(c, "failed to allocate new stripe");
1694                         goto err;
1695                 }
1696         }
1697
1698         if (h->s->allocated)
1699                 goto allocated;
1700
1701         if (h->s->have_existing_stripe)
1702                 goto alloc_existing;
1703
1704         /* First, try to allocate a full stripe: */
1705         ret =   new_stripe_alloc_buckets(trans, h, RESERVE_stripe, NULL) ?:
1706                 __bch2_ec_stripe_head_reserve(trans, h);
1707         if (!ret)
1708                 goto allocate_buf;
1709         if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
1710             bch2_err_matches(ret, ENOMEM))
1711                 goto err;
1712
1713         /*
1714          * Not enough buckets available for a full stripe: we must reuse an
1715          * existing stripe:
1716          */
1717         while (1) {
1718                 ret = __bch2_ec_stripe_head_reuse(trans, h);
1719                 if (!ret)
1720                         break;
1721                 if (waiting || !cl || ret != -BCH_ERR_stripe_alloc_blocked)
1722                         goto err;
1723
1724                 if (reserve == RESERVE_movinggc) {
1725                         ret =   new_stripe_alloc_buckets(trans, h, reserve, NULL) ?:
1726                                 __bch2_ec_stripe_head_reserve(trans, h);
1727                         if (ret)
1728                                 goto err;
1729                         goto allocate_buf;
1730                 }
1731
1732                 /* XXX freelist_wait? */
1733                 closure_wait(&c->freelist_wait, cl);
1734                 waiting = true;
1735         }
1736
1737         if (waiting)
1738                 closure_wake_up(&c->freelist_wait);
1739 alloc_existing:
1740         /*
1741          * Retry allocating buckets, with the reserve watermark for this
1742          * particular write:
1743          */
1744         ret = new_stripe_alloc_buckets(trans, h, reserve, cl);
1745         if (ret)
1746                 goto err;
1747
1748 allocate_buf:
1749         ret = ec_stripe_buf_init(&h->s->new_stripe, 0, h->blocksize);
1750         if (ret)
1751                 goto err;
1752
1753         h->s->allocated = true;
1754 allocated:
1755         BUG_ON(!h->s->idx);
1756         BUG_ON(!h->s->new_stripe.data[0]);
1757         BUG_ON(trans->restarted);
1758         return h;
1759 err:
1760         bch2_ec_stripe_head_put(c, h);
1761         return ERR_PTR(ret);
1762 }
1763
1764 static void __bch2_ec_stop(struct bch_fs *c, struct bch_dev *ca)
1765 {
1766         struct ec_stripe_head *h;
1767         struct open_bucket *ob;
1768         unsigned i;
1769
1770         mutex_lock(&c->ec_stripe_head_lock);
1771         list_for_each_entry(h, &c->ec_stripe_head_list, list) {
1772                 mutex_lock(&h->lock);
1773                 if (!h->s)
1774                         goto unlock;
1775
1776                 if (!ca)
1777                         goto found;
1778
1779                 for (i = 0; i < h->s->new_stripe.key.v.nr_blocks; i++) {
1780                         if (!h->s->blocks[i])
1781                                 continue;
1782
1783                         ob = c->open_buckets + h->s->blocks[i];
1784                         if (ob->dev == ca->dev_idx)
1785                                 goto found;
1786                 }
1787                 goto unlock;
1788 found:
1789                 h->s->err = -EROFS;
1790                 ec_stripe_set_pending(c, h);
1791 unlock:
1792                 mutex_unlock(&h->lock);
1793         }
1794         mutex_unlock(&c->ec_stripe_head_lock);
1795 }
1796
1797 void bch2_ec_stop_dev(struct bch_fs *c, struct bch_dev *ca)
1798 {
1799         __bch2_ec_stop(c, ca);
1800 }
1801
1802 void bch2_fs_ec_stop(struct bch_fs *c)
1803 {
1804         __bch2_ec_stop(c, NULL);
1805 }
1806
1807 static bool bch2_fs_ec_flush_done(struct bch_fs *c)
1808 {
1809         bool ret;
1810
1811         mutex_lock(&c->ec_stripe_new_lock);
1812         ret = list_empty(&c->ec_stripe_new_list);
1813         mutex_unlock(&c->ec_stripe_new_lock);
1814
1815         return ret;
1816 }
1817
1818 void bch2_fs_ec_flush(struct bch_fs *c)
1819 {
1820         wait_event(c->ec_stripe_new_wait, bch2_fs_ec_flush_done(c));
1821 }
1822
1823 int bch2_stripes_read(struct bch_fs *c)
1824 {
1825         struct btree_trans trans;
1826         struct btree_iter iter;
1827         struct bkey_s_c k;
1828         const struct bch_stripe *s;
1829         struct stripe *m;
1830         unsigned i;
1831         int ret;
1832
1833         bch2_trans_init(&trans, c, 0, 0);
1834
1835         for_each_btree_key(&trans, iter, BTREE_ID_stripes, POS_MIN,
1836                            BTREE_ITER_PREFETCH, k, ret) {
1837                 if (k.k->type != KEY_TYPE_stripe)
1838                         continue;
1839
1840                 ret = __ec_stripe_mem_alloc(c, k.k->p.offset, GFP_KERNEL);
1841                 if (ret)
1842                         break;
1843
1844                 s = bkey_s_c_to_stripe(k).v;
1845
1846                 m = genradix_ptr(&c->stripes, k.k->p.offset);
1847                 m->sectors      = le16_to_cpu(s->sectors);
1848                 m->algorithm    = s->algorithm;
1849                 m->nr_blocks    = s->nr_blocks;
1850                 m->nr_redundant = s->nr_redundant;
1851                 m->blocks_nonempty = 0;
1852
1853                 for (i = 0; i < s->nr_blocks; i++)
1854                         m->blocks_nonempty += !!stripe_blockcount_get(s, i);
1855
1856                 bch2_stripes_heap_insert(c, m, k.k->p.offset);
1857         }
1858         bch2_trans_iter_exit(&trans, &iter);
1859
1860         bch2_trans_exit(&trans);
1861
1862         if (ret)
1863                 bch_err(c, "error reading stripes: %i", ret);
1864
1865         return ret;
1866 }
1867
1868 void bch2_stripes_heap_to_text(struct printbuf *out, struct bch_fs *c)
1869 {
1870         ec_stripes_heap *h = &c->ec_stripes_heap;
1871         struct stripe *m;
1872         size_t i;
1873
1874         mutex_lock(&c->ec_stripes_heap_lock);
1875         for (i = 0; i < min_t(size_t, h->used, 50); i++) {
1876                 m = genradix_ptr(&c->stripes, h->data[i].idx);
1877
1878                 prt_printf(out, "%zu %u/%u+%u", h->data[i].idx,
1879                        h->data[i].blocks_nonempty,
1880                        m->nr_blocks - m->nr_redundant,
1881                        m->nr_redundant);
1882                 if (bch2_stripe_is_open(c, h->data[i].idx))
1883                         prt_str(out, " open");
1884                 prt_newline(out);
1885         }
1886         mutex_unlock(&c->ec_stripes_heap_lock);
1887 }
1888
1889 void bch2_new_stripes_to_text(struct printbuf *out, struct bch_fs *c)
1890 {
1891         struct ec_stripe_head *h;
1892         struct ec_stripe_new *s;
1893
1894         mutex_lock(&c->ec_stripe_head_lock);
1895         list_for_each_entry(h, &c->ec_stripe_head_list, list) {
1896                 prt_printf(out, "target %u algo %u redundancy %u %s:\n",
1897                        h->target, h->algo, h->redundancy,
1898                        bch2_alloc_reserves[h->reserve]);
1899
1900                 if (h->s)
1901                         prt_printf(out, "\tidx %llu blocks %u+%u allocated %u\n",
1902                                h->s->idx, h->s->nr_data, h->s->nr_parity,
1903                                bitmap_weight(h->s->blocks_allocated,
1904                                              h->s->nr_data));
1905         }
1906         mutex_unlock(&c->ec_stripe_head_lock);
1907
1908         prt_printf(out, "in flight:\n");
1909
1910         mutex_lock(&c->ec_stripe_new_lock);
1911         list_for_each_entry(s, &c->ec_stripe_new_list, list) {
1912                 prt_printf(out, "\tidx %llu blocks %u+%u ref %u %u %s\n",
1913                            s->idx, s->nr_data, s->nr_parity,
1914                            atomic_read(&s->ref[STRIPE_REF_io]),
1915                            atomic_read(&s->ref[STRIPE_REF_stripe]),
1916                            bch2_alloc_reserves[s->h->reserve]);
1917         }
1918         mutex_unlock(&c->ec_stripe_new_lock);
1919 }
1920
1921 void bch2_fs_ec_exit(struct bch_fs *c)
1922 {
1923         struct ec_stripe_head *h;
1924         unsigned i;
1925
1926         while (1) {
1927                 mutex_lock(&c->ec_stripe_head_lock);
1928                 h = list_first_entry_or_null(&c->ec_stripe_head_list,
1929                                              struct ec_stripe_head, list);
1930                 if (h)
1931                         list_del(&h->list);
1932                 mutex_unlock(&c->ec_stripe_head_lock);
1933                 if (!h)
1934                         break;
1935
1936                 if (h->s) {
1937                         for (i = 0; i < h->s->new_stripe.key.v.nr_blocks; i++)
1938                                 BUG_ON(h->s->blocks[i]);
1939
1940                         kfree(h->s);
1941                 }
1942                 kfree(h);
1943         }
1944
1945         BUG_ON(!list_empty(&c->ec_stripe_new_list));
1946
1947         free_heap(&c->ec_stripes_heap);
1948         genradix_free(&c->stripes);
1949         bioset_exit(&c->ec_bioset);
1950 }
1951
1952 void bch2_fs_ec_init_early(struct bch_fs *c)
1953 {
1954         spin_lock_init(&c->ec_stripes_new_lock);
1955         mutex_init(&c->ec_stripes_heap_lock);
1956
1957         INIT_LIST_HEAD(&c->ec_stripe_head_list);
1958         mutex_init(&c->ec_stripe_head_lock);
1959
1960         INIT_LIST_HEAD(&c->ec_stripe_new_list);
1961         mutex_init(&c->ec_stripe_new_lock);
1962         init_waitqueue_head(&c->ec_stripe_new_wait);
1963
1964         INIT_WORK(&c->ec_stripe_create_work, ec_stripe_create_work);
1965         INIT_WORK(&c->ec_stripe_delete_work, ec_stripe_delete_work);
1966 }
1967
1968 int bch2_fs_ec_init(struct bch_fs *c)
1969 {
1970         return bioset_init(&c->ec_bioset, 1, offsetof(struct ec_bio, bio),
1971                            BIOSET_NEED_BVECS);
1972 }