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