1 // SPDX-License-Identifier: GPL-2.0
4 #include "btree_key_cache.h"
8 #include "journal_io.h"
9 #include "journal_reclaim.h"
13 #include <linux/kthread.h>
14 #include <linux/sched/mm.h>
15 #include <trace/events/bcachefs.h>
17 /* Free space calculations: */
19 static unsigned journal_space_from(struct journal_device *ja,
20 enum journal_space_from from)
23 case journal_space_discarded:
24 return ja->discard_idx;
25 case journal_space_clean_ondisk:
26 return ja->dirty_idx_ondisk;
27 case journal_space_clean:
34 unsigned bch2_journal_dev_buckets_available(struct journal *j,
35 struct journal_device *ja,
36 enum journal_space_from from)
38 unsigned available = (journal_space_from(ja, from) -
39 ja->cur_idx - 1 + ja->nr) % ja->nr;
42 * Don't use the last bucket unless writing the new last_seq
43 * will make another bucket available:
45 if (available && ja->dirty_idx_ondisk == ja->dirty_idx)
51 static void journal_set_remaining(struct journal *j, unsigned u64s_remaining)
53 union journal_preres_state old, new;
54 u64 v = atomic64_read(&j->prereserved.counter);
58 new.remaining = u64s_remaining;
59 } while ((v = atomic64_cmpxchg(&j->prereserved.counter,
60 old.v, new.v)) != old.v);
63 static struct journal_space
64 journal_dev_space_available(struct journal *j, struct bch_dev *ca,
65 enum journal_space_from from)
67 struct journal_device *ja = &ca->journal;
68 unsigned sectors, buckets, unwritten;
71 if (from == journal_space_total)
72 return (struct journal_space) {
73 .next_entry = ca->mi.bucket_size,
74 .total = ca->mi.bucket_size * ja->nr,
77 buckets = bch2_journal_dev_buckets_available(j, ja, from);
78 sectors = ja->sectors_free;
81 * We that we don't allocate the space for a journal entry
82 * until we write it out - thus, account for it here:
84 for (seq = journal_last_unwritten_seq(j);
85 seq <= journal_cur_seq(j);
87 unwritten = j->buf[seq & JOURNAL_BUF_MASK].sectors;
92 /* entry won't fit on this device, skip: */
93 if (unwritten > ca->mi.bucket_size)
96 if (unwritten >= sectors) {
103 sectors = ca->mi.bucket_size;
106 sectors -= unwritten;
109 if (sectors < ca->mi.bucket_size && buckets) {
111 sectors = ca->mi.bucket_size;
114 return (struct journal_space) {
115 .next_entry = sectors,
116 .total = sectors + buckets * ca->mi.bucket_size,
120 static struct journal_space __journal_space_available(struct journal *j, unsigned nr_devs_want,
121 enum journal_space_from from)
123 struct bch_fs *c = container_of(j, struct bch_fs, journal);
125 unsigned i, pos, nr_devs = 0;
126 struct journal_space space, dev_space[BCH_SB_MEMBERS_MAX];
128 BUG_ON(nr_devs_want > ARRAY_SIZE(dev_space));
131 for_each_member_device_rcu(ca, c, i,
132 &c->rw_devs[BCH_DATA_journal]) {
136 space = journal_dev_space_available(j, ca, from);
137 if (!space.next_entry)
140 for (pos = 0; pos < nr_devs; pos++)
141 if (space.total > dev_space[pos].total)
144 array_insert_item(dev_space, nr_devs, pos, space);
148 if (nr_devs < nr_devs_want)
149 return (struct journal_space) { 0, 0 };
152 * We sorted largest to smallest, and we want the smallest out of the
153 * @nr_devs_want largest devices:
155 return dev_space[nr_devs_want - 1];
158 void bch2_journal_space_available(struct journal *j)
160 struct bch_fs *c = container_of(j, struct bch_fs, journal);
162 unsigned clean, clean_ondisk, total;
163 s64 u64s_remaining = 0;
164 unsigned max_entry_size = min(j->buf[0].buf_size >> 9,
165 j->buf[1].buf_size >> 9);
166 unsigned i, nr_online = 0, nr_devs_want;
167 bool can_discard = false;
170 lockdep_assert_held(&j->lock);
173 for_each_member_device_rcu(ca, c, i,
174 &c->rw_devs[BCH_DATA_journal]) {
175 struct journal_device *ja = &ca->journal;
180 while (ja->dirty_idx != ja->cur_idx &&
181 ja->bucket_seq[ja->dirty_idx] < journal_last_seq(j))
182 ja->dirty_idx = (ja->dirty_idx + 1) % ja->nr;
184 while (ja->dirty_idx_ondisk != ja->dirty_idx &&
185 ja->bucket_seq[ja->dirty_idx_ondisk] < j->last_seq_ondisk)
186 ja->dirty_idx_ondisk = (ja->dirty_idx_ondisk + 1) % ja->nr;
188 if (ja->discard_idx != ja->dirty_idx_ondisk)
191 max_entry_size = min_t(unsigned, max_entry_size, ca->mi.bucket_size);
196 j->can_discard = can_discard;
198 if (nr_online < c->opts.metadata_replicas_required) {
199 ret = JOURNAL_ERR_insufficient_devices;
203 nr_devs_want = min_t(unsigned, nr_online, c->opts.metadata_replicas);
205 for (i = 0; i < journal_space_nr; i++)
206 j->space[i] = __journal_space_available(j, nr_devs_want, i);
208 clean_ondisk = j->space[journal_space_clean_ondisk].total;
209 clean = j->space[journal_space_clean].total;
210 total = j->space[journal_space_total].total;
213 journal_cur_seq(j) == j->seq_ondisk) {
214 struct printbuf buf = PRINTBUF;
216 __bch2_journal_debug_to_text(&buf, j);
217 bch_err(c, "journal stuck\n%s", buf.buf);
221 * Hack: bch2_fatal_error() calls bch2_journal_halt() which
222 * takes journal lock:
224 spin_unlock(&j->lock);
228 ret = JOURNAL_ERR_journal_stuck;
229 } else if (!j->space[journal_space_discarded].next_entry)
230 ret = JOURNAL_ERR_journal_full;
232 if ((j->space[journal_space_clean_ondisk].next_entry <
233 j->space[journal_space_clean_ondisk].total) &&
234 (clean - clean_ondisk <= total / 8) &&
235 (clean_ondisk * 2 > clean))
236 set_bit(JOURNAL_MAY_SKIP_FLUSH, &j->flags);
238 clear_bit(JOURNAL_MAY_SKIP_FLUSH, &j->flags);
240 u64s_remaining = (u64) clean << 6;
241 u64s_remaining -= (u64) total << 3;
242 u64s_remaining = max(0LL, u64s_remaining);
244 u64s_remaining = min_t(u64, u64s_remaining, U32_MAX);
246 j->cur_entry_sectors = !ret ? j->space[journal_space_discarded].next_entry : 0;
247 j->cur_entry_error = ret;
248 journal_set_remaining(j, u64s_remaining);
249 journal_set_watermark(j);
255 /* Discards - last part of journal reclaim: */
257 static bool should_discard_bucket(struct journal *j, struct journal_device *ja)
262 ret = ja->discard_idx != ja->dirty_idx_ondisk;
263 spin_unlock(&j->lock);
269 * Advance ja->discard_idx as long as it points to buckets that are no longer
270 * dirty, issuing discards if necessary:
272 void bch2_journal_do_discards(struct journal *j)
274 struct bch_fs *c = container_of(j, struct bch_fs, journal);
278 mutex_lock(&j->discard_lock);
280 for_each_rw_member(ca, c, iter) {
281 struct journal_device *ja = &ca->journal;
283 while (should_discard_bucket(j, ja)) {
284 if (!c->opts.nochanges &&
286 bdev_max_discard_sectors(ca->disk_sb.bdev))
287 blkdev_issue_discard(ca->disk_sb.bdev,
289 ja->buckets[ja->discard_idx]),
290 ca->mi.bucket_size, GFP_NOIO);
293 ja->discard_idx = (ja->discard_idx + 1) % ja->nr;
295 bch2_journal_space_available(j);
296 spin_unlock(&j->lock);
300 mutex_unlock(&j->discard_lock);
304 * Journal entry pinning - machinery for holding a reference on a given journal
305 * entry, holding it open to ensure it gets replayed during recovery:
308 static void bch2_journal_reclaim_fast(struct journal *j)
310 struct journal_entry_pin_list temp;
313 lockdep_assert_held(&j->lock);
316 * Unpin journal entries whose reference counts reached zero, meaning
317 * all btree nodes got written out
319 while (!fifo_empty(&j->pin) &&
320 !atomic_read(&fifo_peek_front(&j->pin).count)) {
321 BUG_ON(!list_empty(&fifo_peek_front(&j->pin).list));
322 BUG_ON(!list_empty(&fifo_peek_front(&j->pin).flushed));
323 BUG_ON(!fifo_pop(&j->pin, temp));
328 bch2_journal_space_available(j);
331 void __bch2_journal_pin_put(struct journal *j, u64 seq)
333 struct journal_entry_pin_list *pin_list = journal_seq_pin(j, seq);
335 if (atomic_dec_and_test(&pin_list->count))
336 bch2_journal_reclaim_fast(j);
339 void bch2_journal_pin_put(struct journal *j, u64 seq)
341 struct journal_entry_pin_list *pin_list = journal_seq_pin(j, seq);
343 if (atomic_dec_and_test(&pin_list->count)) {
345 bch2_journal_reclaim_fast(j);
346 spin_unlock(&j->lock);
350 static inline bool __journal_pin_drop(struct journal *j,
351 struct journal_entry_pin *pin)
353 struct journal_entry_pin_list *pin_list;
355 if (!journal_pin_active(pin))
358 if (j->flush_in_progress == pin)
359 j->flush_in_progress_dropped = true;
361 pin_list = journal_seq_pin(j, pin->seq);
363 list_del_init(&pin->list);
366 * Unpinning a journal entry make make journal_next_bucket() succeed, if
367 * writing a new last_seq will now make another bucket available:
369 return atomic_dec_and_test(&pin_list->count) &&
370 pin_list == &fifo_peek_front(&j->pin);
373 void bch2_journal_pin_drop(struct journal *j,
374 struct journal_entry_pin *pin)
377 if (__journal_pin_drop(j, pin))
378 bch2_journal_reclaim_fast(j);
379 spin_unlock(&j->lock);
382 void bch2_journal_pin_set(struct journal *j, u64 seq,
383 struct journal_entry_pin *pin,
384 journal_pin_flush_fn flush_fn)
386 struct journal_entry_pin_list *pin_list;
391 if (seq < journal_last_seq(j)) {
393 * bch2_journal_pin_copy() raced with bch2_journal_pin_drop() on
394 * the src pin - with the pin dropped, the entry to pin might no
395 * longer to exist, but that means there's no longer anything to
396 * copy and we can bail out here:
398 spin_unlock(&j->lock);
402 pin_list = journal_seq_pin(j, seq);
404 reclaim = __journal_pin_drop(j, pin);
406 atomic_inc(&pin_list->count);
408 pin->flush = flush_fn;
410 if (flush_fn == bch2_btree_key_cache_journal_flush)
411 list_add(&pin->list, &pin_list->key_cache_list);
413 list_add(&pin->list, &pin_list->list);
415 list_add(&pin->list, &pin_list->flushed);
418 bch2_journal_reclaim_fast(j);
419 spin_unlock(&j->lock);
422 * If the journal is currently full, we might want to call flush_fn
429 * bch2_journal_pin_flush: ensure journal pin callback is no longer running
431 void bch2_journal_pin_flush(struct journal *j, struct journal_entry_pin *pin)
433 BUG_ON(journal_pin_active(pin));
435 wait_event(j->pin_flush_wait, j->flush_in_progress != pin);
439 * Journal reclaim: flush references to open journal entries to reclaim space in
442 * May be done by the journal code in the background as needed to free up space
443 * for more journal entries, or as part of doing a clean shutdown, or to migrate
444 * data off of a specific device:
447 static struct journal_entry_pin *
448 journal_get_next_pin(struct journal *j,
451 u64 max_seq, u64 *seq)
453 struct journal_entry_pin_list *pin_list;
454 struct journal_entry_pin *ret = NULL;
456 fifo_for_each_entry_ptr(pin_list, &j->pin, *seq) {
457 if (*seq > max_seq && !get_any && !get_key_cache)
460 if (*seq <= max_seq || get_any) {
461 ret = list_first_entry_or_null(&pin_list->list,
462 struct journal_entry_pin, list);
467 if (*seq <= max_seq || get_any || get_key_cache) {
468 ret = list_first_entry_or_null(&pin_list->key_cache_list,
469 struct journal_entry_pin, list);
478 /* returns true if we did work */
479 static size_t journal_flush_pins(struct journal *j, u64 seq_to_flush,
481 unsigned min_key_cache)
483 struct journal_entry_pin *pin;
484 size_t nr_flushed = 0;
485 journal_pin_flush_fn flush_fn;
489 lockdep_assert_held(&j->reclaim_lock);
494 j->last_flushed = jiffies;
497 pin = journal_get_next_pin(j,
502 BUG_ON(j->flush_in_progress);
503 j->flush_in_progress = pin;
504 j->flush_in_progress_dropped = false;
505 flush_fn = pin->flush;
507 spin_unlock(&j->lock);
512 if (min_key_cache && pin->flush == bch2_btree_key_cache_journal_flush)
518 err = flush_fn(j, pin, seq);
521 /* Pin might have been dropped or rearmed: */
522 if (likely(!err && !j->flush_in_progress_dropped))
523 list_move(&pin->list, &journal_seq_pin(j, seq)->flushed);
524 j->flush_in_progress = NULL;
525 j->flush_in_progress_dropped = false;
526 spin_unlock(&j->lock);
528 wake_up(&j->pin_flush_wait);
539 static u64 journal_seq_to_flush(struct journal *j)
541 struct bch_fs *c = container_of(j, struct bch_fs, journal);
543 u64 seq_to_flush = 0;
548 for_each_rw_member(ca, c, iter) {
549 struct journal_device *ja = &ca->journal;
550 unsigned nr_buckets, bucket_to_flush;
555 /* Try to keep the journal at most half full: */
556 nr_buckets = ja->nr / 2;
558 /* And include pre-reservations: */
559 nr_buckets += DIV_ROUND_UP(j->prereserved.reserved,
560 (ca->mi.bucket_size << 6) -
561 journal_entry_overhead(j));
563 nr_buckets = min(nr_buckets, ja->nr);
565 bucket_to_flush = (ja->cur_idx + nr_buckets) % ja->nr;
566 seq_to_flush = max(seq_to_flush,
567 ja->bucket_seq[bucket_to_flush]);
570 /* Also flush if the pin fifo is more than half full */
571 seq_to_flush = max_t(s64, seq_to_flush,
572 (s64) journal_cur_seq(j) -
574 spin_unlock(&j->lock);
580 * bch2_journal_reclaim - free up journal buckets
582 * Background journal reclaim writes out btree nodes. It should be run
583 * early enough so that we never completely run out of journal buckets.
585 * High watermarks for triggering background reclaim:
586 * - FIFO has fewer than 512 entries left
587 * - fewer than 25% journal buckets free
589 * Background reclaim runs until low watermarks are reached:
590 * - FIFO has more than 1024 entries left
591 * - more than 50% journal buckets free
593 * As long as a reclaim can complete in the time it takes to fill up
594 * 512 journal entries or 25% of all journal buckets, then
595 * journal_next_bucket() should not stall.
597 static int __bch2_journal_reclaim(struct journal *j, bool direct, bool kicked)
599 struct bch_fs *c = container_of(j, struct bch_fs, journal);
600 bool kthread = (current->flags & PF_KTHREAD) != 0;
602 size_t min_nr, min_key_cache, nr_flushed;
607 * We can't invoke memory reclaim while holding the reclaim_lock -
608 * journal reclaim is required to make progress for memory reclaim
609 * (cleaning the caches), so we can't get stuck in memory reclaim while
610 * we're holding the reclaim lock:
612 lockdep_assert_held(&j->reclaim_lock);
613 flags = memalloc_noreclaim_save();
616 if (kthread && kthread_should_stop())
619 if (bch2_journal_error(j)) {
624 bch2_journal_do_discards(j);
626 seq_to_flush = journal_seq_to_flush(j);
630 * If it's been longer than j->reclaim_delay_ms since we last flushed,
631 * make sure to flush at least one journal pin:
633 if (time_after(jiffies, j->last_flushed +
634 msecs_to_jiffies(c->opts.journal_reclaim_delay)))
637 if (j->prereserved.reserved * 4 > j->prereserved.remaining)
640 if (fifo_free(&j->pin) <= 32)
643 if (atomic_read(&c->btree_cache.dirty) * 2 > c->btree_cache.used)
646 min_key_cache = min(bch2_nr_btree_keys_need_flush(c), (size_t) 128);
648 trace_and_count(c, journal_reclaim_start, c,
650 min_nr, min_key_cache,
651 j->prereserved.reserved,
652 j->prereserved.remaining,
653 atomic_read(&c->btree_cache.dirty),
655 atomic_long_read(&c->btree_key_cache.nr_dirty),
656 atomic_long_read(&c->btree_key_cache.nr_keys));
658 nr_flushed = journal_flush_pins(j, seq_to_flush,
659 min_nr, min_key_cache);
662 j->nr_direct_reclaim += nr_flushed;
664 j->nr_background_reclaim += nr_flushed;
665 trace_and_count(c, journal_reclaim_finish, c, nr_flushed);
668 wake_up(&j->reclaim_wait);
669 } while ((min_nr || min_key_cache) && nr_flushed && !direct);
671 memalloc_noreclaim_restore(flags);
676 int bch2_journal_reclaim(struct journal *j)
678 return __bch2_journal_reclaim(j, true, true);
681 static int bch2_journal_reclaim_thread(void *arg)
683 struct journal *j = arg;
684 struct bch_fs *c = container_of(j, struct bch_fs, journal);
685 unsigned long delay, now;
691 j->last_flushed = jiffies;
693 while (!ret && !kthread_should_stop()) {
694 bool kicked = j->reclaim_kicked;
696 j->reclaim_kicked = false;
698 mutex_lock(&j->reclaim_lock);
699 ret = __bch2_journal_reclaim(j, false, kicked);
700 mutex_unlock(&j->reclaim_lock);
703 delay = msecs_to_jiffies(c->opts.journal_reclaim_delay);
704 j->next_reclaim = j->last_flushed + delay;
706 if (!time_in_range(j->next_reclaim, now, now + delay))
707 j->next_reclaim = now + delay;
710 set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
711 if (kthread_should_stop())
713 if (j->reclaim_kicked)
717 journal_empty = fifo_empty(&j->pin);
718 spin_unlock(&j->lock);
722 else if (time_after(j->next_reclaim, jiffies))
723 schedule_timeout(j->next_reclaim - jiffies);
727 __set_current_state(TASK_RUNNING);
733 void bch2_journal_reclaim_stop(struct journal *j)
735 struct task_struct *p = j->reclaim_thread;
737 j->reclaim_thread = NULL;
745 int bch2_journal_reclaim_start(struct journal *j)
747 struct bch_fs *c = container_of(j, struct bch_fs, journal);
748 struct task_struct *p;
751 if (j->reclaim_thread)
754 p = kthread_create(bch2_journal_reclaim_thread, j,
755 "bch-reclaim/%s", c->name);
756 ret = PTR_ERR_OR_ZERO(p);
758 bch_err(c, "error creating journal reclaim thread: %s", bch2_err_str(ret));
763 j->reclaim_thread = p;
768 static int journal_flush_done(struct journal *j, u64 seq_to_flush,
773 ret = bch2_journal_error(j);
777 mutex_lock(&j->reclaim_lock);
779 if (journal_flush_pins(j, seq_to_flush, 0, 0))
784 * If journal replay hasn't completed, the unreplayed journal entries
785 * hold refs on their corresponding sequence numbers
787 ret = !test_bit(JOURNAL_REPLAY_DONE, &j->flags) ||
788 journal_last_seq(j) > seq_to_flush ||
791 spin_unlock(&j->lock);
792 mutex_unlock(&j->reclaim_lock);
797 bool bch2_journal_flush_pins(struct journal *j, u64 seq_to_flush)
799 bool did_work = false;
801 if (!test_bit(JOURNAL_STARTED, &j->flags))
804 closure_wait_event(&j->async_wait,
805 journal_flush_done(j, seq_to_flush, &did_work));
810 int bch2_journal_flush_device_pins(struct journal *j, int dev_idx)
812 struct bch_fs *c = container_of(j, struct bch_fs, journal);
813 struct journal_entry_pin_list *p;
818 fifo_for_each_entry_ptr(p, &j->pin, iter)
820 ? bch2_dev_list_has_dev(p->devs, dev_idx)
821 : p->devs.nr < c->opts.metadata_replicas)
823 spin_unlock(&j->lock);
825 bch2_journal_flush_pins(j, seq);
827 ret = bch2_journal_error(j);
831 mutex_lock(&c->replicas_gc_lock);
832 bch2_replicas_gc_start(c, 1 << BCH_DATA_journal);
838 struct bch_replicas_padded replicas;
840 seq = max(seq, journal_last_seq(j));
841 if (seq >= j->pin.back)
843 bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal,
844 journal_seq_pin(j, seq)->devs);
847 spin_unlock(&j->lock);
848 ret = bch2_mark_replicas(c, &replicas.e);
851 spin_unlock(&j->lock);
853 ret = bch2_replicas_gc_end(c, ret);
854 mutex_unlock(&c->replicas_gc_lock);