1 // SPDX-License-Identifier: GPL-2.0
4 #include "btree_key_cache.h"
7 #include "journal_io.h"
8 #include "journal_reclaim.h"
12 #include <linux/kthread.h>
13 #include <linux/sched/mm.h>
14 #include <trace/events/bcachefs.h>
16 /* Free space calculations: */
18 static unsigned journal_space_from(struct journal_device *ja,
19 enum journal_space_from from)
22 case journal_space_discarded:
23 return ja->discard_idx;
24 case journal_space_clean_ondisk:
25 return ja->dirty_idx_ondisk;
26 case journal_space_clean:
33 unsigned bch2_journal_dev_buckets_available(struct journal *j,
34 struct journal_device *ja,
35 enum journal_space_from from)
37 unsigned available = (journal_space_from(ja, from) -
38 ja->cur_idx - 1 + ja->nr) % ja->nr;
41 * Don't use the last bucket unless writing the new last_seq
42 * will make another bucket available:
44 if (available && ja->dirty_idx_ondisk == ja->dirty_idx)
50 static void journal_set_remaining(struct journal *j, unsigned u64s_remaining)
52 union journal_preres_state old, new;
53 u64 v = atomic64_read(&j->prereserved.counter);
57 new.remaining = u64s_remaining;
58 } while ((v = atomic64_cmpxchg(&j->prereserved.counter,
59 old.v, new.v)) != old.v);
62 static struct journal_space
63 journal_dev_space_available(struct journal *j, struct bch_dev *ca,
64 enum journal_space_from from)
66 struct journal_device *ja = &ca->journal;
67 unsigned sectors, buckets, unwritten;
70 if (from == journal_space_total)
71 return (struct journal_space) {
72 .next_entry = ca->mi.bucket_size,
73 .total = ca->mi.bucket_size * ja->nr,
76 buckets = bch2_journal_dev_buckets_available(j, ja, from);
77 sectors = ja->sectors_free;
80 * We that we don't allocate the space for a journal entry
81 * until we write it out - thus, account for it here:
83 for (seq = journal_last_unwritten_seq(j);
84 seq <= journal_cur_seq(j);
86 unwritten = j->buf[seq & JOURNAL_BUF_MASK].sectors;
91 /* entry won't fit on this device, skip: */
92 if (unwritten > ca->mi.bucket_size)
95 if (unwritten >= sectors) {
102 sectors = ca->mi.bucket_size;
105 sectors -= unwritten;
108 if (sectors < ca->mi.bucket_size && buckets) {
110 sectors = ca->mi.bucket_size;
113 return (struct journal_space) {
114 .next_entry = sectors,
115 .total = sectors + buckets * ca->mi.bucket_size,
119 static struct journal_space __journal_space_available(struct journal *j, unsigned nr_devs_want,
120 enum journal_space_from from)
122 struct bch_fs *c = container_of(j, struct bch_fs, journal);
124 unsigned i, pos, nr_devs = 0;
125 struct journal_space space, dev_space[BCH_SB_MEMBERS_MAX];
127 BUG_ON(nr_devs_want > ARRAY_SIZE(dev_space));
130 for_each_member_device_rcu(ca, c, i,
131 &c->rw_devs[BCH_DATA_journal]) {
135 space = journal_dev_space_available(j, ca, from);
136 if (!space.next_entry)
139 for (pos = 0; pos < nr_devs; pos++)
140 if (space.total > dev_space[pos].total)
143 array_insert_item(dev_space, nr_devs, pos, space);
147 if (nr_devs < nr_devs_want)
148 return (struct journal_space) { 0, 0 };
151 * We sorted largest to smallest, and we want the smallest out of the
152 * @nr_devs_want largest devices:
154 return dev_space[nr_devs_want - 1];
157 void bch2_journal_space_available(struct journal *j)
159 struct bch_fs *c = container_of(j, struct bch_fs, journal);
161 unsigned clean, clean_ondisk, total;
162 s64 u64s_remaining = 0;
163 unsigned max_entry_size = min(j->buf[0].buf_size >> 9,
164 j->buf[1].buf_size >> 9);
165 unsigned i, nr_online = 0, nr_devs_want;
166 bool can_discard = false;
169 lockdep_assert_held(&j->lock);
172 for_each_member_device_rcu(ca, c, i,
173 &c->rw_devs[BCH_DATA_journal]) {
174 struct journal_device *ja = &ca->journal;
179 while (ja->dirty_idx != ja->cur_idx &&
180 ja->bucket_seq[ja->dirty_idx] < journal_last_seq(j))
181 ja->dirty_idx = (ja->dirty_idx + 1) % ja->nr;
183 while (ja->dirty_idx_ondisk != ja->dirty_idx &&
184 ja->bucket_seq[ja->dirty_idx_ondisk] < j->last_seq_ondisk)
185 ja->dirty_idx_ondisk = (ja->dirty_idx_ondisk + 1) % ja->nr;
187 if (ja->discard_idx != ja->dirty_idx_ondisk)
190 max_entry_size = min_t(unsigned, max_entry_size, ca->mi.bucket_size);
195 j->can_discard = can_discard;
197 if (nr_online < c->opts.metadata_replicas_required) {
198 ret = JOURNAL_ERR_insufficient_devices;
202 nr_devs_want = min_t(unsigned, nr_online, c->opts.metadata_replicas);
204 for (i = 0; i < journal_space_nr; i++)
205 j->space[i] = __journal_space_available(j, nr_devs_want, i);
207 clean_ondisk = j->space[journal_space_clean_ondisk].total;
208 clean = j->space[journal_space_clean].total;
209 total = j->space[journal_space_total].total;
212 journal_cur_seq(j) == j->seq_ondisk) {
213 struct printbuf buf = PRINTBUF;
215 __bch2_journal_debug_to_text(&buf, j);
216 bch_err(c, "journal stuck\n%s", buf.buf);
220 * Hack: bch2_fatal_error() calls bch2_journal_halt() which
221 * takes journal lock:
223 spin_unlock(&j->lock);
227 ret = JOURNAL_ERR_journal_stuck;
228 } else if (!j->space[journal_space_discarded].next_entry)
229 ret = JOURNAL_ERR_journal_full;
231 if ((j->space[journal_space_clean_ondisk].next_entry <
232 j->space[journal_space_clean_ondisk].total) &&
233 (clean - clean_ondisk <= total / 8) &&
234 (clean_ondisk * 2 > clean ))
235 set_bit(JOURNAL_MAY_SKIP_FLUSH, &j->flags);
237 clear_bit(JOURNAL_MAY_SKIP_FLUSH, &j->flags);
239 u64s_remaining = (u64) clean << 6;
240 u64s_remaining -= (u64) total << 3;
241 u64s_remaining = max(0LL, u64s_remaining);
243 u64s_remaining = min_t(u64, u64s_remaining, U32_MAX);
245 j->cur_entry_sectors = !ret ? j->space[journal_space_discarded].next_entry : 0;
246 j->cur_entry_error = ret;
247 journal_set_remaining(j, u64s_remaining);
248 journal_set_watermark(j);
254 /* Discards - last part of journal reclaim: */
256 static bool should_discard_bucket(struct journal *j, struct journal_device *ja)
261 ret = ja->discard_idx != ja->dirty_idx_ondisk;
262 spin_unlock(&j->lock);
268 * Advance ja->discard_idx as long as it points to buckets that are no longer
269 * dirty, issuing discards if necessary:
271 void bch2_journal_do_discards(struct journal *j)
273 struct bch_fs *c = container_of(j, struct bch_fs, journal);
277 mutex_lock(&j->discard_lock);
279 for_each_rw_member(ca, c, iter) {
280 struct journal_device *ja = &ca->journal;
282 while (should_discard_bucket(j, ja)) {
283 if (!c->opts.nochanges &&
285 blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
286 blkdev_issue_discard(ca->disk_sb.bdev,
288 ja->buckets[ja->discard_idx]),
289 ca->mi.bucket_size, GFP_NOIO, 0);
292 ja->discard_idx = (ja->discard_idx + 1) % ja->nr;
294 bch2_journal_space_available(j);
295 spin_unlock(&j->lock);
299 mutex_unlock(&j->discard_lock);
303 * Journal entry pinning - machinery for holding a reference on a given journal
304 * entry, holding it open to ensure it gets replayed during recovery:
307 static void bch2_journal_reclaim_fast(struct journal *j)
309 struct journal_entry_pin_list temp;
312 lockdep_assert_held(&j->lock);
315 * Unpin journal entries whose reference counts reached zero, meaning
316 * all btree nodes got written out
318 while (!fifo_empty(&j->pin) &&
319 !atomic_read(&fifo_peek_front(&j->pin).count)) {
320 BUG_ON(!list_empty(&fifo_peek_front(&j->pin).list));
321 BUG_ON(!list_empty(&fifo_peek_front(&j->pin).flushed));
322 BUG_ON(!fifo_pop(&j->pin, temp));
327 bch2_journal_space_available(j);
330 void __bch2_journal_pin_put(struct journal *j, u64 seq)
332 struct journal_entry_pin_list *pin_list = journal_seq_pin(j, seq);
334 if (atomic_dec_and_test(&pin_list->count))
335 bch2_journal_reclaim_fast(j);
338 void bch2_journal_pin_put(struct journal *j, u64 seq)
340 struct journal_entry_pin_list *pin_list = journal_seq_pin(j, seq);
342 if (atomic_dec_and_test(&pin_list->count)) {
344 bch2_journal_reclaim_fast(j);
345 spin_unlock(&j->lock);
349 static inline void __journal_pin_drop(struct journal *j,
350 struct journal_entry_pin *pin)
352 struct journal_entry_pin_list *pin_list;
354 if (!journal_pin_active(pin))
357 if (j->flush_in_progress == pin)
358 j->flush_in_progress_dropped = true;
360 pin_list = journal_seq_pin(j, pin->seq);
362 list_del_init(&pin->list);
365 * Unpinning a journal entry make make journal_next_bucket() succeed, if
366 * writing a new last_seq will now make another bucket available:
368 if (atomic_dec_and_test(&pin_list->count) &&
369 pin_list == &fifo_peek_front(&j->pin))
370 bch2_journal_reclaim_fast(j);
373 void bch2_journal_pin_drop(struct journal *j,
374 struct journal_entry_pin *pin)
377 __journal_pin_drop(j, pin);
378 spin_unlock(&j->lock);
381 void bch2_journal_pin_set(struct journal *j, u64 seq,
382 struct journal_entry_pin *pin,
383 journal_pin_flush_fn flush_fn)
385 struct journal_entry_pin_list *pin_list;
389 if (seq < journal_last_seq(j)) {
391 * bch2_journal_pin_copy() raced with bch2_journal_pin_drop() on
392 * the src pin - with the pin dropped, the entry to pin might no
393 * longer to exist, but that means there's no longer anything to
394 * copy and we can bail out here:
396 spin_unlock(&j->lock);
400 pin_list = journal_seq_pin(j, seq);
402 __journal_pin_drop(j, pin);
404 atomic_inc(&pin_list->count);
406 pin->flush = flush_fn;
408 if (flush_fn == bch2_btree_key_cache_journal_flush)
409 list_add(&pin->list, &pin_list->key_cache_list);
411 list_add(&pin->list, &pin_list->list);
413 list_add(&pin->list, &pin_list->flushed);
414 spin_unlock(&j->lock);
417 * If the journal is currently full, we might want to call flush_fn
424 * bch2_journal_pin_flush: ensure journal pin callback is no longer running
426 void bch2_journal_pin_flush(struct journal *j, struct journal_entry_pin *pin)
428 BUG_ON(journal_pin_active(pin));
430 wait_event(j->pin_flush_wait, j->flush_in_progress != pin);
434 * Journal reclaim: flush references to open journal entries to reclaim space in
437 * May be done by the journal code in the background as needed to free up space
438 * for more journal entries, or as part of doing a clean shutdown, or to migrate
439 * data off of a specific device:
442 static struct journal_entry_pin *
443 journal_get_next_pin(struct journal *j,
446 u64 max_seq, u64 *seq)
448 struct journal_entry_pin_list *pin_list;
449 struct journal_entry_pin *ret = NULL;
451 fifo_for_each_entry_ptr(pin_list, &j->pin, *seq) {
452 if (*seq > max_seq && !get_any && !get_key_cache)
455 if (*seq <= max_seq || get_any) {
456 ret = list_first_entry_or_null(&pin_list->list,
457 struct journal_entry_pin, list);
462 if (*seq <= max_seq || get_any || get_key_cache) {
463 ret = list_first_entry_or_null(&pin_list->key_cache_list,
464 struct journal_entry_pin, list);
473 /* returns true if we did work */
474 static size_t journal_flush_pins(struct journal *j, u64 seq_to_flush,
476 unsigned min_key_cache)
478 struct journal_entry_pin *pin;
479 size_t nr_flushed = 0;
480 journal_pin_flush_fn flush_fn;
484 lockdep_assert_held(&j->reclaim_lock);
489 j->last_flushed = jiffies;
492 pin = journal_get_next_pin(j,
497 BUG_ON(j->flush_in_progress);
498 j->flush_in_progress = pin;
499 j->flush_in_progress_dropped = false;
500 flush_fn = pin->flush;
502 spin_unlock(&j->lock);
507 if (min_key_cache && pin->flush == bch2_btree_key_cache_journal_flush)
513 err = flush_fn(j, pin, seq);
516 /* Pin might have been dropped or rearmed: */
517 if (likely(!err && !j->flush_in_progress_dropped))
518 list_move(&pin->list, &journal_seq_pin(j, seq)->flushed);
519 j->flush_in_progress = NULL;
520 j->flush_in_progress_dropped = false;
521 spin_unlock(&j->lock);
523 wake_up(&j->pin_flush_wait);
534 static u64 journal_seq_to_flush(struct journal *j)
536 struct bch_fs *c = container_of(j, struct bch_fs, journal);
538 u64 seq_to_flush = 0;
543 for_each_rw_member(ca, c, iter) {
544 struct journal_device *ja = &ca->journal;
545 unsigned nr_buckets, bucket_to_flush;
550 /* Try to keep the journal at most half full: */
551 nr_buckets = ja->nr / 2;
553 /* And include pre-reservations: */
554 nr_buckets += DIV_ROUND_UP(j->prereserved.reserved,
555 (ca->mi.bucket_size << 6) -
556 journal_entry_overhead(j));
558 nr_buckets = min(nr_buckets, ja->nr);
560 bucket_to_flush = (ja->cur_idx + nr_buckets) % ja->nr;
561 seq_to_flush = max(seq_to_flush,
562 ja->bucket_seq[bucket_to_flush]);
565 /* Also flush if the pin fifo is more than half full */
566 seq_to_flush = max_t(s64, seq_to_flush,
567 (s64) journal_cur_seq(j) -
569 spin_unlock(&j->lock);
575 * bch2_journal_reclaim - free up journal buckets
577 * Background journal reclaim writes out btree nodes. It should be run
578 * early enough so that we never completely run out of journal buckets.
580 * High watermarks for triggering background reclaim:
581 * - FIFO has fewer than 512 entries left
582 * - fewer than 25% journal buckets free
584 * Background reclaim runs until low watermarks are reached:
585 * - FIFO has more than 1024 entries left
586 * - more than 50% journal buckets free
588 * As long as a reclaim can complete in the time it takes to fill up
589 * 512 journal entries or 25% of all journal buckets, then
590 * journal_next_bucket() should not stall.
592 static int __bch2_journal_reclaim(struct journal *j, bool direct)
594 struct bch_fs *c = container_of(j, struct bch_fs, journal);
595 bool kthread = (current->flags & PF_KTHREAD) != 0;
597 size_t min_nr, min_key_cache, nr_flushed;
602 * We can't invoke memory reclaim while holding the reclaim_lock -
603 * journal reclaim is required to make progress for memory reclaim
604 * (cleaning the caches), so we can't get stuck in memory reclaim while
605 * we're holding the reclaim lock:
607 lockdep_assert_held(&j->reclaim_lock);
608 flags = memalloc_noreclaim_save();
611 if (kthread && kthread_should_stop())
614 if (bch2_journal_error(j)) {
619 bch2_journal_do_discards(j);
621 seq_to_flush = journal_seq_to_flush(j);
625 * If it's been longer than j->reclaim_delay_ms since we last flushed,
626 * make sure to flush at least one journal pin:
628 if (time_after(jiffies, j->last_flushed +
629 msecs_to_jiffies(c->opts.journal_reclaim_delay)))
632 if (j->prereserved.reserved * 4 > j->prereserved.remaining)
635 if (fifo_free(&j->pin) <= 32)
638 if (atomic_read(&c->btree_cache.dirty) * 2 > c->btree_cache.used)
641 trace_journal_reclaim_start(c,
643 j->prereserved.reserved,
644 j->prereserved.remaining,
645 atomic_read(&c->btree_cache.dirty),
647 atomic_long_read(&c->btree_key_cache.nr_dirty),
648 atomic_long_read(&c->btree_key_cache.nr_keys));
650 min_key_cache = min(bch2_nr_btree_keys_need_flush(c), (size_t) 128);
652 nr_flushed = journal_flush_pins(j, seq_to_flush,
653 min_nr, min_key_cache);
656 j->nr_direct_reclaim += nr_flushed;
658 j->nr_background_reclaim += nr_flushed;
659 trace_journal_reclaim_finish(c, nr_flushed);
662 wake_up(&j->reclaim_wait);
663 } while ((min_nr || min_key_cache) && nr_flushed && !direct);
665 memalloc_noreclaim_restore(flags);
670 int bch2_journal_reclaim(struct journal *j)
672 return __bch2_journal_reclaim(j, true);
675 static int bch2_journal_reclaim_thread(void *arg)
677 struct journal *j = arg;
678 struct bch_fs *c = container_of(j, struct bch_fs, journal);
679 unsigned long delay, now;
685 j->last_flushed = jiffies;
687 while (!ret && !kthread_should_stop()) {
688 j->reclaim_kicked = false;
690 mutex_lock(&j->reclaim_lock);
691 ret = __bch2_journal_reclaim(j, false);
692 mutex_unlock(&j->reclaim_lock);
695 delay = msecs_to_jiffies(c->opts.journal_reclaim_delay);
696 j->next_reclaim = j->last_flushed + delay;
698 if (!time_in_range(j->next_reclaim, now, now + delay))
699 j->next_reclaim = now + delay;
702 set_current_state(TASK_INTERRUPTIBLE);
703 if (kthread_should_stop())
705 if (j->reclaim_kicked)
709 journal_empty = fifo_empty(&j->pin);
710 spin_unlock(&j->lock);
713 freezable_schedule();
714 else if (time_after(j->next_reclaim, jiffies))
715 freezable_schedule_timeout(j->next_reclaim - jiffies);
719 __set_current_state(TASK_RUNNING);
725 void bch2_journal_reclaim_stop(struct journal *j)
727 struct task_struct *p = j->reclaim_thread;
729 j->reclaim_thread = NULL;
737 int bch2_journal_reclaim_start(struct journal *j)
739 struct bch_fs *c = container_of(j, struct bch_fs, journal);
740 struct task_struct *p;
742 if (j->reclaim_thread)
745 p = kthread_create(bch2_journal_reclaim_thread, j,
746 "bch-reclaim/%s", c->name);
748 bch_err(c, "error creating journal reclaim thread: %li", PTR_ERR(p));
753 j->reclaim_thread = p;
758 static int journal_flush_done(struct journal *j, u64 seq_to_flush,
763 ret = bch2_journal_error(j);
767 mutex_lock(&j->reclaim_lock);
769 if (journal_flush_pins(j, seq_to_flush, 0, 0))
774 * If journal replay hasn't completed, the unreplayed journal entries
775 * hold refs on their corresponding sequence numbers
777 ret = !test_bit(JOURNAL_REPLAY_DONE, &j->flags) ||
778 journal_last_seq(j) > seq_to_flush ||
781 spin_unlock(&j->lock);
782 mutex_unlock(&j->reclaim_lock);
787 bool bch2_journal_flush_pins(struct journal *j, u64 seq_to_flush)
789 bool did_work = false;
791 if (!test_bit(JOURNAL_STARTED, &j->flags))
794 closure_wait_event(&j->async_wait,
795 journal_flush_done(j, seq_to_flush, &did_work));
800 int bch2_journal_flush_device_pins(struct journal *j, int dev_idx)
802 struct bch_fs *c = container_of(j, struct bch_fs, journal);
803 struct journal_entry_pin_list *p;
808 fifo_for_each_entry_ptr(p, &j->pin, iter)
810 ? bch2_dev_list_has_dev(p->devs, dev_idx)
811 : p->devs.nr < c->opts.metadata_replicas)
813 spin_unlock(&j->lock);
815 bch2_journal_flush_pins(j, seq);
817 ret = bch2_journal_error(j);
821 mutex_lock(&c->replicas_gc_lock);
822 bch2_replicas_gc_start(c, 1 << BCH_DATA_journal);
828 struct bch_replicas_padded replicas;
830 seq = max(seq, journal_last_seq(j));
831 if (seq >= j->pin.back)
833 bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal,
834 journal_seq_pin(j, seq)->devs);
837 spin_unlock(&j->lock);
838 ret = bch2_mark_replicas(c, &replicas.e);
841 spin_unlock(&j->lock);
843 ret = bch2_replicas_gc_end(c, ret);
844 mutex_unlock(&c->replicas_gc_lock);