1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright 2012 Google, Inc.
5 * Foreground allocator code: allocate buckets from freelist, and allocate in
6 * sector granularity from writepoints.
8 * bch2_bucket_alloc() allocates a single bucket from a specific device.
10 * bch2_bucket_alloc_set() allocates one or more buckets from different devices
11 * in a given filesystem.
15 #include "alloc_background.h"
16 #include "alloc_foreground.h"
17 #include "backpointers.h"
18 #include "btree_iter.h"
19 #include "btree_update.h"
22 #include "buckets_waiting_for_journal.h"
25 #include "disk_groups.h"
31 #include "nocow_locking.h"
34 #include <linux/math64.h>
35 #include <linux/rculist.h>
36 #include <linux/rcupdate.h>
38 static void bch2_trans_mutex_lock_norelock(struct btree_trans *trans,
41 if (!mutex_trylock(lock)) {
42 bch2_trans_unlock(trans);
47 const char * const bch2_watermarks[] = {
55 * Open buckets represent a bucket that's currently being allocated from. They
58 * - They track buckets that have been partially allocated, allowing for
59 * sub-bucket sized allocations - they're used by the sector allocator below
61 * - They provide a reference to the buckets they own that mark and sweep GC
62 * can find, until the new allocation has a pointer to it inserted into the
65 * When allocating some space with the sector allocator, the allocation comes
66 * with a reference to an open bucket - the caller is required to put that
67 * reference _after_ doing the index update that makes its allocation reachable.
70 void bch2_reset_alloc_cursors(struct bch_fs *c)
76 for_each_member_device_rcu(ca, c, i, NULL)
81 static void bch2_open_bucket_hash_add(struct bch_fs *c, struct open_bucket *ob)
83 open_bucket_idx_t idx = ob - c->open_buckets;
84 open_bucket_idx_t *slot = open_bucket_hashslot(c, ob->dev, ob->bucket);
90 static void bch2_open_bucket_hash_remove(struct bch_fs *c, struct open_bucket *ob)
92 open_bucket_idx_t idx = ob - c->open_buckets;
93 open_bucket_idx_t *slot = open_bucket_hashslot(c, ob->dev, ob->bucket);
95 while (*slot != idx) {
97 slot = &c->open_buckets[*slot].hash;
104 void __bch2_open_bucket_put(struct bch_fs *c, struct open_bucket *ob)
106 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
109 ec_stripe_new_put(c, ob->ec, STRIPE_REF_io);
113 percpu_down_read(&c->mark_lock);
114 spin_lock(&ob->lock);
119 spin_unlock(&ob->lock);
120 percpu_up_read(&c->mark_lock);
122 spin_lock(&c->freelist_lock);
123 bch2_open_bucket_hash_remove(c, ob);
125 ob->freelist = c->open_buckets_freelist;
126 c->open_buckets_freelist = ob - c->open_buckets;
128 c->open_buckets_nr_free++;
129 ca->nr_open_buckets--;
130 spin_unlock(&c->freelist_lock);
132 closure_wake_up(&c->open_buckets_wait);
135 void bch2_open_bucket_write_error(struct bch_fs *c,
136 struct open_buckets *obs,
139 struct open_bucket *ob;
142 open_bucket_for_each(c, obs, ob, i)
143 if (ob->dev == dev && ob->ec)
144 bch2_ec_bucket_cancel(c, ob);
147 static struct open_bucket *bch2_open_bucket_alloc(struct bch_fs *c)
149 struct open_bucket *ob;
151 BUG_ON(!c->open_buckets_freelist || !c->open_buckets_nr_free);
153 ob = c->open_buckets + c->open_buckets_freelist;
154 c->open_buckets_freelist = ob->freelist;
155 atomic_set(&ob->pin, 1);
158 c->open_buckets_nr_free--;
162 static void open_bucket_free_unused(struct bch_fs *c, struct open_bucket *ob)
164 BUG_ON(c->open_buckets_partial_nr >=
165 ARRAY_SIZE(c->open_buckets_partial));
167 spin_lock(&c->freelist_lock);
168 ob->on_partial_list = true;
169 c->open_buckets_partial[c->open_buckets_partial_nr++] =
170 ob - c->open_buckets;
171 spin_unlock(&c->freelist_lock);
173 closure_wake_up(&c->open_buckets_wait);
174 closure_wake_up(&c->freelist_wait);
177 /* _only_ for allocating the journal on a new device: */
178 long bch2_bucket_alloc_new_fs(struct bch_dev *ca)
180 while (ca->new_fs_bucket_idx < ca->mi.nbuckets) {
181 u64 b = ca->new_fs_bucket_idx++;
183 if (!is_superblock_bucket(ca, b) &&
184 (!ca->buckets_nouse || !test_bit(b, ca->buckets_nouse)))
191 static inline unsigned open_buckets_reserved(enum bch_watermark watermark)
194 case BCH_WATERMARK_reclaim:
196 case BCH_WATERMARK_btree:
197 case BCH_WATERMARK_btree_copygc:
198 return OPEN_BUCKETS_COUNT / 4;
199 case BCH_WATERMARK_copygc:
200 return OPEN_BUCKETS_COUNT / 3;
202 return OPEN_BUCKETS_COUNT / 2;
206 static struct open_bucket *__try_alloc_bucket(struct bch_fs *c, struct bch_dev *ca,
208 enum bch_watermark watermark,
209 const struct bch_alloc_v4 *a,
210 struct bucket_alloc_state *s,
213 struct open_bucket *ob;
215 if (unlikely(ca->buckets_nouse && test_bit(bucket, ca->buckets_nouse))) {
220 if (bch2_bucket_is_open(c, ca->dev_idx, bucket)) {
225 if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
226 c->journal.flushed_seq_ondisk, ca->dev_idx, bucket)) {
227 s->skipped_need_journal_commit++;
231 if (bch2_bucket_nocow_is_locked(&c->nocow_locks, POS(ca->dev_idx, bucket))) {
236 spin_lock(&c->freelist_lock);
238 if (unlikely(c->open_buckets_nr_free <= open_buckets_reserved(watermark))) {
240 closure_wait(&c->open_buckets_wait, cl);
242 if (!c->blocked_allocate_open_bucket)
243 c->blocked_allocate_open_bucket = local_clock();
245 spin_unlock(&c->freelist_lock);
246 return ERR_PTR(-BCH_ERR_open_buckets_empty);
249 /* Recheck under lock: */
250 if (bch2_bucket_is_open(c, ca->dev_idx, bucket)) {
251 spin_unlock(&c->freelist_lock);
256 ob = bch2_open_bucket_alloc(c);
258 spin_lock(&ob->lock);
261 ob->sectors_free = ca->mi.bucket_size;
262 ob->dev = ca->dev_idx;
265 spin_unlock(&ob->lock);
267 ca->nr_open_buckets++;
268 bch2_open_bucket_hash_add(c, ob);
270 if (c->blocked_allocate_open_bucket) {
271 bch2_time_stats_update(
272 &c->times[BCH_TIME_blocked_allocate_open_bucket],
273 c->blocked_allocate_open_bucket);
274 c->blocked_allocate_open_bucket = 0;
277 if (c->blocked_allocate) {
278 bch2_time_stats_update(
279 &c->times[BCH_TIME_blocked_allocate],
280 c->blocked_allocate);
281 c->blocked_allocate = 0;
284 spin_unlock(&c->freelist_lock);
288 static struct open_bucket *try_alloc_bucket(struct btree_trans *trans, struct bch_dev *ca,
289 enum bch_watermark watermark, u64 free_entry,
290 struct bucket_alloc_state *s,
291 struct bkey_s_c freespace_k,
294 struct bch_fs *c = trans->c;
295 struct btree_iter iter = { NULL };
297 struct open_bucket *ob;
298 struct bch_alloc_v4 a_convert;
299 const struct bch_alloc_v4 *a;
300 u64 b = free_entry & ~(~0ULL << 56);
301 unsigned genbits = free_entry >> 56;
302 struct printbuf buf = PRINTBUF;
305 if (b < ca->mi.first_bucket || b >= ca->mi.nbuckets) {
306 prt_printf(&buf, "freespace btree has bucket outside allowed range %u-%llu\n"
308 ca->mi.first_bucket, ca->mi.nbuckets);
309 bch2_bkey_val_to_text(&buf, c, freespace_k);
310 bch2_trans_inconsistent(trans, "%s", buf.buf);
315 k = bch2_bkey_get_iter(trans, &iter,
316 BTREE_ID_alloc, POS(ca->dev_idx, b),
324 a = bch2_alloc_to_v4(k, &a_convert);
326 if (a->data_type != BCH_DATA_free) {
327 if (c->curr_recovery_pass <= BCH_RECOVERY_PASS_check_alloc_info) {
332 prt_printf(&buf, "non free bucket in freespace btree\n"
334 bch2_bkey_val_to_text(&buf, c, freespace_k);
335 prt_printf(&buf, "\n ");
336 bch2_bkey_val_to_text(&buf, c, k);
337 bch2_trans_inconsistent(trans, "%s", buf.buf);
342 if (genbits != (alloc_freespace_genbits(*a) >> 56) &&
343 c->curr_recovery_pass > BCH_RECOVERY_PASS_check_alloc_info) {
344 prt_printf(&buf, "bucket in freespace btree with wrong genbits (got %u should be %llu)\n"
346 genbits, alloc_freespace_genbits(*a) >> 56);
347 bch2_bkey_val_to_text(&buf, c, freespace_k);
348 prt_printf(&buf, "\n ");
349 bch2_bkey_val_to_text(&buf, c, k);
350 bch2_trans_inconsistent(trans, "%s", buf.buf);
355 if (c->curr_recovery_pass <= BCH_RECOVERY_PASS_check_extents_to_backpointers) {
356 struct bch_backpointer bp;
357 struct bpos bp_pos = POS_MIN;
359 ret = bch2_get_next_backpointer(trans, POS(ca->dev_idx, b), -1,
361 BTREE_ITER_NOPRESERVE);
367 if (!bkey_eq(bp_pos, POS_MAX)) {
369 * Bucket may have data in it - we don't call
370 * bc2h_trans_inconnsistent() because fsck hasn't
378 ob = __try_alloc_bucket(c, ca, b, watermark, a, s, cl);
380 iter.path->preserve = false;
382 if (iter.trans && iter.path)
383 set_btree_iter_dontneed(&iter);
384 bch2_trans_iter_exit(trans, &iter);
390 * This path is for before the freespace btree is initialized:
392 * If ca->new_fs_bucket_idx is nonzero, we haven't yet marked superblock &
393 * journal buckets - journal buckets will be < ca->new_fs_bucket_idx
395 static noinline struct open_bucket *
396 bch2_bucket_alloc_early(struct btree_trans *trans,
398 enum bch_watermark watermark,
399 struct bucket_alloc_state *s,
402 struct btree_iter iter, citer;
403 struct bkey_s_c k, ck;
404 struct open_bucket *ob = NULL;
405 u64 first_bucket = max_t(u64, ca->mi.first_bucket, ca->new_fs_bucket_idx);
406 u64 alloc_start = max(first_bucket, READ_ONCE(ca->alloc_cursor));
407 u64 alloc_cursor = alloc_start;
411 * Scan with an uncached iterator to avoid polluting the key cache. An
412 * uncached iter will return a cached key if one exists, but if not
413 * there is no other underlying protection for the associated key cache
414 * slot. To avoid racing bucket allocations, look up the cached key slot
415 * of any likely allocation candidate before attempting to proceed with
416 * the allocation. This provides proper exclusion on the associated
420 for_each_btree_key_norestart(trans, iter, BTREE_ID_alloc, POS(ca->dev_idx, alloc_cursor),
421 BTREE_ITER_SLOTS, k, ret) {
422 struct bch_alloc_v4 a_convert;
423 const struct bch_alloc_v4 *a;
425 if (bkey_ge(k.k->p, POS(ca->dev_idx, ca->mi.nbuckets)))
428 if (ca->new_fs_bucket_idx &&
429 is_superblock_bucket(ca, k.k->p.offset))
432 a = bch2_alloc_to_v4(k, &a_convert);
433 if (a->data_type != BCH_DATA_free)
436 /* now check the cached key to serialize concurrent allocs of the bucket */
437 ck = bch2_bkey_get_iter(trans, &citer, BTREE_ID_alloc, k.k->p, BTREE_ITER_CACHED);
442 a = bch2_alloc_to_v4(ck, &a_convert);
443 if (a->data_type != BCH_DATA_free)
448 ob = __try_alloc_bucket(trans->c, ca, k.k->p.offset, watermark, a, s, cl);
450 citer.path->preserve = false;
451 bch2_trans_iter_exit(trans, &citer);
455 bch2_trans_iter_exit(trans, &iter);
457 alloc_cursor = iter.pos.offset;
458 ca->alloc_cursor = alloc_cursor;
463 if (!ob && alloc_start > first_bucket) {
464 alloc_cursor = alloc_start = first_bucket;
471 static struct open_bucket *bch2_bucket_alloc_freelist(struct btree_trans *trans,
473 enum bch_watermark watermark,
474 struct bucket_alloc_state *s,
477 struct btree_iter iter;
479 struct open_bucket *ob = NULL;
480 u64 alloc_start = max_t(u64, ca->mi.first_bucket, READ_ONCE(ca->alloc_cursor));
481 u64 alloc_cursor = alloc_start;
484 BUG_ON(ca->new_fs_bucket_idx);
486 for_each_btree_key_norestart(trans, iter, BTREE_ID_freespace,
487 POS(ca->dev_idx, alloc_cursor), 0, k, ret) {
488 if (k.k->p.inode != ca->dev_idx)
491 for (alloc_cursor = max(alloc_cursor, bkey_start_offset(k.k));
492 alloc_cursor < k.k->p.offset;
494 ret = btree_trans_too_many_iters(trans);
502 ob = try_alloc_bucket(trans, ca, watermark,
503 alloc_cursor, s, k, cl);
505 iter.path->preserve = false;
513 bch2_trans_iter_exit(trans, &iter);
515 ca->alloc_cursor = alloc_cursor;
520 if (!ob && alloc_start > ca->mi.first_bucket) {
521 alloc_cursor = alloc_start = ca->mi.first_bucket;
529 * bch2_bucket_alloc_trans - allocate a single bucket from a specific device
530 * @trans: transaction object
531 * @ca: device to allocate from
532 * @watermark: how important is this allocation?
533 * @cl: if not NULL, closure to be used to wait if buckets not available
534 * @usage: for secondarily also returning the current device usage
536 * Returns: an open_bucket on success, or an ERR_PTR() on failure.
538 static struct open_bucket *bch2_bucket_alloc_trans(struct btree_trans *trans,
540 enum bch_watermark watermark,
542 struct bch_dev_usage *usage)
544 struct bch_fs *c = trans->c;
545 struct open_bucket *ob = NULL;
546 bool freespace = READ_ONCE(ca->mi.freespace_initialized);
548 struct bucket_alloc_state s = { 0 };
549 bool waiting = false;
551 bch2_dev_usage_read_fast(ca, usage);
552 avail = dev_buckets_free(ca, *usage, watermark);
554 if (usage->d[BCH_DATA_need_discard].buckets > avail)
557 if (usage->d[BCH_DATA_need_gc_gens].buckets > avail)
560 if (should_invalidate_buckets(ca, *usage))
561 bch2_do_invalidates(c);
564 if (cl && !waiting) {
565 closure_wait(&c->freelist_wait, cl);
570 if (!c->blocked_allocate)
571 c->blocked_allocate = local_clock();
573 ob = ERR_PTR(-BCH_ERR_freelist_empty);
578 closure_wake_up(&c->freelist_wait);
580 ob = likely(freespace)
581 ? bch2_bucket_alloc_freelist(trans, ca, watermark, &s, cl)
582 : bch2_bucket_alloc_early(trans, ca, watermark, &s, cl);
584 if (s.skipped_need_journal_commit * 2 > avail)
585 bch2_journal_flush_async(&c->journal, NULL);
587 if (!ob && freespace && c->curr_recovery_pass <= BCH_RECOVERY_PASS_check_alloc_info) {
593 ob = ERR_PTR(-BCH_ERR_no_buckets_found);
596 trace_and_count(c, bucket_alloc, ca,
597 bch2_watermarks[watermark],
599 usage->d[BCH_DATA_free].buckets,
601 bch2_copygc_wait_amount(c),
602 c->copygc_wait - atomic64_read(&c->io_clock[WRITE].now),
606 else if (!bch2_err_matches(PTR_ERR(ob), BCH_ERR_transaction_restart))
607 trace_and_count(c, bucket_alloc_fail, ca,
608 bch2_watermarks[watermark],
610 usage->d[BCH_DATA_free].buckets,
612 bch2_copygc_wait_amount(c),
613 c->copygc_wait - atomic64_read(&c->io_clock[WRITE].now),
616 bch2_err_str(PTR_ERR(ob)));
621 struct open_bucket *bch2_bucket_alloc(struct bch_fs *c, struct bch_dev *ca,
622 enum bch_watermark watermark,
625 struct bch_dev_usage usage;
626 struct open_bucket *ob;
628 bch2_trans_do(c, NULL, NULL, 0,
629 PTR_ERR_OR_ZERO(ob = bch2_bucket_alloc_trans(trans, ca, watermark,
634 static int __dev_stripe_cmp(struct dev_stripe_state *stripe,
635 unsigned l, unsigned r)
637 return ((stripe->next_alloc[l] > stripe->next_alloc[r]) -
638 (stripe->next_alloc[l] < stripe->next_alloc[r]));
641 #define dev_stripe_cmp(l, r) __dev_stripe_cmp(stripe, l, r)
643 struct dev_alloc_list bch2_dev_alloc_list(struct bch_fs *c,
644 struct dev_stripe_state *stripe,
645 struct bch_devs_mask *devs)
647 struct dev_alloc_list ret = { .nr = 0 };
650 for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX)
651 ret.devs[ret.nr++] = i;
653 bubble_sort(ret.devs, ret.nr, dev_stripe_cmp);
657 static inline void bch2_dev_stripe_increment_inlined(struct bch_dev *ca,
658 struct dev_stripe_state *stripe,
659 struct bch_dev_usage *usage)
661 u64 *v = stripe->next_alloc + ca->dev_idx;
662 u64 free_space = dev_buckets_available(ca, BCH_WATERMARK_normal);
663 u64 free_space_inv = free_space
664 ? div64_u64(1ULL << 48, free_space)
668 if (*v + free_space_inv >= *v)
669 *v += free_space_inv;
673 for (v = stripe->next_alloc;
674 v < stripe->next_alloc + ARRAY_SIZE(stripe->next_alloc); v++)
675 *v = *v < scale ? 0 : *v - scale;
678 void bch2_dev_stripe_increment(struct bch_dev *ca,
679 struct dev_stripe_state *stripe)
681 struct bch_dev_usage usage;
683 bch2_dev_usage_read_fast(ca, &usage);
684 bch2_dev_stripe_increment_inlined(ca, stripe, &usage);
687 static int add_new_bucket(struct bch_fs *c,
688 struct open_buckets *ptrs,
689 struct bch_devs_mask *devs_may_alloc,
690 unsigned nr_replicas,
691 unsigned *nr_effective,
694 struct open_bucket *ob)
696 unsigned durability =
697 bch_dev_bkey_exists(c, ob->dev)->mi.durability;
699 BUG_ON(*nr_effective >= nr_replicas);
701 __clear_bit(ob->dev, devs_may_alloc->d);
702 *nr_effective += durability;
703 *have_cache |= !durability;
705 ob_push(c, ptrs, ob);
707 if (*nr_effective >= nr_replicas)
714 int bch2_bucket_alloc_set_trans(struct btree_trans *trans,
715 struct open_buckets *ptrs,
716 struct dev_stripe_state *stripe,
717 struct bch_devs_mask *devs_may_alloc,
718 unsigned nr_replicas,
719 unsigned *nr_effective,
722 enum bch_data_type data_type,
723 enum bch_watermark watermark,
726 struct bch_fs *c = trans->c;
727 struct dev_alloc_list devs_sorted =
728 bch2_dev_alloc_list(c, stripe, devs_may_alloc);
731 int ret = -BCH_ERR_insufficient_devices;
734 BUG_ON(*nr_effective >= nr_replicas);
736 for (i = 0; i < devs_sorted.nr; i++) {
737 struct bch_dev_usage usage;
738 struct open_bucket *ob;
740 dev = devs_sorted.devs[i];
743 ca = rcu_dereference(c->devs[dev]);
745 percpu_ref_get(&ca->ref);
751 if (!ca->mi.durability && *have_cache) {
752 percpu_ref_put(&ca->ref);
756 ob = bch2_bucket_alloc_trans(trans, ca, watermark, cl, &usage);
758 bch2_dev_stripe_increment_inlined(ca, stripe, &usage);
759 percpu_ref_put(&ca->ref);
763 if (bch2_err_matches(ret, BCH_ERR_transaction_restart) || cl)
768 ob->data_type = data_type;
770 if (add_new_bucket(c, ptrs, devs_may_alloc,
771 nr_replicas, nr_effective,
772 have_cache, flags, ob)) {
781 /* Allocate from stripes: */
784 * if we can't allocate a new stripe because there are already too many
785 * partially filled stripes, force allocating from an existing stripe even when
786 * it's to a device we don't want:
789 static int bucket_alloc_from_stripe(struct btree_trans *trans,
790 struct open_buckets *ptrs,
791 struct write_point *wp,
792 struct bch_devs_mask *devs_may_alloc,
794 unsigned nr_replicas,
795 unsigned *nr_effective,
797 enum bch_watermark watermark,
801 struct bch_fs *c = trans->c;
802 struct dev_alloc_list devs_sorted;
803 struct ec_stripe_head *h;
804 struct open_bucket *ob;
811 if (ec_open_bucket(c, ptrs))
814 h = bch2_ec_stripe_head_get(trans, target, 0, nr_replicas - 1, watermark, cl);
820 devs_sorted = bch2_dev_alloc_list(c, &wp->stripe, devs_may_alloc);
822 for (i = 0; i < devs_sorted.nr; i++)
823 for (ec_idx = 0; ec_idx < h->s->nr_data; ec_idx++) {
824 if (!h->s->blocks[ec_idx])
827 ob = c->open_buckets + h->s->blocks[ec_idx];
828 if (ob->dev == devs_sorted.devs[i] &&
829 !test_and_set_bit(ec_idx, h->s->blocks_allocated))
836 ec_stripe_new_get(h->s, STRIPE_REF_io);
838 ret = add_new_bucket(c, ptrs, devs_may_alloc,
839 nr_replicas, nr_effective,
840 have_cache, flags, ob);
842 bch2_ec_stripe_head_put(c, h);
846 /* Sector allocator */
848 static bool want_bucket(struct bch_fs *c,
849 struct write_point *wp,
850 struct bch_devs_mask *devs_may_alloc,
851 bool *have_cache, bool ec,
852 struct open_bucket *ob)
854 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
856 if (!test_bit(ob->dev, devs_may_alloc->d))
859 if (ob->data_type != wp->data_type)
862 if (!ca->mi.durability &&
863 (wp->data_type == BCH_DATA_btree || ec || *have_cache))
866 if (ec != (ob->ec != NULL))
872 static int bucket_alloc_set_writepoint(struct bch_fs *c,
873 struct open_buckets *ptrs,
874 struct write_point *wp,
875 struct bch_devs_mask *devs_may_alloc,
876 unsigned nr_replicas,
877 unsigned *nr_effective,
879 bool ec, unsigned flags)
881 struct open_buckets ptrs_skip = { .nr = 0 };
882 struct open_bucket *ob;
886 open_bucket_for_each(c, &wp->ptrs, ob, i) {
887 if (!ret && want_bucket(c, wp, devs_may_alloc,
889 ret = add_new_bucket(c, ptrs, devs_may_alloc,
890 nr_replicas, nr_effective,
891 have_cache, flags, ob);
893 ob_push(c, &ptrs_skip, ob);
895 wp->ptrs = ptrs_skip;
900 static int bucket_alloc_set_partial(struct bch_fs *c,
901 struct open_buckets *ptrs,
902 struct write_point *wp,
903 struct bch_devs_mask *devs_may_alloc,
904 unsigned nr_replicas,
905 unsigned *nr_effective,
906 bool *have_cache, bool ec,
907 enum bch_watermark watermark,
912 if (!c->open_buckets_partial_nr)
915 spin_lock(&c->freelist_lock);
917 if (!c->open_buckets_partial_nr)
920 for (i = c->open_buckets_partial_nr - 1; i >= 0; --i) {
921 struct open_bucket *ob = c->open_buckets + c->open_buckets_partial[i];
923 if (want_bucket(c, wp, devs_may_alloc, have_cache, ec, ob)) {
924 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
925 struct bch_dev_usage usage;
928 bch2_dev_usage_read_fast(ca, &usage);
929 avail = dev_buckets_free(ca, usage, watermark);
933 array_remove_item(c->open_buckets_partial,
934 c->open_buckets_partial_nr,
936 ob->on_partial_list = false;
938 ret = add_new_bucket(c, ptrs, devs_may_alloc,
939 nr_replicas, nr_effective,
940 have_cache, flags, ob);
946 spin_unlock(&c->freelist_lock);
950 static int __open_bucket_add_buckets(struct btree_trans *trans,
951 struct open_buckets *ptrs,
952 struct write_point *wp,
953 struct bch_devs_list *devs_have,
956 unsigned nr_replicas,
957 unsigned *nr_effective,
959 enum bch_watermark watermark,
963 struct bch_fs *c = trans->c;
964 struct bch_devs_mask devs;
965 struct open_bucket *ob;
966 struct closure *cl = NULL;
970 devs = target_rw_devs(c, wp->data_type, target);
972 /* Don't allocate from devices we already have pointers to: */
973 for (i = 0; i < devs_have->nr; i++)
974 __clear_bit(devs_have->devs[i], devs.d);
976 open_bucket_for_each(c, ptrs, ob, i)
977 __clear_bit(ob->dev, devs.d);
979 if (erasure_code && ec_open_bucket(c, ptrs))
982 ret = bucket_alloc_set_writepoint(c, ptrs, wp, &devs,
983 nr_replicas, nr_effective,
984 have_cache, erasure_code, flags);
988 ret = bucket_alloc_set_partial(c, ptrs, wp, &devs,
989 nr_replicas, nr_effective,
990 have_cache, erasure_code, watermark, flags);
995 ret = bucket_alloc_from_stripe(trans, ptrs, wp, &devs,
997 nr_replicas, nr_effective,
999 watermark, flags, _cl);
1003 * Try nonblocking first, so that if one device is full we'll try from
1006 ret = bch2_bucket_alloc_set_trans(trans, ptrs, &wp->stripe, &devs,
1007 nr_replicas, nr_effective, have_cache,
1008 flags, wp->data_type, watermark, cl);
1010 !bch2_err_matches(ret, BCH_ERR_transaction_restart) &&
1011 !bch2_err_matches(ret, BCH_ERR_insufficient_devices) &&
1014 goto retry_blocking;
1021 static int open_bucket_add_buckets(struct btree_trans *trans,
1022 struct open_buckets *ptrs,
1023 struct write_point *wp,
1024 struct bch_devs_list *devs_have,
1026 unsigned erasure_code,
1027 unsigned nr_replicas,
1028 unsigned *nr_effective,
1030 enum bch_watermark watermark,
1037 ret = __open_bucket_add_buckets(trans, ptrs, wp,
1038 devs_have, target, erasure_code,
1039 nr_replicas, nr_effective, have_cache,
1040 watermark, flags, cl);
1041 if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
1042 bch2_err_matches(ret, BCH_ERR_operation_blocked) ||
1043 bch2_err_matches(ret, BCH_ERR_freelist_empty) ||
1044 bch2_err_matches(ret, BCH_ERR_open_buckets_empty))
1046 if (*nr_effective >= nr_replicas)
1050 ret = __open_bucket_add_buckets(trans, ptrs, wp,
1051 devs_have, target, false,
1052 nr_replicas, nr_effective, have_cache,
1053 watermark, flags, cl);
1054 return ret < 0 ? ret : 0;
1058 * should_drop_bucket - check if this is open_bucket should go away
1059 * @ob: open_bucket to predicate on
1060 * @c: filesystem handle
1061 * @ca: if set, we're killing buckets for a particular device
1062 * @ec: if true, we're shutting down erasure coding and killing all ec
1064 * otherwise, return true
1065 * Returns: true if we should kill this open_bucket
1067 * We're killing open_buckets because we're shutting down a device, erasure
1068 * coding, or the entire filesystem - check if this open_bucket matches:
1070 static bool should_drop_bucket(struct open_bucket *ob, struct bch_fs *c,
1071 struct bch_dev *ca, bool ec)
1074 return ob->ec != NULL;
1076 bool drop = ob->dev == ca->dev_idx;
1077 struct open_bucket *ob2;
1080 if (!drop && ob->ec) {
1083 mutex_lock(&ob->ec->lock);
1084 nr_blocks = bkey_i_to_stripe(&ob->ec->new_stripe.key)->v.nr_blocks;
1086 for (i = 0; i < nr_blocks; i++) {
1087 if (!ob->ec->blocks[i])
1090 ob2 = c->open_buckets + ob->ec->blocks[i];
1091 drop |= ob2->dev == ca->dev_idx;
1093 mutex_unlock(&ob->ec->lock);
1102 static void bch2_writepoint_stop(struct bch_fs *c, struct bch_dev *ca,
1103 bool ec, struct write_point *wp)
1105 struct open_buckets ptrs = { .nr = 0 };
1106 struct open_bucket *ob;
1109 mutex_lock(&wp->lock);
1110 open_bucket_for_each(c, &wp->ptrs, ob, i)
1111 if (should_drop_bucket(ob, c, ca, ec))
1112 bch2_open_bucket_put(c, ob);
1114 ob_push(c, &ptrs, ob);
1116 mutex_unlock(&wp->lock);
1119 void bch2_open_buckets_stop(struct bch_fs *c, struct bch_dev *ca,
1124 /* Next, close write points that point to this device... */
1125 for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1126 bch2_writepoint_stop(c, ca, ec, &c->write_points[i]);
1128 bch2_writepoint_stop(c, ca, ec, &c->copygc_write_point);
1129 bch2_writepoint_stop(c, ca, ec, &c->rebalance_write_point);
1130 bch2_writepoint_stop(c, ca, ec, &c->btree_write_point);
1132 mutex_lock(&c->btree_reserve_cache_lock);
1133 while (c->btree_reserve_cache_nr) {
1134 struct btree_alloc *a =
1135 &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1137 bch2_open_buckets_put(c, &a->ob);
1139 mutex_unlock(&c->btree_reserve_cache_lock);
1141 spin_lock(&c->freelist_lock);
1143 while (i < c->open_buckets_partial_nr) {
1144 struct open_bucket *ob =
1145 c->open_buckets + c->open_buckets_partial[i];
1147 if (should_drop_bucket(ob, c, ca, ec)) {
1148 --c->open_buckets_partial_nr;
1149 swap(c->open_buckets_partial[i],
1150 c->open_buckets_partial[c->open_buckets_partial_nr]);
1151 ob->on_partial_list = false;
1152 spin_unlock(&c->freelist_lock);
1153 bch2_open_bucket_put(c, ob);
1154 spin_lock(&c->freelist_lock);
1159 spin_unlock(&c->freelist_lock);
1161 bch2_ec_stop_dev(c, ca);
1164 static inline struct hlist_head *writepoint_hash(struct bch_fs *c,
1165 unsigned long write_point)
1168 hash_long(write_point, ilog2(ARRAY_SIZE(c->write_points_hash)));
1170 return &c->write_points_hash[hash];
1173 static struct write_point *__writepoint_find(struct hlist_head *head,
1174 unsigned long write_point)
1176 struct write_point *wp;
1179 hlist_for_each_entry_rcu(wp, head, node)
1180 if (wp->write_point == write_point)
1188 static inline bool too_many_writepoints(struct bch_fs *c, unsigned factor)
1190 u64 stranded = c->write_points_nr * c->bucket_size_max;
1191 u64 free = bch2_fs_usage_read_short(c).free;
1193 return stranded * factor > free;
1196 static bool try_increase_writepoints(struct bch_fs *c)
1198 struct write_point *wp;
1200 if (c->write_points_nr == ARRAY_SIZE(c->write_points) ||
1201 too_many_writepoints(c, 32))
1204 wp = c->write_points + c->write_points_nr++;
1205 hlist_add_head_rcu(&wp->node, writepoint_hash(c, wp->write_point));
1209 static bool try_decrease_writepoints(struct btree_trans *trans, unsigned old_nr)
1211 struct bch_fs *c = trans->c;
1212 struct write_point *wp;
1213 struct open_bucket *ob;
1216 mutex_lock(&c->write_points_hash_lock);
1217 if (c->write_points_nr < old_nr) {
1218 mutex_unlock(&c->write_points_hash_lock);
1222 if (c->write_points_nr == 1 ||
1223 !too_many_writepoints(c, 8)) {
1224 mutex_unlock(&c->write_points_hash_lock);
1228 wp = c->write_points + --c->write_points_nr;
1230 hlist_del_rcu(&wp->node);
1231 mutex_unlock(&c->write_points_hash_lock);
1233 bch2_trans_mutex_lock_norelock(trans, &wp->lock);
1234 open_bucket_for_each(c, &wp->ptrs, ob, i)
1235 open_bucket_free_unused(c, ob);
1237 mutex_unlock(&wp->lock);
1241 static struct write_point *writepoint_find(struct btree_trans *trans,
1242 unsigned long write_point)
1244 struct bch_fs *c = trans->c;
1245 struct write_point *wp, *oldest;
1246 struct hlist_head *head;
1248 if (!(write_point & 1UL)) {
1249 wp = (struct write_point *) write_point;
1250 bch2_trans_mutex_lock_norelock(trans, &wp->lock);
1254 head = writepoint_hash(c, write_point);
1256 wp = __writepoint_find(head, write_point);
1259 bch2_trans_mutex_lock_norelock(trans, &wp->lock);
1260 if (wp->write_point == write_point)
1262 mutex_unlock(&wp->lock);
1265 restart_find_oldest:
1267 for (wp = c->write_points;
1268 wp < c->write_points + c->write_points_nr; wp++)
1269 if (!oldest || time_before64(wp->last_used, oldest->last_used))
1272 bch2_trans_mutex_lock_norelock(trans, &oldest->lock);
1273 bch2_trans_mutex_lock_norelock(trans, &c->write_points_hash_lock);
1274 if (oldest >= c->write_points + c->write_points_nr ||
1275 try_increase_writepoints(c)) {
1276 mutex_unlock(&c->write_points_hash_lock);
1277 mutex_unlock(&oldest->lock);
1278 goto restart_find_oldest;
1281 wp = __writepoint_find(head, write_point);
1282 if (wp && wp != oldest) {
1283 mutex_unlock(&c->write_points_hash_lock);
1284 mutex_unlock(&oldest->lock);
1289 hlist_del_rcu(&wp->node);
1290 wp->write_point = write_point;
1291 hlist_add_head_rcu(&wp->node, head);
1292 mutex_unlock(&c->write_points_hash_lock);
1294 wp->last_used = local_clock();
1298 static noinline void
1299 deallocate_extra_replicas(struct bch_fs *c,
1300 struct open_buckets *ptrs,
1301 struct open_buckets *ptrs_no_use,
1302 unsigned extra_replicas)
1304 struct open_buckets ptrs2 = { 0 };
1305 struct open_bucket *ob;
1308 open_bucket_for_each(c, ptrs, ob, i) {
1309 unsigned d = bch_dev_bkey_exists(c, ob->dev)->mi.durability;
1311 if (d && d <= extra_replicas) {
1312 extra_replicas -= d;
1313 ob_push(c, ptrs_no_use, ob);
1315 ob_push(c, &ptrs2, ob);
1323 * Get us an open_bucket we can allocate from, return with it locked:
1325 int bch2_alloc_sectors_start_trans(struct btree_trans *trans,
1327 unsigned erasure_code,
1328 struct write_point_specifier write_point,
1329 struct bch_devs_list *devs_have,
1330 unsigned nr_replicas,
1331 unsigned nr_replicas_required,
1332 enum bch_watermark watermark,
1335 struct write_point **wp_ret)
1337 struct bch_fs *c = trans->c;
1338 struct write_point *wp;
1339 struct open_bucket *ob;
1340 struct open_buckets ptrs;
1341 unsigned nr_effective, write_points_nr;
1346 if (!IS_ENABLED(CONFIG_BCACHEFS_ERASURE_CODING))
1347 erasure_code = false;
1349 BUG_ON(flags & BCH_WRITE_ONLY_SPECIFIED_DEVS);
1351 BUG_ON(!nr_replicas || !nr_replicas_required);
1355 write_points_nr = c->write_points_nr;
1358 *wp_ret = wp = writepoint_find(trans, write_point.v);
1360 /* metadata may not allocate on cache devices: */
1361 if (wp->data_type != BCH_DATA_user)
1364 if (target && !(flags & BCH_WRITE_ONLY_SPECIFIED_DEVS)) {
1365 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1366 target, erasure_code,
1367 nr_replicas, &nr_effective,
1368 &have_cache, watermark,
1371 bch2_err_matches(ret, BCH_ERR_transaction_restart))
1374 /* Don't retry from all devices if we're out of open buckets: */
1375 if (bch2_err_matches(ret, BCH_ERR_open_buckets_empty))
1376 goto allocate_blocking;
1379 * Only try to allocate cache (durability = 0 devices) from the
1384 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1386 nr_replicas, &nr_effective,
1387 &have_cache, watermark,
1391 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1392 target, erasure_code,
1393 nr_replicas, &nr_effective,
1394 &have_cache, watermark,
1398 BUG_ON(!ret && nr_effective < nr_replicas);
1400 if (erasure_code && !ec_open_bucket(c, &ptrs))
1401 pr_debug("failed to get ec bucket: ret %u", ret);
1403 if (ret == -BCH_ERR_insufficient_devices &&
1404 nr_effective >= nr_replicas_required)
1410 if (nr_effective > nr_replicas)
1411 deallocate_extra_replicas(c, &ptrs, &wp->ptrs, nr_effective - nr_replicas);
1413 /* Free buckets we didn't use: */
1414 open_bucket_for_each(c, &wp->ptrs, ob, i)
1415 open_bucket_free_unused(c, ob);
1419 wp->sectors_free = UINT_MAX;
1421 open_bucket_for_each(c, &wp->ptrs, ob, i)
1422 wp->sectors_free = min(wp->sectors_free, ob->sectors_free);
1424 BUG_ON(!wp->sectors_free || wp->sectors_free == UINT_MAX);
1428 open_bucket_for_each(c, &wp->ptrs, ob, i)
1429 if (ptrs.nr < ARRAY_SIZE(ptrs.v))
1430 ob_push(c, &ptrs, ob);
1432 open_bucket_free_unused(c, ob);
1435 mutex_unlock(&wp->lock);
1437 if (bch2_err_matches(ret, BCH_ERR_freelist_empty) &&
1438 try_decrease_writepoints(trans, write_points_nr))
1441 if (bch2_err_matches(ret, BCH_ERR_open_buckets_empty) ||
1442 bch2_err_matches(ret, BCH_ERR_freelist_empty))
1444 ? -BCH_ERR_bucket_alloc_blocked
1445 : -BCH_ERR_ENOSPC_bucket_alloc;
1450 struct bch_extent_ptr bch2_ob_ptr(struct bch_fs *c, struct open_bucket *ob)
1452 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
1454 return (struct bch_extent_ptr) {
1455 .type = 1 << BCH_EXTENT_ENTRY_ptr,
1458 .offset = bucket_to_sector(ca, ob->bucket) +
1459 ca->mi.bucket_size -
1464 void bch2_alloc_sectors_append_ptrs(struct bch_fs *c, struct write_point *wp,
1465 struct bkey_i *k, unsigned sectors,
1468 bch2_alloc_sectors_append_ptrs_inlined(c, wp, k, sectors, cached);
1472 * Append pointers to the space we just allocated to @k, and mark @sectors space
1473 * as allocated out of @ob
1475 void bch2_alloc_sectors_done(struct bch_fs *c, struct write_point *wp)
1477 bch2_alloc_sectors_done_inlined(c, wp);
1480 static inline void writepoint_init(struct write_point *wp,
1481 enum bch_data_type type)
1483 mutex_init(&wp->lock);
1484 wp->data_type = type;
1486 INIT_WORK(&wp->index_update_work, bch2_write_point_do_index_updates);
1487 INIT_LIST_HEAD(&wp->writes);
1488 spin_lock_init(&wp->writes_lock);
1491 void bch2_fs_allocator_foreground_init(struct bch_fs *c)
1493 struct open_bucket *ob;
1494 struct write_point *wp;
1496 mutex_init(&c->write_points_hash_lock);
1497 c->write_points_nr = ARRAY_SIZE(c->write_points);
1499 /* open bucket 0 is a sentinal NULL: */
1500 spin_lock_init(&c->open_buckets[0].lock);
1502 for (ob = c->open_buckets + 1;
1503 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets); ob++) {
1504 spin_lock_init(&ob->lock);
1505 c->open_buckets_nr_free++;
1507 ob->freelist = c->open_buckets_freelist;
1508 c->open_buckets_freelist = ob - c->open_buckets;
1511 writepoint_init(&c->btree_write_point, BCH_DATA_btree);
1512 writepoint_init(&c->rebalance_write_point, BCH_DATA_user);
1513 writepoint_init(&c->copygc_write_point, BCH_DATA_user);
1515 for (wp = c->write_points;
1516 wp < c->write_points + c->write_points_nr; wp++) {
1517 writepoint_init(wp, BCH_DATA_user);
1519 wp->last_used = local_clock();
1520 wp->write_point = (unsigned long) wp;
1521 hlist_add_head_rcu(&wp->node,
1522 writepoint_hash(c, wp->write_point));
1526 static void bch2_open_bucket_to_text(struct printbuf *out, struct bch_fs *c, struct open_bucket *ob)
1528 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
1529 unsigned data_type = ob->data_type;
1530 barrier(); /* READ_ONCE() doesn't work on bitfields */
1532 prt_printf(out, "%zu ref %u %s %u:%llu gen %u allocated %u/%u",
1533 ob - c->open_buckets,
1534 atomic_read(&ob->pin),
1535 data_type < BCH_DATA_NR ? bch2_data_types[data_type] : "invalid data type",
1536 ob->dev, ob->bucket, ob->gen,
1537 ca->mi.bucket_size - ob->sectors_free, ca->mi.bucket_size);
1539 prt_printf(out, " ec idx %llu", ob->ec->idx);
1540 if (ob->on_partial_list)
1541 prt_str(out, " partial");
1545 void bch2_open_buckets_to_text(struct printbuf *out, struct bch_fs *c)
1547 struct open_bucket *ob;
1551 for (ob = c->open_buckets;
1552 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1554 spin_lock(&ob->lock);
1555 if (ob->valid && !ob->on_partial_list)
1556 bch2_open_bucket_to_text(out, c, ob);
1557 spin_unlock(&ob->lock);
1563 void bch2_open_buckets_partial_to_text(struct printbuf *out, struct bch_fs *c)
1568 spin_lock(&c->freelist_lock);
1570 for (i = 0; i < c->open_buckets_partial_nr; i++)
1571 bch2_open_bucket_to_text(out, c,
1572 c->open_buckets + c->open_buckets_partial[i]);
1574 spin_unlock(&c->freelist_lock);
1578 static const char * const bch2_write_point_states[] = {
1580 WRITE_POINT_STATES()
1585 static void bch2_write_point_to_text(struct printbuf *out, struct bch_fs *c,
1586 struct write_point *wp)
1588 struct open_bucket *ob;
1591 prt_printf(out, "%lu: ", wp->write_point);
1592 prt_human_readable_u64(out, wp->sectors_allocated);
1594 prt_printf(out, " last wrote: ");
1595 bch2_pr_time_units(out, sched_clock() - wp->last_used);
1597 for (i = 0; i < WRITE_POINT_STATE_NR; i++) {
1598 prt_printf(out, " %s: ", bch2_write_point_states[i]);
1599 bch2_pr_time_units(out, wp->time[i]);
1604 printbuf_indent_add(out, 2);
1605 open_bucket_for_each(c, &wp->ptrs, ob, i)
1606 bch2_open_bucket_to_text(out, c, ob);
1607 printbuf_indent_sub(out, 2);
1610 void bch2_write_points_to_text(struct printbuf *out, struct bch_fs *c)
1612 struct write_point *wp;
1614 prt_str(out, "Foreground write points\n");
1615 for (wp = c->write_points;
1616 wp < c->write_points + ARRAY_SIZE(c->write_points);
1618 bch2_write_point_to_text(out, c, wp);
1620 prt_str(out, "Copygc write point\n");
1621 bch2_write_point_to_text(out, c, &c->copygc_write_point);
1623 prt_str(out, "Rebalance write point\n");
1624 bch2_write_point_to_text(out, c, &c->rebalance_write_point);
1626 prt_str(out, "Btree write point\n");
1627 bch2_write_point_to_text(out, c, &c->btree_write_point);