1 // SPDX-License-Identifier: GPL-2.0
3 #include "alloc_background.h"
4 #include "alloc_foreground.h"
5 #include "btree_cache.h"
7 #include "btree_update.h"
8 #include "btree_update_interior.h"
17 #include <linux/kthread.h>
18 #include <linux/math64.h>
19 #include <linux/random.h>
20 #include <linux/rculist.h>
21 #include <linux/rcupdate.h>
22 #include <linux/sched/task.h>
23 #include <linux/sort.h>
24 #include <trace/events/bcachefs.h>
26 static const char * const bch2_alloc_field_names[] = {
27 #define x(name, bytes) #name,
33 static void bch2_recalc_oldest_io(struct bch_fs *, struct bch_dev *, int);
35 /* Ratelimiting/PD controllers */
37 static void pd_controllers_update(struct work_struct *work)
39 struct bch_fs *c = container_of(to_delayed_work(work),
41 pd_controllers_update);
45 for_each_member_device(ca, c, i) {
46 struct bch_dev_usage stats = bch2_dev_usage_read(c, ca);
48 u64 free = bucket_to_sector(ca,
49 __dev_buckets_free(ca, stats)) << 9;
51 * Bytes of internal fragmentation, which can be
52 * reclaimed by copy GC
54 s64 fragmented = (bucket_to_sector(ca,
55 stats.buckets[BCH_DATA_USER] +
56 stats.buckets[BCH_DATA_CACHED]) -
57 (stats.sectors[BCH_DATA_USER] +
58 stats.sectors[BCH_DATA_CACHED])) << 9;
60 fragmented = max(0LL, fragmented);
62 bch2_pd_controller_update(&ca->copygc_pd,
63 free, fragmented, -1);
66 schedule_delayed_work(&c->pd_controllers_update,
67 c->pd_controllers_update_seconds * HZ);
70 /* Persistent alloc info: */
72 static inline u64 get_alloc_field(const struct bch_alloc *a,
73 const void **p, unsigned field)
75 unsigned bytes = BCH_ALLOC_FIELD_BYTES[field];
78 if (!(a->fields & (1 << field)))
83 v = *((const u8 *) *p);
102 static inline void put_alloc_field(struct bkey_i_alloc *a, void **p,
103 unsigned field, u64 v)
105 unsigned bytes = BCH_ALLOC_FIELD_BYTES[field];
110 a->v.fields |= 1 << field;
117 *((__le16 *) *p) = cpu_to_le16(v);
120 *((__le32 *) *p) = cpu_to_le32(v);
123 *((__le64 *) *p) = cpu_to_le64(v);
132 struct bkey_alloc_unpacked bch2_alloc_unpack(struct bkey_s_c k)
134 struct bkey_alloc_unpacked ret = { .gen = 0 };
136 if (k.k->type == KEY_TYPE_alloc) {
137 const struct bch_alloc *a = bkey_s_c_to_alloc(k).v;
138 const void *d = a->data;
143 #define x(_name, _bits) ret._name = get_alloc_field(a, &d, idx++);
150 void bch2_alloc_pack(struct bkey_i_alloc *dst,
151 const struct bkey_alloc_unpacked src)
154 void *d = dst->v.data;
158 dst->v.gen = src.gen;
160 #define x(_name, _bits) put_alloc_field(dst, &d, idx++, src._name);
164 bytes = (void *) d - (void *) &dst->v;
165 set_bkey_val_bytes(&dst->k, bytes);
166 memset_u64s_tail(&dst->v, 0, bytes);
169 static unsigned bch_alloc_val_u64s(const struct bch_alloc *a)
171 unsigned i, bytes = offsetof(struct bch_alloc, data);
173 for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_FIELD_BYTES); i++)
174 if (a->fields & (1 << i))
175 bytes += BCH_ALLOC_FIELD_BYTES[i];
177 return DIV_ROUND_UP(bytes, sizeof(u64));
180 const char *bch2_alloc_invalid(const struct bch_fs *c, struct bkey_s_c k)
182 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
184 if (k.k->p.inode >= c->sb.nr_devices ||
185 !c->devs[k.k->p.inode])
186 return "invalid device";
188 /* allow for unknown fields */
189 if (bkey_val_u64s(a.k) < bch_alloc_val_u64s(a.v))
190 return "incorrect value size";
195 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
198 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
199 const void *d = a.v->data;
202 pr_buf(out, "gen %u", a.v->gen);
204 for (i = 0; i < BCH_ALLOC_FIELD_NR; i++)
205 if (a.v->fields & (1 << i))
206 pr_buf(out, " %s %llu",
207 bch2_alloc_field_names[i],
208 get_alloc_field(a.v, &d, i));
211 int bch2_alloc_read(struct bch_fs *c, struct journal_keys *journal_keys)
213 struct btree_trans trans;
214 struct btree_and_journal_iter iter;
220 bch2_trans_init(&trans, c, 0, 0);
222 bch2_btree_and_journal_iter_init(&iter, &trans, journal_keys,
223 BTREE_ID_ALLOC, POS_MIN);
225 while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
226 bch2_mark_key(c, k, 0, 0, NULL, 0,
227 BTREE_TRIGGER_ALLOC_READ|
228 BTREE_TRIGGER_NOATOMIC);
230 bch2_btree_and_journal_iter_advance(&iter);
233 ret = bch2_trans_exit(&trans) ?: ret;
235 bch_err(c, "error reading alloc info: %i", ret);
239 percpu_down_write(&c->mark_lock);
240 bch2_dev_usage_from_buckets(c);
241 percpu_up_write(&c->mark_lock);
243 mutex_lock(&c->bucket_clock[READ].lock);
244 for_each_member_device(ca, c, i) {
245 down_read(&ca->bucket_lock);
246 bch2_recalc_oldest_io(c, ca, READ);
247 up_read(&ca->bucket_lock);
249 mutex_unlock(&c->bucket_clock[READ].lock);
251 mutex_lock(&c->bucket_clock[WRITE].lock);
252 for_each_member_device(ca, c, i) {
253 down_read(&ca->bucket_lock);
254 bch2_recalc_oldest_io(c, ca, WRITE);
255 up_read(&ca->bucket_lock);
257 mutex_unlock(&c->bucket_clock[WRITE].lock);
262 enum alloc_write_ret {
268 static int bch2_alloc_write_key(struct btree_trans *trans,
269 struct btree_iter *iter,
272 struct bch_fs *c = trans->c;
275 struct bucket_array *ba;
277 struct bucket_mark m;
278 struct bkey_alloc_unpacked old_u, new_u;
279 __BKEY_PADDED(k, 8) alloc_key; /* hack: */
280 struct bkey_i_alloc *a;
283 k = bch2_btree_iter_peek_slot(iter);
288 old_u = bch2_alloc_unpack(k);
290 if (iter->pos.inode >= c->sb.nr_devices ||
291 !c->devs[iter->pos.inode])
294 percpu_down_read(&c->mark_lock);
295 ca = bch_dev_bkey_exists(c, iter->pos.inode);
296 ba = bucket_array(ca);
298 if (iter->pos.offset >= ba->nbuckets) {
299 percpu_up_read(&c->mark_lock);
303 g = &ba->b[iter->pos.offset];
304 m = READ_ONCE(g->mark);
305 new_u = alloc_mem_to_key(g, m);
306 percpu_up_read(&c->mark_lock);
308 if (!bkey_alloc_unpacked_cmp(old_u, new_u))
309 return ALLOC_NOWROTE;
311 a = bkey_alloc_init(&alloc_key.k);
313 bch2_alloc_pack(a, new_u);
315 bch2_trans_update(trans, iter, &a->k_i,
316 BTREE_TRIGGER_NORUN);
317 ret = bch2_trans_commit(trans, NULL, NULL,
319 BTREE_INSERT_USE_RESERVE|
327 int bch2_alloc_write(struct bch_fs *c, unsigned flags, bool *wrote)
329 struct btree_trans trans;
330 struct btree_iter *iter;
335 BUG_ON(BKEY_ALLOC_VAL_U64s_MAX > 8);
337 bch2_trans_init(&trans, c, 0, 0);
339 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC, POS_MIN,
340 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
342 for_each_rw_member(ca, c, i) {
343 unsigned first_bucket;
345 percpu_down_read(&c->mark_lock);
346 first_bucket = bucket_array(ca)->first_bucket;
347 percpu_up_read(&c->mark_lock);
349 bch2_btree_iter_set_pos(iter, POS(i, first_bucket));
352 ret = bch2_alloc_write_key(&trans, iter, flags);
353 if (ret < 0 || ret == ALLOC_END)
355 if (ret == ALLOC_WROTE)
357 bch2_btree_iter_next_slot(iter);
361 percpu_ref_put(&ca->io_ref);
366 bch2_trans_exit(&trans);
368 return ret < 0 ? ret : 0;
371 int bch2_alloc_replay_key(struct bch_fs *c, struct bkey_i *k)
373 struct btree_trans trans;
374 struct btree_iter *iter;
377 bch2_trans_init(&trans, c, 0, 0);
379 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC, k->k.p,
380 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
382 ret = bch2_alloc_write_key(&trans, iter,
384 BTREE_INSERT_LAZY_RW|
385 BTREE_INSERT_JOURNAL_REPLAY);
386 bch2_trans_exit(&trans);
387 return ret < 0 ? ret : 0;
390 /* Bucket IO clocks: */
392 static void bch2_recalc_oldest_io(struct bch_fs *c, struct bch_dev *ca, int rw)
394 struct bucket_clock *clock = &c->bucket_clock[rw];
395 struct bucket_array *buckets = bucket_array(ca);
400 lockdep_assert_held(&c->bucket_clock[rw].lock);
402 /* Recalculate max_last_io for this device: */
403 for_each_bucket(g, buckets)
404 max_last_io = max(max_last_io, bucket_last_io(c, g, rw));
406 ca->max_last_bucket_io[rw] = max_last_io;
408 /* Recalculate global max_last_io: */
411 for_each_member_device(ca, c, i)
412 max_last_io = max(max_last_io, ca->max_last_bucket_io[rw]);
414 clock->max_last_io = max_last_io;
417 static void bch2_rescale_bucket_io_times(struct bch_fs *c, int rw)
419 struct bucket_clock *clock = &c->bucket_clock[rw];
420 struct bucket_array *buckets;
425 trace_rescale_prios(c);
427 for_each_member_device(ca, c, i) {
428 down_read(&ca->bucket_lock);
429 buckets = bucket_array(ca);
431 for_each_bucket(g, buckets)
432 g->io_time[rw] = clock->hand -
433 bucket_last_io(c, g, rw) / 2;
435 bch2_recalc_oldest_io(c, ca, rw);
437 up_read(&ca->bucket_lock);
441 static inline u64 bucket_clock_freq(u64 capacity)
443 return max(capacity >> 10, 2028ULL);
446 static void bch2_inc_clock_hand(struct io_timer *timer)
448 struct bucket_clock *clock = container_of(timer,
449 struct bucket_clock, rescale);
450 struct bch_fs *c = container_of(clock,
451 struct bch_fs, bucket_clock[clock->rw]);
456 mutex_lock(&clock->lock);
458 /* if clock cannot be advanced more, rescale prio */
459 if (clock->max_last_io >= U16_MAX - 2)
460 bch2_rescale_bucket_io_times(c, clock->rw);
462 BUG_ON(clock->max_last_io >= U16_MAX - 2);
464 for_each_member_device(ca, c, i)
465 ca->max_last_bucket_io[clock->rw]++;
466 clock->max_last_io++;
469 mutex_unlock(&clock->lock);
471 capacity = READ_ONCE(c->capacity);
477 * we only increment when 0.1% of the filesystem capacity has been read
478 * or written too, this determines if it's time
480 * XXX: we shouldn't really be going off of the capacity of devices in
481 * RW mode (that will be 0 when we're RO, yet we can still service
484 timer->expire += bucket_clock_freq(capacity);
486 bch2_io_timer_add(&c->io_clock[clock->rw], timer);
489 static void bch2_bucket_clock_init(struct bch_fs *c, int rw)
491 struct bucket_clock *clock = &c->bucket_clock[rw];
495 clock->rescale.fn = bch2_inc_clock_hand;
496 clock->rescale.expire = bucket_clock_freq(c->capacity);
497 mutex_init(&clock->lock);
500 /* Background allocator thread: */
503 * Scans for buckets to be invalidated, invalidates them, rewrites prios/gens
504 * (marking them as invalidated on disk), then optionally issues discard
505 * commands to the newly free buckets, then puts them on the various freelists.
508 #define BUCKET_GC_GEN_MAX 96U
511 * wait_buckets_available - wait on reclaimable buckets
513 * If there aren't enough available buckets to fill up free_inc, wait until
516 static int wait_buckets_available(struct bch_fs *c, struct bch_dev *ca)
518 unsigned long gc_count = c->gc_count;
521 ca->allocator_state = ALLOCATOR_BLOCKED;
522 closure_wake_up(&c->freelist_wait);
525 set_current_state(TASK_INTERRUPTIBLE);
526 if (kthread_should_stop()) {
531 if (gc_count != c->gc_count)
532 ca->inc_gen_really_needs_gc = 0;
534 if ((ssize_t) (dev_buckets_available(c, ca) -
535 ca->inc_gen_really_needs_gc) >=
536 (ssize_t) fifo_free(&ca->free_inc))
539 up_read(&c->gc_lock);
542 down_read(&c->gc_lock);
545 __set_current_state(TASK_RUNNING);
546 ca->allocator_state = ALLOCATOR_RUNNING;
547 closure_wake_up(&c->freelist_wait);
552 static bool bch2_can_invalidate_bucket(struct bch_dev *ca,
554 struct bucket_mark mark)
558 if (!is_available_bucket(mark))
561 if (ca->buckets_nouse &&
562 test_bit(bucket, ca->buckets_nouse))
565 gc_gen = bucket_gc_gen(ca, bucket);
567 if (gc_gen >= BUCKET_GC_GEN_MAX / 2)
568 ca->inc_gen_needs_gc++;
570 if (gc_gen >= BUCKET_GC_GEN_MAX)
571 ca->inc_gen_really_needs_gc++;
573 return gc_gen < BUCKET_GC_GEN_MAX;
577 * Determines what order we're going to reuse buckets, smallest bucket_key()
581 * - We take into account the read prio of the bucket, which gives us an
582 * indication of how hot the data is -- we scale the prio so that the prio
583 * farthest from the clock is worth 1/8th of the closest.
585 * - The number of sectors of cached data in the bucket, which gives us an
586 * indication of the cost in cache misses this eviction will cause.
588 * - If hotness * sectors used compares equal, we pick the bucket with the
589 * smallest bucket_gc_gen() - since incrementing the same bucket's generation
590 * number repeatedly forces us to run mark and sweep gc to avoid generation
594 static unsigned long bucket_sort_key(struct bch_fs *c, struct bch_dev *ca,
595 size_t b, struct bucket_mark m)
597 unsigned last_io = bucket_last_io(c, bucket(ca, b), READ);
598 unsigned max_last_io = ca->max_last_bucket_io[READ];
601 * Time since last read, scaled to [0, 8) where larger value indicates
602 * more recently read data:
604 unsigned long hotness = (max_last_io - last_io) * 7 / max_last_io;
606 /* How much we want to keep the data in this bucket: */
607 unsigned long data_wantness =
608 (hotness + 1) * bucket_sectors_used(m);
610 unsigned long needs_journal_commit =
611 bucket_needs_journal_commit(m, c->journal.last_seq_ondisk);
613 return (data_wantness << 9) |
614 (needs_journal_commit << 8) |
615 (bucket_gc_gen(ca, b) / 16);
618 static inline int bucket_alloc_cmp(alloc_heap *h,
619 struct alloc_heap_entry l,
620 struct alloc_heap_entry r)
622 return cmp_int(l.key, r.key) ?:
623 cmp_int(r.nr, l.nr) ?:
624 cmp_int(l.bucket, r.bucket);
627 static inline int bucket_idx_cmp(const void *_l, const void *_r)
629 const struct alloc_heap_entry *l = _l, *r = _r;
631 return cmp_int(l->bucket, r->bucket);
634 static void find_reclaimable_buckets_lru(struct bch_fs *c, struct bch_dev *ca)
636 struct bucket_array *buckets;
637 struct alloc_heap_entry e = { 0 };
640 ca->alloc_heap.used = 0;
642 mutex_lock(&c->bucket_clock[READ].lock);
643 down_read(&ca->bucket_lock);
645 buckets = bucket_array(ca);
647 bch2_recalc_oldest_io(c, ca, READ);
650 * Find buckets with lowest read priority, by building a maxheap sorted
651 * by read priority and repeatedly replacing the maximum element until
652 * all buckets have been visited.
654 for (b = ca->mi.first_bucket; b < ca->mi.nbuckets; b++) {
655 struct bucket_mark m = READ_ONCE(buckets->b[b].mark);
656 unsigned long key = bucket_sort_key(c, ca, b, m);
658 if (!bch2_can_invalidate_bucket(ca, b, m))
661 if (e.nr && e.bucket + e.nr == b && e.key == key) {
665 heap_add_or_replace(&ca->alloc_heap, e,
666 -bucket_alloc_cmp, NULL);
668 e = (struct alloc_heap_entry) {
679 heap_add_or_replace(&ca->alloc_heap, e,
680 -bucket_alloc_cmp, NULL);
682 for (i = 0; i < ca->alloc_heap.used; i++)
683 nr += ca->alloc_heap.data[i].nr;
685 while (nr - ca->alloc_heap.data[0].nr >= ALLOC_SCAN_BATCH(ca)) {
686 nr -= ca->alloc_heap.data[0].nr;
687 heap_pop(&ca->alloc_heap, e, -bucket_alloc_cmp, NULL);
690 up_read(&ca->bucket_lock);
691 mutex_unlock(&c->bucket_clock[READ].lock);
694 static void find_reclaimable_buckets_fifo(struct bch_fs *c, struct bch_dev *ca)
696 struct bucket_array *buckets = bucket_array(ca);
697 struct bucket_mark m;
700 if (ca->fifo_last_bucket < ca->mi.first_bucket ||
701 ca->fifo_last_bucket >= ca->mi.nbuckets)
702 ca->fifo_last_bucket = ca->mi.first_bucket;
704 start = ca->fifo_last_bucket;
707 ca->fifo_last_bucket++;
708 if (ca->fifo_last_bucket == ca->mi.nbuckets)
709 ca->fifo_last_bucket = ca->mi.first_bucket;
711 b = ca->fifo_last_bucket;
712 m = READ_ONCE(buckets->b[b].mark);
714 if (bch2_can_invalidate_bucket(ca, b, m)) {
715 struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
717 heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
718 if (heap_full(&ca->alloc_heap))
723 } while (ca->fifo_last_bucket != start);
726 static void find_reclaimable_buckets_random(struct bch_fs *c, struct bch_dev *ca)
728 struct bucket_array *buckets = bucket_array(ca);
729 struct bucket_mark m;
733 checked < ca->mi.nbuckets / 2;
735 size_t b = bch2_rand_range(ca->mi.nbuckets -
736 ca->mi.first_bucket) +
739 m = READ_ONCE(buckets->b[b].mark);
741 if (bch2_can_invalidate_bucket(ca, b, m)) {
742 struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
744 heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
745 if (heap_full(&ca->alloc_heap))
752 sort(ca->alloc_heap.data,
754 sizeof(ca->alloc_heap.data[0]),
755 bucket_idx_cmp, NULL);
757 /* remove duplicates: */
758 for (i = 0; i + 1 < ca->alloc_heap.used; i++)
759 if (ca->alloc_heap.data[i].bucket ==
760 ca->alloc_heap.data[i + 1].bucket)
761 ca->alloc_heap.data[i].nr = 0;
764 static size_t find_reclaimable_buckets(struct bch_fs *c, struct bch_dev *ca)
768 ca->inc_gen_needs_gc = 0;
770 switch (ca->mi.replacement) {
771 case CACHE_REPLACEMENT_LRU:
772 find_reclaimable_buckets_lru(c, ca);
774 case CACHE_REPLACEMENT_FIFO:
775 find_reclaimable_buckets_fifo(c, ca);
777 case CACHE_REPLACEMENT_RANDOM:
778 find_reclaimable_buckets_random(c, ca);
782 heap_resort(&ca->alloc_heap, bucket_alloc_cmp, NULL);
784 for (i = 0; i < ca->alloc_heap.used; i++)
785 nr += ca->alloc_heap.data[i].nr;
790 static inline long next_alloc_bucket(struct bch_dev *ca)
792 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
794 while (ca->alloc_heap.used) {
796 size_t b = top->bucket;
803 heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
810 * returns sequence number of most recent journal entry that updated this
813 static u64 bucket_journal_seq(struct bch_fs *c, struct bucket_mark m)
815 if (m.journal_seq_valid) {
816 u64 journal_seq = atomic64_read(&c->journal.seq);
817 u64 bucket_seq = journal_seq;
819 bucket_seq &= ~((u64) U16_MAX);
820 bucket_seq |= m.journal_seq;
822 if (bucket_seq > journal_seq)
823 bucket_seq -= 1 << 16;
831 static int bch2_invalidate_one_bucket2(struct btree_trans *trans,
833 struct btree_iter *iter,
834 u64 *journal_seq, unsigned flags)
837 __BKEY_PADDED(k, BKEY_ALLOC_VAL_U64s_MAX) alloc_key;
840 __BKEY_PADDED(k, 8) alloc_key;
842 struct bch_fs *c = trans->c;
843 struct bkey_i_alloc *a;
844 struct bkey_alloc_unpacked u;
846 struct bucket_mark m;
848 bool invalidating_cached_data;
852 BUG_ON(!ca->alloc_heap.used ||
853 !ca->alloc_heap.data[0].nr);
854 b = ca->alloc_heap.data[0].bucket;
856 /* first, put on free_inc and mark as owned by allocator: */
857 percpu_down_read(&c->mark_lock);
858 spin_lock(&c->freelist_lock);
860 verify_not_on_freelist(c, ca, b);
862 BUG_ON(!fifo_push(&ca->free_inc, b));
864 bch2_mark_alloc_bucket(c, ca, b, true, gc_pos_alloc(c, NULL), 0);
866 spin_unlock(&c->freelist_lock);
867 percpu_up_read(&c->mark_lock);
869 BUG_ON(BKEY_ALLOC_VAL_U64s_MAX > 8);
871 bch2_btree_iter_set_pos(iter, POS(ca->dev_idx, b));
873 k = bch2_btree_iter_peek_slot(iter);
879 * The allocator has to start before journal replay is finished - thus,
880 * we have to trust the in memory bucket @m, not the version in the
883 percpu_down_read(&c->mark_lock);
885 m = READ_ONCE(g->mark);
886 u = alloc_mem_to_key(g, m);
887 percpu_up_read(&c->mark_lock);
889 invalidating_cached_data = m.cached_sectors != 0;
894 u.cached_sectors = 0;
895 u.read_time = c->bucket_clock[READ].hand;
896 u.write_time = c->bucket_clock[WRITE].hand;
898 a = bkey_alloc_init(&alloc_key.k);
900 bch2_alloc_pack(a, u);
902 bch2_trans_update(trans, iter, &a->k_i,
903 BTREE_TRIGGER_BUCKET_INVALIDATE);
907 * when using deferred btree updates, we have journal reclaim doing
908 * btree updates and thus requiring the allocator to make forward
909 * progress, and here the allocator is requiring space in the journal -
910 * so we need a journal pre-reservation:
912 ret = bch2_trans_commit(trans, NULL,
913 invalidating_cached_data ? journal_seq : NULL,
914 BTREE_INSERT_NOUNLOCK|
915 BTREE_INSERT_NOCHECK_RW|
917 BTREE_INSERT_USE_RESERVE|
918 BTREE_INSERT_USE_ALLOC_RESERVE|
924 /* remove from alloc_heap: */
925 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
931 heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
934 * Make sure we flush the last journal entry that updated this
935 * bucket (i.e. deleting the last reference) before writing to
938 *journal_seq = max(*journal_seq, bucket_journal_seq(c, m));
942 /* remove from free_inc: */
943 percpu_down_read(&c->mark_lock);
944 spin_lock(&c->freelist_lock);
946 bch2_mark_alloc_bucket(c, ca, b, false,
947 gc_pos_alloc(c, NULL), 0);
949 BUG_ON(!fifo_pop_back(&ca->free_inc, b2));
952 spin_unlock(&c->freelist_lock);
953 percpu_up_read(&c->mark_lock);
959 static bool bch2_invalidate_one_bucket(struct bch_fs *c, struct bch_dev *ca,
960 size_t bucket, u64 *flush_seq)
962 struct bucket_mark m;
964 percpu_down_read(&c->mark_lock);
965 spin_lock(&c->freelist_lock);
967 bch2_invalidate_bucket(c, ca, bucket, &m);
969 verify_not_on_freelist(c, ca, bucket);
970 BUG_ON(!fifo_push(&ca->free_inc, bucket));
972 spin_unlock(&c->freelist_lock);
974 bucket_io_clock_reset(c, ca, bucket, READ);
975 bucket_io_clock_reset(c, ca, bucket, WRITE);
977 percpu_up_read(&c->mark_lock);
979 *flush_seq = max(*flush_seq, bucket_journal_seq(c, m));
981 return m.cached_sectors != 0;
985 * Pull buckets off ca->alloc_heap, invalidate them, move them to ca->free_inc:
987 static int bch2_invalidate_buckets(struct bch_fs *c, struct bch_dev *ca)
989 struct btree_trans trans;
990 struct btree_iter *iter;
994 bch2_trans_init(&trans, c, 0, 0);
996 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC,
998 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1000 /* Only use nowait if we've already invalidated at least one bucket: */
1002 !fifo_full(&ca->free_inc) &&
1003 ca->alloc_heap.used)
1004 ret = bch2_invalidate_one_bucket2(&trans, ca, iter, &journal_seq,
1005 BTREE_INSERT_GC_LOCK_HELD|
1006 (!fifo_empty(&ca->free_inc)
1007 ? BTREE_INSERT_NOWAIT : 0));
1009 bch2_trans_exit(&trans);
1011 /* If we used NOWAIT, don't return the error: */
1012 if (!fifo_empty(&ca->free_inc))
1015 bch_err(ca, "error invalidating buckets: %i", ret);
1020 ret = bch2_journal_flush_seq(&c->journal, journal_seq);
1022 bch_err(ca, "journal error: %i", ret);
1029 static int push_invalidated_bucket(struct bch_fs *c, struct bch_dev *ca, size_t bucket)
1035 set_current_state(TASK_INTERRUPTIBLE);
1037 spin_lock(&c->freelist_lock);
1038 for (i = 0; i < RESERVE_NR; i++) {
1041 * Don't strand buckets on the copygc freelist until
1042 * after recovery is finished:
1044 if (!test_bit(BCH_FS_STARTED, &c->flags) &&
1045 i == RESERVE_MOVINGGC)
1048 if (fifo_push(&ca->free[i], bucket)) {
1049 fifo_pop(&ca->free_inc, bucket);
1051 closure_wake_up(&c->freelist_wait);
1052 ca->allocator_state = ALLOCATOR_RUNNING;
1054 spin_unlock(&c->freelist_lock);
1059 if (ca->allocator_state != ALLOCATOR_BLOCKED_FULL) {
1060 ca->allocator_state = ALLOCATOR_BLOCKED_FULL;
1061 closure_wake_up(&c->freelist_wait);
1064 spin_unlock(&c->freelist_lock);
1066 if ((current->flags & PF_KTHREAD) &&
1067 kthread_should_stop()) {
1076 __set_current_state(TASK_RUNNING);
1081 * Pulls buckets off free_inc, discards them (if enabled), then adds them to
1082 * freelists, waiting until there's room if necessary:
1084 static int discard_invalidated_buckets(struct bch_fs *c, struct bch_dev *ca)
1086 while (!fifo_empty(&ca->free_inc)) {
1087 size_t bucket = fifo_peek(&ca->free_inc);
1089 if (ca->mi.discard &&
1090 blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
1091 blkdev_issue_discard(ca->disk_sb.bdev,
1092 bucket_to_sector(ca, bucket),
1093 ca->mi.bucket_size, GFP_NOIO, 0);
1095 if (push_invalidated_bucket(c, ca, bucket))
1103 * bch_allocator_thread - move buckets from free_inc to reserves
1105 * The free_inc FIFO is populated by find_reclaimable_buckets(), and
1106 * the reserves are depleted by bucket allocation. When we run out
1107 * of free_inc, try to invalidate some buckets and write out
1110 static int bch2_allocator_thread(void *arg)
1112 struct bch_dev *ca = arg;
1113 struct bch_fs *c = ca->fs;
1118 ca->allocator_state = ALLOCATOR_RUNNING;
1123 pr_debug("discarding %zu invalidated buckets",
1124 fifo_used(&ca->free_inc));
1126 ret = discard_invalidated_buckets(c, ca);
1130 down_read(&c->gc_lock);
1132 ret = bch2_invalidate_buckets(c, ca);
1134 up_read(&c->gc_lock);
1138 if (!fifo_empty(&ca->free_inc)) {
1139 up_read(&c->gc_lock);
1143 pr_debug("free_inc now empty");
1147 * Find some buckets that we can invalidate, either
1148 * they're completely unused, or only contain clean data
1149 * that's been written back to the backing device or
1150 * another cache tier
1153 pr_debug("scanning for reclaimable buckets");
1155 nr = find_reclaimable_buckets(c, ca);
1157 pr_debug("found %zu buckets", nr);
1159 trace_alloc_batch(ca, nr, ca->alloc_heap.size);
1161 if ((ca->inc_gen_needs_gc >= ALLOC_SCAN_BATCH(ca) ||
1162 ca->inc_gen_really_needs_gc) &&
1164 atomic_inc(&c->kick_gc);
1165 wake_up_process(c->gc_thread);
1169 * If we found any buckets, we have to invalidate them
1170 * before we scan for more - but if we didn't find very
1171 * many we may want to wait on more buckets being
1172 * available so we don't spin:
1175 (nr < ALLOC_SCAN_BATCH(ca) &&
1176 !fifo_empty(&ca->free[RESERVE_NONE]))) {
1177 ret = wait_buckets_available(c, ca);
1179 up_read(&c->gc_lock);
1185 up_read(&c->gc_lock);
1187 pr_debug("%zu buckets to invalidate", nr);
1190 * alloc_heap is now full of newly-invalidated buckets: next,
1191 * write out the new bucket gens:
1196 pr_debug("alloc thread stopping (ret %i)", ret);
1197 ca->allocator_state = ALLOCATOR_STOPPED;
1198 closure_wake_up(&c->freelist_wait);
1202 /* Startup/shutdown (ro/rw): */
1204 void bch2_recalc_capacity(struct bch_fs *c)
1207 u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1208 unsigned bucket_size_max = 0;
1209 unsigned long ra_pages = 0;
1212 lockdep_assert_held(&c->state_lock);
1214 for_each_online_member(ca, c, i) {
1215 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_bdi;
1217 ra_pages += bdi->ra_pages;
1220 bch2_set_ra_pages(c, ra_pages);
1222 for_each_rw_member(ca, c, i) {
1223 u64 dev_reserve = 0;
1226 * We need to reserve buckets (from the number
1227 * of currently available buckets) against
1228 * foreground writes so that mainly copygc can
1229 * make forward progress.
1231 * We need enough to refill the various reserves
1232 * from scratch - copygc will use its entire
1233 * reserve all at once, then run against when
1234 * its reserve is refilled (from the formerly
1235 * available buckets).
1237 * This reserve is just used when considering if
1238 * allocations for foreground writes must wait -
1239 * not -ENOSPC calculations.
1241 for (j = 0; j < RESERVE_NONE; j++)
1242 dev_reserve += ca->free[j].size;
1244 dev_reserve += 1; /* btree write point */
1245 dev_reserve += 1; /* copygc write point */
1246 dev_reserve += 1; /* rebalance write point */
1248 dev_reserve *= ca->mi.bucket_size;
1250 ca->copygc_threshold = dev_reserve;
1252 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1253 ca->mi.first_bucket);
1255 reserved_sectors += dev_reserve * 2;
1257 bucket_size_max = max_t(unsigned, bucket_size_max,
1258 ca->mi.bucket_size);
1261 gc_reserve = c->opts.gc_reserve_bytes
1262 ? c->opts.gc_reserve_bytes >> 9
1263 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1265 reserved_sectors = max(gc_reserve, reserved_sectors);
1267 reserved_sectors = min(reserved_sectors, capacity);
1269 c->capacity = capacity - reserved_sectors;
1271 c->bucket_size_max = bucket_size_max;
1274 bch2_io_timer_add(&c->io_clock[READ],
1275 &c->bucket_clock[READ].rescale);
1276 bch2_io_timer_add(&c->io_clock[WRITE],
1277 &c->bucket_clock[WRITE].rescale);
1279 bch2_io_timer_del(&c->io_clock[READ],
1280 &c->bucket_clock[READ].rescale);
1281 bch2_io_timer_del(&c->io_clock[WRITE],
1282 &c->bucket_clock[WRITE].rescale);
1285 /* Wake up case someone was waiting for buckets */
1286 closure_wake_up(&c->freelist_wait);
1289 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1291 struct open_bucket *ob;
1294 for (ob = c->open_buckets;
1295 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1297 spin_lock(&ob->lock);
1298 if (ob->valid && !ob->on_partial_list &&
1299 ob->ptr.dev == ca->dev_idx)
1301 spin_unlock(&ob->lock);
1307 /* device goes ro: */
1308 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1312 BUG_ON(ca->alloc_thread);
1314 /* First, remove device from allocation groups: */
1316 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1317 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1320 * Capacity is calculated based off of devices in allocation groups:
1322 bch2_recalc_capacity(c);
1324 /* Next, close write points that point to this device... */
1325 for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1326 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1328 bch2_writepoint_stop(c, ca, &ca->copygc_write_point);
1329 bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1330 bch2_writepoint_stop(c, ca, &c->btree_write_point);
1332 mutex_lock(&c->btree_reserve_cache_lock);
1333 while (c->btree_reserve_cache_nr) {
1334 struct btree_alloc *a =
1335 &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1337 bch2_open_buckets_put(c, &a->ob);
1339 mutex_unlock(&c->btree_reserve_cache_lock);
1342 struct open_bucket *ob;
1344 spin_lock(&c->freelist_lock);
1345 if (!ca->open_buckets_partial_nr) {
1346 spin_unlock(&c->freelist_lock);
1349 ob = c->open_buckets +
1350 ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1351 ob->on_partial_list = false;
1352 spin_unlock(&c->freelist_lock);
1354 bch2_open_bucket_put(c, ob);
1357 bch2_ec_stop_dev(c, ca);
1360 * Wake up threads that were blocked on allocation, so they can notice
1361 * the device can no longer be removed and the capacity has changed:
1363 closure_wake_up(&c->freelist_wait);
1366 * journal_res_get() can block waiting for free space in the journal -
1367 * it needs to notice there may not be devices to allocate from anymore:
1369 wake_up(&c->journal.wait);
1371 /* Now wait for any in flight writes: */
1373 closure_wait_event(&c->open_buckets_wait,
1374 !bch2_dev_has_open_write_point(c, ca));
1377 /* device goes rw: */
1378 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1382 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1383 if (ca->mi.data_allowed & (1 << i))
1384 set_bit(ca->dev_idx, c->rw_devs[i].d);
1387 void bch2_dev_allocator_quiesce(struct bch_fs *c, struct bch_dev *ca)
1389 if (ca->alloc_thread)
1390 closure_wait_event(&c->freelist_wait,
1391 ca->allocator_state != ALLOCATOR_RUNNING);
1394 /* stop allocator thread: */
1395 void bch2_dev_allocator_stop(struct bch_dev *ca)
1397 struct task_struct *p;
1399 p = rcu_dereference_protected(ca->alloc_thread, 1);
1400 ca->alloc_thread = NULL;
1403 * We need an rcu barrier between setting ca->alloc_thread = NULL and
1404 * the thread shutting down to avoid bch2_wake_allocator() racing:
1406 * XXX: it would be better to have the rcu barrier be asynchronous
1407 * instead of blocking us here
1417 /* start allocator thread: */
1418 int bch2_dev_allocator_start(struct bch_dev *ca)
1420 struct task_struct *p;
1423 * allocator thread already started?
1425 if (ca->alloc_thread)
1428 p = kthread_create(bch2_allocator_thread, ca,
1429 "bch_alloc[%s]", ca->name);
1434 rcu_assign_pointer(ca->alloc_thread, p);
1439 static bool flush_held_btree_writes(struct bch_fs *c)
1441 struct bucket_table *tbl;
1442 struct rhash_head *pos;
1444 bool nodes_unwritten;
1448 nodes_unwritten = false;
1450 if (bch2_journal_error(&c->journal))
1454 for_each_cached_btree(b, c, tbl, i, pos)
1455 if (btree_node_need_write(b)) {
1456 if (btree_node_may_write(b)) {
1458 btree_node_lock_type(c, b, SIX_LOCK_read);
1459 bch2_btree_node_write(c, b, SIX_LOCK_read);
1460 six_unlock_read(&b->lock);
1463 nodes_unwritten = true;
1468 if (c->btree_roots_dirty) {
1469 bch2_journal_meta(&c->journal);
1473 return !nodes_unwritten &&
1474 !bch2_btree_interior_updates_nr_pending(c);
1477 static void allocator_start_issue_discards(struct bch_fs *c)
1483 for_each_rw_member(ca, c, dev_iter)
1484 while (fifo_pop(&ca->free_inc, bu))
1485 blkdev_issue_discard(ca->disk_sb.bdev,
1486 bucket_to_sector(ca, bu),
1487 ca->mi.bucket_size, GFP_NOIO, 0);
1490 static int resize_free_inc(struct bch_dev *ca)
1492 alloc_fifo free_inc;
1494 if (!fifo_full(&ca->free_inc))
1497 if (!init_fifo(&free_inc,
1498 ca->free_inc.size * 2,
1502 fifo_move(&free_inc, &ca->free_inc);
1503 swap(free_inc, ca->free_inc);
1504 free_fifo(&free_inc);
1508 static bool bch2_fs_allocator_start_fast(struct bch_fs *c)
1514 if (test_alloc_startup(c))
1517 down_read(&c->gc_lock);
1519 /* Scan for buckets that are already invalidated: */
1520 for_each_rw_member(ca, c, dev_iter) {
1521 struct bucket_array *buckets;
1522 struct bucket_mark m;
1525 down_read(&ca->bucket_lock);
1526 buckets = bucket_array(ca);
1528 for (bu = buckets->first_bucket;
1529 bu < buckets->nbuckets; bu++) {
1530 m = READ_ONCE(buckets->b[bu].mark);
1532 if (!buckets->b[bu].gen_valid ||
1533 !is_available_bucket(m) ||
1535 (ca->buckets_nouse &&
1536 test_bit(bu, ca->buckets_nouse)))
1539 percpu_down_read(&c->mark_lock);
1540 bch2_mark_alloc_bucket(c, ca, bu, true,
1541 gc_pos_alloc(c, NULL), 0);
1542 percpu_up_read(&c->mark_lock);
1544 fifo_push(&ca->free_inc, bu);
1546 discard_invalidated_buckets(c, ca);
1548 if (fifo_full(&ca->free[RESERVE_BTREE]))
1551 up_read(&ca->bucket_lock);
1554 up_read(&c->gc_lock);
1556 /* did we find enough buckets? */
1557 for_each_rw_member(ca, c, dev_iter)
1558 if (!fifo_full(&ca->free[RESERVE_BTREE]))
1564 int bch2_fs_allocator_start(struct bch_fs *c)
1568 u64 journal_seq = 0;
1573 if (!test_alloc_startup(c) &&
1574 bch2_fs_allocator_start_fast(c))
1577 pr_debug("not enough empty buckets; scanning for reclaimable buckets");
1580 * We're moving buckets to freelists _before_ they've been marked as
1581 * invalidated on disk - we have to so that we can allocate new btree
1582 * nodes to mark them as invalidated on disk.
1584 * However, we can't _write_ to any of these buckets yet - they might
1585 * have cached data in them, which is live until they're marked as
1586 * invalidated on disk:
1588 set_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1590 down_read(&c->gc_lock);
1594 for_each_rw_member(ca, c, dev_iter) {
1595 find_reclaimable_buckets(c, ca);
1597 while (!fifo_full(&ca->free[RESERVE_BTREE]) &&
1598 (bu = next_alloc_bucket(ca)) >= 0) {
1599 ret = resize_free_inc(ca);
1601 percpu_ref_put(&ca->io_ref);
1602 up_read(&c->gc_lock);
1606 bch2_invalidate_one_bucket(c, ca, bu,
1609 fifo_push(&ca->free[RESERVE_BTREE], bu);
1613 pr_debug("done scanning for reclaimable buckets");
1616 * XXX: it's possible for this to deadlock waiting on journal reclaim,
1617 * since we're holding btree writes. What then?
1619 ret = bch2_alloc_write(c,
1620 BTREE_INSERT_NOCHECK_RW|
1621 BTREE_INSERT_USE_ALLOC_RESERVE|
1622 BTREE_INSERT_NOWAIT, &wrote);
1625 * If bch2_alloc_write() did anything, it may have used some
1626 * buckets, and we need the RESERVE_BTREE freelist full - so we
1627 * need to loop and scan again.
1628 * And if it errored, it may have been because there weren't
1629 * enough buckets, so just scan and loop again as long as it
1630 * made some progress:
1633 up_read(&c->gc_lock);
1638 pr_debug("flushing journal");
1640 ret = bch2_journal_flush(&c->journal);
1644 pr_debug("issuing discards");
1645 allocator_start_issue_discards(c);
1647 clear_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1648 closure_wait_event(&c->btree_interior_update_wait,
1649 flush_held_btree_writes(c));
1654 void bch2_fs_allocator_background_init(struct bch_fs *c)
1656 spin_lock_init(&c->freelist_lock);
1657 bch2_bucket_clock_init(c, READ);
1658 bch2_bucket_clock_init(c, WRITE);
1660 c->pd_controllers_update_seconds = 5;
1661 INIT_DELAYED_WORK(&c->pd_controllers_update, pd_controllers_update);