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