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 static unsigned bch_alloc_val_u64s(const struct bch_alloc *a)
133 unsigned i, bytes = offsetof(struct bch_alloc, data);
135 for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_FIELD_BYTES); i++)
136 if (a->fields & (1 << i))
137 bytes += BCH_ALLOC_FIELD_BYTES[i];
139 return DIV_ROUND_UP(bytes, sizeof(u64));
142 const char *bch2_alloc_invalid(const struct bch_fs *c, struct bkey_s_c k)
144 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
146 if (k.k->p.inode >= c->sb.nr_devices ||
147 !c->devs[k.k->p.inode])
148 return "invalid device";
150 /* allow for unknown fields */
151 if (bkey_val_u64s(a.k) < bch_alloc_val_u64s(a.v))
152 return "incorrect value size";
157 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
160 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
161 const void *d = a.v->data;
164 pr_buf(out, "gen %u", a.v->gen);
166 for (i = 0; i < BCH_ALLOC_FIELD_NR; i++)
167 if (a.v->fields & (1 << i))
168 pr_buf(out, " %s %llu",
169 bch2_alloc_field_names[i],
170 get_alloc_field(a.v, &d, i));
173 static void __alloc_read_key(struct bucket *g, const struct bch_alloc *a)
175 const void *d = a->data;
178 g->_mark.gen = a->gen;
180 g->io_time[READ] = get_alloc_field(a, &d, idx++);
181 g->io_time[WRITE] = get_alloc_field(a, &d, idx++);
182 g->_mark.data_type = get_alloc_field(a, &d, idx++);
183 g->_mark.dirty_sectors = get_alloc_field(a, &d, idx++);
184 g->_mark.cached_sectors = get_alloc_field(a, &d, idx++);
187 static void __alloc_write_key(struct bkey_i_alloc *a, struct bucket *g,
188 struct bucket_mark m)
197 put_alloc_field(a, &d, idx++, g->io_time[READ]);
198 put_alloc_field(a, &d, idx++, g->io_time[WRITE]);
199 put_alloc_field(a, &d, idx++, m.data_type);
200 put_alloc_field(a, &d, idx++, m.dirty_sectors);
201 put_alloc_field(a, &d, idx++, m.cached_sectors);
203 set_bkey_val_bytes(&a->k, (void *) d - (void *) &a->v);
206 static void bch2_alloc_read_key(struct bch_fs *c, struct bkey_s_c k)
209 struct bkey_s_c_alloc a;
211 if (k.k->type != KEY_TYPE_alloc)
214 a = bkey_s_c_to_alloc(k);
215 ca = bch_dev_bkey_exists(c, a.k->p.inode);
217 if (a.k->p.offset >= ca->mi.nbuckets)
220 percpu_down_read_preempt_disable(&c->mark_lock);
221 __alloc_read_key(bucket(ca, a.k->p.offset), a.v);
222 percpu_up_read_preempt_enable(&c->mark_lock);
225 int bch2_alloc_read(struct bch_fs *c, struct list_head *journal_replay_list)
227 struct journal_replay *r;
228 struct btree_iter iter;
234 for_each_btree_key(&iter, c, BTREE_ID_ALLOC, POS_MIN, 0, k) {
235 bch2_alloc_read_key(c, k);
236 bch2_btree_iter_cond_resched(&iter);
239 ret = bch2_btree_iter_unlock(&iter);
243 list_for_each_entry(r, journal_replay_list, list) {
244 struct bkey_i *k, *n;
245 struct jset_entry *entry;
247 for_each_jset_key(k, n, entry, &r->j)
248 if (entry->btree_id == BTREE_ID_ALLOC)
249 bch2_alloc_read_key(c, bkey_i_to_s_c(k));
252 mutex_lock(&c->bucket_clock[READ].lock);
253 for_each_member_device(ca, c, i) {
254 down_read(&ca->bucket_lock);
255 bch2_recalc_oldest_io(c, ca, READ);
256 up_read(&ca->bucket_lock);
258 mutex_unlock(&c->bucket_clock[READ].lock);
260 mutex_lock(&c->bucket_clock[WRITE].lock);
261 for_each_member_device(ca, c, i) {
262 down_read(&ca->bucket_lock);
263 bch2_recalc_oldest_io(c, ca, WRITE);
264 up_read(&ca->bucket_lock);
266 mutex_unlock(&c->bucket_clock[WRITE].lock);
271 static int __bch2_alloc_write_key(struct bch_fs *c, struct bch_dev *ca,
272 size_t b, struct btree_iter *iter,
273 u64 *journal_seq, unsigned flags)
276 __BKEY_PADDED(k, BKEY_ALLOC_VAL_U64s_MAX) alloc_key;
279 __BKEY_PADDED(k, 8) alloc_key;
281 struct bkey_i_alloc *a = bkey_alloc_init(&alloc_key.k);
283 struct bucket_mark m;
286 BUG_ON(BKEY_ALLOC_VAL_U64s_MAX > 8);
288 a->k.p = POS(ca->dev_idx, b);
290 percpu_down_read_preempt_disable(&c->mark_lock);
292 m = bucket_cmpxchg(g, m, m.dirty = false);
294 __alloc_write_key(a, g, m);
295 percpu_up_read_preempt_enable(&c->mark_lock);
297 bch2_btree_iter_cond_resched(iter);
299 bch2_btree_iter_set_pos(iter, a->k.p);
301 ret = bch2_btree_insert_at(c, NULL, journal_seq,
303 BTREE_INSERT_USE_RESERVE|
304 BTREE_INSERT_USE_ALLOC_RESERVE|
306 BTREE_INSERT_ENTRY(iter, &a->k_i));
308 if (!ret && ca->buckets_written)
309 set_bit(b, ca->buckets_written);
314 int bch2_alloc_replay_key(struct bch_fs *c, struct bkey_i *k)
317 struct btree_iter iter;
320 if (k->k.p.inode >= c->sb.nr_devices ||
321 !c->devs[k->k.p.inode])
324 ca = bch_dev_bkey_exists(c, k->k.p.inode);
326 if (k->k.p.offset >= ca->mi.nbuckets)
329 bch2_btree_iter_init(&iter, c, BTREE_ID_ALLOC, k->k.p,
332 ret = bch2_btree_iter_traverse(&iter);
336 /* check buckets_written with btree node locked: */
338 ret = test_bit(k->k.p.offset, ca->buckets_written)
340 : bch2_btree_insert_at(c, NULL, NULL,
342 BTREE_INSERT_JOURNAL_REPLAY,
343 BTREE_INSERT_ENTRY(&iter, k));
345 bch2_btree_iter_unlock(&iter);
349 int bch2_alloc_write(struct bch_fs *c, bool nowait, bool *wrote)
357 for_each_rw_member(ca, c, i) {
358 struct btree_iter iter;
359 struct bucket_array *buckets;
362 bch2_btree_iter_init(&iter, c, BTREE_ID_ALLOC, POS_MIN,
363 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
365 down_read(&ca->bucket_lock);
366 buckets = bucket_array(ca);
368 for (b = buckets->first_bucket;
369 b < buckets->nbuckets;
371 if (!buckets->b[b].mark.dirty)
374 ret = __bch2_alloc_write_key(c, ca, b, &iter, NULL,
376 ? BTREE_INSERT_NOWAIT
383 up_read(&ca->bucket_lock);
384 bch2_btree_iter_unlock(&iter);
387 percpu_ref_put(&ca->io_ref);
395 /* Bucket IO clocks: */
397 static void bch2_recalc_oldest_io(struct bch_fs *c, struct bch_dev *ca, int rw)
399 struct bucket_clock *clock = &c->bucket_clock[rw];
400 struct bucket_array *buckets = bucket_array(ca);
405 lockdep_assert_held(&c->bucket_clock[rw].lock);
407 /* Recalculate max_last_io for this device: */
408 for_each_bucket(g, buckets)
409 max_last_io = max(max_last_io, bucket_last_io(c, g, rw));
411 ca->max_last_bucket_io[rw] = max_last_io;
413 /* Recalculate global max_last_io: */
416 for_each_member_device(ca, c, i)
417 max_last_io = max(max_last_io, ca->max_last_bucket_io[rw]);
419 clock->max_last_io = max_last_io;
422 static void bch2_rescale_bucket_io_times(struct bch_fs *c, int rw)
424 struct bucket_clock *clock = &c->bucket_clock[rw];
425 struct bucket_array *buckets;
430 trace_rescale_prios(c);
432 for_each_member_device(ca, c, i) {
433 down_read(&ca->bucket_lock);
434 buckets = bucket_array(ca);
436 for_each_bucket(g, buckets)
437 g->io_time[rw] = clock->hand -
438 bucket_last_io(c, g, rw) / 2;
440 bch2_recalc_oldest_io(c, ca, rw);
442 up_read(&ca->bucket_lock);
446 static inline u64 bucket_clock_freq(u64 capacity)
448 return max(capacity >> 10, 2028ULL);
451 static void bch2_inc_clock_hand(struct io_timer *timer)
453 struct bucket_clock *clock = container_of(timer,
454 struct bucket_clock, rescale);
455 struct bch_fs *c = container_of(clock,
456 struct bch_fs, bucket_clock[clock->rw]);
461 mutex_lock(&clock->lock);
463 /* if clock cannot be advanced more, rescale prio */
464 if (clock->max_last_io >= U16_MAX - 2)
465 bch2_rescale_bucket_io_times(c, clock->rw);
467 BUG_ON(clock->max_last_io >= U16_MAX - 2);
469 for_each_member_device(ca, c, i)
470 ca->max_last_bucket_io[clock->rw]++;
471 clock->max_last_io++;
474 mutex_unlock(&clock->lock);
476 capacity = READ_ONCE(c->capacity);
482 * we only increment when 0.1% of the filesystem capacity has been read
483 * or written too, this determines if it's time
485 * XXX: we shouldn't really be going off of the capacity of devices in
486 * RW mode (that will be 0 when we're RO, yet we can still service
489 timer->expire += bucket_clock_freq(capacity);
491 bch2_io_timer_add(&c->io_clock[clock->rw], timer);
494 static void bch2_bucket_clock_init(struct bch_fs *c, int rw)
496 struct bucket_clock *clock = &c->bucket_clock[rw];
500 clock->rescale.fn = bch2_inc_clock_hand;
501 clock->rescale.expire = bucket_clock_freq(c->capacity);
502 mutex_init(&clock->lock);
505 /* Background allocator thread: */
508 * Scans for buckets to be invalidated, invalidates them, rewrites prios/gens
509 * (marking them as invalidated on disk), then optionally issues discard
510 * commands to the newly free buckets, then puts them on the various freelists.
513 #define BUCKET_GC_GEN_MAX 96U
516 * wait_buckets_available - wait on reclaimable buckets
518 * If there aren't enough available buckets to fill up free_inc, wait until
521 static int wait_buckets_available(struct bch_fs *c, struct bch_dev *ca)
523 unsigned long gc_count = c->gc_count;
527 set_current_state(TASK_INTERRUPTIBLE);
528 if (kthread_should_stop()) {
533 if (gc_count != c->gc_count)
534 ca->inc_gen_really_needs_gc = 0;
536 if ((ssize_t) (dev_buckets_available(c, ca) -
537 ca->inc_gen_really_needs_gc) >=
538 (ssize_t) fifo_free(&ca->free_inc))
541 up_read(&c->gc_lock);
544 down_read(&c->gc_lock);
547 __set_current_state(TASK_RUNNING);
551 static bool bch2_can_invalidate_bucket(struct bch_dev *ca,
553 struct bucket_mark mark)
557 if (!is_available_bucket(mark))
560 if (ca->buckets_nouse &&
561 test_bit(bucket, ca->buckets_nouse))
564 gc_gen = bucket_gc_gen(ca, bucket);
566 if (gc_gen >= BUCKET_GC_GEN_MAX / 2)
567 ca->inc_gen_needs_gc++;
569 if (gc_gen >= BUCKET_GC_GEN_MAX)
570 ca->inc_gen_really_needs_gc++;
572 return gc_gen < BUCKET_GC_GEN_MAX;
576 * Determines what order we're going to reuse buckets, smallest bucket_key()
580 * - We take into account the read prio of the bucket, which gives us an
581 * indication of how hot the data is -- we scale the prio so that the prio
582 * farthest from the clock is worth 1/8th of the closest.
584 * - The number of sectors of cached data in the bucket, which gives us an
585 * indication of the cost in cache misses this eviction will cause.
587 * - If hotness * sectors used compares equal, we pick the bucket with the
588 * smallest bucket_gc_gen() - since incrementing the same bucket's generation
589 * number repeatedly forces us to run mark and sweep gc to avoid generation
593 static unsigned long bucket_sort_key(struct bch_fs *c, struct bch_dev *ca,
594 size_t b, struct bucket_mark m)
596 unsigned last_io = bucket_last_io(c, bucket(ca, b), READ);
597 unsigned max_last_io = ca->max_last_bucket_io[READ];
600 * Time since last read, scaled to [0, 8) where larger value indicates
601 * more recently read data:
603 unsigned long hotness = (max_last_io - last_io) * 7 / max_last_io;
605 /* How much we want to keep the data in this bucket: */
606 unsigned long data_wantness =
607 (hotness + 1) * bucket_sectors_used(m);
609 unsigned long needs_journal_commit =
610 bucket_needs_journal_commit(m, c->journal.last_seq_ondisk);
612 return (data_wantness << 9) |
613 (needs_journal_commit << 8) |
614 (bucket_gc_gen(ca, b) / 16);
617 static inline int bucket_alloc_cmp(alloc_heap *h,
618 struct alloc_heap_entry l,
619 struct alloc_heap_entry r)
621 return (l.key > r.key) - (l.key < r.key) ?:
622 (l.nr < r.nr) - (l.nr > r.nr) ?:
623 (l.bucket > r.bucket) - (l.bucket < r.bucket);
626 static inline int bucket_idx_cmp(const void *_l, const void *_r)
628 const struct alloc_heap_entry *l = _l, *r = _r;
630 return (l->bucket > r->bucket) - (l->bucket < r->bucket);
633 static void find_reclaimable_buckets_lru(struct bch_fs *c, struct bch_dev *ca)
635 struct bucket_array *buckets;
636 struct alloc_heap_entry e = { 0 };
639 ca->alloc_heap.used = 0;
641 mutex_lock(&c->bucket_clock[READ].lock);
642 down_read(&ca->bucket_lock);
644 buckets = bucket_array(ca);
646 bch2_recalc_oldest_io(c, ca, READ);
649 * Find buckets with lowest read priority, by building a maxheap sorted
650 * by read priority and repeatedly replacing the maximum element until
651 * all buckets have been visited.
653 for (b = ca->mi.first_bucket; b < ca->mi.nbuckets; b++) {
654 struct bucket_mark m = READ_ONCE(buckets->b[b].mark);
655 unsigned long key = bucket_sort_key(c, ca, b, m);
657 if (!bch2_can_invalidate_bucket(ca, b, m))
660 if (e.nr && e.bucket + e.nr == b && e.key == key) {
664 heap_add_or_replace(&ca->alloc_heap, e,
665 -bucket_alloc_cmp, NULL);
667 e = (struct alloc_heap_entry) {
678 heap_add_or_replace(&ca->alloc_heap, e,
679 -bucket_alloc_cmp, NULL);
681 for (i = 0; i < ca->alloc_heap.used; i++)
682 nr += ca->alloc_heap.data[i].nr;
684 while (nr - ca->alloc_heap.data[0].nr >= ALLOC_SCAN_BATCH(ca)) {
685 nr -= ca->alloc_heap.data[0].nr;
686 heap_pop(&ca->alloc_heap, e, -bucket_alloc_cmp, NULL);
689 up_read(&ca->bucket_lock);
690 mutex_unlock(&c->bucket_clock[READ].lock);
693 static void find_reclaimable_buckets_fifo(struct bch_fs *c, struct bch_dev *ca)
695 struct bucket_array *buckets = bucket_array(ca);
696 struct bucket_mark m;
699 if (ca->fifo_last_bucket < ca->mi.first_bucket ||
700 ca->fifo_last_bucket >= ca->mi.nbuckets)
701 ca->fifo_last_bucket = ca->mi.first_bucket;
703 start = ca->fifo_last_bucket;
706 ca->fifo_last_bucket++;
707 if (ca->fifo_last_bucket == ca->mi.nbuckets)
708 ca->fifo_last_bucket = ca->mi.first_bucket;
710 b = ca->fifo_last_bucket;
711 m = READ_ONCE(buckets->b[b].mark);
713 if (bch2_can_invalidate_bucket(ca, b, m)) {
714 struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
716 heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
717 if (heap_full(&ca->alloc_heap))
722 } while (ca->fifo_last_bucket != start);
725 static void find_reclaimable_buckets_random(struct bch_fs *c, struct bch_dev *ca)
727 struct bucket_array *buckets = bucket_array(ca);
728 struct bucket_mark m;
732 checked < ca->mi.nbuckets / 2;
734 size_t b = bch2_rand_range(ca->mi.nbuckets -
735 ca->mi.first_bucket) +
738 m = READ_ONCE(buckets->b[b].mark);
740 if (bch2_can_invalidate_bucket(ca, b, m)) {
741 struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
743 heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
744 if (heap_full(&ca->alloc_heap))
751 sort(ca->alloc_heap.data,
753 sizeof(ca->alloc_heap.data[0]),
754 bucket_idx_cmp, NULL);
756 /* remove duplicates: */
757 for (i = 0; i + 1 < ca->alloc_heap.used; i++)
758 if (ca->alloc_heap.data[i].bucket ==
759 ca->alloc_heap.data[i + 1].bucket)
760 ca->alloc_heap.data[i].nr = 0;
763 static size_t find_reclaimable_buckets(struct bch_fs *c, struct bch_dev *ca)
767 ca->inc_gen_needs_gc = 0;
769 switch (ca->mi.replacement) {
770 case CACHE_REPLACEMENT_LRU:
771 find_reclaimable_buckets_lru(c, ca);
773 case CACHE_REPLACEMENT_FIFO:
774 find_reclaimable_buckets_fifo(c, ca);
776 case CACHE_REPLACEMENT_RANDOM:
777 find_reclaimable_buckets_random(c, ca);
781 heap_resort(&ca->alloc_heap, bucket_alloc_cmp, NULL);
783 for (i = 0; i < ca->alloc_heap.used; i++)
784 nr += ca->alloc_heap.data[i].nr;
789 static inline long next_alloc_bucket(struct bch_dev *ca)
791 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
793 while (ca->alloc_heap.used) {
795 size_t b = top->bucket;
802 heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
808 static bool bch2_invalidate_one_bucket(struct bch_fs *c, struct bch_dev *ca,
809 size_t bucket, u64 *flush_seq)
811 struct bucket_mark m;
813 percpu_down_read_preempt_disable(&c->mark_lock);
814 spin_lock(&c->freelist_lock);
816 bch2_invalidate_bucket(c, ca, bucket, &m);
818 verify_not_on_freelist(c, ca, bucket);
819 BUG_ON(!fifo_push(&ca->free_inc, bucket));
821 spin_unlock(&c->freelist_lock);
823 bucket_io_clock_reset(c, ca, bucket, READ);
824 bucket_io_clock_reset(c, ca, bucket, WRITE);
826 percpu_up_read_preempt_enable(&c->mark_lock);
828 if (m.journal_seq_valid) {
829 u64 journal_seq = atomic64_read(&c->journal.seq);
830 u64 bucket_seq = journal_seq;
832 bucket_seq &= ~((u64) U16_MAX);
833 bucket_seq |= m.journal_seq;
835 if (bucket_seq > journal_seq)
836 bucket_seq -= 1 << 16;
838 *flush_seq = max(*flush_seq, bucket_seq);
841 return m.cached_sectors != 0;
845 * Pull buckets off ca->alloc_heap, invalidate them, move them to ca->free_inc:
847 static int bch2_invalidate_buckets(struct bch_fs *c, struct bch_dev *ca)
849 struct btree_iter iter;
854 bch2_btree_iter_init(&iter, c, BTREE_ID_ALLOC, POS(ca->dev_idx, 0),
855 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
857 /* Only use nowait if we've already invalidated at least one bucket: */
859 !fifo_full(&ca->free_inc) &&
860 (b = next_alloc_bucket(ca)) >= 0) {
862 bch2_invalidate_one_bucket(c, ca, b, &journal_seq);
864 ret = __bch2_alloc_write_key(c, ca, b, &iter,
865 must_flush ? &journal_seq : NULL,
866 !fifo_empty(&ca->free_inc) ? BTREE_INSERT_NOWAIT : 0);
869 bch2_btree_iter_unlock(&iter);
871 /* If we used NOWAIT, don't return the error: */
872 if (!fifo_empty(&ca->free_inc))
875 bch_err(ca, "error invalidating buckets: %i", ret);
880 ret = bch2_journal_flush_seq(&c->journal, journal_seq);
882 bch_err(ca, "journal error: %i", ret);
889 static int push_invalidated_bucket(struct bch_fs *c, struct bch_dev *ca, size_t bucket)
895 set_current_state(TASK_INTERRUPTIBLE);
897 spin_lock(&c->freelist_lock);
898 for (i = 0; i < RESERVE_NR; i++)
899 if (fifo_push(&ca->free[i], bucket)) {
900 fifo_pop(&ca->free_inc, bucket);
901 closure_wake_up(&c->freelist_wait);
902 spin_unlock(&c->freelist_lock);
905 spin_unlock(&c->freelist_lock);
907 if ((current->flags & PF_KTHREAD) &&
908 kthread_should_stop()) {
917 __set_current_state(TASK_RUNNING);
922 * Pulls buckets off free_inc, discards them (if enabled), then adds them to
923 * freelists, waiting until there's room if necessary:
925 static int discard_invalidated_buckets(struct bch_fs *c, struct bch_dev *ca)
927 while (!fifo_empty(&ca->free_inc)) {
928 size_t bucket = fifo_peek(&ca->free_inc);
930 if (ca->mi.discard &&
931 blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
932 blkdev_issue_discard(ca->disk_sb.bdev,
933 bucket_to_sector(ca, bucket),
934 ca->mi.bucket_size, GFP_NOIO, 0);
936 if (push_invalidated_bucket(c, ca, bucket))
944 * bch_allocator_thread - move buckets from free_inc to reserves
946 * The free_inc FIFO is populated by find_reclaimable_buckets(), and
947 * the reserves are depleted by bucket allocation. When we run out
948 * of free_inc, try to invalidate some buckets and write out
951 static int bch2_allocator_thread(void *arg)
953 struct bch_dev *ca = arg;
954 struct bch_fs *c = ca->fs;
963 pr_debug("discarding %zu invalidated buckets",
964 fifo_used(&ca->free_inc));
966 ret = discard_invalidated_buckets(c, ca);
970 down_read(&c->gc_lock);
972 ret = bch2_invalidate_buckets(c, ca);
974 up_read(&c->gc_lock);
978 if (!fifo_empty(&ca->free_inc)) {
979 up_read(&c->gc_lock);
983 pr_debug("free_inc now empty");
987 * Find some buckets that we can invalidate, either
988 * they're completely unused, or only contain clean data
989 * that's been written back to the backing device or
993 pr_debug("scanning for reclaimable buckets");
995 nr = find_reclaimable_buckets(c, ca);
997 pr_debug("found %zu buckets", nr);
999 trace_alloc_batch(ca, nr, ca->alloc_heap.size);
1001 if ((ca->inc_gen_needs_gc >= ALLOC_SCAN_BATCH(ca) ||
1002 ca->inc_gen_really_needs_gc) &&
1004 atomic_inc(&c->kick_gc);
1005 wake_up_process(c->gc_thread);
1009 * If we found any buckets, we have to invalidate them
1010 * before we scan for more - but if we didn't find very
1011 * many we may want to wait on more buckets being
1012 * available so we don't spin:
1015 (nr < ALLOC_SCAN_BATCH(ca) &&
1016 !fifo_full(&ca->free[RESERVE_MOVINGGC]))) {
1017 ca->allocator_blocked = true;
1018 closure_wake_up(&c->freelist_wait);
1020 ret = wait_buckets_available(c, ca);
1022 up_read(&c->gc_lock);
1028 ca->allocator_blocked = false;
1029 up_read(&c->gc_lock);
1031 pr_debug("%zu buckets to invalidate", nr);
1034 * alloc_heap is now full of newly-invalidated buckets: next,
1035 * write out the new bucket gens:
1040 pr_debug("alloc thread stopping (ret %i)", ret);
1044 /* Startup/shutdown (ro/rw): */
1046 void bch2_recalc_capacity(struct bch_fs *c)
1049 u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1050 unsigned bucket_size_max = 0;
1051 unsigned long ra_pages = 0;
1054 lockdep_assert_held(&c->state_lock);
1056 for_each_online_member(ca, c, i) {
1057 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_bdi;
1059 ra_pages += bdi->ra_pages;
1062 bch2_set_ra_pages(c, ra_pages);
1064 for_each_rw_member(ca, c, i) {
1065 u64 dev_reserve = 0;
1068 * We need to reserve buckets (from the number
1069 * of currently available buckets) against
1070 * foreground writes so that mainly copygc can
1071 * make forward progress.
1073 * We need enough to refill the various reserves
1074 * from scratch - copygc will use its entire
1075 * reserve all at once, then run against when
1076 * its reserve is refilled (from the formerly
1077 * available buckets).
1079 * This reserve is just used when considering if
1080 * allocations for foreground writes must wait -
1081 * not -ENOSPC calculations.
1083 for (j = 0; j < RESERVE_NONE; j++)
1084 dev_reserve += ca->free[j].size;
1086 dev_reserve += 1; /* btree write point */
1087 dev_reserve += 1; /* copygc write point */
1088 dev_reserve += 1; /* rebalance write point */
1090 dev_reserve *= ca->mi.bucket_size;
1092 ca->copygc_threshold = dev_reserve;
1094 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1095 ca->mi.first_bucket);
1097 reserved_sectors += dev_reserve * 2;
1099 bucket_size_max = max_t(unsigned, bucket_size_max,
1100 ca->mi.bucket_size);
1103 gc_reserve = c->opts.gc_reserve_bytes
1104 ? c->opts.gc_reserve_bytes >> 9
1105 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1107 reserved_sectors = max(gc_reserve, reserved_sectors);
1109 reserved_sectors = min(reserved_sectors, capacity);
1111 c->capacity = capacity - reserved_sectors;
1113 c->bucket_size_max = bucket_size_max;
1116 bch2_io_timer_add(&c->io_clock[READ],
1117 &c->bucket_clock[READ].rescale);
1118 bch2_io_timer_add(&c->io_clock[WRITE],
1119 &c->bucket_clock[WRITE].rescale);
1121 bch2_io_timer_del(&c->io_clock[READ],
1122 &c->bucket_clock[READ].rescale);
1123 bch2_io_timer_del(&c->io_clock[WRITE],
1124 &c->bucket_clock[WRITE].rescale);
1127 /* Wake up case someone was waiting for buckets */
1128 closure_wake_up(&c->freelist_wait);
1131 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1133 struct open_bucket *ob;
1136 for (ob = c->open_buckets;
1137 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1139 spin_lock(&ob->lock);
1140 if (ob->valid && !ob->on_partial_list &&
1141 ob->ptr.dev == ca->dev_idx)
1143 spin_unlock(&ob->lock);
1149 /* device goes ro: */
1150 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1154 BUG_ON(ca->alloc_thread);
1156 /* First, remove device from allocation groups: */
1158 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1159 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1162 * Capacity is calculated based off of devices in allocation groups:
1164 bch2_recalc_capacity(c);
1166 /* Next, close write points that point to this device... */
1167 for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1168 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1170 bch2_writepoint_stop(c, ca, &ca->copygc_write_point);
1171 bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1172 bch2_writepoint_stop(c, ca, &c->btree_write_point);
1174 mutex_lock(&c->btree_reserve_cache_lock);
1175 while (c->btree_reserve_cache_nr) {
1176 struct btree_alloc *a =
1177 &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1179 bch2_open_buckets_put(c, &a->ob);
1181 mutex_unlock(&c->btree_reserve_cache_lock);
1184 struct open_bucket *ob;
1186 spin_lock(&c->freelist_lock);
1187 if (!ca->open_buckets_partial_nr) {
1188 spin_unlock(&c->freelist_lock);
1191 ob = c->open_buckets +
1192 ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1193 ob->on_partial_list = false;
1194 spin_unlock(&c->freelist_lock);
1196 bch2_open_bucket_put(c, ob);
1199 bch2_ec_stop_dev(c, ca);
1202 * Wake up threads that were blocked on allocation, so they can notice
1203 * the device can no longer be removed and the capacity has changed:
1205 closure_wake_up(&c->freelist_wait);
1208 * journal_res_get() can block waiting for free space in the journal -
1209 * it needs to notice there may not be devices to allocate from anymore:
1211 wake_up(&c->journal.wait);
1213 /* Now wait for any in flight writes: */
1215 closure_wait_event(&c->open_buckets_wait,
1216 !bch2_dev_has_open_write_point(c, ca));
1219 /* device goes rw: */
1220 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1224 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1225 if (ca->mi.data_allowed & (1 << i))
1226 set_bit(ca->dev_idx, c->rw_devs[i].d);
1229 /* stop allocator thread: */
1230 void bch2_dev_allocator_stop(struct bch_dev *ca)
1232 struct task_struct *p;
1234 p = rcu_dereference_protected(ca->alloc_thread, 1);
1235 ca->alloc_thread = NULL;
1238 * We need an rcu barrier between setting ca->alloc_thread = NULL and
1239 * the thread shutting down to avoid bch2_wake_allocator() racing:
1241 * XXX: it would be better to have the rcu barrier be asynchronous
1242 * instead of blocking us here
1252 /* start allocator thread: */
1253 int bch2_dev_allocator_start(struct bch_dev *ca)
1255 struct task_struct *p;
1258 * allocator thread already started?
1260 if (ca->alloc_thread)
1263 p = kthread_create(bch2_allocator_thread, ca,
1264 "bch_alloc[%s]", ca->name);
1269 rcu_assign_pointer(ca->alloc_thread, p);
1274 static void flush_held_btree_writes(struct bch_fs *c)
1276 struct bucket_table *tbl;
1277 struct rhash_head *pos;
1283 closure_init_stack(&cl);
1285 clear_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1287 pr_debug("flushing dirty btree nodes");
1289 closure_wait(&c->btree_interior_update_wait, &cl);
1291 nodes_blocked = false;
1294 for_each_cached_btree(b, c, tbl, i, pos)
1295 if (btree_node_need_write(b)) {
1296 if (btree_node_may_write(b)) {
1298 btree_node_lock_type(c, b, SIX_LOCK_read);
1299 bch2_btree_node_write(c, b, SIX_LOCK_read);
1300 six_unlock_read(&b->lock);
1303 nodes_blocked = true;
1308 if (c->btree_roots_dirty)
1309 bch2_journal_meta(&c->journal);
1311 if (nodes_blocked) {
1316 closure_wake_up(&c->btree_interior_update_wait);
1319 closure_wait_event(&c->btree_interior_update_wait,
1320 !bch2_btree_interior_updates_nr_pending(c));
1323 static void allocator_start_issue_discards(struct bch_fs *c)
1329 for_each_rw_member(ca, c, dev_iter)
1330 while (fifo_pop(&ca->free_inc, bu))
1331 blkdev_issue_discard(ca->disk_sb.bdev,
1332 bucket_to_sector(ca, bu),
1333 ca->mi.bucket_size, GFP_NOIO, 0);
1336 static int __bch2_fs_allocator_start(struct bch_fs *c)
1340 u64 journal_seq = 0;
1344 if (test_alloc_startup(c))
1347 /* Scan for buckets that are already invalidated: */
1348 for_each_rw_member(ca, c, dev_iter) {
1349 struct bucket_array *buckets;
1350 struct bucket_mark m;
1352 down_read(&ca->bucket_lock);
1353 percpu_down_read_preempt_disable(&c->mark_lock);
1355 buckets = bucket_array(ca);
1357 for (bu = buckets->first_bucket;
1358 bu < buckets->nbuckets; bu++) {
1359 m = READ_ONCE(buckets->b[bu].mark);
1361 if (!buckets->b[bu].gen_valid ||
1362 !test_bit(bu, ca->buckets_nouse) ||
1363 !is_available_bucket(m) ||
1367 bch2_mark_alloc_bucket(c, ca, bu, true,
1368 gc_pos_alloc(c, NULL), 0);
1370 fifo_push(&ca->free_inc, bu);
1372 discard_invalidated_buckets(c, ca);
1374 if (fifo_full(&ca->free[RESERVE_BTREE]))
1377 percpu_up_read_preempt_enable(&c->mark_lock);
1378 up_read(&ca->bucket_lock);
1381 /* did we find enough buckets? */
1382 for_each_rw_member(ca, c, dev_iter)
1383 if (!fifo_full(&ca->free[RESERVE_BTREE])) {
1384 percpu_ref_put(&ca->io_ref);
1390 pr_debug("not enough empty buckets; scanning for reclaimable buckets");
1393 * We're moving buckets to freelists _before_ they've been marked as
1394 * invalidated on disk - we have to so that we can allocate new btree
1395 * nodes to mark them as invalidated on disk.
1397 * However, we can't _write_ to any of these buckets yet - they might
1398 * have cached data in them, which is live until they're marked as
1399 * invalidated on disk:
1401 set_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1406 for_each_rw_member(ca, c, dev_iter) {
1407 find_reclaimable_buckets(c, ca);
1409 while (!fifo_full(&ca->free[RESERVE_BTREE]) &&
1410 (bu = next_alloc_bucket(ca)) >= 0) {
1411 bch2_invalidate_one_bucket(c, ca, bu,
1414 fifo_push(&ca->free[RESERVE_BTREE], bu);
1415 bucket_set_dirty(ca, bu);
1419 pr_debug("done scanning for reclaimable buckets");
1422 * XXX: it's possible for this to deadlock waiting on journal reclaim,
1423 * since we're holding btree writes. What then?
1425 ret = bch2_alloc_write(c, true, &wrote);
1428 * If bch2_alloc_write() did anything, it may have used some
1429 * buckets, and we need the RESERVE_BTREE freelist full - so we
1430 * need to loop and scan again.
1431 * And if it errored, it may have been because there weren't
1432 * enough buckets, so just scan and loop again as long as it
1433 * made some progress:
1441 pr_debug("flushing journal");
1443 ret = bch2_journal_flush(&c->journal);
1447 pr_debug("issuing discards");
1448 allocator_start_issue_discards(c);
1450 set_bit(BCH_FS_ALLOCATOR_STARTED, &c->flags);
1452 /* now flush dirty btree nodes: */
1453 flush_held_btree_writes(c);
1458 int bch2_fs_allocator_start(struct bch_fs *c)
1465 down_read(&c->gc_lock);
1466 ret = __bch2_fs_allocator_start(c);
1467 up_read(&c->gc_lock);
1472 for_each_rw_member(ca, c, i) {
1473 ret = bch2_dev_allocator_start(ca);
1475 percpu_ref_put(&ca->io_ref);
1480 return bch2_alloc_write(c, false, &wrote);
1483 void bch2_fs_allocator_background_init(struct bch_fs *c)
1485 spin_lock_init(&c->freelist_lock);
1486 bch2_bucket_clock_init(c, READ);
1487 bch2_bucket_clock_init(c, WRITE);
1489 c->pd_controllers_update_seconds = 5;
1490 INIT_DELAYED_WORK(&c->pd_controllers_update, pd_controllers_update);