xref: /linux/fs/bcachefs/journal_reclaim.c (revision 4a4b30ea80d8cb5e8c4c62bb86201f4ea0d9b030)
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 
journal_space_from(struct journal_device * ja,enum journal_space_from from)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 
bch2_journal_dev_buckets_available(struct journal * j,struct journal_device * ja,enum journal_space_from from)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 
bch2_journal_set_watermark(struct journal * j)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
journal_dev_space_available(struct journal * j,struct bch_dev * ca,enum journal_space_from from)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 
__journal_space_available(struct journal * j,unsigned nr_devs_want,enum journal_space_from from)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 
bch2_journal_space_available(struct journal * j)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 = -BCH_ERR_insufficient_journal_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 = -BCH_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 
should_discard_bucket(struct journal * j,struct journal_device * ja)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  */
bch2_journal_do_discards(struct journal * j)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 
bch2_journal_reclaim_fast(struct journal * j)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 
__bch2_journal_pin_put(struct journal * j,u64 seq)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 
bch2_journal_pin_put(struct journal * j,u64 seq)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 
__journal_pin_drop(struct journal * j,struct journal_entry_pin * pin)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 
bch2_journal_pin_drop(struct journal * j,struct journal_entry_pin * pin)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 
journal_pin_type(struct journal_entry_pin * pin,journal_pin_flush_fn fn)387 static enum journal_pin_type journal_pin_type(struct journal_entry_pin *pin,
388 					      journal_pin_flush_fn fn)
389 {
390 	if (fn == bch2_btree_node_flush0 ||
391 	    fn == bch2_btree_node_flush1) {
392 		unsigned idx = fn == bch2_btree_node_flush1;
393 		struct btree *b = container_of(pin, struct btree, writes[idx].journal);
394 
395 		return JOURNAL_PIN_TYPE_btree0 - b->c.level;
396 	} else if (fn == bch2_btree_key_cache_journal_flush)
397 		return JOURNAL_PIN_TYPE_key_cache;
398 	else
399 		return JOURNAL_PIN_TYPE_other;
400 }
401 
bch2_journal_pin_set_locked(struct journal * j,u64 seq,struct journal_entry_pin * pin,journal_pin_flush_fn flush_fn,enum journal_pin_type type)402 static inline void bch2_journal_pin_set_locked(struct journal *j, u64 seq,
403 			  struct journal_entry_pin *pin,
404 			  journal_pin_flush_fn flush_fn,
405 			  enum journal_pin_type type)
406 {
407 	struct journal_entry_pin_list *pin_list = journal_seq_pin(j, seq);
408 
409 	/*
410 	 * flush_fn is how we identify journal pins in debugfs, so must always
411 	 * exist, even if it doesn't do anything:
412 	 */
413 	BUG_ON(!flush_fn);
414 
415 	atomic_inc(&pin_list->count);
416 	pin->seq	= seq;
417 	pin->flush	= flush_fn;
418 
419 	if (list_empty(&pin_list->unflushed[type]) &&
420 	    j->reclaim_flush_wait.list.first)
421 		__closure_wake_up(&j->reclaim_flush_wait);
422 
423 	list_add(&pin->list, &pin_list->unflushed[type]);
424 }
425 
bch2_journal_pin_copy(struct journal * j,struct journal_entry_pin * dst,struct journal_entry_pin * src,journal_pin_flush_fn flush_fn)426 void bch2_journal_pin_copy(struct journal *j,
427 			   struct journal_entry_pin *dst,
428 			   struct journal_entry_pin *src,
429 			   journal_pin_flush_fn flush_fn)
430 {
431 	spin_lock(&j->lock);
432 
433 	u64 seq = READ_ONCE(src->seq);
434 
435 	if (seq < journal_last_seq(j)) {
436 		/*
437 		 * bch2_journal_pin_copy() raced with bch2_journal_pin_drop() on
438 		 * the src pin - with the pin dropped, the entry to pin might no
439 		 * longer to exist, but that means there's no longer anything to
440 		 * copy and we can bail out here:
441 		 */
442 		spin_unlock(&j->lock);
443 		return;
444 	}
445 
446 	bool reclaim = __journal_pin_drop(j, dst);
447 
448 	bch2_journal_pin_set_locked(j, seq, dst, flush_fn, journal_pin_type(dst, flush_fn));
449 
450 	if (reclaim)
451 		bch2_journal_reclaim_fast(j);
452 
453 	/*
454 	 * If the journal is currently full,  we might want to call flush_fn
455 	 * immediately:
456 	 */
457 	if (seq == journal_last_seq(j))
458 		journal_wake(j);
459 	spin_unlock(&j->lock);
460 }
461 
bch2_journal_pin_set(struct journal * j,u64 seq,struct journal_entry_pin * pin,journal_pin_flush_fn flush_fn)462 void bch2_journal_pin_set(struct journal *j, u64 seq,
463 			  struct journal_entry_pin *pin,
464 			  journal_pin_flush_fn flush_fn)
465 {
466 	spin_lock(&j->lock);
467 
468 	BUG_ON(seq < journal_last_seq(j));
469 
470 	bool reclaim = __journal_pin_drop(j, pin);
471 
472 	bch2_journal_pin_set_locked(j, seq, pin, flush_fn, journal_pin_type(pin, flush_fn));
473 
474 	if (reclaim)
475 		bch2_journal_reclaim_fast(j);
476 	/*
477 	 * If the journal is currently full,  we might want to call flush_fn
478 	 * immediately:
479 	 */
480 	if (seq == journal_last_seq(j))
481 		journal_wake(j);
482 
483 	spin_unlock(&j->lock);
484 }
485 
486 /**
487  * bch2_journal_pin_flush: ensure journal pin callback is no longer running
488  * @j:		journal object
489  * @pin:	pin to flush
490  */
bch2_journal_pin_flush(struct journal * j,struct journal_entry_pin * pin)491 void bch2_journal_pin_flush(struct journal *j, struct journal_entry_pin *pin)
492 {
493 	BUG_ON(journal_pin_active(pin));
494 
495 	wait_event(j->pin_flush_wait, j->flush_in_progress != pin);
496 }
497 
498 /*
499  * Journal reclaim: flush references to open journal entries to reclaim space in
500  * the journal
501  *
502  * May be done by the journal code in the background as needed to free up space
503  * for more journal entries, or as part of doing a clean shutdown, or to migrate
504  * data off of a specific device:
505  */
506 
507 static struct journal_entry_pin *
journal_get_next_pin(struct journal * j,u64 seq_to_flush,unsigned allowed_below_seq,unsigned allowed_above_seq,u64 * seq)508 journal_get_next_pin(struct journal *j,
509 		     u64 seq_to_flush,
510 		     unsigned allowed_below_seq,
511 		     unsigned allowed_above_seq,
512 		     u64 *seq)
513 {
514 	struct journal_entry_pin_list *pin_list;
515 	struct journal_entry_pin *ret = NULL;
516 
517 	fifo_for_each_entry_ptr(pin_list, &j->pin, *seq) {
518 		if (*seq > seq_to_flush && !allowed_above_seq)
519 			break;
520 
521 		for (unsigned i = 0; i < JOURNAL_PIN_TYPE_NR; i++)
522 			if (((BIT(i) & allowed_below_seq) && *seq <= seq_to_flush) ||
523 			    (BIT(i) & allowed_above_seq)) {
524 				ret = list_first_entry_or_null(&pin_list->unflushed[i],
525 					struct journal_entry_pin, list);
526 				if (ret)
527 					return ret;
528 			}
529 	}
530 
531 	return NULL;
532 }
533 
534 /* returns true if we did work */
journal_flush_pins(struct journal * j,u64 seq_to_flush,unsigned allowed_below_seq,unsigned allowed_above_seq,unsigned min_any,unsigned min_key_cache)535 static size_t journal_flush_pins(struct journal *j,
536 				 u64 seq_to_flush,
537 				 unsigned allowed_below_seq,
538 				 unsigned allowed_above_seq,
539 				 unsigned min_any,
540 				 unsigned min_key_cache)
541 {
542 	struct journal_entry_pin *pin;
543 	size_t nr_flushed = 0;
544 	journal_pin_flush_fn flush_fn;
545 	u64 seq;
546 	int err;
547 
548 	lockdep_assert_held(&j->reclaim_lock);
549 
550 	while (1) {
551 		unsigned allowed_above = allowed_above_seq;
552 		unsigned allowed_below = allowed_below_seq;
553 
554 		if (min_any) {
555 			allowed_above |= ~0;
556 			allowed_below |= ~0;
557 		}
558 
559 		if (min_key_cache) {
560 			allowed_above |= BIT(JOURNAL_PIN_TYPE_key_cache);
561 			allowed_below |= BIT(JOURNAL_PIN_TYPE_key_cache);
562 		}
563 
564 		cond_resched();
565 
566 		j->last_flushed = jiffies;
567 
568 		spin_lock(&j->lock);
569 		pin = journal_get_next_pin(j, seq_to_flush,
570 					   allowed_below,
571 					   allowed_above, &seq);
572 		if (pin) {
573 			BUG_ON(j->flush_in_progress);
574 			j->flush_in_progress = pin;
575 			j->flush_in_progress_dropped = false;
576 			flush_fn = pin->flush;
577 		}
578 		spin_unlock(&j->lock);
579 
580 		if (!pin)
581 			break;
582 
583 		if (min_key_cache && pin->flush == bch2_btree_key_cache_journal_flush)
584 			min_key_cache--;
585 
586 		if (min_any)
587 			min_any--;
588 
589 		err = flush_fn(j, pin, seq);
590 
591 		spin_lock(&j->lock);
592 		/* Pin might have been dropped or rearmed: */
593 		if (likely(!err && !j->flush_in_progress_dropped))
594 			list_move(&pin->list, &journal_seq_pin(j, seq)->flushed[journal_pin_type(pin, flush_fn)]);
595 		j->flush_in_progress = NULL;
596 		j->flush_in_progress_dropped = false;
597 		spin_unlock(&j->lock);
598 
599 		wake_up(&j->pin_flush_wait);
600 
601 		if (err)
602 			break;
603 
604 		nr_flushed++;
605 	}
606 
607 	return nr_flushed;
608 }
609 
journal_seq_to_flush(struct journal * j)610 static u64 journal_seq_to_flush(struct journal *j)
611 {
612 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
613 	u64 seq_to_flush = 0;
614 
615 	spin_lock(&j->lock);
616 
617 	for_each_rw_member(c, ca) {
618 		struct journal_device *ja = &ca->journal;
619 		unsigned nr_buckets, bucket_to_flush;
620 
621 		if (!ja->nr)
622 			continue;
623 
624 		/* Try to keep the journal at most half full: */
625 		nr_buckets = ja->nr / 2;
626 
627 		nr_buckets = min(nr_buckets, ja->nr);
628 
629 		bucket_to_flush = (ja->cur_idx + nr_buckets) % ja->nr;
630 		seq_to_flush = max(seq_to_flush,
631 				   ja->bucket_seq[bucket_to_flush]);
632 	}
633 
634 	/* Also flush if the pin fifo is more than half full */
635 	seq_to_flush = max_t(s64, seq_to_flush,
636 			     (s64) journal_cur_seq(j) -
637 			     (j->pin.size >> 1));
638 	spin_unlock(&j->lock);
639 
640 	return seq_to_flush;
641 }
642 
643 /**
644  * __bch2_journal_reclaim - free up journal buckets
645  * @j:		journal object
646  * @direct:	direct or background reclaim?
647  * @kicked:	requested to run since we last ran?
648  *
649  * Background journal reclaim writes out btree nodes. It should be run
650  * early enough so that we never completely run out of journal buckets.
651  *
652  * High watermarks for triggering background reclaim:
653  * - FIFO has fewer than 512 entries left
654  * - fewer than 25% journal buckets free
655  *
656  * Background reclaim runs until low watermarks are reached:
657  * - FIFO has more than 1024 entries left
658  * - more than 50% journal buckets free
659  *
660  * As long as a reclaim can complete in the time it takes to fill up
661  * 512 journal entries or 25% of all journal buckets, then
662  * journal_next_bucket() should not stall.
663  */
__bch2_journal_reclaim(struct journal * j,bool direct,bool kicked)664 static int __bch2_journal_reclaim(struct journal *j, bool direct, bool kicked)
665 {
666 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
667 	struct btree_cache *bc = &c->btree_cache;
668 	bool kthread = (current->flags & PF_KTHREAD) != 0;
669 	u64 seq_to_flush;
670 	size_t min_nr, min_key_cache, nr_flushed;
671 	unsigned flags;
672 	int ret = 0;
673 
674 	/*
675 	 * We can't invoke memory reclaim while holding the reclaim_lock -
676 	 * journal reclaim is required to make progress for memory reclaim
677 	 * (cleaning the caches), so we can't get stuck in memory reclaim while
678 	 * we're holding the reclaim lock:
679 	 */
680 	lockdep_assert_held(&j->reclaim_lock);
681 	flags = memalloc_noreclaim_save();
682 
683 	do {
684 		if (kthread && kthread_should_stop())
685 			break;
686 
687 		ret = bch2_journal_error(j);
688 		if (ret)
689 			break;
690 
691 		bch2_journal_do_discards(j);
692 
693 		seq_to_flush = journal_seq_to_flush(j);
694 		min_nr = 0;
695 
696 		/*
697 		 * If it's been longer than j->reclaim_delay_ms since we last flushed,
698 		 * make sure to flush at least one journal pin:
699 		 */
700 		if (time_after(jiffies, j->last_flushed +
701 			       msecs_to_jiffies(c->opts.journal_reclaim_delay)))
702 			min_nr = 1;
703 
704 		if (j->watermark != BCH_WATERMARK_stripe)
705 			min_nr = 1;
706 
707 		size_t btree_cache_live = bc->live[0].nr + bc->live[1].nr;
708 		if (atomic_long_read(&bc->nr_dirty) * 2 > btree_cache_live)
709 			min_nr = 1;
710 
711 		min_key_cache = min(bch2_nr_btree_keys_need_flush(c), (size_t) 128);
712 
713 		trace_and_count(c, journal_reclaim_start, c,
714 				direct, kicked,
715 				min_nr, min_key_cache,
716 				atomic_long_read(&bc->nr_dirty), btree_cache_live,
717 				atomic_long_read(&c->btree_key_cache.nr_dirty),
718 				atomic_long_read(&c->btree_key_cache.nr_keys));
719 
720 		nr_flushed = journal_flush_pins(j, seq_to_flush,
721 						~0, 0,
722 						min_nr, min_key_cache);
723 
724 		if (direct)
725 			j->nr_direct_reclaim += nr_flushed;
726 		else
727 			j->nr_background_reclaim += nr_flushed;
728 		trace_and_count(c, journal_reclaim_finish, c, nr_flushed);
729 
730 		if (nr_flushed)
731 			wake_up(&j->reclaim_wait);
732 	} while ((min_nr || min_key_cache) && nr_flushed && !direct);
733 
734 	memalloc_noreclaim_restore(flags);
735 
736 	return ret;
737 }
738 
bch2_journal_reclaim(struct journal * j)739 int bch2_journal_reclaim(struct journal *j)
740 {
741 	return __bch2_journal_reclaim(j, true, true);
742 }
743 
bch2_journal_reclaim_thread(void * arg)744 static int bch2_journal_reclaim_thread(void *arg)
745 {
746 	struct journal *j = arg;
747 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
748 	unsigned long delay, now;
749 	bool journal_empty;
750 	int ret = 0;
751 
752 	set_freezable();
753 
754 	j->last_flushed = jiffies;
755 
756 	while (!ret && !kthread_should_stop()) {
757 		bool kicked = j->reclaim_kicked;
758 
759 		j->reclaim_kicked = false;
760 
761 		mutex_lock(&j->reclaim_lock);
762 		ret = __bch2_journal_reclaim(j, false, kicked);
763 		mutex_unlock(&j->reclaim_lock);
764 
765 		now = jiffies;
766 		delay = msecs_to_jiffies(c->opts.journal_reclaim_delay);
767 		j->next_reclaim = j->last_flushed + delay;
768 
769 		if (!time_in_range(j->next_reclaim, now, now + delay))
770 			j->next_reclaim = now + delay;
771 
772 		while (1) {
773 			set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
774 			if (kthread_should_stop())
775 				break;
776 			if (j->reclaim_kicked)
777 				break;
778 
779 			spin_lock(&j->lock);
780 			journal_empty = fifo_empty(&j->pin);
781 			spin_unlock(&j->lock);
782 
783 			long timeout = j->next_reclaim - jiffies;
784 
785 			if (journal_empty)
786 				schedule();
787 			else if (timeout > 0)
788 				schedule_timeout(timeout);
789 			else
790 				break;
791 		}
792 		__set_current_state(TASK_RUNNING);
793 	}
794 
795 	return 0;
796 }
797 
bch2_journal_reclaim_stop(struct journal * j)798 void bch2_journal_reclaim_stop(struct journal *j)
799 {
800 	struct task_struct *p = j->reclaim_thread;
801 
802 	j->reclaim_thread = NULL;
803 
804 	if (p) {
805 		kthread_stop(p);
806 		put_task_struct(p);
807 	}
808 }
809 
bch2_journal_reclaim_start(struct journal * j)810 int bch2_journal_reclaim_start(struct journal *j)
811 {
812 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
813 	struct task_struct *p;
814 	int ret;
815 
816 	if (j->reclaim_thread)
817 		return 0;
818 
819 	p = kthread_create(bch2_journal_reclaim_thread, j,
820 			   "bch-reclaim/%s", c->name);
821 	ret = PTR_ERR_OR_ZERO(p);
822 	bch_err_msg(c, ret, "creating journal reclaim thread");
823 	if (ret)
824 		return ret;
825 
826 	get_task_struct(p);
827 	j->reclaim_thread = p;
828 	wake_up_process(p);
829 	return 0;
830 }
831 
journal_pins_still_flushing(struct journal * j,u64 seq_to_flush,unsigned types)832 static bool journal_pins_still_flushing(struct journal *j, u64 seq_to_flush,
833 					unsigned types)
834 {
835 	struct journal_entry_pin_list *pin_list;
836 	u64 seq;
837 
838 	spin_lock(&j->lock);
839 	fifo_for_each_entry_ptr(pin_list, &j->pin, seq) {
840 		if (seq > seq_to_flush)
841 			break;
842 
843 		for (unsigned i = 0; i < JOURNAL_PIN_TYPE_NR; i++)
844 			if ((BIT(i) & types) &&
845 			    (!list_empty(&pin_list->unflushed[i]) ||
846 			     !list_empty(&pin_list->flushed[i]))) {
847 				spin_unlock(&j->lock);
848 				return true;
849 			}
850 	}
851 	spin_unlock(&j->lock);
852 
853 	return false;
854 }
855 
journal_flush_pins_or_still_flushing(struct journal * j,u64 seq_to_flush,unsigned types)856 static bool journal_flush_pins_or_still_flushing(struct journal *j, u64 seq_to_flush,
857 						 unsigned types)
858 {
859 	return  journal_flush_pins(j, seq_to_flush, types, 0, 0, 0) ||
860 		journal_pins_still_flushing(j, seq_to_flush, types);
861 }
862 
journal_flush_done(struct journal * j,u64 seq_to_flush,bool * did_work)863 static int journal_flush_done(struct journal *j, u64 seq_to_flush,
864 			      bool *did_work)
865 {
866 	int ret = 0;
867 
868 	ret = bch2_journal_error(j);
869 	if (ret)
870 		return ret;
871 
872 	mutex_lock(&j->reclaim_lock);
873 
874 	for (int type = JOURNAL_PIN_TYPE_NR - 1;
875 	     type >= 0;
876 	     --type)
877 		if (journal_flush_pins_or_still_flushing(j, seq_to_flush, BIT(type))) {
878 			*did_work = true;
879 			goto unlock;
880 		}
881 
882 	if (seq_to_flush > journal_cur_seq(j))
883 		bch2_journal_entry_close(j);
884 
885 	spin_lock(&j->lock);
886 	/*
887 	 * If journal replay hasn't completed, the unreplayed journal entries
888 	 * hold refs on their corresponding sequence numbers
889 	 */
890 	ret = !test_bit(JOURNAL_replay_done, &j->flags) ||
891 		journal_last_seq(j) > seq_to_flush ||
892 		!fifo_used(&j->pin);
893 
894 	spin_unlock(&j->lock);
895 unlock:
896 	mutex_unlock(&j->reclaim_lock);
897 
898 	return ret;
899 }
900 
bch2_journal_flush_pins(struct journal * j,u64 seq_to_flush)901 bool bch2_journal_flush_pins(struct journal *j, u64 seq_to_flush)
902 {
903 	/* time_stats this */
904 	bool did_work = false;
905 
906 	if (!test_bit(JOURNAL_running, &j->flags))
907 		return false;
908 
909 	closure_wait_event(&j->reclaim_flush_wait,
910 		journal_flush_done(j, seq_to_flush, &did_work));
911 
912 	return did_work;
913 }
914 
bch2_journal_flush_device_pins(struct journal * j,int dev_idx)915 int bch2_journal_flush_device_pins(struct journal *j, int dev_idx)
916 {
917 	struct bch_fs *c = container_of(j, struct bch_fs, journal);
918 	struct journal_entry_pin_list *p;
919 	u64 iter, seq = 0;
920 	int ret = 0;
921 
922 	spin_lock(&j->lock);
923 	fifo_for_each_entry_ptr(p, &j->pin, iter)
924 		if (dev_idx >= 0
925 		    ? bch2_dev_list_has_dev(p->devs, dev_idx)
926 		    : p->devs.nr < c->opts.metadata_replicas)
927 			seq = iter;
928 	spin_unlock(&j->lock);
929 
930 	bch2_journal_flush_pins(j, seq);
931 
932 	ret = bch2_journal_error(j);
933 	if (ret)
934 		return ret;
935 
936 	mutex_lock(&c->replicas_gc_lock);
937 	bch2_replicas_gc_start(c, 1 << BCH_DATA_journal);
938 
939 	/*
940 	 * Now that we've populated replicas_gc, write to the journal to mark
941 	 * active journal devices. This handles the case where the journal might
942 	 * be empty. Otherwise we could clear all journal replicas and
943 	 * temporarily put the fs into an unrecoverable state. Journal recovery
944 	 * expects to find devices marked for journal data on unclean mount.
945 	 */
946 	ret = bch2_journal_meta(&c->journal);
947 	if (ret)
948 		goto err;
949 
950 	seq = 0;
951 	spin_lock(&j->lock);
952 	while (!ret) {
953 		struct bch_replicas_padded replicas;
954 
955 		seq = max(seq, journal_last_seq(j));
956 		if (seq >= j->pin.back)
957 			break;
958 		bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal,
959 					 journal_seq_pin(j, seq)->devs);
960 		seq++;
961 
962 		if (replicas.e.nr_devs) {
963 			spin_unlock(&j->lock);
964 			ret = bch2_mark_replicas(c, &replicas.e);
965 			spin_lock(&j->lock);
966 		}
967 	}
968 	spin_unlock(&j->lock);
969 err:
970 	ret = bch2_replicas_gc_end(c, ret);
971 	mutex_unlock(&c->replicas_gc_lock);
972 
973 	return ret;
974 }
975 
bch2_journal_seq_pins_to_text(struct printbuf * out,struct journal * j,u64 * seq)976 bool bch2_journal_seq_pins_to_text(struct printbuf *out, struct journal *j, u64 *seq)
977 {
978 	struct journal_entry_pin_list *pin_list;
979 	struct journal_entry_pin *pin;
980 
981 	spin_lock(&j->lock);
982 	if (!test_bit(JOURNAL_running, &j->flags)) {
983 		spin_unlock(&j->lock);
984 		return true;
985 	}
986 
987 	*seq = max(*seq, j->pin.front);
988 
989 	if (*seq >= j->pin.back) {
990 		spin_unlock(&j->lock);
991 		return true;
992 	}
993 
994 	out->atomic++;
995 
996 	pin_list = journal_seq_pin(j, *seq);
997 
998 	prt_printf(out, "%llu: count %u\n", *seq, atomic_read(&pin_list->count));
999 	printbuf_indent_add(out, 2);
1000 
1001 	prt_printf(out, "unflushed:\n");
1002 	for (unsigned i = 0; i < ARRAY_SIZE(pin_list->unflushed); i++)
1003 		list_for_each_entry(pin, &pin_list->unflushed[i], list)
1004 			prt_printf(out, "\t%px %ps\n", pin, pin->flush);
1005 
1006 	prt_printf(out, "flushed:\n");
1007 	for (unsigned i = 0; i < ARRAY_SIZE(pin_list->flushed); i++)
1008 		list_for_each_entry(pin, &pin_list->flushed[i], list)
1009 			prt_printf(out, "\t%px %ps\n", pin, pin->flush);
1010 
1011 	printbuf_indent_sub(out, 2);
1012 
1013 	--out->atomic;
1014 	spin_unlock(&j->lock);
1015 
1016 	return false;
1017 }
1018 
bch2_journal_pins_to_text(struct printbuf * out,struct journal * j)1019 void bch2_journal_pins_to_text(struct printbuf *out, struct journal *j)
1020 {
1021 	u64 seq = 0;
1022 
1023 	while (!bch2_journal_seq_pins_to_text(out, j, &seq))
1024 		seq++;
1025 }
1026