]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_background.c
Update bcachefs sources to 078a1a596a bcachefs: Optimize bucket reuse
[bcachefs-tools-debian] / libbcachefs / alloc_background.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include "bcachefs.h"
3 #include "alloc_background.h"
4 #include "alloc_foreground.h"
5 #include "btree_cache.h"
6 #include "btree_io.h"
7 #include "btree_key_cache.h"
8 #include "btree_update.h"
9 #include "btree_update_interior.h"
10 #include "btree_gc.h"
11 #include "buckets.h"
12 #include "clock.h"
13 #include "debug.h"
14 #include "ec.h"
15 #include "error.h"
16 #include "recovery.h"
17 #include "varint.h"
18
19 #include <linux/kthread.h>
20 #include <linux/math64.h>
21 #include <linux/random.h>
22 #include <linux/rculist.h>
23 #include <linux/rcupdate.h>
24 #include <linux/sched/task.h>
25 #include <linux/sort.h>
26 #include <trace/events/bcachefs.h>
27
28 const char * const bch2_allocator_states[] = {
29 #define x(n)    #n,
30         ALLOC_THREAD_STATES()
31 #undef x
32         NULL
33 };
34
35 static const unsigned BCH_ALLOC_V1_FIELD_BYTES[] = {
36 #define x(name, bits) [BCH_ALLOC_FIELD_V1_##name] = bits / 8,
37         BCH_ALLOC_FIELDS_V1()
38 #undef x
39 };
40
41 struct bkey_alloc_buf {
42         struct bkey_i   k;
43         struct bch_alloc_v3 v;
44
45 #define x(_name,  _bits)                + _bits / 8
46         u8              _pad[0 + BCH_ALLOC_FIELDS_V2()];
47 #undef  x
48 } __attribute__((packed, aligned(8)));
49
50 /* Persistent alloc info: */
51
52 static inline u64 alloc_field_v1_get(const struct bch_alloc *a,
53                                      const void **p, unsigned field)
54 {
55         unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
56         u64 v;
57
58         if (!(a->fields & (1 << field)))
59                 return 0;
60
61         switch (bytes) {
62         case 1:
63                 v = *((const u8 *) *p);
64                 break;
65         case 2:
66                 v = le16_to_cpup(*p);
67                 break;
68         case 4:
69                 v = le32_to_cpup(*p);
70                 break;
71         case 8:
72                 v = le64_to_cpup(*p);
73                 break;
74         default:
75                 BUG();
76         }
77
78         *p += bytes;
79         return v;
80 }
81
82 static inline void alloc_field_v1_put(struct bkey_i_alloc *a, void **p,
83                                       unsigned field, u64 v)
84 {
85         unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
86
87         if (!v)
88                 return;
89
90         a->v.fields |= 1 << field;
91
92         switch (bytes) {
93         case 1:
94                 *((u8 *) *p) = v;
95                 break;
96         case 2:
97                 *((__le16 *) *p) = cpu_to_le16(v);
98                 break;
99         case 4:
100                 *((__le32 *) *p) = cpu_to_le32(v);
101                 break;
102         case 8:
103                 *((__le64 *) *p) = cpu_to_le64(v);
104                 break;
105         default:
106                 BUG();
107         }
108
109         *p += bytes;
110 }
111
112 static void bch2_alloc_unpack_v1(struct bkey_alloc_unpacked *out,
113                                  struct bkey_s_c k)
114 {
115         const struct bch_alloc *in = bkey_s_c_to_alloc(k).v;
116         const void *d = in->data;
117         unsigned idx = 0;
118
119         out->gen = in->gen;
120
121 #define x(_name, _bits) out->_name = alloc_field_v1_get(in, &d, idx++);
122         BCH_ALLOC_FIELDS_V1()
123 #undef  x
124 }
125
126 static int bch2_alloc_unpack_v2(struct bkey_alloc_unpacked *out,
127                                 struct bkey_s_c k)
128 {
129         struct bkey_s_c_alloc_v2 a = bkey_s_c_to_alloc_v2(k);
130         const u8 *in = a.v->data;
131         const u8 *end = bkey_val_end(a);
132         unsigned fieldnr = 0;
133         int ret;
134         u64 v;
135
136         out->gen        = a.v->gen;
137         out->oldest_gen = a.v->oldest_gen;
138         out->data_type  = a.v->data_type;
139
140 #define x(_name, _bits)                                                 \
141         if (fieldnr < a.v->nr_fields) {                                 \
142                 ret = bch2_varint_decode_fast(in, end, &v);             \
143                 if (ret < 0)                                            \
144                         return ret;                                     \
145                 in += ret;                                              \
146         } else {                                                        \
147                 v = 0;                                                  \
148         }                                                               \
149         out->_name = v;                                                 \
150         if (v != out->_name)                                            \
151                 return -1;                                              \
152         fieldnr++;
153
154         BCH_ALLOC_FIELDS_V2()
155 #undef  x
156         return 0;
157 }
158
159 static int bch2_alloc_unpack_v3(struct bkey_alloc_unpacked *out,
160                                 struct bkey_s_c k)
161 {
162         struct bkey_s_c_alloc_v3 a = bkey_s_c_to_alloc_v3(k);
163         const u8 *in = a.v->data;
164         const u8 *end = bkey_val_end(a);
165         unsigned fieldnr = 0;
166         int ret;
167         u64 v;
168
169         out->gen        = a.v->gen;
170         out->oldest_gen = a.v->oldest_gen;
171         out->data_type  = a.v->data_type;
172         out->journal_seq = le64_to_cpu(a.v->journal_seq);
173
174 #define x(_name, _bits)                                                 \
175         if (fieldnr < a.v->nr_fields) {                                 \
176                 ret = bch2_varint_decode_fast(in, end, &v);             \
177                 if (ret < 0)                                            \
178                         return ret;                                     \
179                 in += ret;                                              \
180         } else {                                                        \
181                 v = 0;                                                  \
182         }                                                               \
183         out->_name = v;                                                 \
184         if (v != out->_name)                                            \
185                 return -1;                                              \
186         fieldnr++;
187
188         BCH_ALLOC_FIELDS_V2()
189 #undef  x
190         return 0;
191 }
192
193 static void bch2_alloc_pack_v3(struct bkey_alloc_buf *dst,
194                                const struct bkey_alloc_unpacked src)
195 {
196         struct bkey_i_alloc_v3 *a = bkey_alloc_v3_init(&dst->k);
197         unsigned nr_fields = 0, last_nonzero_fieldnr = 0;
198         u8 *out = a->v.data;
199         u8 *end = (void *) &dst[1];
200         u8 *last_nonzero_field = out;
201         unsigned bytes;
202
203         a->k.p          = POS(src.dev, src.bucket);
204         a->v.gen        = src.gen;
205         a->v.oldest_gen = src.oldest_gen;
206         a->v.data_type  = src.data_type;
207         a->v.journal_seq = cpu_to_le64(src.journal_seq);
208
209 #define x(_name, _bits)                                                 \
210         nr_fields++;                                                    \
211                                                                         \
212         if (src._name) {                                                \
213                 out += bch2_varint_encode_fast(out, src._name);         \
214                                                                         \
215                 last_nonzero_field = out;                               \
216                 last_nonzero_fieldnr = nr_fields;                       \
217         } else {                                                        \
218                 *out++ = 0;                                             \
219         }
220
221         BCH_ALLOC_FIELDS_V2()
222 #undef  x
223         BUG_ON(out > end);
224
225         out = last_nonzero_field;
226         a->v.nr_fields = last_nonzero_fieldnr;
227
228         bytes = (u8 *) out - (u8 *) &a->v;
229         set_bkey_val_bytes(&a->k, bytes);
230         memset_u64s_tail(&a->v, 0, bytes);
231 }
232
233 struct bkey_alloc_unpacked bch2_alloc_unpack(struct bkey_s_c k)
234 {
235         struct bkey_alloc_unpacked ret = {
236                 .dev    = k.k->p.inode,
237                 .bucket = k.k->p.offset,
238                 .gen    = 0,
239         };
240
241         switch (k.k->type) {
242         case KEY_TYPE_alloc:
243                 bch2_alloc_unpack_v1(&ret, k);
244                 break;
245         case KEY_TYPE_alloc_v2:
246                 bch2_alloc_unpack_v2(&ret, k);
247                 break;
248         case KEY_TYPE_alloc_v3:
249                 bch2_alloc_unpack_v3(&ret, k);
250                 break;
251         }
252
253         return ret;
254 }
255
256 static void bch2_alloc_pack(struct bch_fs *c,
257                             struct bkey_alloc_buf *dst,
258                             const struct bkey_alloc_unpacked src)
259 {
260         bch2_alloc_pack_v3(dst, src);
261 }
262
263 int bch2_alloc_write(struct btree_trans *trans, struct btree_iter *iter,
264                      struct bkey_alloc_unpacked *u, unsigned trigger_flags)
265 {
266         struct bkey_alloc_buf *a;
267
268         a = bch2_trans_kmalloc(trans, sizeof(struct bkey_alloc_buf));
269         if (IS_ERR(a))
270                 return PTR_ERR(a);
271
272         bch2_alloc_pack(trans->c, a, *u);
273         return bch2_trans_update(trans, iter, &a->k, trigger_flags);
274 }
275
276 static unsigned bch_alloc_v1_val_u64s(const struct bch_alloc *a)
277 {
278         unsigned i, bytes = offsetof(struct bch_alloc, data);
279
280         for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_V1_FIELD_BYTES); i++)
281                 if (a->fields & (1 << i))
282                         bytes += BCH_ALLOC_V1_FIELD_BYTES[i];
283
284         return DIV_ROUND_UP(bytes, sizeof(u64));
285 }
286
287 const char *bch2_alloc_v1_invalid(const struct bch_fs *c, struct bkey_s_c k)
288 {
289         struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
290
291         if (k.k->p.inode >= c->sb.nr_devices ||
292             !c->devs[k.k->p.inode])
293                 return "invalid device";
294
295         /* allow for unknown fields */
296         if (bkey_val_u64s(a.k) < bch_alloc_v1_val_u64s(a.v))
297                 return "incorrect value size";
298
299         return NULL;
300 }
301
302 const char *bch2_alloc_v2_invalid(const struct bch_fs *c, struct bkey_s_c k)
303 {
304         struct bkey_alloc_unpacked u;
305
306         if (k.k->p.inode >= c->sb.nr_devices ||
307             !c->devs[k.k->p.inode])
308                 return "invalid device";
309
310         if (bch2_alloc_unpack_v2(&u, k))
311                 return "unpack error";
312
313         return NULL;
314 }
315
316 const char *bch2_alloc_v3_invalid(const struct bch_fs *c, struct bkey_s_c k)
317 {
318         struct bkey_alloc_unpacked u;
319
320         if (k.k->p.inode >= c->sb.nr_devices ||
321             !c->devs[k.k->p.inode])
322                 return "invalid device";
323
324         if (bch2_alloc_unpack_v3(&u, k))
325                 return "unpack error";
326
327         return NULL;
328 }
329
330 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
331                            struct bkey_s_c k)
332 {
333         struct bkey_alloc_unpacked u = bch2_alloc_unpack(k);
334
335         pr_buf(out, "gen %u oldest_gen %u data_type %s journal_seq %llu",
336                u.gen, u.oldest_gen, bch2_data_types[u.data_type],
337                u.journal_seq);
338 #define x(_name, ...)   pr_buf(out, " " #_name " %llu", (u64) u._name);
339         BCH_ALLOC_FIELDS_V2()
340 #undef  x
341 }
342
343 static int bch2_alloc_read_fn(struct btree_trans *trans, struct bkey_s_c k)
344 {
345         struct bch_fs *c = trans->c;
346         struct bch_dev *ca;
347         struct bucket *g;
348         struct bkey_alloc_unpacked u;
349
350         if (!bkey_is_alloc(k.k))
351                 return 0;
352
353         ca = bch_dev_bkey_exists(c, k.k->p.inode);
354         g = bucket(ca, k.k->p.offset);
355         u = bch2_alloc_unpack(k);
356
357         *bucket_gen(ca, k.k->p.offset) = u.gen;
358         g->_mark.gen            = u.gen;
359         g->_mark.data_type      = u.data_type;
360         g->_mark.dirty_sectors  = u.dirty_sectors;
361         g->_mark.cached_sectors = u.cached_sectors;
362         g->_mark.stripe         = u.stripe != 0;
363         g->stripe               = u.stripe;
364         g->stripe_redundancy    = u.stripe_redundancy;
365         g->io_time[READ]        = u.read_time;
366         g->io_time[WRITE]       = u.write_time;
367         g->oldest_gen           = u.oldest_gen;
368         g->gen_valid            = 1;
369
370         return 0;
371 }
372
373 int bch2_alloc_read(struct bch_fs *c)
374 {
375         struct btree_trans trans;
376         int ret;
377
378         bch2_trans_init(&trans, c, 0, 0);
379         down_read(&c->gc_lock);
380         ret = bch2_btree_and_journal_walk(&trans, BTREE_ID_alloc, bch2_alloc_read_fn);
381         up_read(&c->gc_lock);
382         bch2_trans_exit(&trans);
383         if (ret) {
384                 bch_err(c, "error reading alloc info: %i", ret);
385                 return ret;
386         }
387
388         return 0;
389 }
390
391 static int bch2_alloc_write_key(struct btree_trans *trans,
392                                 struct btree_iter *iter,
393                                 unsigned flags)
394 {
395         struct bch_fs *c = trans->c;
396         struct bkey_s_c k;
397         struct bkey_alloc_unpacked old_u, new_u;
398         int ret;
399 retry:
400         bch2_trans_begin(trans);
401
402         ret = bch2_btree_key_cache_flush(trans,
403                         BTREE_ID_alloc, iter->pos);
404         if (ret)
405                 goto err;
406
407         k = bch2_btree_iter_peek_slot(iter);
408         ret = bkey_err(k);
409         if (ret)
410                 goto err;
411
412         old_u   = bch2_alloc_unpack(k);
413         new_u   = alloc_mem_to_key(c, iter);
414
415         if (!bkey_alloc_unpacked_cmp(old_u, new_u))
416                 return 0;
417
418         ret   = bch2_alloc_write(trans, iter, &new_u,
419                                   BTREE_TRIGGER_NORUN) ?:
420                 bch2_trans_commit(trans, NULL, NULL,
421                                 BTREE_INSERT_NOFAIL|flags);
422 err:
423         if (ret == -EINTR)
424                 goto retry;
425         return ret;
426 }
427
428 int bch2_alloc_write_all(struct bch_fs *c, unsigned flags)
429 {
430         struct btree_trans trans;
431         struct btree_iter iter;
432         struct bch_dev *ca;
433         unsigned i;
434         int ret = 0;
435
436         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
437         bch2_trans_iter_init(&trans, &iter, BTREE_ID_alloc, POS_MIN,
438                              BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
439
440         for_each_member_device(ca, c, i) {
441                 bch2_btree_iter_set_pos(&iter,
442                         POS(ca->dev_idx, ca->mi.first_bucket));
443
444                 while (iter.pos.offset < ca->mi.nbuckets) {
445                         ret = bch2_alloc_write_key(&trans, &iter, flags);
446                         if (ret) {
447                                 percpu_ref_put(&ca->ref);
448                                 goto err;
449                         }
450                         bch2_btree_iter_advance(&iter);
451                 }
452         }
453 err:
454         bch2_trans_iter_exit(&trans, &iter);
455         bch2_trans_exit(&trans);
456         return ret;
457 }
458
459 /* Bucket IO clocks: */
460
461 int bch2_bucket_io_time_reset(struct btree_trans *trans, unsigned dev,
462                               size_t bucket_nr, int rw)
463 {
464         struct bch_fs *c = trans->c;
465         struct btree_iter iter;
466         struct bkey_alloc_unpacked u;
467         u64 *time, now;
468         int ret = 0;
469
470         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, POS(dev, bucket_nr),
471                              BTREE_ITER_CACHED|
472                              BTREE_ITER_CACHED_NOFILL|
473                              BTREE_ITER_INTENT);
474         ret = bch2_btree_iter_traverse(&iter);
475         if (ret)
476                 goto out;
477
478         u = alloc_mem_to_key(c, &iter);
479
480         time = rw == READ ? &u.read_time : &u.write_time;
481         now = atomic64_read(&c->io_clock[rw].now);
482         if (*time == now)
483                 goto out;
484
485         *time = now;
486
487         ret   = bch2_alloc_write(trans, &iter, &u, 0) ?:
488                 bch2_trans_commit(trans, NULL, NULL, 0);
489 out:
490         bch2_trans_iter_exit(trans, &iter);
491         return ret;
492 }
493
494 /* Background allocator thread: */
495
496 /*
497  * Scans for buckets to be invalidated, invalidates them, rewrites prios/gens
498  * (marking them as invalidated on disk), then optionally issues discard
499  * commands to the newly free buckets, then puts them on the various freelists.
500  */
501
502 static bool bch2_can_invalidate_bucket(struct bch_dev *ca, size_t b,
503                                        struct bucket_mark m)
504 {
505         u8 gc_gen;
506
507         if (!is_available_bucket(m))
508                 return false;
509
510         if (m.owned_by_allocator)
511                 return false;
512
513         if (ca->buckets_nouse &&
514             test_bit(b, ca->buckets_nouse))
515                 return false;
516
517         if (ca->new_fs_bucket_idx) {
518                 /*
519                  * Device or filesystem is still being initialized, and we
520                  * haven't fully marked superblocks & journal:
521                  */
522                 if (is_superblock_bucket(ca, b))
523                         return false;
524
525                 if (b < ca->new_fs_bucket_idx)
526                         return false;
527         }
528
529         gc_gen = bucket_gc_gen(bucket(ca, b));
530
531         ca->inc_gen_needs_gc            += gc_gen >= BUCKET_GC_GEN_MAX / 2;
532         ca->inc_gen_really_needs_gc     += gc_gen >= BUCKET_GC_GEN_MAX;
533
534         return gc_gen < BUCKET_GC_GEN_MAX;
535 }
536
537 /*
538  * Determines what order we're going to reuse buckets, smallest bucket_key()
539  * first.
540  */
541
542 static unsigned bucket_sort_key(struct bucket *g, struct bucket_mark m,
543                                 u64 now, u64 last_seq_ondisk)
544 {
545         unsigned used = bucket_sectors_used(m);
546
547         if (used) {
548                 /*
549                  * Prefer to keep buckets that have been read more recently, and
550                  * buckets that have more data in them:
551                  */
552                 u64 last_read = max_t(s64, 0, now - g->io_time[READ]);
553                 u32 last_read_scaled = max_t(u64, U32_MAX, div_u64(last_read, used));
554
555                 return -last_read_scaled;
556         } else {
557                 /*
558                  * Prefer to use buckets with smaller gc_gen so that we don't
559                  * have to walk the btree and recalculate oldest_gen - but shift
560                  * off the low bits so that buckets will still have equal sort
561                  * keys when there's only a small difference, so that we can
562                  * keep sequential buckets together:
563                  */
564                 return  (bucket_needs_journal_commit(m, last_seq_ondisk) << 4)|
565                         (bucket_gc_gen(g) >> 4);
566         }
567 }
568
569 static inline int bucket_alloc_cmp(alloc_heap *h,
570                                    struct alloc_heap_entry l,
571                                    struct alloc_heap_entry r)
572 {
573         return  cmp_int(l.key, r.key) ?:
574                 cmp_int(r.nr, l.nr) ?:
575                 cmp_int(l.bucket, r.bucket);
576 }
577
578 static inline int bucket_idx_cmp(const void *_l, const void *_r)
579 {
580         const struct alloc_heap_entry *l = _l, *r = _r;
581
582         return cmp_int(l->bucket, r->bucket);
583 }
584
585 static void find_reclaimable_buckets_lru(struct bch_fs *c, struct bch_dev *ca)
586 {
587         struct bucket_array *buckets;
588         struct alloc_heap_entry e = { 0 };
589         u64 now, last_seq_ondisk;
590         size_t b, i, nr = 0;
591
592         down_read(&ca->bucket_lock);
593
594         buckets = bucket_array(ca);
595         ca->alloc_heap.used = 0;
596         now = atomic64_read(&c->io_clock[READ].now);
597         last_seq_ondisk = c->journal.flushed_seq_ondisk;
598
599         /*
600          * Find buckets with lowest read priority, by building a maxheap sorted
601          * by read priority and repeatedly replacing the maximum element until
602          * all buckets have been visited.
603          */
604         for (b = ca->mi.first_bucket; b < ca->mi.nbuckets; b++) {
605                 struct bucket *g = &buckets->b[b];
606                 struct bucket_mark m = READ_ONCE(g->mark);
607                 unsigned key = bucket_sort_key(g, m, now, last_seq_ondisk);
608
609                 cond_resched();
610
611                 if (!bch2_can_invalidate_bucket(ca, b, m))
612                         continue;
613
614                 if (e.nr && e.bucket + e.nr == b && e.key == key) {
615                         e.nr++;
616                 } else {
617                         if (e.nr)
618                                 heap_add_or_replace(&ca->alloc_heap, e,
619                                         -bucket_alloc_cmp, NULL);
620
621                         e = (struct alloc_heap_entry) {
622                                 .bucket = b,
623                                 .nr     = 1,
624                                 .key    = key,
625                         };
626                 }
627         }
628
629         if (e.nr)
630                 heap_add_or_replace(&ca->alloc_heap, e,
631                                 -bucket_alloc_cmp, NULL);
632
633         for (i = 0; i < ca->alloc_heap.used; i++)
634                 nr += ca->alloc_heap.data[i].nr;
635
636         while (nr - ca->alloc_heap.data[0].nr >= ALLOC_SCAN_BATCH(ca)) {
637                 nr -= ca->alloc_heap.data[0].nr;
638                 heap_pop(&ca->alloc_heap, e, -bucket_alloc_cmp, NULL);
639         }
640
641         up_read(&ca->bucket_lock);
642 }
643
644 static size_t find_reclaimable_buckets(struct bch_fs *c, struct bch_dev *ca)
645 {
646         size_t i, nr = 0;
647
648         ca->inc_gen_needs_gc                    = 0;
649         ca->inc_gen_really_needs_gc             = 0;
650
651         find_reclaimable_buckets_lru(c, ca);
652
653         heap_resort(&ca->alloc_heap, bucket_alloc_cmp, NULL);
654
655         for (i = 0; i < ca->alloc_heap.used; i++)
656                 nr += ca->alloc_heap.data[i].nr;
657
658         return nr;
659 }
660
661 static int bucket_invalidate_btree(struct btree_trans *trans,
662                                    struct bch_dev *ca, u64 b,
663                                    struct bkey_alloc_unpacked *u)
664 {
665         struct bch_fs *c = trans->c;
666         struct btree_iter iter;
667         int ret;
668
669         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
670                              POS(ca->dev_idx, b),
671                              BTREE_ITER_CACHED|
672                              BTREE_ITER_CACHED_NOFILL|
673                              BTREE_ITER_INTENT);
674
675         ret = bch2_btree_iter_traverse(&iter);
676         if (ret)
677                 goto err;
678
679         *u = alloc_mem_to_key(c, &iter);
680
681         u->gen++;
682         u->data_type            = 0;
683         u->dirty_sectors        = 0;
684         u->cached_sectors       = 0;
685         u->read_time            = atomic64_read(&c->io_clock[READ].now);
686         u->write_time           = atomic64_read(&c->io_clock[WRITE].now);
687
688         ret = bch2_alloc_write(trans, &iter, u,
689                                BTREE_TRIGGER_BUCKET_INVALIDATE);
690 err:
691         bch2_trans_iter_exit(trans, &iter);
692         return ret;
693 }
694
695 static int bch2_invalidate_one_bucket(struct bch_fs *c, struct bch_dev *ca,
696                                       u64 *journal_seq, unsigned flags)
697 {
698         struct bkey_alloc_unpacked u;
699         size_t b;
700         int ret = 0;
701
702         /*
703          * If the read-only path is trying to shut down, we can't be generating
704          * new btree updates:
705          */
706         if (test_bit(BCH_FS_ALLOCATOR_STOPPING, &c->flags))
707                 return 1;
708
709         BUG_ON(!ca->alloc_heap.used ||
710                !ca->alloc_heap.data[0].nr);
711         b = ca->alloc_heap.data[0].bucket;
712
713         /* first, put on free_inc and mark as owned by allocator: */
714         percpu_down_read(&c->mark_lock);
715
716         bch2_mark_alloc_bucket(c, ca, b, true);
717
718         spin_lock(&c->freelist_lock);
719         verify_not_on_freelist(c, ca, b);
720         BUG_ON(!fifo_push(&ca->free_inc, b));
721         spin_unlock(&c->freelist_lock);
722
723         percpu_up_read(&c->mark_lock);
724
725         ret = bch2_trans_do(c, NULL, journal_seq,
726                             BTREE_INSERT_NOCHECK_RW|
727                             BTREE_INSERT_NOFAIL|
728                             BTREE_INSERT_JOURNAL_RESERVED|
729                             flags,
730                             bucket_invalidate_btree(&trans, ca, b, &u));
731
732         if (!ret) {
733                 /* remove from alloc_heap: */
734                 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
735
736                 top->bucket++;
737                 top->nr--;
738
739                 if (!top->nr)
740                         heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
741
742                 /*
743                  * Make sure we flush the last journal entry that updated this
744                  * bucket (i.e. deleting the last reference) before writing to
745                  * this bucket again:
746                  */
747                 *journal_seq = max(*journal_seq, u.journal_seq);
748         } else {
749                 size_t b2;
750
751                 /* remove from free_inc: */
752                 percpu_down_read(&c->mark_lock);
753                 spin_lock(&c->freelist_lock);
754
755                 bch2_mark_alloc_bucket(c, ca, b, false);
756
757                 BUG_ON(!fifo_pop_back(&ca->free_inc, b2));
758                 BUG_ON(b != b2);
759
760                 spin_unlock(&c->freelist_lock);
761                 percpu_up_read(&c->mark_lock);
762         }
763
764         return ret < 0 ? ret : 0;
765 }
766
767 /*
768  * Pull buckets off ca->alloc_heap, invalidate them, move them to ca->free_inc:
769  */
770 static int bch2_invalidate_buckets(struct bch_fs *c, struct bch_dev *ca)
771 {
772         u64 journal_seq = 0;
773         int ret = 0;
774
775         /* Only use nowait if we've already invalidated at least one bucket: */
776         while (!ret &&
777                !fifo_full(&ca->free_inc) &&
778                ca->alloc_heap.used) {
779                 if (kthread_should_stop()) {
780                         ret = 1;
781                         break;
782                 }
783
784                 ret = bch2_invalidate_one_bucket(c, ca, &journal_seq,
785                                 (!fifo_empty(&ca->free_inc)
786                                  ? BTREE_INSERT_NOWAIT : 0));
787                 /*
788                  * We only want to batch up invalidates when they're going to
789                  * require flushing the journal:
790                  */
791                 if (!journal_seq)
792                         break;
793         }
794
795         /* If we used NOWAIT, don't return the error: */
796         if (!fifo_empty(&ca->free_inc))
797                 ret = 0;
798         if (ret < 0)
799                 bch_err(ca, "error invalidating buckets: %i", ret);
800         if (ret)
801                 return ret;
802
803         if (journal_seq)
804                 ret = bch2_journal_flush_seq(&c->journal, journal_seq);
805         if (ret) {
806                 bch_err(ca, "journal error: %i", ret);
807                 return ret;
808         }
809
810         return 0;
811 }
812
813 static void alloc_thread_set_state(struct bch_dev *ca, unsigned new_state)
814 {
815         if (ca->allocator_state != new_state) {
816                 ca->allocator_state = new_state;
817                 closure_wake_up(&ca->fs->freelist_wait);
818         }
819 }
820
821 static int push_invalidated_bucket(struct bch_fs *c, struct bch_dev *ca, u64 b)
822 {
823         unsigned i;
824         int ret = 0;
825
826         spin_lock(&c->freelist_lock);
827         for (i = 0; i < RESERVE_NR; i++) {
828                 /*
829                  * Don't strand buckets on the copygc freelist until
830                  * after recovery is finished:
831                  */
832                 if (i == RESERVE_MOVINGGC &&
833                     !test_bit(BCH_FS_STARTED, &c->flags))
834                         continue;
835
836                 if (fifo_push(&ca->free[i], b)) {
837                         fifo_pop(&ca->free_inc, b);
838                         ret = 1;
839                         break;
840                 }
841         }
842         spin_unlock(&c->freelist_lock);
843
844         ca->allocator_state = ret
845                 ? ALLOCATOR_running
846                 : ALLOCATOR_blocked_full;
847         closure_wake_up(&c->freelist_wait);
848         return ret;
849 }
850
851 static void discard_one_bucket(struct bch_fs *c, struct bch_dev *ca, u64 b)
852 {
853         if (ca->mi.discard &&
854             blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
855                 blkdev_issue_discard(ca->disk_sb.bdev, bucket_to_sector(ca, b),
856                                      ca->mi.bucket_size, GFP_NOFS, 0);
857 }
858
859 static bool allocator_thread_running(struct bch_dev *ca)
860 {
861         unsigned state = ca->mi.state == BCH_MEMBER_STATE_rw &&
862                 test_bit(BCH_FS_ALLOCATOR_RUNNING, &ca->fs->flags)
863                 ? ALLOCATOR_running
864                 : ALLOCATOR_stopped;
865         alloc_thread_set_state(ca, state);
866         return state == ALLOCATOR_running;
867 }
868
869 static int buckets_available(struct bch_dev *ca, unsigned long gc_count)
870 {
871         s64 available = dev_buckets_reclaimable(ca) -
872                 (gc_count == ca->fs->gc_count ? ca->inc_gen_really_needs_gc : 0);
873         bool ret = available > 0;
874
875         alloc_thread_set_state(ca, ret
876                                ? ALLOCATOR_running
877                                : ALLOCATOR_blocked);
878         return ret;
879 }
880
881 /**
882  * bch_allocator_thread - move buckets from free_inc to reserves
883  *
884  * The free_inc FIFO is populated by find_reclaimable_buckets(), and
885  * the reserves are depleted by bucket allocation. When we run out
886  * of free_inc, try to invalidate some buckets and write out
887  * prios and gens.
888  */
889 static int bch2_allocator_thread(void *arg)
890 {
891         struct bch_dev *ca = arg;
892         struct bch_fs *c = ca->fs;
893         unsigned long gc_count = c->gc_count;
894         size_t nr;
895         int ret;
896
897         set_freezable();
898
899         while (1) {
900                 ret = kthread_wait_freezable(allocator_thread_running(ca));
901                 if (ret)
902                         goto stop;
903
904                 while (!ca->alloc_heap.used) {
905                         cond_resched();
906
907                         ret = kthread_wait_freezable(buckets_available(ca, gc_count));
908                         if (ret)
909                                 goto stop;
910
911                         gc_count = c->gc_count;
912                         nr = find_reclaimable_buckets(c, ca);
913
914                         trace_alloc_scan(ca, nr, ca->inc_gen_needs_gc,
915                                          ca->inc_gen_really_needs_gc);
916
917                         if ((ca->inc_gen_needs_gc >= ALLOC_SCAN_BATCH(ca) ||
918                              ca->inc_gen_really_needs_gc) &&
919                             c->gc_thread) {
920                                 atomic_inc(&c->kick_gc);
921                                 wake_up_process(c->gc_thread);
922                         }
923                 }
924
925                 ret = bch2_invalidate_buckets(c, ca);
926                 if (ret)
927                         goto stop;
928
929                 while (!fifo_empty(&ca->free_inc)) {
930                         u64 b = fifo_peek(&ca->free_inc);
931
932                         discard_one_bucket(c, ca, b);
933
934                         ret = kthread_wait_freezable(push_invalidated_bucket(c, ca, b));
935                         if (ret)
936                                 goto stop;
937                 }
938         }
939 stop:
940         alloc_thread_set_state(ca, ALLOCATOR_stopped);
941         return 0;
942 }
943
944 /* Startup/shutdown (ro/rw): */
945
946 void bch2_recalc_capacity(struct bch_fs *c)
947 {
948         struct bch_dev *ca;
949         u64 capacity = 0, reserved_sectors = 0, gc_reserve;
950         unsigned bucket_size_max = 0;
951         unsigned long ra_pages = 0;
952         unsigned i, j;
953
954         lockdep_assert_held(&c->state_lock);
955
956         for_each_online_member(ca, c, i) {
957                 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_disk->bdi;
958
959                 ra_pages += bdi->ra_pages;
960         }
961
962         bch2_set_ra_pages(c, ra_pages);
963
964         for_each_rw_member(ca, c, i) {
965                 u64 dev_reserve = 0;
966
967                 /*
968                  * We need to reserve buckets (from the number
969                  * of currently available buckets) against
970                  * foreground writes so that mainly copygc can
971                  * make forward progress.
972                  *
973                  * We need enough to refill the various reserves
974                  * from scratch - copygc will use its entire
975                  * reserve all at once, then run against when
976                  * its reserve is refilled (from the formerly
977                  * available buckets).
978                  *
979                  * This reserve is just used when considering if
980                  * allocations for foreground writes must wait -
981                  * not -ENOSPC calculations.
982                  */
983                 for (j = 0; j < RESERVE_NONE; j++)
984                         dev_reserve += ca->free[j].size;
985
986                 dev_reserve += 1;       /* btree write point */
987                 dev_reserve += 1;       /* copygc write point */
988                 dev_reserve += 1;       /* rebalance write point */
989
990                 dev_reserve *= ca->mi.bucket_size;
991
992                 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
993                                              ca->mi.first_bucket);
994
995                 reserved_sectors += dev_reserve * 2;
996
997                 bucket_size_max = max_t(unsigned, bucket_size_max,
998                                         ca->mi.bucket_size);
999         }
1000
1001         gc_reserve = c->opts.gc_reserve_bytes
1002                 ? c->opts.gc_reserve_bytes >> 9
1003                 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1004
1005         reserved_sectors = max(gc_reserve, reserved_sectors);
1006
1007         reserved_sectors = min(reserved_sectors, capacity);
1008
1009         c->capacity = capacity - reserved_sectors;
1010
1011         c->bucket_size_max = bucket_size_max;
1012
1013         /* Wake up case someone was waiting for buckets */
1014         closure_wake_up(&c->freelist_wait);
1015 }
1016
1017 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1018 {
1019         struct open_bucket *ob;
1020         bool ret = false;
1021
1022         for (ob = c->open_buckets;
1023              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1024              ob++) {
1025                 spin_lock(&ob->lock);
1026                 if (ob->valid && !ob->on_partial_list &&
1027                     ob->dev == ca->dev_idx)
1028                         ret = true;
1029                 spin_unlock(&ob->lock);
1030         }
1031
1032         return ret;
1033 }
1034
1035 /* device goes ro: */
1036 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1037 {
1038         unsigned i;
1039
1040         BUG_ON(ca->alloc_thread);
1041
1042         /* First, remove device from allocation groups: */
1043
1044         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1045                 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1046
1047         /*
1048          * Capacity is calculated based off of devices in allocation groups:
1049          */
1050         bch2_recalc_capacity(c);
1051
1052         /* Next, close write points that point to this device... */
1053         for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1054                 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1055
1056         bch2_writepoint_stop(c, ca, &c->copygc_write_point);
1057         bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1058         bch2_writepoint_stop(c, ca, &c->btree_write_point);
1059
1060         mutex_lock(&c->btree_reserve_cache_lock);
1061         while (c->btree_reserve_cache_nr) {
1062                 struct btree_alloc *a =
1063                         &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1064
1065                 bch2_open_buckets_put(c, &a->ob);
1066         }
1067         mutex_unlock(&c->btree_reserve_cache_lock);
1068
1069         while (1) {
1070                 struct open_bucket *ob;
1071
1072                 spin_lock(&c->freelist_lock);
1073                 if (!ca->open_buckets_partial_nr) {
1074                         spin_unlock(&c->freelist_lock);
1075                         break;
1076                 }
1077                 ob = c->open_buckets +
1078                         ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1079                 ob->on_partial_list = false;
1080                 spin_unlock(&c->freelist_lock);
1081
1082                 bch2_open_bucket_put(c, ob);
1083         }
1084
1085         bch2_ec_stop_dev(c, ca);
1086
1087         /*
1088          * Wake up threads that were blocked on allocation, so they can notice
1089          * the device can no longer be removed and the capacity has changed:
1090          */
1091         closure_wake_up(&c->freelist_wait);
1092
1093         /*
1094          * journal_res_get() can block waiting for free space in the journal -
1095          * it needs to notice there may not be devices to allocate from anymore:
1096          */
1097         wake_up(&c->journal.wait);
1098
1099         /* Now wait for any in flight writes: */
1100
1101         closure_wait_event(&c->open_buckets_wait,
1102                            !bch2_dev_has_open_write_point(c, ca));
1103 }
1104
1105 /* device goes rw: */
1106 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1107 {
1108         unsigned i;
1109
1110         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1111                 if (ca->mi.data_allowed & (1 << i))
1112                         set_bit(ca->dev_idx, c->rw_devs[i].d);
1113 }
1114
1115 void bch2_dev_allocator_quiesce(struct bch_fs *c, struct bch_dev *ca)
1116 {
1117         if (ca->alloc_thread)
1118                 closure_wait_event(&c->freelist_wait,
1119                                    ca->allocator_state != ALLOCATOR_running);
1120 }
1121
1122 /* stop allocator thread: */
1123 void bch2_dev_allocator_stop(struct bch_dev *ca)
1124 {
1125         struct task_struct *p;
1126
1127         p = rcu_dereference_protected(ca->alloc_thread, 1);
1128         ca->alloc_thread = NULL;
1129
1130         /*
1131          * We need an rcu barrier between setting ca->alloc_thread = NULL and
1132          * the thread shutting down to avoid bch2_wake_allocator() racing:
1133          *
1134          * XXX: it would be better to have the rcu barrier be asynchronous
1135          * instead of blocking us here
1136          */
1137         synchronize_rcu();
1138
1139         if (p) {
1140                 kthread_stop(p);
1141                 put_task_struct(p);
1142         }
1143 }
1144
1145 /* start allocator thread: */
1146 int bch2_dev_allocator_start(struct bch_dev *ca)
1147 {
1148         struct task_struct *p;
1149
1150         /*
1151          * allocator thread already started?
1152          */
1153         if (ca->alloc_thread)
1154                 return 0;
1155
1156         p = kthread_create(bch2_allocator_thread, ca,
1157                            "bch-alloc/%s", ca->name);
1158         if (IS_ERR(p)) {
1159                 bch_err(ca->fs, "error creating allocator thread: %li",
1160                         PTR_ERR(p));
1161                 return PTR_ERR(p);
1162         }
1163
1164         get_task_struct(p);
1165         rcu_assign_pointer(ca->alloc_thread, p);
1166         wake_up_process(p);
1167         return 0;
1168 }
1169
1170 void bch2_fs_allocator_background_init(struct bch_fs *c)
1171 {
1172         spin_lock_init(&c->freelist_lock);
1173 }