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;
157 dst->v.gen = src.gen;
159 #define x(_name, _bits) put_alloc_field(dst, &d, idx++, src._name);
163 set_bkey_val_bytes(&dst->k, (void *) d - (void *) &dst->v);
166 static unsigned bch_alloc_val_u64s(const struct bch_alloc *a)
168 unsigned i, bytes = offsetof(struct bch_alloc, data);
170 for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_FIELD_BYTES); i++)
171 if (a->fields & (1 << i))
172 bytes += BCH_ALLOC_FIELD_BYTES[i];
174 return DIV_ROUND_UP(bytes, sizeof(u64));
177 const char *bch2_alloc_invalid(const struct bch_fs *c, struct bkey_s_c k)
179 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
181 if (k.k->p.inode >= c->sb.nr_devices ||
182 !c->devs[k.k->p.inode])
183 return "invalid device";
185 /* allow for unknown fields */
186 if (bkey_val_u64s(a.k) < bch_alloc_val_u64s(a.v))
187 return "incorrect value size";
192 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
195 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
196 const void *d = a.v->data;
199 pr_buf(out, "gen %u", a.v->gen);
201 for (i = 0; i < BCH_ALLOC_FIELD_NR; i++)
202 if (a.v->fields & (1 << i))
203 pr_buf(out, " %s %llu",
204 bch2_alloc_field_names[i],
205 get_alloc_field(a.v, &d, i));
208 int bch2_alloc_read(struct bch_fs *c, struct journal_keys *journal_keys)
210 struct btree_trans trans;
211 struct btree_iter *iter;
214 struct journal_key *j;
218 bch2_trans_init(&trans, c, 0, 0);
220 for_each_btree_key(&trans, iter, BTREE_ID_ALLOC, POS_MIN, 0, k, ret)
221 bch2_mark_key(c, k, 0, 0, NULL, 0,
222 BCH_BUCKET_MARK_ALLOC_READ|
223 BCH_BUCKET_MARK_NOATOMIC);
225 ret = bch2_trans_exit(&trans) ?: ret;
227 bch_err(c, "error reading alloc info: %i", ret);
231 for_each_journal_key(*journal_keys, j)
232 if (j->btree_id == BTREE_ID_ALLOC)
233 bch2_mark_key(c, bkey_i_to_s_c(j->k),
235 BCH_BUCKET_MARK_ALLOC_READ|
236 BCH_BUCKET_MARK_NOATOMIC);
238 percpu_down_write(&c->mark_lock);
239 bch2_dev_usage_from_buckets(c);
240 percpu_up_write(&c->mark_lock);
242 mutex_lock(&c->bucket_clock[READ].lock);
243 for_each_member_device(ca, c, i) {
244 down_read(&ca->bucket_lock);
245 bch2_recalc_oldest_io(c, ca, READ);
246 up_read(&ca->bucket_lock);
248 mutex_unlock(&c->bucket_clock[READ].lock);
250 mutex_lock(&c->bucket_clock[WRITE].lock);
251 for_each_member_device(ca, c, i) {
252 down_read(&ca->bucket_lock);
253 bch2_recalc_oldest_io(c, ca, WRITE);
254 up_read(&ca->bucket_lock);
256 mutex_unlock(&c->bucket_clock[WRITE].lock);
261 enum alloc_write_ret {
267 static int bch2_alloc_write_key(struct btree_trans *trans,
268 struct btree_iter *iter,
271 struct bch_fs *c = trans->c;
274 struct bucket_array *ba;
276 struct bucket_mark m;
277 struct bkey_alloc_unpacked old_u, new_u;
278 __BKEY_PADDED(k, 8) alloc_key; /* hack: */
279 struct bkey_i_alloc *a;
282 k = bch2_btree_iter_peek_slot(iter);
287 old_u = bch2_alloc_unpack(k);
289 if (iter->pos.inode >= c->sb.nr_devices ||
290 !c->devs[iter->pos.inode])
293 percpu_down_read(&c->mark_lock);
294 ca = bch_dev_bkey_exists(c, iter->pos.inode);
295 ba = bucket_array(ca);
297 if (iter->pos.offset >= ba->nbuckets) {
298 percpu_up_read(&c->mark_lock);
302 g = &ba->b[iter->pos.offset];
303 m = READ_ONCE(g->mark);
304 new_u = alloc_mem_to_key(g, m);
305 percpu_up_read(&c->mark_lock);
307 if (!bkey_alloc_unpacked_cmp(old_u, new_u))
308 return ALLOC_NOWROTE;
310 a = bkey_alloc_init(&alloc_key.k);
312 bch2_alloc_pack(a, new_u);
314 bch2_trans_update(trans, BTREE_INSERT_ENTRY(iter, &a->k_i));
315 ret = bch2_trans_commit(trans, NULL, NULL,
326 int bch2_alloc_write(struct bch_fs *c, unsigned flags, bool *wrote)
328 struct btree_trans trans;
329 struct btree_iter *iter;
334 BUG_ON(BKEY_ALLOC_VAL_U64s_MAX > 8);
336 bch2_trans_init(&trans, c, 0, 0);
338 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC, POS_MIN,
339 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
341 for_each_rw_member(ca, c, i) {
342 unsigned first_bucket;
344 percpu_down_read(&c->mark_lock);
345 first_bucket = bucket_array(ca)->first_bucket;
346 percpu_up_read(&c->mark_lock);
348 bch2_btree_iter_set_pos(iter, POS(i, first_bucket));
351 ret = bch2_alloc_write_key(&trans, iter, flags);
352 if (ret < 0 || ret == ALLOC_END)
354 if (ret == ALLOC_WROTE)
356 bch2_btree_iter_next_slot(iter);
360 percpu_ref_put(&ca->io_ref);
365 bch2_trans_exit(&trans);
367 return ret < 0 ? ret : 0;
370 int bch2_alloc_replay_key(struct bch_fs *c, struct bkey_i *k)
372 struct btree_trans trans;
373 struct btree_iter *iter;
376 bch2_trans_init(&trans, c, 0, 0);
378 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC, k->k.p,
379 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
381 ret = bch2_alloc_write_key(&trans, iter,
383 BTREE_INSERT_LAZY_RW|
384 BTREE_INSERT_JOURNAL_REPLAY|
385 BTREE_INSERT_NOMARK);
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, BTREE_INSERT_ENTRY(iter, &a->k_i));
906 * when using deferred btree updates, we have journal reclaim doing
907 * btree updates and thus requiring the allocator to make forward
908 * progress, and here the allocator is requiring space in the journal -
909 * so we need a journal pre-reservation:
911 ret = bch2_trans_commit(trans, NULL,
912 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|
919 BTREE_INSERT_BUCKET_INVALIDATE|
925 /* remove from alloc_heap: */
926 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
932 heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
935 * Make sure we flush the last journal entry that updated this
936 * bucket (i.e. deleting the last reference) before writing to
939 *journal_seq = max(*journal_seq, bucket_journal_seq(c, m));
943 /* remove from free_inc: */
944 percpu_down_read(&c->mark_lock);
945 spin_lock(&c->freelist_lock);
947 bch2_mark_alloc_bucket(c, ca, b, false,
948 gc_pos_alloc(c, NULL), 0);
950 BUG_ON(!fifo_pop_back(&ca->free_inc, b2));
953 spin_unlock(&c->freelist_lock);
954 percpu_up_read(&c->mark_lock);
960 static bool bch2_invalidate_one_bucket(struct bch_fs *c, struct bch_dev *ca,
961 size_t bucket, u64 *flush_seq)
963 struct bucket_mark m;
965 percpu_down_read(&c->mark_lock);
966 spin_lock(&c->freelist_lock);
968 bch2_invalidate_bucket(c, ca, bucket, &m);
970 verify_not_on_freelist(c, ca, bucket);
971 BUG_ON(!fifo_push(&ca->free_inc, bucket));
973 spin_unlock(&c->freelist_lock);
975 bucket_io_clock_reset(c, ca, bucket, READ);
976 bucket_io_clock_reset(c, ca, bucket, WRITE);
978 percpu_up_read(&c->mark_lock);
980 *flush_seq = max(*flush_seq, bucket_journal_seq(c, m));
982 return m.cached_sectors != 0;
986 * Pull buckets off ca->alloc_heap, invalidate them, move them to ca->free_inc:
988 static int bch2_invalidate_buckets(struct bch_fs *c, struct bch_dev *ca)
990 struct btree_trans trans;
991 struct btree_iter *iter;
995 bch2_trans_init(&trans, c, 0, 0);
997 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC,
999 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1001 /* Only use nowait if we've already invalidated at least one bucket: */
1003 !fifo_full(&ca->free_inc) &&
1004 ca->alloc_heap.used)
1005 ret = bch2_invalidate_one_bucket2(&trans, ca, iter, &journal_seq,
1006 BTREE_INSERT_GC_LOCK_HELD|
1007 (!fifo_empty(&ca->free_inc)
1008 ? BTREE_INSERT_NOWAIT : 0));
1010 bch2_trans_exit(&trans);
1012 /* If we used NOWAIT, don't return the error: */
1013 if (!fifo_empty(&ca->free_inc))
1016 bch_err(ca, "error invalidating buckets: %i", ret);
1021 ret = bch2_journal_flush_seq(&c->journal, journal_seq);
1023 bch_err(ca, "journal error: %i", ret);
1030 static int push_invalidated_bucket(struct bch_fs *c, struct bch_dev *ca, size_t bucket)
1036 set_current_state(TASK_INTERRUPTIBLE);
1038 spin_lock(&c->freelist_lock);
1039 for (i = 0; i < RESERVE_NR; i++)
1040 if (fifo_push(&ca->free[i], bucket)) {
1041 fifo_pop(&ca->free_inc, bucket);
1043 closure_wake_up(&c->freelist_wait);
1044 ca->allocator_state = ALLOCATOR_RUNNING;
1046 spin_unlock(&c->freelist_lock);
1050 if (ca->allocator_state != ALLOCATOR_BLOCKED_FULL) {
1051 ca->allocator_state = ALLOCATOR_BLOCKED_FULL;
1052 closure_wake_up(&c->freelist_wait);
1055 spin_unlock(&c->freelist_lock);
1057 if ((current->flags & PF_KTHREAD) &&
1058 kthread_should_stop()) {
1067 __set_current_state(TASK_RUNNING);
1072 * Pulls buckets off free_inc, discards them (if enabled), then adds them to
1073 * freelists, waiting until there's room if necessary:
1075 static int discard_invalidated_buckets(struct bch_fs *c, struct bch_dev *ca)
1077 while (!fifo_empty(&ca->free_inc)) {
1078 size_t bucket = fifo_peek(&ca->free_inc);
1080 if (ca->mi.discard &&
1081 blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
1082 blkdev_issue_discard(ca->disk_sb.bdev,
1083 bucket_to_sector(ca, bucket),
1084 ca->mi.bucket_size, GFP_NOIO, 0);
1086 if (push_invalidated_bucket(c, ca, bucket))
1094 * bch_allocator_thread - move buckets from free_inc to reserves
1096 * The free_inc FIFO is populated by find_reclaimable_buckets(), and
1097 * the reserves are depleted by bucket allocation. When we run out
1098 * of free_inc, try to invalidate some buckets and write out
1101 static int bch2_allocator_thread(void *arg)
1103 struct bch_dev *ca = arg;
1104 struct bch_fs *c = ca->fs;
1109 ca->allocator_state = ALLOCATOR_RUNNING;
1114 pr_debug("discarding %zu invalidated buckets",
1115 fifo_used(&ca->free_inc));
1117 ret = discard_invalidated_buckets(c, ca);
1121 down_read(&c->gc_lock);
1123 ret = bch2_invalidate_buckets(c, ca);
1125 up_read(&c->gc_lock);
1129 if (!fifo_empty(&ca->free_inc)) {
1130 up_read(&c->gc_lock);
1134 pr_debug("free_inc now empty");
1138 * Find some buckets that we can invalidate, either
1139 * they're completely unused, or only contain clean data
1140 * that's been written back to the backing device or
1141 * another cache tier
1144 pr_debug("scanning for reclaimable buckets");
1146 nr = find_reclaimable_buckets(c, ca);
1148 pr_debug("found %zu buckets", nr);
1150 trace_alloc_batch(ca, nr, ca->alloc_heap.size);
1152 if ((ca->inc_gen_needs_gc >= ALLOC_SCAN_BATCH(ca) ||
1153 ca->inc_gen_really_needs_gc) &&
1155 atomic_inc(&c->kick_gc);
1156 wake_up_process(c->gc_thread);
1160 * If we found any buckets, we have to invalidate them
1161 * before we scan for more - but if we didn't find very
1162 * many we may want to wait on more buckets being
1163 * available so we don't spin:
1166 (nr < ALLOC_SCAN_BATCH(ca) &&
1167 !fifo_full(&ca->free[RESERVE_MOVINGGC]))) {
1168 ret = wait_buckets_available(c, ca);
1170 up_read(&c->gc_lock);
1176 up_read(&c->gc_lock);
1178 pr_debug("%zu buckets to invalidate", nr);
1181 * alloc_heap is now full of newly-invalidated buckets: next,
1182 * write out the new bucket gens:
1187 pr_debug("alloc thread stopping (ret %i)", ret);
1188 ca->allocator_state = ALLOCATOR_STOPPED;
1189 closure_wake_up(&c->freelist_wait);
1193 /* Startup/shutdown (ro/rw): */
1195 void bch2_recalc_capacity(struct bch_fs *c)
1198 u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1199 unsigned bucket_size_max = 0;
1200 unsigned long ra_pages = 0;
1203 lockdep_assert_held(&c->state_lock);
1205 for_each_online_member(ca, c, i) {
1206 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_bdi;
1208 ra_pages += bdi->ra_pages;
1211 bch2_set_ra_pages(c, ra_pages);
1213 for_each_rw_member(ca, c, i) {
1214 u64 dev_reserve = 0;
1217 * We need to reserve buckets (from the number
1218 * of currently available buckets) against
1219 * foreground writes so that mainly copygc can
1220 * make forward progress.
1222 * We need enough to refill the various reserves
1223 * from scratch - copygc will use its entire
1224 * reserve all at once, then run against when
1225 * its reserve is refilled (from the formerly
1226 * available buckets).
1228 * This reserve is just used when considering if
1229 * allocations for foreground writes must wait -
1230 * not -ENOSPC calculations.
1232 for (j = 0; j < RESERVE_NONE; j++)
1233 dev_reserve += ca->free[j].size;
1235 dev_reserve += 1; /* btree write point */
1236 dev_reserve += 1; /* copygc write point */
1237 dev_reserve += 1; /* rebalance write point */
1239 dev_reserve *= ca->mi.bucket_size;
1241 ca->copygc_threshold = dev_reserve;
1243 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1244 ca->mi.first_bucket);
1246 reserved_sectors += dev_reserve * 2;
1248 bucket_size_max = max_t(unsigned, bucket_size_max,
1249 ca->mi.bucket_size);
1252 gc_reserve = c->opts.gc_reserve_bytes
1253 ? c->opts.gc_reserve_bytes >> 9
1254 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1256 reserved_sectors = max(gc_reserve, reserved_sectors);
1258 reserved_sectors = min(reserved_sectors, capacity);
1260 c->capacity = capacity - reserved_sectors;
1262 c->bucket_size_max = bucket_size_max;
1265 bch2_io_timer_add(&c->io_clock[READ],
1266 &c->bucket_clock[READ].rescale);
1267 bch2_io_timer_add(&c->io_clock[WRITE],
1268 &c->bucket_clock[WRITE].rescale);
1270 bch2_io_timer_del(&c->io_clock[READ],
1271 &c->bucket_clock[READ].rescale);
1272 bch2_io_timer_del(&c->io_clock[WRITE],
1273 &c->bucket_clock[WRITE].rescale);
1276 /* Wake up case someone was waiting for buckets */
1277 closure_wake_up(&c->freelist_wait);
1280 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1282 struct open_bucket *ob;
1285 for (ob = c->open_buckets;
1286 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1288 spin_lock(&ob->lock);
1289 if (ob->valid && !ob->on_partial_list &&
1290 ob->ptr.dev == ca->dev_idx)
1292 spin_unlock(&ob->lock);
1298 /* device goes ro: */
1299 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1303 BUG_ON(ca->alloc_thread);
1305 /* First, remove device from allocation groups: */
1307 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1308 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1311 * Capacity is calculated based off of devices in allocation groups:
1313 bch2_recalc_capacity(c);
1315 /* Next, close write points that point to this device... */
1316 for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1317 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1319 bch2_writepoint_stop(c, ca, &ca->copygc_write_point);
1320 bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1321 bch2_writepoint_stop(c, ca, &c->btree_write_point);
1323 mutex_lock(&c->btree_reserve_cache_lock);
1324 while (c->btree_reserve_cache_nr) {
1325 struct btree_alloc *a =
1326 &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1328 bch2_open_buckets_put(c, &a->ob);
1330 mutex_unlock(&c->btree_reserve_cache_lock);
1333 struct open_bucket *ob;
1335 spin_lock(&c->freelist_lock);
1336 if (!ca->open_buckets_partial_nr) {
1337 spin_unlock(&c->freelist_lock);
1340 ob = c->open_buckets +
1341 ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1342 ob->on_partial_list = false;
1343 spin_unlock(&c->freelist_lock);
1345 bch2_open_bucket_put(c, ob);
1348 bch2_ec_stop_dev(c, ca);
1351 * Wake up threads that were blocked on allocation, so they can notice
1352 * the device can no longer be removed and the capacity has changed:
1354 closure_wake_up(&c->freelist_wait);
1357 * journal_res_get() can block waiting for free space in the journal -
1358 * it needs to notice there may not be devices to allocate from anymore:
1360 wake_up(&c->journal.wait);
1362 /* Now wait for any in flight writes: */
1364 closure_wait_event(&c->open_buckets_wait,
1365 !bch2_dev_has_open_write_point(c, ca));
1368 /* device goes rw: */
1369 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1373 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1374 if (ca->mi.data_allowed & (1 << i))
1375 set_bit(ca->dev_idx, c->rw_devs[i].d);
1378 void bch2_dev_allocator_quiesce(struct bch_fs *c, struct bch_dev *ca)
1380 if (ca->alloc_thread)
1381 closure_wait_event(&c->freelist_wait,
1382 ca->allocator_state != ALLOCATOR_RUNNING);
1385 /* stop allocator thread: */
1386 void bch2_dev_allocator_stop(struct bch_dev *ca)
1388 struct task_struct *p;
1390 p = rcu_dereference_protected(ca->alloc_thread, 1);
1391 ca->alloc_thread = NULL;
1394 * We need an rcu barrier between setting ca->alloc_thread = NULL and
1395 * the thread shutting down to avoid bch2_wake_allocator() racing:
1397 * XXX: it would be better to have the rcu barrier be asynchronous
1398 * instead of blocking us here
1408 /* start allocator thread: */
1409 int bch2_dev_allocator_start(struct bch_dev *ca)
1411 struct task_struct *p;
1414 * allocator thread already started?
1416 if (ca->alloc_thread)
1419 p = kthread_create(bch2_allocator_thread, ca,
1420 "bch_alloc[%s]", ca->name);
1425 rcu_assign_pointer(ca->alloc_thread, p);
1430 static bool flush_held_btree_writes(struct bch_fs *c)
1432 struct bucket_table *tbl;
1433 struct rhash_head *pos;
1435 bool nodes_unwritten;
1439 nodes_unwritten = false;
1442 for_each_cached_btree(b, c, tbl, i, pos)
1443 if (btree_node_need_write(b)) {
1444 if (btree_node_may_write(b)) {
1446 btree_node_lock_type(c, b, SIX_LOCK_read);
1447 bch2_btree_node_write(c, b, SIX_LOCK_read);
1448 six_unlock_read(&b->lock);
1451 nodes_unwritten = true;
1456 if (c->btree_roots_dirty) {
1457 bch2_journal_meta(&c->journal);
1461 return !nodes_unwritten &&
1462 !bch2_btree_interior_updates_nr_pending(c);
1465 static void allocator_start_issue_discards(struct bch_fs *c)
1471 for_each_rw_member(ca, c, dev_iter)
1472 while (fifo_pop(&ca->free_inc, bu))
1473 blkdev_issue_discard(ca->disk_sb.bdev,
1474 bucket_to_sector(ca, bu),
1475 ca->mi.bucket_size, GFP_NOIO, 0);
1478 static int resize_free_inc(struct bch_dev *ca)
1480 alloc_fifo free_inc;
1482 if (!fifo_full(&ca->free_inc))
1485 if (!init_fifo(&free_inc,
1486 ca->free_inc.size * 2,
1490 fifo_move(&free_inc, &ca->free_inc);
1491 swap(free_inc, ca->free_inc);
1492 free_fifo(&free_inc);
1496 static bool bch2_fs_allocator_start_fast(struct bch_fs *c)
1502 if (test_alloc_startup(c))
1505 down_read(&c->gc_lock);
1507 /* Scan for buckets that are already invalidated: */
1508 for_each_rw_member(ca, c, dev_iter) {
1509 struct bucket_array *buckets;
1510 struct bucket_mark m;
1513 down_read(&ca->bucket_lock);
1514 buckets = bucket_array(ca);
1516 for (bu = buckets->first_bucket;
1517 bu < buckets->nbuckets; bu++) {
1518 m = READ_ONCE(buckets->b[bu].mark);
1520 if (!buckets->b[bu].gen_valid ||
1521 !is_available_bucket(m) ||
1523 (ca->buckets_nouse &&
1524 test_bit(bu, ca->buckets_nouse)))
1527 percpu_down_read(&c->mark_lock);
1528 bch2_mark_alloc_bucket(c, ca, bu, true,
1529 gc_pos_alloc(c, NULL), 0);
1530 percpu_up_read(&c->mark_lock);
1532 fifo_push(&ca->free_inc, bu);
1534 discard_invalidated_buckets(c, ca);
1536 if (fifo_full(&ca->free[RESERVE_BTREE]))
1539 up_read(&ca->bucket_lock);
1542 up_read(&c->gc_lock);
1544 /* did we find enough buckets? */
1545 for_each_rw_member(ca, c, dev_iter)
1546 if (!fifo_full(&ca->free[RESERVE_BTREE]))
1552 int bch2_fs_allocator_start(struct bch_fs *c)
1556 u64 journal_seq = 0;
1561 if (!test_alloc_startup(c) &&
1562 bch2_fs_allocator_start_fast(c))
1565 pr_debug("not enough empty buckets; scanning for reclaimable buckets");
1568 * We're moving buckets to freelists _before_ they've been marked as
1569 * invalidated on disk - we have to so that we can allocate new btree
1570 * nodes to mark them as invalidated on disk.
1572 * However, we can't _write_ to any of these buckets yet - they might
1573 * have cached data in them, which is live until they're marked as
1574 * invalidated on disk:
1576 set_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1578 down_read(&c->gc_lock);
1582 for_each_rw_member(ca, c, dev_iter) {
1583 find_reclaimable_buckets(c, ca);
1585 while (!fifo_full(&ca->free[RESERVE_BTREE]) &&
1586 (bu = next_alloc_bucket(ca)) >= 0) {
1587 ret = resize_free_inc(ca);
1589 percpu_ref_put(&ca->io_ref);
1590 up_read(&c->gc_lock);
1594 bch2_invalidate_one_bucket(c, ca, bu,
1597 fifo_push(&ca->free[RESERVE_BTREE], bu);
1601 pr_debug("done scanning for reclaimable buckets");
1604 * XXX: it's possible for this to deadlock waiting on journal reclaim,
1605 * since we're holding btree writes. What then?
1607 ret = bch2_alloc_write(c,
1608 BTREE_INSERT_NOCHECK_RW|
1609 BTREE_INSERT_USE_ALLOC_RESERVE|
1610 BTREE_INSERT_NOWAIT, &wrote);
1613 * If bch2_alloc_write() did anything, it may have used some
1614 * buckets, and we need the RESERVE_BTREE freelist full - so we
1615 * need to loop and scan again.
1616 * And if it errored, it may have been because there weren't
1617 * enough buckets, so just scan and loop again as long as it
1618 * made some progress:
1621 up_read(&c->gc_lock);
1626 pr_debug("flushing journal");
1628 ret = bch2_journal_flush(&c->journal);
1632 pr_debug("issuing discards");
1633 allocator_start_issue_discards(c);
1635 clear_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1636 closure_wait_event(&c->btree_interior_update_wait,
1637 flush_held_btree_writes(c));
1642 void bch2_fs_allocator_background_init(struct bch_fs *c)
1644 spin_lock_init(&c->freelist_lock);
1645 bch2_bucket_clock_init(c, READ);
1646 bch2_bucket_clock_init(c, WRITE);
1648 c->pd_controllers_update_seconds = 5;
1649 INIT_DELAYED_WORK(&c->pd_controllers_update, pd_controllers_update);