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