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