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_key_cache.h"
8 #include "btree_update.h"
9 #include "btree_update_interior.h"
19 #include <linux/kthread.h>
20 #include <linux/math64.h>
21 #include <linux/random.h>
22 #include <linux/rculist.h>
23 #include <linux/rcupdate.h>
24 #include <linux/sched/task.h>
25 #include <linux/sort.h>
26 #include <trace/events/bcachefs.h>
28 const char * const bch2_allocator_states[] = {
35 static const unsigned BCH_ALLOC_V1_FIELD_BYTES[] = {
36 #define x(name, bits) [BCH_ALLOC_FIELD_V1_##name] = bits / 8,
41 /* Persistent alloc info: */
43 static inline u64 alloc_field_v1_get(const struct bch_alloc *a,
44 const void **p, unsigned field)
46 unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
49 if (!(a->fields & (1 << field)))
54 v = *((const u8 *) *p);
73 static inline void alloc_field_v1_put(struct bkey_i_alloc *a, void **p,
74 unsigned field, u64 v)
76 unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
81 a->v.fields |= 1 << field;
88 *((__le16 *) *p) = cpu_to_le16(v);
91 *((__le32 *) *p) = cpu_to_le32(v);
94 *((__le64 *) *p) = cpu_to_le64(v);
103 static void bch2_alloc_unpack_v1(struct bkey_alloc_unpacked *out,
106 const struct bch_alloc *in = bkey_s_c_to_alloc(k).v;
107 const void *d = in->data;
112 #define x(_name, _bits) out->_name = alloc_field_v1_get(in, &d, idx++);
113 BCH_ALLOC_FIELDS_V1()
117 static int bch2_alloc_unpack_v2(struct bkey_alloc_unpacked *out,
120 struct bkey_s_c_alloc_v2 a = bkey_s_c_to_alloc_v2(k);
121 const u8 *in = a.v->data;
122 const u8 *end = bkey_val_end(a);
123 unsigned fieldnr = 0;
128 out->oldest_gen = a.v->oldest_gen;
129 out->data_type = a.v->data_type;
131 #define x(_name, _bits) \
132 if (fieldnr < a.v->nr_fields) { \
133 ret = bch2_varint_decode_fast(in, end, &v); \
141 if (v != out->_name) \
145 BCH_ALLOC_FIELDS_V2()
150 static void bch2_alloc_pack_v2(struct bkey_alloc_buf *dst,
151 const struct bkey_alloc_unpacked src)
153 struct bkey_i_alloc_v2 *a = bkey_alloc_v2_init(&dst->k);
154 unsigned nr_fields = 0, last_nonzero_fieldnr = 0;
156 u8 *end = (void *) &dst[1];
157 u8 *last_nonzero_field = out;
160 a->k.p = POS(src.dev, src.bucket);
162 a->v.oldest_gen = src.oldest_gen;
163 a->v.data_type = src.data_type;
165 #define x(_name, _bits) \
169 out += bch2_varint_encode_fast(out, src._name); \
171 last_nonzero_field = out; \
172 last_nonzero_fieldnr = nr_fields; \
177 BCH_ALLOC_FIELDS_V2()
181 out = last_nonzero_field;
182 a->v.nr_fields = last_nonzero_fieldnr;
184 bytes = (u8 *) out - (u8 *) &a->v;
185 set_bkey_val_bytes(&a->k, bytes);
186 memset_u64s_tail(&a->v, 0, bytes);
189 struct bkey_alloc_unpacked bch2_alloc_unpack(struct bkey_s_c k)
191 struct bkey_alloc_unpacked ret = {
193 .bucket = k.k->p.offset,
197 if (k.k->type == KEY_TYPE_alloc_v2)
198 bch2_alloc_unpack_v2(&ret, k);
199 else if (k.k->type == KEY_TYPE_alloc)
200 bch2_alloc_unpack_v1(&ret, k);
205 void bch2_alloc_pack(struct bch_fs *c,
206 struct bkey_alloc_buf *dst,
207 const struct bkey_alloc_unpacked src)
209 bch2_alloc_pack_v2(dst, src);
212 static unsigned bch_alloc_v1_val_u64s(const struct bch_alloc *a)
214 unsigned i, bytes = offsetof(struct bch_alloc, data);
216 for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_V1_FIELD_BYTES); i++)
217 if (a->fields & (1 << i))
218 bytes += BCH_ALLOC_V1_FIELD_BYTES[i];
220 return DIV_ROUND_UP(bytes, sizeof(u64));
223 const char *bch2_alloc_v1_invalid(const struct bch_fs *c, struct bkey_s_c k)
225 struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
227 if (k.k->p.inode >= c->sb.nr_devices ||
228 !c->devs[k.k->p.inode])
229 return "invalid device";
231 /* allow for unknown fields */
232 if (bkey_val_u64s(a.k) < bch_alloc_v1_val_u64s(a.v))
233 return "incorrect value size";
238 const char *bch2_alloc_v2_invalid(const struct bch_fs *c, struct bkey_s_c k)
240 struct bkey_alloc_unpacked u;
242 if (k.k->p.inode >= c->sb.nr_devices ||
243 !c->devs[k.k->p.inode])
244 return "invalid device";
246 if (bch2_alloc_unpack_v2(&u, k))
247 return "unpack error";
252 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
255 struct bkey_alloc_unpacked u = bch2_alloc_unpack(k);
257 pr_buf(out, "gen %u oldest_gen %u data_type %s",
258 u.gen, u.oldest_gen, bch2_data_types[u.data_type]);
259 #define x(_name, ...) pr_buf(out, " " #_name " %llu", (u64) u._name);
260 BCH_ALLOC_FIELDS_V2()
264 static int bch2_alloc_read_fn(struct bch_fs *c, struct bkey_s_c k)
268 struct bkey_alloc_unpacked u;
270 if (k.k->type != KEY_TYPE_alloc &&
271 k.k->type != KEY_TYPE_alloc_v2)
274 ca = bch_dev_bkey_exists(c, k.k->p.inode);
275 g = bucket(ca, k.k->p.offset);
276 u = bch2_alloc_unpack(k);
278 g->_mark.gen = u.gen;
279 g->_mark.data_type = u.data_type;
280 g->_mark.dirty_sectors = u.dirty_sectors;
281 g->_mark.cached_sectors = u.cached_sectors;
282 g->io_time[READ] = u.read_time;
283 g->io_time[WRITE] = u.write_time;
284 g->oldest_gen = u.oldest_gen;
290 int bch2_alloc_read(struct bch_fs *c)
294 down_read(&c->gc_lock);
295 ret = bch2_btree_and_journal_walk(c, BTREE_ID_alloc, bch2_alloc_read_fn);
296 up_read(&c->gc_lock);
298 bch_err(c, "error reading alloc info: %i", ret);
305 static int bch2_alloc_write_key(struct btree_trans *trans,
306 struct btree_iter *iter,
309 struct bch_fs *c = trans->c;
313 struct bucket_mark m;
314 struct bkey_alloc_unpacked old_u, new_u;
315 struct bkey_alloc_buf a;
318 bch2_trans_begin(trans);
320 ret = bch2_btree_key_cache_flush(trans,
321 BTREE_ID_alloc, iter->pos);
325 k = bch2_btree_iter_peek_slot(iter);
330 old_u = bch2_alloc_unpack(k);
332 percpu_down_read(&c->mark_lock);
333 ca = bch_dev_bkey_exists(c, iter->pos.inode);
334 g = bucket(ca, iter->pos.offset);
335 m = READ_ONCE(g->mark);
336 new_u = alloc_mem_to_key(iter, g, m);
337 percpu_up_read(&c->mark_lock);
339 if (!bkey_alloc_unpacked_cmp(old_u, new_u))
342 bch2_alloc_pack(c, &a, new_u);
343 ret = bch2_trans_update(trans, iter, &a.k,
344 BTREE_TRIGGER_NORUN) ?:
345 bch2_trans_commit(trans, NULL, NULL,
346 BTREE_INSERT_NOFAIL|flags);
353 int bch2_alloc_write(struct bch_fs *c, unsigned flags)
355 struct btree_trans trans;
356 struct btree_iter iter;
361 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
362 bch2_trans_iter_init(&trans, &iter, BTREE_ID_alloc, POS_MIN,
363 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
365 for_each_member_device(ca, c, i) {
366 bch2_btree_iter_set_pos(&iter,
367 POS(ca->dev_idx, ca->mi.first_bucket));
369 while (iter.pos.offset < ca->mi.nbuckets) {
370 ret = bch2_alloc_write_key(&trans, &iter, flags);
372 percpu_ref_put(&ca->ref);
375 bch2_btree_iter_advance(&iter);
379 bch2_trans_iter_exit(&trans, &iter);
380 bch2_trans_exit(&trans);
384 /* Bucket IO clocks: */
386 int bch2_bucket_io_time_reset(struct btree_trans *trans, unsigned dev,
387 size_t bucket_nr, int rw)
389 struct bch_fs *c = trans->c;
390 struct bch_dev *ca = bch_dev_bkey_exists(c, dev);
391 struct btree_iter iter;
393 struct bkey_alloc_buf *a;
394 struct bkey_alloc_unpacked u;
398 bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, POS(dev, bucket_nr),
400 BTREE_ITER_CACHED_NOFILL|
402 ret = bch2_btree_iter_traverse(&iter);
406 a = bch2_trans_kmalloc(trans, sizeof(struct bkey_alloc_buf));
407 ret = PTR_ERR_OR_ZERO(a);
411 percpu_down_read(&c->mark_lock);
412 g = bucket(ca, bucket_nr);
413 u = alloc_mem_to_key(&iter, g, READ_ONCE(g->mark));
414 percpu_up_read(&c->mark_lock);
416 time = rw == READ ? &u.read_time : &u.write_time;
417 now = atomic64_read(&c->io_clock[rw].now);
423 bch2_alloc_pack(c, a, u);
424 ret = bch2_trans_update(trans, &iter, &a->k, 0) ?:
425 bch2_trans_commit(trans, NULL, NULL, 0);
427 bch2_trans_iter_exit(trans, &iter);
431 /* Background allocator thread: */
434 * Scans for buckets to be invalidated, invalidates them, rewrites prios/gens
435 * (marking them as invalidated on disk), then optionally issues discard
436 * commands to the newly free buckets, then puts them on the various freelists.
439 static bool bch2_can_invalidate_bucket(struct bch_dev *ca, size_t b,
440 struct bucket_mark m)
444 if (!is_available_bucket(m))
447 if (m.owned_by_allocator)
450 if (ca->buckets_nouse &&
451 test_bit(b, ca->buckets_nouse))
454 gc_gen = bucket_gc_gen(bucket(ca, b));
456 ca->inc_gen_needs_gc += gc_gen >= BUCKET_GC_GEN_MAX / 2;
457 ca->inc_gen_really_needs_gc += gc_gen >= BUCKET_GC_GEN_MAX;
459 return gc_gen < BUCKET_GC_GEN_MAX;
463 * Determines what order we're going to reuse buckets, smallest bucket_key()
467 static unsigned bucket_sort_key(struct bucket *g, struct bucket_mark m,
468 u64 now, u64 last_seq_ondisk)
470 unsigned used = bucket_sectors_used(m);
474 * Prefer to keep buckets that have been read more recently, and
475 * buckets that have more data in them:
477 u64 last_read = max_t(s64, 0, now - g->io_time[READ]);
478 u32 last_read_scaled = max_t(u64, U32_MAX, div_u64(last_read, used));
480 return -last_read_scaled;
483 * Prefer to use buckets with smaller gc_gen so that we don't
484 * have to walk the btree and recalculate oldest_gen - but shift
485 * off the low bits so that buckets will still have equal sort
486 * keys when there's only a small difference, so that we can
487 * keep sequential buckets together:
489 return (bucket_needs_journal_commit(m, last_seq_ondisk) << 4)|
490 (bucket_gc_gen(g) >> 4);
494 static inline int bucket_alloc_cmp(alloc_heap *h,
495 struct alloc_heap_entry l,
496 struct alloc_heap_entry r)
498 return cmp_int(l.key, r.key) ?:
499 cmp_int(r.nr, l.nr) ?:
500 cmp_int(l.bucket, r.bucket);
503 static inline int bucket_idx_cmp(const void *_l, const void *_r)
505 const struct alloc_heap_entry *l = _l, *r = _r;
507 return cmp_int(l->bucket, r->bucket);
510 static void find_reclaimable_buckets_lru(struct bch_fs *c, struct bch_dev *ca)
512 struct bucket_array *buckets;
513 struct alloc_heap_entry e = { 0 };
514 u64 now, last_seq_ondisk;
517 down_read(&ca->bucket_lock);
519 buckets = bucket_array(ca);
520 ca->alloc_heap.used = 0;
521 now = atomic64_read(&c->io_clock[READ].now);
522 last_seq_ondisk = c->journal.last_seq_ondisk;
525 * Find buckets with lowest read priority, by building a maxheap sorted
526 * by read priority and repeatedly replacing the maximum element until
527 * all buckets have been visited.
529 for (b = ca->mi.first_bucket; b < ca->mi.nbuckets; b++) {
530 struct bucket *g = &buckets->b[b];
531 struct bucket_mark m = READ_ONCE(g->mark);
532 unsigned key = bucket_sort_key(g, m, now, last_seq_ondisk);
536 if (!bch2_can_invalidate_bucket(ca, b, m))
539 if (e.nr && e.bucket + e.nr == b && e.key == key) {
543 heap_add_or_replace(&ca->alloc_heap, e,
544 -bucket_alloc_cmp, NULL);
546 e = (struct alloc_heap_entry) {
555 heap_add_or_replace(&ca->alloc_heap, e,
556 -bucket_alloc_cmp, NULL);
558 for (i = 0; i < ca->alloc_heap.used; i++)
559 nr += ca->alloc_heap.data[i].nr;
561 while (nr - ca->alloc_heap.data[0].nr >= ALLOC_SCAN_BATCH(ca)) {
562 nr -= ca->alloc_heap.data[0].nr;
563 heap_pop(&ca->alloc_heap, e, -bucket_alloc_cmp, NULL);
566 up_read(&ca->bucket_lock);
569 static void find_reclaimable_buckets_fifo(struct bch_fs *c, struct bch_dev *ca)
571 struct bucket_array *buckets = bucket_array(ca);
572 struct bucket_mark m;
575 if (ca->fifo_last_bucket < ca->mi.first_bucket ||
576 ca->fifo_last_bucket >= ca->mi.nbuckets)
577 ca->fifo_last_bucket = ca->mi.first_bucket;
579 start = ca->fifo_last_bucket;
582 ca->fifo_last_bucket++;
583 if (ca->fifo_last_bucket == ca->mi.nbuckets)
584 ca->fifo_last_bucket = ca->mi.first_bucket;
586 b = ca->fifo_last_bucket;
587 m = READ_ONCE(buckets->b[b].mark);
589 if (bch2_can_invalidate_bucket(ca, b, m)) {
590 struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
592 heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
593 if (heap_full(&ca->alloc_heap))
598 } while (ca->fifo_last_bucket != start);
601 static void find_reclaimable_buckets_random(struct bch_fs *c, struct bch_dev *ca)
603 struct bucket_array *buckets = bucket_array(ca);
604 struct bucket_mark m;
608 checked < ca->mi.nbuckets / 2;
610 size_t b = bch2_rand_range(ca->mi.nbuckets -
611 ca->mi.first_bucket) +
614 m = READ_ONCE(buckets->b[b].mark);
616 if (bch2_can_invalidate_bucket(ca, b, m)) {
617 struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
619 heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
620 if (heap_full(&ca->alloc_heap))
627 sort(ca->alloc_heap.data,
629 sizeof(ca->alloc_heap.data[0]),
630 bucket_idx_cmp, NULL);
632 /* remove duplicates: */
633 for (i = 0; i + 1 < ca->alloc_heap.used; i++)
634 if (ca->alloc_heap.data[i].bucket ==
635 ca->alloc_heap.data[i + 1].bucket)
636 ca->alloc_heap.data[i].nr = 0;
639 static size_t find_reclaimable_buckets(struct bch_fs *c, struct bch_dev *ca)
643 ca->inc_gen_needs_gc = 0;
644 ca->inc_gen_really_needs_gc = 0;
646 switch (ca->mi.replacement) {
647 case BCH_CACHE_REPLACEMENT_lru:
648 find_reclaimable_buckets_lru(c, ca);
650 case BCH_CACHE_REPLACEMENT_fifo:
651 find_reclaimable_buckets_fifo(c, ca);
653 case BCH_CACHE_REPLACEMENT_random:
654 find_reclaimable_buckets_random(c, ca);
658 heap_resort(&ca->alloc_heap, bucket_alloc_cmp, NULL);
660 for (i = 0; i < ca->alloc_heap.used; i++)
661 nr += ca->alloc_heap.data[i].nr;
667 * returns sequence number of most recent journal entry that updated this
670 static u64 bucket_journal_seq(struct bch_fs *c, struct bucket_mark m)
672 if (m.journal_seq_valid) {
673 u64 journal_seq = atomic64_read(&c->journal.seq);
674 u64 bucket_seq = journal_seq;
676 bucket_seq &= ~((u64) U16_MAX);
677 bucket_seq |= m.journal_seq;
679 if (bucket_seq > journal_seq)
680 bucket_seq -= 1 << 16;
688 static int bucket_invalidate_btree(struct btree_trans *trans,
689 struct bch_dev *ca, u64 b)
691 struct bch_fs *c = trans->c;
692 struct bkey_alloc_buf *a;
693 struct bkey_alloc_unpacked u;
695 struct bucket_mark m;
696 struct btree_iter iter;
699 bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
702 BTREE_ITER_CACHED_NOFILL|
705 a = bch2_trans_kmalloc(trans, sizeof(*a));
706 ret = PTR_ERR_OR_ZERO(a);
710 ret = bch2_btree_iter_traverse(&iter);
714 percpu_down_read(&c->mark_lock);
716 m = READ_ONCE(g->mark);
717 u = alloc_mem_to_key(&iter, g, m);
718 percpu_up_read(&c->mark_lock);
723 u.cached_sectors = 0;
724 u.read_time = atomic64_read(&c->io_clock[READ].now);
725 u.write_time = atomic64_read(&c->io_clock[WRITE].now);
727 bch2_alloc_pack(c, a, u);
728 ret = bch2_trans_update(trans, &iter, &a->k,
729 BTREE_TRIGGER_BUCKET_INVALIDATE);
731 bch2_trans_iter_exit(trans, &iter);
735 static int bch2_invalidate_one_bucket(struct bch_fs *c, struct bch_dev *ca,
736 u64 *journal_seq, unsigned flags)
739 struct bucket_mark m;
743 BUG_ON(!ca->alloc_heap.used ||
744 !ca->alloc_heap.data[0].nr);
745 b = ca->alloc_heap.data[0].bucket;
747 /* first, put on free_inc and mark as owned by allocator: */
748 percpu_down_read(&c->mark_lock);
750 m = READ_ONCE(g->mark);
752 BUG_ON(m.dirty_sectors);
754 bch2_mark_alloc_bucket(c, ca, b, true);
756 spin_lock(&c->freelist_lock);
757 verify_not_on_freelist(c, ca, b);
758 BUG_ON(!fifo_push(&ca->free_inc, b));
759 spin_unlock(&c->freelist_lock);
762 * If we're not invalidating cached data, we only increment the bucket
763 * gen in memory here, the incremented gen will be updated in the btree
764 * by bch2_trans_mark_pointer():
766 if (!m.cached_sectors &&
767 !bucket_needs_journal_commit(m, c->journal.last_seq_ondisk)) {
769 bucket_cmpxchg(g, m, m.gen++);
770 percpu_up_read(&c->mark_lock);
774 percpu_up_read(&c->mark_lock);
777 * If the read-only path is trying to shut down, we can't be generating
780 if (test_bit(BCH_FS_ALLOCATOR_STOPPING, &c->flags)) {
785 ret = bch2_trans_do(c, NULL, journal_seq,
786 BTREE_INSERT_NOCHECK_RW|
788 BTREE_INSERT_JOURNAL_RESERVED|
790 bucket_invalidate_btree(&trans, ca, b));
793 /* remove from alloc_heap: */
794 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
800 heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
803 * Make sure we flush the last journal entry that updated this
804 * bucket (i.e. deleting the last reference) before writing to
807 *journal_seq = max(*journal_seq, bucket_journal_seq(c, m));
811 /* remove from free_inc: */
812 percpu_down_read(&c->mark_lock);
813 spin_lock(&c->freelist_lock);
815 bch2_mark_alloc_bucket(c, ca, b, false);
817 BUG_ON(!fifo_pop_back(&ca->free_inc, b2));
820 spin_unlock(&c->freelist_lock);
821 percpu_up_read(&c->mark_lock);
824 return ret < 0 ? ret : 0;
828 * Pull buckets off ca->alloc_heap, invalidate them, move them to ca->free_inc:
830 static int bch2_invalidate_buckets(struct bch_fs *c, struct bch_dev *ca)
835 /* Only use nowait if we've already invalidated at least one bucket: */
837 !fifo_full(&ca->free_inc) &&
838 ca->alloc_heap.used) {
839 if (kthread_should_stop()) {
844 ret = bch2_invalidate_one_bucket(c, ca, &journal_seq,
845 (!fifo_empty(&ca->free_inc)
846 ? BTREE_INSERT_NOWAIT : 0));
848 * We only want to batch up invalidates when they're going to
849 * require flushing the journal:
855 /* If we used NOWAIT, don't return the error: */
856 if (!fifo_empty(&ca->free_inc))
859 bch_err(ca, "error invalidating buckets: %i", ret);
864 ret = bch2_journal_flush_seq(&c->journal, journal_seq);
866 bch_err(ca, "journal error: %i", ret);
873 static void alloc_thread_set_state(struct bch_dev *ca, unsigned new_state)
875 if (ca->allocator_state != new_state) {
876 ca->allocator_state = new_state;
877 closure_wake_up(&ca->fs->freelist_wait);
881 static int push_invalidated_bucket(struct bch_fs *c, struct bch_dev *ca, u64 b)
886 spin_lock(&c->freelist_lock);
887 for (i = 0; i < RESERVE_NR; i++) {
889 * Don't strand buckets on the copygc freelist until
890 * after recovery is finished:
892 if (i == RESERVE_MOVINGGC &&
893 !test_bit(BCH_FS_STARTED, &c->flags))
896 if (fifo_push(&ca->free[i], b)) {
897 fifo_pop(&ca->free_inc, b);
902 spin_unlock(&c->freelist_lock);
904 ca->allocator_state = ret
906 : ALLOCATOR_blocked_full;
907 closure_wake_up(&c->freelist_wait);
911 static void discard_one_bucket(struct bch_fs *c, struct bch_dev *ca, u64 b)
913 if (ca->mi.discard &&
914 blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
915 blkdev_issue_discard(ca->disk_sb.bdev, bucket_to_sector(ca, b),
916 ca->mi.bucket_size, GFP_NOFS, 0);
919 static bool allocator_thread_running(struct bch_dev *ca)
921 unsigned state = ca->mi.state == BCH_MEMBER_STATE_rw &&
922 test_bit(BCH_FS_ALLOCATOR_RUNNING, &ca->fs->flags)
925 alloc_thread_set_state(ca, state);
926 return state == ALLOCATOR_running;
929 static int buckets_available(struct bch_dev *ca, unsigned long gc_count)
931 s64 available = dev_buckets_reclaimable(ca) -
932 (gc_count == ca->fs->gc_count ? ca->inc_gen_really_needs_gc : 0);
933 bool ret = available > 0;
935 alloc_thread_set_state(ca, ret
937 : ALLOCATOR_blocked);
942 * bch_allocator_thread - move buckets from free_inc to reserves
944 * The free_inc FIFO is populated by find_reclaimable_buckets(), and
945 * the reserves are depleted by bucket allocation. When we run out
946 * of free_inc, try to invalidate some buckets and write out
949 static int bch2_allocator_thread(void *arg)
951 struct bch_dev *ca = arg;
952 struct bch_fs *c = ca->fs;
953 unsigned long gc_count = c->gc_count;
960 ret = kthread_wait_freezable(allocator_thread_running(ca));
964 while (!ca->alloc_heap.used) {
967 ret = kthread_wait_freezable(buckets_available(ca, gc_count));
971 gc_count = c->gc_count;
972 nr = find_reclaimable_buckets(c, ca);
974 trace_alloc_scan(ca, nr, ca->inc_gen_needs_gc,
975 ca->inc_gen_really_needs_gc);
977 if ((ca->inc_gen_needs_gc >= ALLOC_SCAN_BATCH(ca) ||
978 ca->inc_gen_really_needs_gc) &&
980 atomic_inc(&c->kick_gc);
981 wake_up_process(c->gc_thread);
985 ret = bch2_invalidate_buckets(c, ca);
989 while (!fifo_empty(&ca->free_inc)) {
990 u64 b = fifo_peek(&ca->free_inc);
992 discard_one_bucket(c, ca, b);
994 ret = kthread_wait_freezable(push_invalidated_bucket(c, ca, b));
1000 alloc_thread_set_state(ca, ALLOCATOR_stopped);
1004 /* Startup/shutdown (ro/rw): */
1006 void bch2_recalc_capacity(struct bch_fs *c)
1009 u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1010 unsigned bucket_size_max = 0;
1011 unsigned long ra_pages = 0;
1014 lockdep_assert_held(&c->state_lock);
1016 for_each_online_member(ca, c, i) {
1017 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_bdi;
1019 ra_pages += bdi->ra_pages;
1022 bch2_set_ra_pages(c, ra_pages);
1024 for_each_rw_member(ca, c, i) {
1025 u64 dev_reserve = 0;
1028 * We need to reserve buckets (from the number
1029 * of currently available buckets) against
1030 * foreground writes so that mainly copygc can
1031 * make forward progress.
1033 * We need enough to refill the various reserves
1034 * from scratch - copygc will use its entire
1035 * reserve all at once, then run against when
1036 * its reserve is refilled (from the formerly
1037 * available buckets).
1039 * This reserve is just used when considering if
1040 * allocations for foreground writes must wait -
1041 * not -ENOSPC calculations.
1043 for (j = 0; j < RESERVE_NONE; j++)
1044 dev_reserve += ca->free[j].size;
1046 dev_reserve += 1; /* btree write point */
1047 dev_reserve += 1; /* copygc write point */
1048 dev_reserve += 1; /* rebalance write point */
1050 dev_reserve *= ca->mi.bucket_size;
1052 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1053 ca->mi.first_bucket);
1055 reserved_sectors += dev_reserve * 2;
1057 bucket_size_max = max_t(unsigned, bucket_size_max,
1058 ca->mi.bucket_size);
1061 gc_reserve = c->opts.gc_reserve_bytes
1062 ? c->opts.gc_reserve_bytes >> 9
1063 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1065 reserved_sectors = max(gc_reserve, reserved_sectors);
1067 reserved_sectors = min(reserved_sectors, capacity);
1069 c->capacity = capacity - reserved_sectors;
1071 c->bucket_size_max = bucket_size_max;
1073 /* Wake up case someone was waiting for buckets */
1074 closure_wake_up(&c->freelist_wait);
1077 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1079 struct open_bucket *ob;
1082 for (ob = c->open_buckets;
1083 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1085 spin_lock(&ob->lock);
1086 if (ob->valid && !ob->on_partial_list &&
1087 ob->ptr.dev == ca->dev_idx)
1089 spin_unlock(&ob->lock);
1095 /* device goes ro: */
1096 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1100 BUG_ON(ca->alloc_thread);
1102 /* First, remove device from allocation groups: */
1104 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1105 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1108 * Capacity is calculated based off of devices in allocation groups:
1110 bch2_recalc_capacity(c);
1112 /* Next, close write points that point to this device... */
1113 for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1114 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1116 bch2_writepoint_stop(c, ca, &c->copygc_write_point);
1117 bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1118 bch2_writepoint_stop(c, ca, &c->btree_write_point);
1120 mutex_lock(&c->btree_reserve_cache_lock);
1121 while (c->btree_reserve_cache_nr) {
1122 struct btree_alloc *a =
1123 &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1125 bch2_open_buckets_put(c, &a->ob);
1127 mutex_unlock(&c->btree_reserve_cache_lock);
1130 struct open_bucket *ob;
1132 spin_lock(&c->freelist_lock);
1133 if (!ca->open_buckets_partial_nr) {
1134 spin_unlock(&c->freelist_lock);
1137 ob = c->open_buckets +
1138 ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1139 ob->on_partial_list = false;
1140 spin_unlock(&c->freelist_lock);
1142 bch2_open_bucket_put(c, ob);
1145 bch2_ec_stop_dev(c, ca);
1148 * Wake up threads that were blocked on allocation, so they can notice
1149 * the device can no longer be removed and the capacity has changed:
1151 closure_wake_up(&c->freelist_wait);
1154 * journal_res_get() can block waiting for free space in the journal -
1155 * it needs to notice there may not be devices to allocate from anymore:
1157 wake_up(&c->journal.wait);
1159 /* Now wait for any in flight writes: */
1161 closure_wait_event(&c->open_buckets_wait,
1162 !bch2_dev_has_open_write_point(c, ca));
1165 /* device goes rw: */
1166 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1170 for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1171 if (ca->mi.data_allowed & (1 << i))
1172 set_bit(ca->dev_idx, c->rw_devs[i].d);
1175 void bch2_dev_allocator_quiesce(struct bch_fs *c, struct bch_dev *ca)
1177 if (ca->alloc_thread)
1178 closure_wait_event(&c->freelist_wait,
1179 ca->allocator_state != ALLOCATOR_running);
1182 /* stop allocator thread: */
1183 void bch2_dev_allocator_stop(struct bch_dev *ca)
1185 struct task_struct *p;
1187 p = rcu_dereference_protected(ca->alloc_thread, 1);
1188 ca->alloc_thread = NULL;
1191 * We need an rcu barrier between setting ca->alloc_thread = NULL and
1192 * the thread shutting down to avoid bch2_wake_allocator() racing:
1194 * XXX: it would be better to have the rcu barrier be asynchronous
1195 * instead of blocking us here
1205 /* start allocator thread: */
1206 int bch2_dev_allocator_start(struct bch_dev *ca)
1208 struct task_struct *p;
1211 * allocator thread already started?
1213 if (ca->alloc_thread)
1216 p = kthread_create(bch2_allocator_thread, ca,
1217 "bch-alloc/%s", ca->name);
1219 bch_err(ca->fs, "error creating allocator thread: %li",
1225 rcu_assign_pointer(ca->alloc_thread, p);
1230 void bch2_fs_allocator_background_init(struct bch_fs *c)
1232 spin_lock_init(&c->freelist_lock);
1235 void bch2_open_buckets_to_text(struct printbuf *out, struct bch_fs *c)
1237 struct open_bucket *ob;
1239 for (ob = c->open_buckets;
1240 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1242 spin_lock(&ob->lock);
1243 if (ob->valid && !ob->on_partial_list) {
1244 pr_buf(out, "%zu ref %u type %s\n",
1245 ob - c->open_buckets,
1246 atomic_read(&ob->pin),
1247 bch2_data_types[ob->type]);
1249 spin_unlock(&ob->lock);