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