xref: /linux/fs/bcachefs/journal_reclaim.c (revision df2e3152f1cb798ed8ffa7e488c50261e6dc50e3)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "btree_key_cache.h"
5 #include "btree_update.h"
6 #include "btree_write_buffer.h"
7 #include "buckets.h"
8 #include "errcode.h"
9 #include "error.h"
10 #include "journal.h"
11 #include "journal_io.h"
12 #include "journal_reclaim.h"
13 #include "replicas.h"
14 #include "sb-members.h"
15 #include "trace.h"
16 
17 #include <linux/kthread.h>
18 #include <linux/sched/mm.h>
19 
20 /* Free space calculations: */
21 
22 static unsigned journal_space_from(struct journal_device *ja,
23 				   enum journal_space_from from)
24 {
25 	switch (from) {
26 	case journal_space_discarded:
27 		return ja->discard_idx;
28 	case journal_space_clean_ondisk:
29 		return ja->dirty_idx_ondisk;
30 	case journal_space_clean:
31 		return ja->dirty_idx;
32 	default:
33 		BUG();
34 	}
35 }
36 
37 unsigned bch2_journal_dev_buckets_available(struct journal *j,
38 					    struct journal_device *ja,
39 					    enum journal_space_from from)
40 {
41 	if (!ja->nr)
42 		return 0;
43 
44 	unsigned available = (journal_space_from(ja, from) -
45 			      ja->cur_idx - 1 + ja->nr) % ja->nr;
46 
47 	/*
48 	 * Don't use the last bucket unless writing the new last_seq
49 	 * will make another bucket available:
50 	 */
51 	if (available && ja->dirty_idx_ondisk == ja->dirty_idx)
52 		--available;
53 
54 	return available;
55 }
56 
57 void bch2_journal_set_watermark(struct journal *j)
58 {
59 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
60 	bool low_on_space = j->space[journal_space_clean].total * 4 <=
61 		j->space[journal_space_total].total;
62 	bool low_on_pin = fifo_free(&j->pin) < j->pin.size / 4;
63 	bool low_on_wb = bch2_btree_write_buffer_must_wait(c);
64 	unsigned watermark = low_on_space || low_on_pin || low_on_wb
65 		? BCH_WATERMARK_reclaim
66 		: BCH_WATERMARK_stripe;
67 
68 	if (track_event_change(&c->times[BCH_TIME_blocked_journal_low_on_space], low_on_space) ||
69 	    track_event_change(&c->times[BCH_TIME_blocked_journal_low_on_pin], low_on_pin) ||
70 	    track_event_change(&c->times[BCH_TIME_blocked_write_buffer_full], low_on_wb))
71 		trace_and_count(c, journal_full, c);
72 
73 	mod_bit(JOURNAL_space_low, &j->flags, low_on_space || low_on_pin);
74 
75 	swap(watermark, j->watermark);
76 	if (watermark > j->watermark)
77 		journal_wake(j);
78 }
79 
80 static struct journal_space
81 journal_dev_space_available(struct journal *j, struct bch_dev *ca,
82 			    enum journal_space_from from)
83 {
84 	struct journal_device *ja = &ca->journal;
85 	unsigned sectors, buckets, unwritten;
86 	u64 seq;
87 
88 	if (from == journal_space_total)
89 		return (struct journal_space) {
90 			.next_entry	= ca->mi.bucket_size,
91 			.total		= ca->mi.bucket_size * ja->nr,
92 		};
93 
94 	buckets = bch2_journal_dev_buckets_available(j, ja, from);
95 	sectors = ja->sectors_free;
96 
97 	/*
98 	 * We that we don't allocate the space for a journal entry
99 	 * until we write it out - thus, account for it here:
100 	 */
101 	for (seq = journal_last_unwritten_seq(j);
102 	     seq <= journal_cur_seq(j);
103 	     seq++) {
104 		unwritten = j->buf[seq & JOURNAL_BUF_MASK].sectors;
105 
106 		if (!unwritten)
107 			continue;
108 
109 		/* entry won't fit on this device, skip: */
110 		if (unwritten > ca->mi.bucket_size)
111 			continue;
112 
113 		if (unwritten >= sectors) {
114 			if (!buckets) {
115 				sectors = 0;
116 				break;
117 			}
118 
119 			buckets--;
120 			sectors = ca->mi.bucket_size;
121 		}
122 
123 		sectors -= unwritten;
124 	}
125 
126 	if (sectors < ca->mi.bucket_size && buckets) {
127 		buckets--;
128 		sectors = ca->mi.bucket_size;
129 	}
130 
131 	return (struct journal_space) {
132 		.next_entry	= sectors,
133 		.total		= sectors + buckets * ca->mi.bucket_size,
134 	};
135 }
136 
137 static struct journal_space __journal_space_available(struct journal *j, unsigned nr_devs_want,
138 			    enum journal_space_from from)
139 {
140 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
141 	unsigned pos, nr_devs = 0;
142 	struct journal_space space, dev_space[BCH_SB_MEMBERS_MAX];
143 	unsigned min_bucket_size = U32_MAX;
144 
145 	BUG_ON(nr_devs_want > ARRAY_SIZE(dev_space));
146 
147 	rcu_read_lock();
148 	for_each_member_device_rcu(c, ca, &c->rw_devs[BCH_DATA_journal]) {
149 		if (!ca->journal.nr ||
150 		    !ca->mi.durability)
151 			continue;
152 
153 		min_bucket_size = min(min_bucket_size, ca->mi.bucket_size);
154 
155 		space = journal_dev_space_available(j, ca, from);
156 		if (!space.next_entry)
157 			continue;
158 
159 		for (pos = 0; pos < nr_devs; pos++)
160 			if (space.total > dev_space[pos].total)
161 				break;
162 
163 		array_insert_item(dev_space, nr_devs, pos, space);
164 	}
165 	rcu_read_unlock();
166 
167 	if (nr_devs < nr_devs_want)
168 		return (struct journal_space) { 0, 0 };
169 
170 	/*
171 	 * We sorted largest to smallest, and we want the smallest out of the
172 	 * @nr_devs_want largest devices:
173 	 */
174 	space = dev_space[nr_devs_want - 1];
175 	space.next_entry = min(space.next_entry, min_bucket_size);
176 	return space;
177 }
178 
179 void bch2_journal_space_available(struct journal *j)
180 {
181 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
182 	unsigned clean, clean_ondisk, total;
183 	unsigned max_entry_size	 = min(j->buf[0].buf_size >> 9,
184 				       j->buf[1].buf_size >> 9);
185 	unsigned nr_online = 0, nr_devs_want;
186 	bool can_discard = false;
187 	int ret = 0;
188 
189 	lockdep_assert_held(&j->lock);
190 
191 	rcu_read_lock();
192 	for_each_member_device_rcu(c, ca, &c->rw_devs[BCH_DATA_journal]) {
193 		struct journal_device *ja = &ca->journal;
194 
195 		if (!ja->nr)
196 			continue;
197 
198 		while (ja->dirty_idx != ja->cur_idx &&
199 		       ja->bucket_seq[ja->dirty_idx] < journal_last_seq(j))
200 			ja->dirty_idx = (ja->dirty_idx + 1) % ja->nr;
201 
202 		while (ja->dirty_idx_ondisk != ja->dirty_idx &&
203 		       ja->bucket_seq[ja->dirty_idx_ondisk] < j->last_seq_ondisk)
204 			ja->dirty_idx_ondisk = (ja->dirty_idx_ondisk + 1) % ja->nr;
205 
206 		if (ja->discard_idx != ja->dirty_idx_ondisk)
207 			can_discard = true;
208 
209 		max_entry_size = min_t(unsigned, max_entry_size, ca->mi.bucket_size);
210 		nr_online++;
211 	}
212 	rcu_read_unlock();
213 
214 	j->can_discard = can_discard;
215 
216 	if (nr_online < metadata_replicas_required(c)) {
217 		struct printbuf buf = PRINTBUF;
218 		buf.atomic++;
219 		prt_printf(&buf, "insufficient writeable journal devices available: have %u, need %u\n"
220 			   "rw journal devs:", nr_online, metadata_replicas_required(c));
221 
222 		rcu_read_lock();
223 		for_each_member_device_rcu(c, ca, &c->rw_devs[BCH_DATA_journal])
224 			prt_printf(&buf, " %s", ca->name);
225 		rcu_read_unlock();
226 
227 		bch_err(c, "%s", buf.buf);
228 		printbuf_exit(&buf);
229 		ret = JOURNAL_ERR_insufficient_devices;
230 		goto out;
231 	}
232 
233 	nr_devs_want = min_t(unsigned, nr_online, c->opts.metadata_replicas);
234 
235 	for (unsigned i = 0; i < journal_space_nr; i++)
236 		j->space[i] = __journal_space_available(j, nr_devs_want, i);
237 
238 	clean_ondisk	= j->space[journal_space_clean_ondisk].total;
239 	clean		= j->space[journal_space_clean].total;
240 	total		= j->space[journal_space_total].total;
241 
242 	if (!j->space[journal_space_discarded].next_entry)
243 		ret = JOURNAL_ERR_journal_full;
244 
245 	if ((j->space[journal_space_clean_ondisk].next_entry <
246 	     j->space[journal_space_clean_ondisk].total) &&
247 	    (clean - clean_ondisk <= total / 8) &&
248 	    (clean_ondisk * 2 > clean))
249 		set_bit(JOURNAL_may_skip_flush, &j->flags);
250 	else
251 		clear_bit(JOURNAL_may_skip_flush, &j->flags);
252 
253 	bch2_journal_set_watermark(j);
254 out:
255 	j->cur_entry_sectors	= !ret ? j->space[journal_space_discarded].next_entry : 0;
256 	j->cur_entry_error	= ret;
257 
258 	if (!ret)
259 		journal_wake(j);
260 }
261 
262 /* Discards - last part of journal reclaim: */
263 
264 static bool should_discard_bucket(struct journal *j, struct journal_device *ja)
265 {
266 	bool ret;
267 
268 	spin_lock(&j->lock);
269 	ret = ja->discard_idx != ja->dirty_idx_ondisk;
270 	spin_unlock(&j->lock);
271 
272 	return ret;
273 }
274 
275 /*
276  * Advance ja->discard_idx as long as it points to buckets that are no longer
277  * dirty, issuing discards if necessary:
278  */
279 void bch2_journal_do_discards(struct journal *j)
280 {
281 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
282 
283 	mutex_lock(&j->discard_lock);
284 
285 	for_each_rw_member(c, ca) {
286 		struct journal_device *ja = &ca->journal;
287 
288 		while (should_discard_bucket(j, ja)) {
289 			if (!c->opts.nochanges &&
290 			    ca->mi.discard &&
291 			    bdev_max_discard_sectors(ca->disk_sb.bdev))
292 				blkdev_issue_discard(ca->disk_sb.bdev,
293 					bucket_to_sector(ca,
294 						ja->buckets[ja->discard_idx]),
295 					ca->mi.bucket_size, GFP_NOFS);
296 
297 			spin_lock(&j->lock);
298 			ja->discard_idx = (ja->discard_idx + 1) % ja->nr;
299 
300 			bch2_journal_space_available(j);
301 			spin_unlock(&j->lock);
302 		}
303 	}
304 
305 	mutex_unlock(&j->discard_lock);
306 }
307 
308 /*
309  * Journal entry pinning - machinery for holding a reference on a given journal
310  * entry, holding it open to ensure it gets replayed during recovery:
311  */
312 
313 void bch2_journal_reclaim_fast(struct journal *j)
314 {
315 	bool popped = false;
316 
317 	lockdep_assert_held(&j->lock);
318 
319 	/*
320 	 * Unpin journal entries whose reference counts reached zero, meaning
321 	 * all btree nodes got written out
322 	 */
323 	while (!fifo_empty(&j->pin) &&
324 	       j->pin.front <= j->seq_ondisk &&
325 	       !atomic_read(&fifo_peek_front(&j->pin).count)) {
326 		j->pin.front++;
327 		popped = true;
328 	}
329 
330 	if (popped) {
331 		bch2_journal_space_available(j);
332 		__closure_wake_up(&j->reclaim_flush_wait);
333 	}
334 }
335 
336 bool __bch2_journal_pin_put(struct journal *j, u64 seq)
337 {
338 	struct journal_entry_pin_list *pin_list = journal_seq_pin(j, seq);
339 
340 	return atomic_dec_and_test(&pin_list->count);
341 }
342 
343 void bch2_journal_pin_put(struct journal *j, u64 seq)
344 {
345 	if (__bch2_journal_pin_put(j, seq)) {
346 		spin_lock(&j->lock);
347 		bch2_journal_reclaim_fast(j);
348 		spin_unlock(&j->lock);
349 	}
350 }
351 
352 static inline bool __journal_pin_drop(struct journal *j,
353 				      struct journal_entry_pin *pin)
354 {
355 	struct journal_entry_pin_list *pin_list;
356 
357 	if (!journal_pin_active(pin))
358 		return false;
359 
360 	if (j->flush_in_progress == pin)
361 		j->flush_in_progress_dropped = true;
362 
363 	pin_list = journal_seq_pin(j, pin->seq);
364 	pin->seq = 0;
365 	list_del_init(&pin->list);
366 
367 	if (j->reclaim_flush_wait.list.first)
368 		__closure_wake_up(&j->reclaim_flush_wait);
369 
370 	/*
371 	 * Unpinning a journal entry may make journal_next_bucket() succeed, if
372 	 * writing a new last_seq will now make another bucket available:
373 	 */
374 	return atomic_dec_and_test(&pin_list->count) &&
375 		pin_list == &fifo_peek_front(&j->pin);
376 }
377 
378 void bch2_journal_pin_drop(struct journal *j,
379 			   struct journal_entry_pin *pin)
380 {
381 	spin_lock(&j->lock);
382 	if (__journal_pin_drop(j, pin))
383 		bch2_journal_reclaim_fast(j);
384 	spin_unlock(&j->lock);
385 }
386 
387 static enum journal_pin_type journal_pin_type(journal_pin_flush_fn fn)
388 {
389 	if (fn == bch2_btree_node_flush0 ||
390 	    fn == bch2_btree_node_flush1)
391 		return JOURNAL_PIN_TYPE_btree;
392 	else if (fn == bch2_btree_key_cache_journal_flush)
393 		return JOURNAL_PIN_TYPE_key_cache;
394 	else
395 		return JOURNAL_PIN_TYPE_other;
396 }
397 
398 static inline void bch2_journal_pin_set_locked(struct journal *j, u64 seq,
399 			  struct journal_entry_pin *pin,
400 			  journal_pin_flush_fn flush_fn,
401 			  enum journal_pin_type type)
402 {
403 	struct journal_entry_pin_list *pin_list = journal_seq_pin(j, seq);
404 
405 	/*
406 	 * flush_fn is how we identify journal pins in debugfs, so must always
407 	 * exist, even if it doesn't do anything:
408 	 */
409 	BUG_ON(!flush_fn);
410 
411 	atomic_inc(&pin_list->count);
412 	pin->seq	= seq;
413 	pin->flush	= flush_fn;
414 
415 	if (list_empty(&pin_list->unflushed[type]) &&
416 	    j->reclaim_flush_wait.list.first)
417 		__closure_wake_up(&j->reclaim_flush_wait);
418 
419 	list_add(&pin->list, &pin_list->unflushed[type]);
420 }
421 
422 void bch2_journal_pin_copy(struct journal *j,
423 			   struct journal_entry_pin *dst,
424 			   struct journal_entry_pin *src,
425 			   journal_pin_flush_fn flush_fn)
426 {
427 	spin_lock(&j->lock);
428 
429 	u64 seq = READ_ONCE(src->seq);
430 
431 	if (seq < journal_last_seq(j)) {
432 		/*
433 		 * bch2_journal_pin_copy() raced with bch2_journal_pin_drop() on
434 		 * the src pin - with the pin dropped, the entry to pin might no
435 		 * longer to exist, but that means there's no longer anything to
436 		 * copy and we can bail out here:
437 		 */
438 		spin_unlock(&j->lock);
439 		return;
440 	}
441 
442 	bool reclaim = __journal_pin_drop(j, dst);
443 
444 	bch2_journal_pin_set_locked(j, seq, dst, flush_fn, journal_pin_type(flush_fn));
445 
446 	if (reclaim)
447 		bch2_journal_reclaim_fast(j);
448 
449 	/*
450 	 * If the journal is currently full,  we might want to call flush_fn
451 	 * immediately:
452 	 */
453 	if (seq == journal_last_seq(j))
454 		journal_wake(j);
455 	spin_unlock(&j->lock);
456 }
457 
458 void bch2_journal_pin_set(struct journal *j, u64 seq,
459 			  struct journal_entry_pin *pin,
460 			  journal_pin_flush_fn flush_fn)
461 {
462 	spin_lock(&j->lock);
463 
464 	BUG_ON(seq < journal_last_seq(j));
465 
466 	bool reclaim = __journal_pin_drop(j, pin);
467 
468 	bch2_journal_pin_set_locked(j, seq, pin, flush_fn, journal_pin_type(flush_fn));
469 
470 	if (reclaim)
471 		bch2_journal_reclaim_fast(j);
472 	/*
473 	 * If the journal is currently full,  we might want to call flush_fn
474 	 * immediately:
475 	 */
476 	if (seq == journal_last_seq(j))
477 		journal_wake(j);
478 
479 	spin_unlock(&j->lock);
480 }
481 
482 /**
483  * bch2_journal_pin_flush: ensure journal pin callback is no longer running
484  * @j:		journal object
485  * @pin:	pin to flush
486  */
487 void bch2_journal_pin_flush(struct journal *j, struct journal_entry_pin *pin)
488 {
489 	BUG_ON(journal_pin_active(pin));
490 
491 	wait_event(j->pin_flush_wait, j->flush_in_progress != pin);
492 }
493 
494 /*
495  * Journal reclaim: flush references to open journal entries to reclaim space in
496  * the journal
497  *
498  * May be done by the journal code in the background as needed to free up space
499  * for more journal entries, or as part of doing a clean shutdown, or to migrate
500  * data off of a specific device:
501  */
502 
503 static struct journal_entry_pin *
504 journal_get_next_pin(struct journal *j,
505 		     u64 seq_to_flush,
506 		     unsigned allowed_below_seq,
507 		     unsigned allowed_above_seq,
508 		     u64 *seq)
509 {
510 	struct journal_entry_pin_list *pin_list;
511 	struct journal_entry_pin *ret = NULL;
512 
513 	fifo_for_each_entry_ptr(pin_list, &j->pin, *seq) {
514 		if (*seq > seq_to_flush && !allowed_above_seq)
515 			break;
516 
517 		for (unsigned i = 0; i < JOURNAL_PIN_TYPE_NR; i++)
518 			if (((BIT(i) & allowed_below_seq) && *seq <= seq_to_flush) ||
519 			    (BIT(i) & allowed_above_seq)) {
520 				ret = list_first_entry_or_null(&pin_list->unflushed[i],
521 					struct journal_entry_pin, list);
522 				if (ret)
523 					return ret;
524 			}
525 	}
526 
527 	return NULL;
528 }
529 
530 /* returns true if we did work */
531 static size_t journal_flush_pins(struct journal *j,
532 				 u64 seq_to_flush,
533 				 unsigned allowed_below_seq,
534 				 unsigned allowed_above_seq,
535 				 unsigned min_any,
536 				 unsigned min_key_cache)
537 {
538 	struct journal_entry_pin *pin;
539 	size_t nr_flushed = 0;
540 	journal_pin_flush_fn flush_fn;
541 	u64 seq;
542 	int err;
543 
544 	lockdep_assert_held(&j->reclaim_lock);
545 
546 	while (1) {
547 		unsigned allowed_above = allowed_above_seq;
548 		unsigned allowed_below = allowed_below_seq;
549 
550 		if (min_any) {
551 			allowed_above |= ~0;
552 			allowed_below |= ~0;
553 		}
554 
555 		if (min_key_cache) {
556 			allowed_above |= BIT(JOURNAL_PIN_TYPE_key_cache);
557 			allowed_below |= BIT(JOURNAL_PIN_TYPE_key_cache);
558 		}
559 
560 		cond_resched();
561 
562 		j->last_flushed = jiffies;
563 
564 		spin_lock(&j->lock);
565 		pin = journal_get_next_pin(j, seq_to_flush,
566 					   allowed_below,
567 					   allowed_above, &seq);
568 		if (pin) {
569 			BUG_ON(j->flush_in_progress);
570 			j->flush_in_progress = pin;
571 			j->flush_in_progress_dropped = false;
572 			flush_fn = pin->flush;
573 		}
574 		spin_unlock(&j->lock);
575 
576 		if (!pin)
577 			break;
578 
579 		if (min_key_cache && pin->flush == bch2_btree_key_cache_journal_flush)
580 			min_key_cache--;
581 
582 		if (min_any)
583 			min_any--;
584 
585 		err = flush_fn(j, pin, seq);
586 
587 		spin_lock(&j->lock);
588 		/* Pin might have been dropped or rearmed: */
589 		if (likely(!err && !j->flush_in_progress_dropped))
590 			list_move(&pin->list, &journal_seq_pin(j, seq)->flushed[journal_pin_type(flush_fn)]);
591 		j->flush_in_progress = NULL;
592 		j->flush_in_progress_dropped = false;
593 		spin_unlock(&j->lock);
594 
595 		wake_up(&j->pin_flush_wait);
596 
597 		if (err)
598 			break;
599 
600 		nr_flushed++;
601 	}
602 
603 	return nr_flushed;
604 }
605 
606 static u64 journal_seq_to_flush(struct journal *j)
607 {
608 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
609 	u64 seq_to_flush = 0;
610 
611 	spin_lock(&j->lock);
612 
613 	for_each_rw_member(c, ca) {
614 		struct journal_device *ja = &ca->journal;
615 		unsigned nr_buckets, bucket_to_flush;
616 
617 		if (!ja->nr)
618 			continue;
619 
620 		/* Try to keep the journal at most half full: */
621 		nr_buckets = ja->nr / 2;
622 
623 		nr_buckets = min(nr_buckets, ja->nr);
624 
625 		bucket_to_flush = (ja->cur_idx + nr_buckets) % ja->nr;
626 		seq_to_flush = max(seq_to_flush,
627 				   ja->bucket_seq[bucket_to_flush]);
628 	}
629 
630 	/* Also flush if the pin fifo is more than half full */
631 	seq_to_flush = max_t(s64, seq_to_flush,
632 			     (s64) journal_cur_seq(j) -
633 			     (j->pin.size >> 1));
634 	spin_unlock(&j->lock);
635 
636 	return seq_to_flush;
637 }
638 
639 /**
640  * __bch2_journal_reclaim - free up journal buckets
641  * @j:		journal object
642  * @direct:	direct or background reclaim?
643  * @kicked:	requested to run since we last ran?
644  * Returns:	0 on success, or -EIO if the journal has been shutdown
645  *
646  * Background journal reclaim writes out btree nodes. It should be run
647  * early enough so that we never completely run out of journal buckets.
648  *
649  * High watermarks for triggering background reclaim:
650  * - FIFO has fewer than 512 entries left
651  * - fewer than 25% journal buckets free
652  *
653  * Background reclaim runs until low watermarks are reached:
654  * - FIFO has more than 1024 entries left
655  * - more than 50% journal buckets free
656  *
657  * As long as a reclaim can complete in the time it takes to fill up
658  * 512 journal entries or 25% of all journal buckets, then
659  * journal_next_bucket() should not stall.
660  */
661 static int __bch2_journal_reclaim(struct journal *j, bool direct, bool kicked)
662 {
663 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
664 	struct btree_cache *bc = &c->btree_cache;
665 	bool kthread = (current->flags & PF_KTHREAD) != 0;
666 	u64 seq_to_flush;
667 	size_t min_nr, min_key_cache, nr_flushed;
668 	unsigned flags;
669 	int ret = 0;
670 
671 	/*
672 	 * We can't invoke memory reclaim while holding the reclaim_lock -
673 	 * journal reclaim is required to make progress for memory reclaim
674 	 * (cleaning the caches), so we can't get stuck in memory reclaim while
675 	 * we're holding the reclaim lock:
676 	 */
677 	lockdep_assert_held(&j->reclaim_lock);
678 	flags = memalloc_noreclaim_save();
679 
680 	do {
681 		if (kthread && kthread_should_stop())
682 			break;
683 
684 		if (bch2_journal_error(j)) {
685 			ret = -EIO;
686 			break;
687 		}
688 
689 		bch2_journal_do_discards(j);
690 
691 		seq_to_flush = journal_seq_to_flush(j);
692 		min_nr = 0;
693 
694 		/*
695 		 * If it's been longer than j->reclaim_delay_ms since we last flushed,
696 		 * make sure to flush at least one journal pin:
697 		 */
698 		if (time_after(jiffies, j->last_flushed +
699 			       msecs_to_jiffies(c->opts.journal_reclaim_delay)))
700 			min_nr = 1;
701 
702 		if (j->watermark != BCH_WATERMARK_stripe)
703 			min_nr = 1;
704 
705 		size_t btree_cache_live = bc->live[0].nr + bc->live[1].nr;
706 		if (atomic_long_read(&bc->nr_dirty) * 2 > btree_cache_live)
707 			min_nr = 1;
708 
709 		min_key_cache = min(bch2_nr_btree_keys_need_flush(c), (size_t) 128);
710 
711 		trace_and_count(c, journal_reclaim_start, c,
712 				direct, kicked,
713 				min_nr, min_key_cache,
714 				atomic_long_read(&bc->nr_dirty), btree_cache_live,
715 				atomic_long_read(&c->btree_key_cache.nr_dirty),
716 				atomic_long_read(&c->btree_key_cache.nr_keys));
717 
718 		nr_flushed = journal_flush_pins(j, seq_to_flush,
719 						~0, 0,
720 						min_nr, min_key_cache);
721 
722 		if (direct)
723 			j->nr_direct_reclaim += nr_flushed;
724 		else
725 			j->nr_background_reclaim += nr_flushed;
726 		trace_and_count(c, journal_reclaim_finish, c, nr_flushed);
727 
728 		if (nr_flushed)
729 			wake_up(&j->reclaim_wait);
730 	} while ((min_nr || min_key_cache) && nr_flushed && !direct);
731 
732 	memalloc_noreclaim_restore(flags);
733 
734 	return ret;
735 }
736 
737 int bch2_journal_reclaim(struct journal *j)
738 {
739 	return __bch2_journal_reclaim(j, true, true);
740 }
741 
742 static int bch2_journal_reclaim_thread(void *arg)
743 {
744 	struct journal *j = arg;
745 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
746 	unsigned long delay, now;
747 	bool journal_empty;
748 	int ret = 0;
749 
750 	set_freezable();
751 
752 	j->last_flushed = jiffies;
753 
754 	while (!ret && !kthread_should_stop()) {
755 		bool kicked = j->reclaim_kicked;
756 
757 		j->reclaim_kicked = false;
758 
759 		mutex_lock(&j->reclaim_lock);
760 		ret = __bch2_journal_reclaim(j, false, kicked);
761 		mutex_unlock(&j->reclaim_lock);
762 
763 		now = jiffies;
764 		delay = msecs_to_jiffies(c->opts.journal_reclaim_delay);
765 		j->next_reclaim = j->last_flushed + delay;
766 
767 		if (!time_in_range(j->next_reclaim, now, now + delay))
768 			j->next_reclaim = now + delay;
769 
770 		while (1) {
771 			set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
772 			if (kthread_should_stop())
773 				break;
774 			if (j->reclaim_kicked)
775 				break;
776 
777 			spin_lock(&j->lock);
778 			journal_empty = fifo_empty(&j->pin);
779 			spin_unlock(&j->lock);
780 
781 			long timeout = j->next_reclaim - jiffies;
782 
783 			if (journal_empty)
784 				schedule();
785 			else if (timeout > 0)
786 				schedule_timeout(timeout);
787 			else
788 				break;
789 		}
790 		__set_current_state(TASK_RUNNING);
791 	}
792 
793 	return 0;
794 }
795 
796 void bch2_journal_reclaim_stop(struct journal *j)
797 {
798 	struct task_struct *p = j->reclaim_thread;
799 
800 	j->reclaim_thread = NULL;
801 
802 	if (p) {
803 		kthread_stop(p);
804 		put_task_struct(p);
805 	}
806 }
807 
808 int bch2_journal_reclaim_start(struct journal *j)
809 {
810 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
811 	struct task_struct *p;
812 	int ret;
813 
814 	if (j->reclaim_thread)
815 		return 0;
816 
817 	p = kthread_create(bch2_journal_reclaim_thread, j,
818 			   "bch-reclaim/%s", c->name);
819 	ret = PTR_ERR_OR_ZERO(p);
820 	bch_err_msg(c, ret, "creating journal reclaim thread");
821 	if (ret)
822 		return ret;
823 
824 	get_task_struct(p);
825 	j->reclaim_thread = p;
826 	wake_up_process(p);
827 	return 0;
828 }
829 
830 static bool journal_pins_still_flushing(struct journal *j, u64 seq_to_flush,
831 					unsigned types)
832 {
833 	struct journal_entry_pin_list *pin_list;
834 	u64 seq;
835 
836 	spin_lock(&j->lock);
837 	fifo_for_each_entry_ptr(pin_list, &j->pin, seq) {
838 		if (seq > seq_to_flush)
839 			break;
840 
841 		for (unsigned i = 0; i < JOURNAL_PIN_TYPE_NR; i++)
842 			if ((BIT(i) & types) &&
843 			    (!list_empty(&pin_list->unflushed[i]) ||
844 			     !list_empty(&pin_list->flushed[i]))) {
845 				spin_unlock(&j->lock);
846 				return true;
847 			}
848 	}
849 	spin_unlock(&j->lock);
850 
851 	return false;
852 }
853 
854 static bool journal_flush_pins_or_still_flushing(struct journal *j, u64 seq_to_flush,
855 						 unsigned types)
856 {
857 	return  journal_flush_pins(j, seq_to_flush, types, 0, 0, 0) ||
858 		journal_pins_still_flushing(j, seq_to_flush, types);
859 }
860 
861 static int journal_flush_done(struct journal *j, u64 seq_to_flush,
862 			      bool *did_work)
863 {
864 	int ret = 0;
865 
866 	ret = bch2_journal_error(j);
867 	if (ret)
868 		return ret;
869 
870 	mutex_lock(&j->reclaim_lock);
871 
872 	if (journal_flush_pins_or_still_flushing(j, seq_to_flush,
873 			       BIT(JOURNAL_PIN_TYPE_key_cache)|
874 			       BIT(JOURNAL_PIN_TYPE_other))) {
875 		*did_work = true;
876 		goto unlock;
877 	}
878 
879 	if (journal_flush_pins_or_still_flushing(j, seq_to_flush,
880 			       BIT(JOURNAL_PIN_TYPE_btree))) {
881 		*did_work = true;
882 		goto unlock;
883 	}
884 
885 	if (seq_to_flush > journal_cur_seq(j))
886 		bch2_journal_entry_close(j);
887 
888 	spin_lock(&j->lock);
889 	/*
890 	 * If journal replay hasn't completed, the unreplayed journal entries
891 	 * hold refs on their corresponding sequence numbers
892 	 */
893 	ret = !test_bit(JOURNAL_replay_done, &j->flags) ||
894 		journal_last_seq(j) > seq_to_flush ||
895 		!fifo_used(&j->pin);
896 
897 	spin_unlock(&j->lock);
898 unlock:
899 	mutex_unlock(&j->reclaim_lock);
900 
901 	return ret;
902 }
903 
904 bool bch2_journal_flush_pins(struct journal *j, u64 seq_to_flush)
905 {
906 	/* time_stats this */
907 	bool did_work = false;
908 
909 	if (!test_bit(JOURNAL_running, &j->flags))
910 		return false;
911 
912 	closure_wait_event(&j->reclaim_flush_wait,
913 		journal_flush_done(j, seq_to_flush, &did_work));
914 
915 	return did_work;
916 }
917 
918 int bch2_journal_flush_device_pins(struct journal *j, int dev_idx)
919 {
920 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
921 	struct journal_entry_pin_list *p;
922 	u64 iter, seq = 0;
923 	int ret = 0;
924 
925 	spin_lock(&j->lock);
926 	fifo_for_each_entry_ptr(p, &j->pin, iter)
927 		if (dev_idx >= 0
928 		    ? bch2_dev_list_has_dev(p->devs, dev_idx)
929 		    : p->devs.nr < c->opts.metadata_replicas)
930 			seq = iter;
931 	spin_unlock(&j->lock);
932 
933 	bch2_journal_flush_pins(j, seq);
934 
935 	ret = bch2_journal_error(j);
936 	if (ret)
937 		return ret;
938 
939 	mutex_lock(&c->replicas_gc_lock);
940 	bch2_replicas_gc_start(c, 1 << BCH_DATA_journal);
941 
942 	/*
943 	 * Now that we've populated replicas_gc, write to the journal to mark
944 	 * active journal devices. This handles the case where the journal might
945 	 * be empty. Otherwise we could clear all journal replicas and
946 	 * temporarily put the fs into an unrecoverable state. Journal recovery
947 	 * expects to find devices marked for journal data on unclean mount.
948 	 */
949 	ret = bch2_journal_meta(&c->journal);
950 	if (ret)
951 		goto err;
952 
953 	seq = 0;
954 	spin_lock(&j->lock);
955 	while (!ret) {
956 		struct bch_replicas_padded replicas;
957 
958 		seq = max(seq, journal_last_seq(j));
959 		if (seq >= j->pin.back)
960 			break;
961 		bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal,
962 					 journal_seq_pin(j, seq)->devs);
963 		seq++;
964 
965 		if (replicas.e.nr_devs) {
966 			spin_unlock(&j->lock);
967 			ret = bch2_mark_replicas(c, &replicas.e);
968 			spin_lock(&j->lock);
969 		}
970 	}
971 	spin_unlock(&j->lock);
972 err:
973 	ret = bch2_replicas_gc_end(c, ret);
974 	mutex_unlock(&c->replicas_gc_lock);
975 
976 	return ret;
977 }
978 
979 bool bch2_journal_seq_pins_to_text(struct printbuf *out, struct journal *j, u64 *seq)
980 {
981 	struct journal_entry_pin_list *pin_list;
982 	struct journal_entry_pin *pin;
983 
984 	spin_lock(&j->lock);
985 	if (!test_bit(JOURNAL_running, &j->flags)) {
986 		spin_unlock(&j->lock);
987 		return true;
988 	}
989 
990 	*seq = max(*seq, j->pin.front);
991 
992 	if (*seq >= j->pin.back) {
993 		spin_unlock(&j->lock);
994 		return true;
995 	}
996 
997 	out->atomic++;
998 
999 	pin_list = journal_seq_pin(j, *seq);
1000 
1001 	prt_printf(out, "%llu: count %u\n", *seq, atomic_read(&pin_list->count));
1002 	printbuf_indent_add(out, 2);
1003 
1004 	prt_printf(out, "unflushed:\n");
1005 	for (unsigned i = 0; i < ARRAY_SIZE(pin_list->unflushed); i++)
1006 		list_for_each_entry(pin, &pin_list->unflushed[i], list)
1007 			prt_printf(out, "\t%px %ps\n", pin, pin->flush);
1008 
1009 	prt_printf(out, "flushed:\n");
1010 	for (unsigned i = 0; i < ARRAY_SIZE(pin_list->flushed); i++)
1011 		list_for_each_entry(pin, &pin_list->flushed[i], list)
1012 			prt_printf(out, "\t%px %ps\n", pin, pin->flush);
1013 
1014 	printbuf_indent_sub(out, 2);
1015 
1016 	--out->atomic;
1017 	spin_unlock(&j->lock);
1018 
1019 	return false;
1020 }
1021 
1022 void bch2_journal_pins_to_text(struct printbuf *out, struct journal *j)
1023 {
1024 	u64 seq = 0;
1025 
1026 	while (!bch2_journal_seq_pins_to_text(out, j, &seq))
1027 		seq++;
1028 }
1029