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