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