2 #include "alloc_background.h"
3 #include "alloc_foreground.h"
4 #include "btree_cache.h"
6 #include "btree_update.h"
7 #include "btree_update_interior.h"
14 #include "journal_io.h"
16 #include <linux/kthread.h>
17 #include <linux/math64.h>
18 #include <linux/random.h>
19 #include <linux/rculist.h>
20 #include <linux/rcupdate.h>
21 #include <linux/sched/task.h>
22 #include <linux/sort.h>
23 #include <trace/events/bcachefs.h>
25 static const char * const bch2_alloc_field_names[] = {
26 #define x(name, bytes) #name,
32 static void bch2_recalc_oldest_io(struct bch_fs *, struct bch_dev *, int);
34 /* Ratelimiting/PD controllers */
36 static void pd_controllers_update(struct work_struct *work)
38 struct bch_fs *c = container_of(to_delayed_work(work),
40 pd_controllers_update);
44 for_each_member_device(ca, c, i) {
45 struct bch_dev_usage stats = bch2_dev_usage_read(c, ca);
47 u64 free = bucket_to_sector(ca,
48 __dev_buckets_free(ca, stats)) << 9;
50 * Bytes of internal fragmentation, which can be
51 * reclaimed by copy GC
53 s64 fragmented = (bucket_to_sector(ca,
54 stats.buckets[BCH_DATA_USER] +
55 stats.buckets[BCH_DATA_CACHED]) -
56 (stats.sectors[BCH_DATA_USER] +
57 stats.sectors[BCH_DATA_CACHED])) << 9;
59 fragmented = max(0LL, fragmented);
61 bch2_pd_controller_update(&ca->copygc_pd,
62 free, fragmented, -1);
65 schedule_delayed_work(&c->pd_controllers_update,
66 c->pd_controllers_update_seconds * HZ);
69 /* Persistent alloc info: */
71 static inline u64 get_alloc_field(const struct bch_alloc *a,
72 const void **p, unsigned field)
74 unsigned bytes = BCH_ALLOC_FIELD_BYTES[field];
77 if (!(a->fields & (1 << field)))
82 v = *((const u8 *) *p);
101 static inline void put_alloc_field(struct bkey_i_alloc *a, void **p,
102 unsigned field, u64 v)
104 unsigned bytes = BCH_ALLOC_FIELD_BYTES[field];
109 a->v.fields |= 1 << field;
116 *((__le16 *) *p) = cpu_to_le16(v);
119 *((__le32 *) *p) = cpu_to_le32(v);
122 *((__le64 *) *p) = cpu_to_le64(v);
131 struct bkey_alloc_unpacked bch2_alloc_unpack(const struct bch_alloc *a)
133 struct bkey_alloc_unpacked ret = { .gen = a->gen };
134 const void *d = a->data;
137 #define x(_name, _bits) ret._name = get_alloc_field(a, &d, idx++);
143 static void bch2_alloc_pack(struct bkey_i_alloc *dst,
144 const struct bkey_alloc_unpacked src)
147 void *d = dst->v.data;
150 dst->v.gen = src.gen;
152 #define x(_name, _bits) put_alloc_field(dst, &d, idx++, src._name);
156 set_bkey_val_bytes(&dst->k, (void *) d - (void *) &dst->v);
159 static unsigned bch_alloc_val_u64s(const struct bch_alloc *a)
161 unsigned i, bytes = offsetof(struct bch_alloc, data);
163 for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_FIELD_BYTES); i++)
164 if (a->fields & (1 << i))
165 bytes += BCH_ALLOC_FIELD_BYTES[i];
167 return DIV_ROUND_UP(bytes, sizeof(u64));
170 const char *bch2_alloc_invalid(const struct bch_fs *c, struct bkey_s_c k)
172 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
174 if (k.k->p.inode >= c->sb.nr_devices ||
175 !c->devs[k.k->p.inode])
176 return "invalid device";
178 /* allow for unknown fields */
179 if (bkey_val_u64s(a.k) < bch_alloc_val_u64s(a.v))
180 return "incorrect value size";
185 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
188 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
189 const void *d = a.v->data;
192 pr_buf(out, "gen %u", a.v->gen);
194 for (i = 0; i < BCH_ALLOC_FIELD_NR; i++)
195 if (a.v->fields & (1 << i))
196 pr_buf(out, " %s %llu",
197 bch2_alloc_field_names[i],
198 get_alloc_field(a.v, &d, i));
201 static void __alloc_read_key(struct bucket *g, const struct bch_alloc *a)
203 const void *d = a->data;
204 unsigned idx = 0, data_type, dirty_sectors, cached_sectors;
205 struct bucket_mark m;
207 g->io_time[READ] = get_alloc_field(a, &d, idx++);
208 g->io_time[WRITE] = get_alloc_field(a, &d, idx++);
209 data_type = get_alloc_field(a, &d, idx++);
210 dirty_sectors = get_alloc_field(a, &d, idx++);
211 cached_sectors = get_alloc_field(a, &d, idx++);
212 g->oldest_gen = get_alloc_field(a, &d, idx++);
214 bucket_cmpxchg(g, m, ({
216 m.data_type = data_type;
217 m.dirty_sectors = dirty_sectors;
218 m.cached_sectors = cached_sectors;
224 static void __alloc_write_key(struct bkey_i_alloc *a, struct bucket *g,
225 struct bucket_mark m)
234 put_alloc_field(a, &d, idx++, g->io_time[READ]);
235 put_alloc_field(a, &d, idx++, g->io_time[WRITE]);
236 put_alloc_field(a, &d, idx++, m.data_type);
237 put_alloc_field(a, &d, idx++, m.dirty_sectors);
238 put_alloc_field(a, &d, idx++, m.cached_sectors);
239 put_alloc_field(a, &d, idx++, g->oldest_gen);
241 set_bkey_val_bytes(&a->k, (void *) d - (void *) &a->v);
244 static void bch2_alloc_read_key(struct bch_fs *c, struct bkey_s_c k)
247 struct bkey_s_c_alloc a;
249 if (k.k->type != KEY_TYPE_alloc)
252 a = bkey_s_c_to_alloc(k);
253 ca = bch_dev_bkey_exists(c, a.k->p.inode);
255 if (a.k->p.offset >= ca->mi.nbuckets)
258 percpu_down_read_preempt_disable(&c->mark_lock);
259 __alloc_read_key(bucket(ca, a.k->p.offset), a.v);
260 percpu_up_read_preempt_enable(&c->mark_lock);
263 int bch2_alloc_read(struct bch_fs *c, struct list_head *journal_replay_list)
265 struct journal_replay *r;
266 struct btree_iter iter;
272 for_each_btree_key(&iter, c, BTREE_ID_ALLOC, POS_MIN, 0, k) {
273 bch2_alloc_read_key(c, k);
274 bch2_btree_iter_cond_resched(&iter);
277 ret = bch2_btree_iter_unlock(&iter);
281 list_for_each_entry(r, journal_replay_list, list) {
282 struct bkey_i *k, *n;
283 struct jset_entry *entry;
285 for_each_jset_key(k, n, entry, &r->j)
286 if (entry->btree_id == BTREE_ID_ALLOC)
287 bch2_alloc_read_key(c, bkey_i_to_s_c(k));
290 for_each_member_device(ca, c, i)
291 bch2_dev_usage_from_buckets(c, ca);
293 mutex_lock(&c->bucket_clock[READ].lock);
294 for_each_member_device(ca, c, i) {
295 down_read(&ca->bucket_lock);
296 bch2_recalc_oldest_io(c, ca, READ);
297 up_read(&ca->bucket_lock);
299 mutex_unlock(&c->bucket_clock[READ].lock);
301 mutex_lock(&c->bucket_clock[WRITE].lock);
302 for_each_member_device(ca, c, i) {
303 down_read(&ca->bucket_lock);
304 bch2_recalc_oldest_io(c, ca, WRITE);
305 up_read(&ca->bucket_lock);
307 mutex_unlock(&c->bucket_clock[WRITE].lock);
312 int bch2_alloc_replay_key(struct bch_fs *c, struct bkey_i *k)
314 struct btree_trans trans;
315 struct btree_iter *iter;
319 if (k->k.p.inode >= c->sb.nr_devices ||
320 !c->devs[k->k.p.inode])
323 ca = bch_dev_bkey_exists(c, k->k.p.inode);
325 if (k->k.p.offset >= ca->mi.nbuckets)
328 bch2_trans_init(&trans, c);
330 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC, k->k.p,
333 ret = bch2_btree_iter_traverse(iter);
337 /* check buckets_written with btree node locked: */
338 if (test_bit(k->k.p.offset, ca->buckets_written)) {
343 bch2_trans_update(&trans, BTREE_INSERT_ENTRY(iter, k));
345 ret = bch2_trans_commit(&trans, NULL, NULL,
347 BTREE_INSERT_LAZY_RW|
348 BTREE_INSERT_JOURNAL_REPLAY|
349 BTREE_INSERT_NOMARK);
351 bch2_trans_exit(&trans);
355 static int __bch2_alloc_write_key(struct btree_trans *trans, struct bch_dev *ca,
356 size_t b, struct btree_iter *iter,
357 u64 *journal_seq, unsigned flags)
359 struct bch_fs *c = trans->c;
361 __BKEY_PADDED(k, BKEY_ALLOC_VAL_U64s_MAX) alloc_key;
364 __BKEY_PADDED(k, 8) alloc_key;
366 struct bkey_i_alloc *a = bkey_alloc_init(&alloc_key.k);
368 struct bucket_mark m, new;
371 BUG_ON(BKEY_ALLOC_VAL_U64s_MAX > 8);
373 a->k.p = POS(ca->dev_idx, b);
375 bch2_btree_iter_set_pos(iter, a->k.p);
377 ret = bch2_btree_iter_traverse(iter);
381 percpu_down_read_preempt_disable(&c->mark_lock);
383 m = READ_ONCE(g->mark);
386 percpu_up_read_preempt_enable(&c->mark_lock);
390 __alloc_write_key(a, g, m);
391 percpu_up_read_preempt_enable(&c->mark_lock);
393 bch2_btree_iter_cond_resched(iter);
395 bch2_trans_update(trans, BTREE_INSERT_ENTRY(iter, &a->k_i));
397 ret = bch2_trans_commit(trans, NULL, journal_seq,
398 BTREE_INSERT_NOCHECK_RW|
400 BTREE_INSERT_USE_RESERVE|
401 BTREE_INSERT_USE_ALLOC_RESERVE|
409 atomic64_cmpxchg(&g->_mark.v, m.v.counter, new.v.counter);
411 if (ca->buckets_written)
412 set_bit(b, ca->buckets_written);
417 int bch2_alloc_write(struct bch_fs *c, bool nowait, bool *wrote)
425 for_each_rw_member(ca, c, i) {
426 struct btree_trans trans;
427 struct btree_iter *iter;
428 struct bucket_array *buckets;
431 bch2_trans_init(&trans, c);
433 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC, POS_MIN,
434 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
436 down_read(&ca->bucket_lock);
437 buckets = bucket_array(ca);
439 for (b = buckets->first_bucket;
440 b < buckets->nbuckets;
442 if (!buckets->b[b].mark.dirty)
445 ret = __bch2_alloc_write_key(&trans, ca, b, iter, NULL,
447 ? BTREE_INSERT_NOWAIT
454 up_read(&ca->bucket_lock);
456 bch2_trans_exit(&trans);
459 percpu_ref_put(&ca->io_ref);
467 /* Bucket IO clocks: */
469 static void bch2_recalc_oldest_io(struct bch_fs *c, struct bch_dev *ca, int rw)
471 struct bucket_clock *clock = &c->bucket_clock[rw];
472 struct bucket_array *buckets = bucket_array(ca);
477 lockdep_assert_held(&c->bucket_clock[rw].lock);
479 /* Recalculate max_last_io for this device: */
480 for_each_bucket(g, buckets)
481 max_last_io = max(max_last_io, bucket_last_io(c, g, rw));
483 ca->max_last_bucket_io[rw] = max_last_io;
485 /* Recalculate global max_last_io: */
488 for_each_member_device(ca, c, i)
489 max_last_io = max(max_last_io, ca->max_last_bucket_io[rw]);
491 clock->max_last_io = max_last_io;
494 static void bch2_rescale_bucket_io_times(struct bch_fs *c, int rw)
496 struct bucket_clock *clock = &c->bucket_clock[rw];
497 struct bucket_array *buckets;
502 trace_rescale_prios(c);
504 for_each_member_device(ca, c, i) {
505 down_read(&ca->bucket_lock);
506 buckets = bucket_array(ca);
508 for_each_bucket(g, buckets)
509 g->io_time[rw] = clock->hand -
510 bucket_last_io(c, g, rw) / 2;
512 bch2_recalc_oldest_io(c, ca, rw);
514 up_read(&ca->bucket_lock);
518 static inline u64 bucket_clock_freq(u64 capacity)
520 return max(capacity >> 10, 2028ULL);
523 static void bch2_inc_clock_hand(struct io_timer *timer)
525 struct bucket_clock *clock = container_of(timer,
526 struct bucket_clock, rescale);
527 struct bch_fs *c = container_of(clock,
528 struct bch_fs, bucket_clock[clock->rw]);
533 mutex_lock(&clock->lock);
535 /* if clock cannot be advanced more, rescale prio */
536 if (clock->max_last_io >= U16_MAX - 2)
537 bch2_rescale_bucket_io_times(c, clock->rw);
539 BUG_ON(clock->max_last_io >= U16_MAX - 2);
541 for_each_member_device(ca, c, i)
542 ca->max_last_bucket_io[clock->rw]++;
543 clock->max_last_io++;
546 mutex_unlock(&clock->lock);
548 capacity = READ_ONCE(c->capacity);
554 * we only increment when 0.1% of the filesystem capacity has been read
555 * or written too, this determines if it's time
557 * XXX: we shouldn't really be going off of the capacity of devices in
558 * RW mode (that will be 0 when we're RO, yet we can still service
561 timer->expire += bucket_clock_freq(capacity);
563 bch2_io_timer_add(&c->io_clock[clock->rw], timer);
566 static void bch2_bucket_clock_init(struct bch_fs *c, int rw)
568 struct bucket_clock *clock = &c->bucket_clock[rw];
572 clock->rescale.fn = bch2_inc_clock_hand;
573 clock->rescale.expire = bucket_clock_freq(c->capacity);
574 mutex_init(&clock->lock);
577 /* Background allocator thread: */
580 * Scans for buckets to be invalidated, invalidates them, rewrites prios/gens
581 * (marking them as invalidated on disk), then optionally issues discard
582 * commands to the newly free buckets, then puts them on the various freelists.
585 #define BUCKET_GC_GEN_MAX 96U
588 * wait_buckets_available - wait on reclaimable buckets
590 * If there aren't enough available buckets to fill up free_inc, wait until
593 static int wait_buckets_available(struct bch_fs *c, struct bch_dev *ca)
595 unsigned long gc_count = c->gc_count;
599 set_current_state(TASK_INTERRUPTIBLE);
600 if (kthread_should_stop()) {
605 if (gc_count != c->gc_count)
606 ca->inc_gen_really_needs_gc = 0;
608 if ((ssize_t) (dev_buckets_available(c, ca) -
609 ca->inc_gen_really_needs_gc) >=
610 (ssize_t) fifo_free(&ca->free_inc))
613 up_read(&c->gc_lock);
616 down_read(&c->gc_lock);
619 __set_current_state(TASK_RUNNING);
623 static bool bch2_can_invalidate_bucket(struct bch_dev *ca,
625 struct bucket_mark mark)
629 if (!is_available_bucket(mark))
632 if (ca->buckets_nouse &&
633 test_bit(bucket, ca->buckets_nouse))
636 gc_gen = bucket_gc_gen(ca, bucket);
638 if (gc_gen >= BUCKET_GC_GEN_MAX / 2)
639 ca->inc_gen_needs_gc++;
641 if (gc_gen >= BUCKET_GC_GEN_MAX)
642 ca->inc_gen_really_needs_gc++;
644 return gc_gen < BUCKET_GC_GEN_MAX;
648 * Determines what order we're going to reuse buckets, smallest bucket_key()
652 * - We take into account the read prio of the bucket, which gives us an
653 * indication of how hot the data is -- we scale the prio so that the prio
654 * farthest from the clock is worth 1/8th of the closest.
656 * - The number of sectors of cached data in the bucket, which gives us an
657 * indication of the cost in cache misses this eviction will cause.
659 * - If hotness * sectors used compares equal, we pick the bucket with the
660 * smallest bucket_gc_gen() - since incrementing the same bucket's generation
661 * number repeatedly forces us to run mark and sweep gc to avoid generation
665 static unsigned long bucket_sort_key(struct bch_fs *c, struct bch_dev *ca,
666 size_t b, struct bucket_mark m)
668 unsigned last_io = bucket_last_io(c, bucket(ca, b), READ);
669 unsigned max_last_io = ca->max_last_bucket_io[READ];
672 * Time since last read, scaled to [0, 8) where larger value indicates
673 * more recently read data:
675 unsigned long hotness = (max_last_io - last_io) * 7 / max_last_io;
677 /* How much we want to keep the data in this bucket: */
678 unsigned long data_wantness =
679 (hotness + 1) * bucket_sectors_used(m);
681 unsigned long needs_journal_commit =
682 bucket_needs_journal_commit(m, c->journal.last_seq_ondisk);
684 return (data_wantness << 9) |
685 (needs_journal_commit << 8) |
686 (bucket_gc_gen(ca, b) / 16);
689 static inline int bucket_alloc_cmp(alloc_heap *h,
690 struct alloc_heap_entry l,
691 struct alloc_heap_entry r)
693 return (l.key > r.key) - (l.key < r.key) ?:
694 (l.nr < r.nr) - (l.nr > r.nr) ?:
695 (l.bucket > r.bucket) - (l.bucket < r.bucket);
698 static inline int bucket_idx_cmp(const void *_l, const void *_r)
700 const struct alloc_heap_entry *l = _l, *r = _r;
702 return (l->bucket > r->bucket) - (l->bucket < r->bucket);
705 static void find_reclaimable_buckets_lru(struct bch_fs *c, struct bch_dev *ca)
707 struct bucket_array *buckets;
708 struct alloc_heap_entry e = { 0 };
711 ca->alloc_heap.used = 0;
713 mutex_lock(&c->bucket_clock[READ].lock);
714 down_read(&ca->bucket_lock);
716 buckets = bucket_array(ca);
718 bch2_recalc_oldest_io(c, ca, READ);
721 * Find buckets with lowest read priority, by building a maxheap sorted
722 * by read priority and repeatedly replacing the maximum element until
723 * all buckets have been visited.
725 for (b = ca->mi.first_bucket; b < ca->mi.nbuckets; b++) {
726 struct bucket_mark m = READ_ONCE(buckets->b[b].mark);
727 unsigned long key = bucket_sort_key(c, ca, b, m);
729 if (!bch2_can_invalidate_bucket(ca, b, m))
732 if (e.nr && e.bucket + e.nr == b && e.key == key) {
736 heap_add_or_replace(&ca->alloc_heap, e,
737 -bucket_alloc_cmp, NULL);
739 e = (struct alloc_heap_entry) {
750 heap_add_or_replace(&ca->alloc_heap, e,
751 -bucket_alloc_cmp, NULL);
753 for (i = 0; i < ca->alloc_heap.used; i++)
754 nr += ca->alloc_heap.data[i].nr;
756 while (nr - ca->alloc_heap.data[0].nr >= ALLOC_SCAN_BATCH(ca)) {
757 nr -= ca->alloc_heap.data[0].nr;
758 heap_pop(&ca->alloc_heap, e, -bucket_alloc_cmp, NULL);
761 up_read(&ca->bucket_lock);
762 mutex_unlock(&c->bucket_clock[READ].lock);
765 static void find_reclaimable_buckets_fifo(struct bch_fs *c, struct bch_dev *ca)
767 struct bucket_array *buckets = bucket_array(ca);
768 struct bucket_mark m;
771 if (ca->fifo_last_bucket < ca->mi.first_bucket ||
772 ca->fifo_last_bucket >= ca->mi.nbuckets)
773 ca->fifo_last_bucket = ca->mi.first_bucket;
775 start = ca->fifo_last_bucket;
778 ca->fifo_last_bucket++;
779 if (ca->fifo_last_bucket == ca->mi.nbuckets)
780 ca->fifo_last_bucket = ca->mi.first_bucket;
782 b = ca->fifo_last_bucket;
783 m = READ_ONCE(buckets->b[b].mark);
785 if (bch2_can_invalidate_bucket(ca, b, m)) {
786 struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
788 heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
789 if (heap_full(&ca->alloc_heap))
794 } while (ca->fifo_last_bucket != start);
797 static void find_reclaimable_buckets_random(struct bch_fs *c, struct bch_dev *ca)
799 struct bucket_array *buckets = bucket_array(ca);
800 struct bucket_mark m;
804 checked < ca->mi.nbuckets / 2;
806 size_t b = bch2_rand_range(ca->mi.nbuckets -
807 ca->mi.first_bucket) +
810 m = READ_ONCE(buckets->b[b].mark);
812 if (bch2_can_invalidate_bucket(ca, b, m)) {
813 struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
815 heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
816 if (heap_full(&ca->alloc_heap))
823 sort(ca->alloc_heap.data,
825 sizeof(ca->alloc_heap.data[0]),
826 bucket_idx_cmp, NULL);
828 /* remove duplicates: */
829 for (i = 0; i + 1 < ca->alloc_heap.used; i++)
830 if (ca->alloc_heap.data[i].bucket ==
831 ca->alloc_heap.data[i + 1].bucket)
832 ca->alloc_heap.data[i].nr = 0;
835 static size_t find_reclaimable_buckets(struct bch_fs *c, struct bch_dev *ca)
839 ca->inc_gen_needs_gc = 0;
841 switch (ca->mi.replacement) {
842 case CACHE_REPLACEMENT_LRU:
843 find_reclaimable_buckets_lru(c, ca);
845 case CACHE_REPLACEMENT_FIFO:
846 find_reclaimable_buckets_fifo(c, ca);
848 case CACHE_REPLACEMENT_RANDOM:
849 find_reclaimable_buckets_random(c, ca);
853 heap_resort(&ca->alloc_heap, bucket_alloc_cmp, NULL);
855 for (i = 0; i < ca->alloc_heap.used; i++)
856 nr += ca->alloc_heap.data[i].nr;
861 static inline long next_alloc_bucket(struct bch_dev *ca)
863 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
865 while (ca->alloc_heap.used) {
867 size_t b = top->bucket;
874 heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
881 * returns sequence number of most recent journal entry that updated this
884 static u64 bucket_journal_seq(struct bch_fs *c, struct bucket_mark m)
886 if (m.journal_seq_valid) {
887 u64 journal_seq = atomic64_read(&c->journal.seq);
888 u64 bucket_seq = journal_seq;
890 bucket_seq &= ~((u64) U16_MAX);
891 bucket_seq |= m.journal_seq;
893 if (bucket_seq > journal_seq)
894 bucket_seq -= 1 << 16;
902 static int bch2_invalidate_one_bucket2(struct btree_trans *trans,
904 struct btree_iter *iter,
905 u64 *journal_seq, unsigned flags)
908 __BKEY_PADDED(k, BKEY_ALLOC_VAL_U64s_MAX) alloc_key;
911 __BKEY_PADDED(k, 8) alloc_key;
913 struct bch_fs *c = trans->c;
914 struct bkey_i_alloc *a;
915 struct bkey_alloc_unpacked u;
916 struct bucket_mark m;
918 bool invalidating_cached_data;
922 BUG_ON(!ca->alloc_heap.used ||
923 !ca->alloc_heap.data[0].nr);
924 b = ca->alloc_heap.data[0].bucket;
926 /* first, put on free_inc and mark as owned by allocator: */
927 percpu_down_read_preempt_disable(&c->mark_lock);
928 spin_lock(&c->freelist_lock);
930 verify_not_on_freelist(c, ca, b);
932 BUG_ON(!fifo_push(&ca->free_inc, b));
934 bch2_mark_alloc_bucket(c, ca, b, true, gc_pos_alloc(c, NULL), 0);
935 m = bucket(ca, b)->mark;
937 spin_unlock(&c->freelist_lock);
938 percpu_up_read_preempt_enable(&c->mark_lock);
940 bch2_btree_iter_cond_resched(iter);
942 BUG_ON(BKEY_ALLOC_VAL_U64s_MAX > 8);
944 bch2_btree_iter_set_pos(iter, POS(ca->dev_idx, b));
946 k = bch2_btree_iter_peek_slot(iter);
947 ret = btree_iter_err(k);
951 if (k.k && k.k->type == KEY_TYPE_alloc)
952 u = bch2_alloc_unpack(bkey_s_c_to_alloc(k).v);
954 memset(&u, 0, sizeof(u));
956 invalidating_cached_data = m.cached_sectors != 0;
958 //BUG_ON(u.dirty_sectors);
961 u.cached_sectors = 0;
962 u.read_time = c->bucket_clock[READ].hand;
963 u.write_time = c->bucket_clock[WRITE].hand;
966 * The allocator has to start before journal replay is finished - thus,
967 * we have to trust the in memory bucket @m, not the version in the
972 a = bkey_alloc_init(&alloc_key.k);
974 bch2_alloc_pack(a, u);
976 bch2_trans_update(trans, BTREE_INSERT_ENTRY(iter, &a->k_i));
980 * when using deferred btree updates, we have journal reclaim doing
981 * btree updates and thus requiring the allocator to make forward
982 * progress, and here the allocator is requiring space in the journal -
983 * so we need a journal pre-reservation:
985 ret = bch2_trans_commit(trans, NULL,
986 invalidating_cached_data ? journal_seq : NULL,
988 BTREE_INSERT_NOUNLOCK|
989 BTREE_INSERT_NOCHECK_RW|
991 BTREE_INSERT_USE_RESERVE|
992 BTREE_INSERT_USE_ALLOC_RESERVE|
998 /* remove from alloc_heap: */
999 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
1005 heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
1007 /* with btree still locked: */
1008 if (ca->buckets_written)
1009 set_bit(b, ca->buckets_written);
1012 * Make sure we flush the last journal entry that updated this
1013 * bucket (i.e. deleting the last reference) before writing to
1014 * this bucket again:
1016 *journal_seq = max(*journal_seq, bucket_journal_seq(c, m));
1020 /* remove from free_inc: */
1021 percpu_down_read_preempt_disable(&c->mark_lock);
1022 spin_lock(&c->freelist_lock);
1024 bch2_mark_alloc_bucket(c, ca, b, false,
1025 gc_pos_alloc(c, NULL), 0);
1027 BUG_ON(!fifo_pop_back(&ca->free_inc, b2));
1030 spin_unlock(&c->freelist_lock);
1031 percpu_up_read_preempt_enable(&c->mark_lock);
1037 static bool bch2_invalidate_one_bucket(struct bch_fs *c, struct bch_dev *ca,
1038 size_t bucket, u64 *flush_seq)
1040 struct bucket_mark m;
1042 percpu_down_read_preempt_disable(&c->mark_lock);
1043 spin_lock(&c->freelist_lock);
1045 bch2_invalidate_bucket(c, ca, bucket, &m);
1047 verify_not_on_freelist(c, ca, bucket);
1048 BUG_ON(!fifo_push(&ca->free_inc, bucket));
1050 spin_unlock(&c->freelist_lock);
1052 bucket_io_clock_reset(c, ca, bucket, READ);
1053 bucket_io_clock_reset(c, ca, bucket, WRITE);
1055 percpu_up_read_preempt_enable(&c->mark_lock);
1057 *flush_seq = max(*flush_seq, bucket_journal_seq(c, m));
1059 return m.cached_sectors != 0;
1063 * Pull buckets off ca->alloc_heap, invalidate them, move them to ca->free_inc:
1065 static int bch2_invalidate_buckets(struct bch_fs *c, struct bch_dev *ca)
1067 struct btree_trans trans;
1068 struct btree_iter *iter;
1069 u64 journal_seq = 0;
1072 bch2_trans_init(&trans, c);
1074 iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC,
1075 POS(ca->dev_idx, 0),
1076 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1078 /* Only use nowait if we've already invalidated at least one bucket: */
1080 !fifo_full(&ca->free_inc) &&
1081 ca->alloc_heap.used)
1082 ret = bch2_invalidate_one_bucket2(&trans, ca, iter, &journal_seq,
1083 BTREE_INSERT_GC_LOCK_HELD|
1084 (!fifo_empty(&ca->free_inc)
1085 ? BTREE_INSERT_NOWAIT : 0));
1087 bch2_trans_exit(&trans);
1089 /* If we used NOWAIT, don't return the error: */
1090 if (!fifo_empty(&ca->free_inc))
1093 bch_err(ca, "error invalidating buckets: %i", ret);
1098 ret = bch2_journal_flush_seq(&c->journal, journal_seq);
1100 bch_err(ca, "journal error: %i", ret);
1107 static int push_invalidated_bucket(struct bch_fs *c, struct bch_dev *ca, size_t bucket)
1113 set_current_state(TASK_INTERRUPTIBLE);
1115 spin_lock(&c->freelist_lock);
1116 for (i = 0; i < RESERVE_NR; i++)
1117 if (fifo_push(&ca->free[i], bucket)) {
1118 fifo_pop(&ca->free_inc, bucket);
1120 closure_wake_up(&c->freelist_wait);
1121 ca->allocator_blocked_full = false;
1123 spin_unlock(&c->freelist_lock);
1127 if (!ca->allocator_blocked_full) {
1128 ca->allocator_blocked_full = true;
1129 closure_wake_up(&c->freelist_wait);
1132 spin_unlock(&c->freelist_lock);
1134 if ((current->flags & PF_KTHREAD) &&
1135 kthread_should_stop()) {
1144 __set_current_state(TASK_RUNNING);
1149 * Pulls buckets off free_inc, discards them (if enabled), then adds them to
1150 * freelists, waiting until there's room if necessary:
1152 static int discard_invalidated_buckets(struct bch_fs *c, struct bch_dev *ca)
1154 while (!fifo_empty(&ca->free_inc)) {
1155 size_t bucket = fifo_peek(&ca->free_inc);
1157 if (ca->mi.discard &&
1158 blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
1159 blkdev_issue_discard(ca->disk_sb.bdev,
1160 bucket_to_sector(ca, bucket),
1161 ca->mi.bucket_size, GFP_NOIO, 0);
1163 if (push_invalidated_bucket(c, ca, bucket))
1171 * bch_allocator_thread - move buckets from free_inc to reserves
1173 * The free_inc FIFO is populated by find_reclaimable_buckets(), and
1174 * the reserves are depleted by bucket allocation. When we run out
1175 * of free_inc, try to invalidate some buckets and write out
1178 static int bch2_allocator_thread(void *arg)
1180 struct bch_dev *ca = arg;
1181 struct bch_fs *c = ca->fs;
1190 pr_debug("discarding %zu invalidated buckets",
1191 fifo_used(&ca->free_inc));
1193 ret = discard_invalidated_buckets(c, ca);
1197 down_read(&c->gc_lock);
1199 ret = bch2_invalidate_buckets(c, ca);
1201 up_read(&c->gc_lock);
1205 if (!fifo_empty(&ca->free_inc)) {
1206 up_read(&c->gc_lock);
1210 pr_debug("free_inc now empty");
1214 * Find some buckets that we can invalidate, either
1215 * they're completely unused, or only contain clean data
1216 * that's been written back to the backing device or
1217 * another cache tier
1220 pr_debug("scanning for reclaimable buckets");
1222 nr = find_reclaimable_buckets(c, ca);
1224 pr_debug("found %zu buckets", nr);
1226 trace_alloc_batch(ca, nr, ca->alloc_heap.size);
1228 if ((ca->inc_gen_needs_gc >= ALLOC_SCAN_BATCH(ca) ||
1229 ca->inc_gen_really_needs_gc) &&
1231 atomic_inc(&c->kick_gc);
1232 wake_up_process(c->gc_thread);
1236 * If we found any buckets, we have to invalidate them
1237 * before we scan for more - but if we didn't find very
1238 * many we may want to wait on more buckets being
1239 * available so we don't spin:
1242 (nr < ALLOC_SCAN_BATCH(ca) &&
1243 !fifo_full(&ca->free[RESERVE_MOVINGGC]))) {
1244 ca->allocator_blocked = true;
1245 closure_wake_up(&c->freelist_wait);
1247 ret = wait_buckets_available(c, ca);
1249 up_read(&c->gc_lock);
1255 ca->allocator_blocked = false;
1256 up_read(&c->gc_lock);
1258 pr_debug("%zu buckets to invalidate", nr);
1261 * alloc_heap is now full of newly-invalidated buckets: next,
1262 * write out the new bucket gens:
1267 pr_debug("alloc thread stopping (ret %i)", ret);
1271 /* Startup/shutdown (ro/rw): */
1273 void bch2_recalc_capacity(struct bch_fs *c)
1276 u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1277 unsigned bucket_size_max = 0;
1278 unsigned long ra_pages = 0;
1281 lockdep_assert_held(&c->state_lock);
1283 for_each_online_member(ca, c, i) {
1284 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_bdi;
1286 ra_pages += bdi->ra_pages;
1289 bch2_set_ra_pages(c, ra_pages);
1291 for_each_rw_member(ca, c, i) {
1292 u64 dev_reserve = 0;
1295 * We need to reserve buckets (from the number
1296 * of currently available buckets) against
1297 * foreground writes so that mainly copygc can
1298 * make forward progress.
1300 * We need enough to refill the various reserves
1301 * from scratch - copygc will use its entire
1302 * reserve all at once, then run against when
1303 * its reserve is refilled (from the formerly
1304 * available buckets).
1306 * This reserve is just used when considering if
1307 * allocations for foreground writes must wait -
1308 * not -ENOSPC calculations.
1310 for (j = 0; j < RESERVE_NONE; j++)
1311 dev_reserve += ca->free[j].size;
1313 dev_reserve += 1; /* btree write point */
1314 dev_reserve += 1; /* copygc write point */
1315 dev_reserve += 1; /* rebalance write point */
1317 dev_reserve *= ca->mi.bucket_size;
1319 ca->copygc_threshold = dev_reserve;
1321 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1322 ca->mi.first_bucket);
1324 reserved_sectors += dev_reserve * 2;
1326 bucket_size_max = max_t(unsigned, bucket_size_max,
1327 ca->mi.bucket_size);
1330 gc_reserve = c->opts.gc_reserve_bytes
1331 ? c->opts.gc_reserve_bytes >> 9
1332 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1334 reserved_sectors = max(gc_reserve, reserved_sectors);
1336 reserved_sectors = min(reserved_sectors, capacity);
1338 c->capacity = capacity - reserved_sectors;
1340 c->bucket_size_max = bucket_size_max;
1343 bch2_io_timer_add(&c->io_clock[READ],
1344 &c->bucket_clock[READ].rescale);
1345 bch2_io_timer_add(&c->io_clock[WRITE],
1346 &c->bucket_clock[WRITE].rescale);
1348 bch2_io_timer_del(&c->io_clock[READ],
1349 &c->bucket_clock[READ].rescale);
1350 bch2_io_timer_del(&c->io_clock[WRITE],
1351 &c->bucket_clock[WRITE].rescale);
1354 /* Wake up case someone was waiting for buckets */
1355 closure_wake_up(&c->freelist_wait);
1358 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1360 struct open_bucket *ob;
1363 for (ob = c->open_buckets;
1364 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1366 spin_lock(&ob->lock);
1367 if (ob->valid && !ob->on_partial_list &&
1368 ob->ptr.dev == ca->dev_idx)
1370 spin_unlock(&ob->lock);
1376 /* device goes ro: */
1377 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1381 BUG_ON(ca->alloc_thread);
1383 /* First, remove device from allocation groups: */
1385 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1386 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1389 * Capacity is calculated based off of devices in allocation groups:
1391 bch2_recalc_capacity(c);
1393 /* Next, close write points that point to this device... */
1394 for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1395 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1397 bch2_writepoint_stop(c, ca, &ca->copygc_write_point);
1398 bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1399 bch2_writepoint_stop(c, ca, &c->btree_write_point);
1401 mutex_lock(&c->btree_reserve_cache_lock);
1402 while (c->btree_reserve_cache_nr) {
1403 struct btree_alloc *a =
1404 &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1406 bch2_open_buckets_put(c, &a->ob);
1408 mutex_unlock(&c->btree_reserve_cache_lock);
1411 struct open_bucket *ob;
1413 spin_lock(&c->freelist_lock);
1414 if (!ca->open_buckets_partial_nr) {
1415 spin_unlock(&c->freelist_lock);
1418 ob = c->open_buckets +
1419 ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1420 ob->on_partial_list = false;
1421 spin_unlock(&c->freelist_lock);
1423 bch2_open_bucket_put(c, ob);
1426 bch2_ec_stop_dev(c, ca);
1429 * Wake up threads that were blocked on allocation, so they can notice
1430 * the device can no longer be removed and the capacity has changed:
1432 closure_wake_up(&c->freelist_wait);
1435 * journal_res_get() can block waiting for free space in the journal -
1436 * it needs to notice there may not be devices to allocate from anymore:
1438 wake_up(&c->journal.wait);
1440 /* Now wait for any in flight writes: */
1442 closure_wait_event(&c->open_buckets_wait,
1443 !bch2_dev_has_open_write_point(c, ca));
1446 /* device goes rw: */
1447 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1451 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1452 if (ca->mi.data_allowed & (1 << i))
1453 set_bit(ca->dev_idx, c->rw_devs[i].d);
1456 void bch2_dev_allocator_quiesce(struct bch_fs *c, struct bch_dev *ca)
1458 if (ca->alloc_thread)
1459 closure_wait_event(&c->freelist_wait, ca->allocator_blocked_full);
1462 /* stop allocator thread: */
1463 void bch2_dev_allocator_stop(struct bch_dev *ca)
1465 struct task_struct *p;
1467 p = rcu_dereference_protected(ca->alloc_thread, 1);
1468 ca->alloc_thread = NULL;
1471 * We need an rcu barrier between setting ca->alloc_thread = NULL and
1472 * the thread shutting down to avoid bch2_wake_allocator() racing:
1474 * XXX: it would be better to have the rcu barrier be asynchronous
1475 * instead of blocking us here
1485 /* start allocator thread: */
1486 int bch2_dev_allocator_start(struct bch_dev *ca)
1488 struct task_struct *p;
1491 * allocator thread already started?
1493 if (ca->alloc_thread)
1496 p = kthread_create(bch2_allocator_thread, ca,
1497 "bch_alloc[%s]", ca->name);
1502 rcu_assign_pointer(ca->alloc_thread, p);
1507 static bool flush_held_btree_writes(struct bch_fs *c)
1509 struct bucket_table *tbl;
1510 struct rhash_head *pos;
1512 bool nodes_unwritten;
1516 nodes_unwritten = false;
1519 for_each_cached_btree(b, c, tbl, i, pos)
1520 if (btree_node_need_write(b)) {
1521 if (btree_node_may_write(b)) {
1523 btree_node_lock_type(c, b, SIX_LOCK_read);
1524 bch2_btree_node_write(c, b, SIX_LOCK_read);
1525 six_unlock_read(&b->lock);
1528 nodes_unwritten = true;
1533 if (c->btree_roots_dirty) {
1534 bch2_journal_meta(&c->journal);
1538 return !nodes_unwritten &&
1539 !bch2_btree_interior_updates_nr_pending(c);
1542 static void allocator_start_issue_discards(struct bch_fs *c)
1548 for_each_rw_member(ca, c, dev_iter)
1549 while (fifo_pop(&ca->free_inc, bu))
1550 blkdev_issue_discard(ca->disk_sb.bdev,
1551 bucket_to_sector(ca, bu),
1552 ca->mi.bucket_size, GFP_NOIO, 0);
1555 static int resize_free_inc(struct bch_dev *ca)
1557 alloc_fifo free_inc;
1559 if (!fifo_full(&ca->free_inc))
1562 if (!init_fifo(&free_inc,
1563 ca->free_inc.size * 2,
1567 fifo_move(&free_inc, &ca->free_inc);
1568 swap(free_inc, ca->free_inc);
1569 free_fifo(&free_inc);
1573 static bool bch2_fs_allocator_start_fast(struct bch_fs *c)
1579 if (test_alloc_startup(c))
1582 down_read(&c->gc_lock);
1584 /* Scan for buckets that are already invalidated: */
1585 for_each_rw_member(ca, c, dev_iter) {
1586 struct bucket_array *buckets;
1587 struct bucket_mark m;
1590 down_read(&ca->bucket_lock);
1591 buckets = bucket_array(ca);
1593 for (bu = buckets->first_bucket;
1594 bu < buckets->nbuckets; bu++) {
1595 m = READ_ONCE(buckets->b[bu].mark);
1597 if (!buckets->b[bu].gen_valid ||
1598 !is_available_bucket(m) ||
1600 (ca->buckets_nouse &&
1601 test_bit(bu, ca->buckets_nouse)))
1604 percpu_down_read_preempt_disable(&c->mark_lock);
1605 bch2_mark_alloc_bucket(c, ca, bu, true,
1606 gc_pos_alloc(c, NULL), 0);
1607 percpu_up_read_preempt_enable(&c->mark_lock);
1609 fifo_push(&ca->free_inc, bu);
1611 discard_invalidated_buckets(c, ca);
1613 if (fifo_full(&ca->free[RESERVE_BTREE]))
1616 up_read(&ca->bucket_lock);
1619 up_read(&c->gc_lock);
1621 /* did we find enough buckets? */
1622 for_each_rw_member(ca, c, dev_iter)
1623 if (!fifo_full(&ca->free[RESERVE_BTREE]))
1629 int bch2_fs_allocator_start(struct bch_fs *c)
1633 u64 journal_seq = 0;
1638 if (!test_alloc_startup(c) &&
1639 bch2_fs_allocator_start_fast(c))
1642 pr_debug("not enough empty buckets; scanning for reclaimable buckets");
1645 * We're moving buckets to freelists _before_ they've been marked as
1646 * invalidated on disk - we have to so that we can allocate new btree
1647 * nodes to mark them as invalidated on disk.
1649 * However, we can't _write_ to any of these buckets yet - they might
1650 * have cached data in them, which is live until they're marked as
1651 * invalidated on disk:
1653 set_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1655 down_read(&c->gc_lock);
1659 for_each_rw_member(ca, c, dev_iter) {
1660 find_reclaimable_buckets(c, ca);
1662 while (!fifo_full(&ca->free[RESERVE_BTREE]) &&
1663 (bu = next_alloc_bucket(ca)) >= 0) {
1664 ret = resize_free_inc(ca);
1666 percpu_ref_put(&ca->io_ref);
1667 up_read(&c->gc_lock);
1671 bch2_invalidate_one_bucket(c, ca, bu,
1674 fifo_push(&ca->free[RESERVE_BTREE], bu);
1678 pr_debug("done scanning for reclaimable buckets");
1681 * XXX: it's possible for this to deadlock waiting on journal reclaim,
1682 * since we're holding btree writes. What then?
1684 ret = bch2_alloc_write(c, true, &wrote);
1687 * If bch2_alloc_write() did anything, it may have used some
1688 * buckets, and we need the RESERVE_BTREE freelist full - so we
1689 * need to loop and scan again.
1690 * And if it errored, it may have been because there weren't
1691 * enough buckets, so just scan and loop again as long as it
1692 * made some progress:
1695 up_read(&c->gc_lock);
1700 pr_debug("flushing journal");
1702 ret = bch2_journal_flush(&c->journal);
1706 pr_debug("issuing discards");
1707 allocator_start_issue_discards(c);
1709 clear_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1710 closure_wait_event(&c->btree_interior_update_wait,
1711 flush_held_btree_writes(c));
1716 void bch2_fs_allocator_background_init(struct bch_fs *c)
1718 spin_lock_init(&c->freelist_lock);
1719 bch2_bucket_clock_init(c, READ);
1720 bch2_bucket_clock_init(c, WRITE);
1722 c->pd_controllers_update_seconds = 5;
1723 INIT_DELAYED_WORK(&c->pd_controllers_update, pd_controllers_update);