]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/journal.c
Disable pristine-tar option in gbp.conf, since there is no pristine-tar branch.
[bcachefs-tools-debian] / libbcachefs / journal.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * bcachefs journalling code, for btree insertions
4  *
5  * Copyright 2012 Google, Inc.
6  */
7
8 #include "bcachefs.h"
9 #include "alloc_foreground.h"
10 #include "bkey_methods.h"
11 #include "btree_gc.h"
12 #include "btree_update.h"
13 #include "btree_write_buffer.h"
14 #include "buckets.h"
15 #include "error.h"
16 #include "journal.h"
17 #include "journal_io.h"
18 #include "journal_reclaim.h"
19 #include "journal_sb.h"
20 #include "journal_seq_blacklist.h"
21 #include "trace.h"
22
23 static const char * const bch2_journal_errors[] = {
24 #define x(n)    #n,
25         JOURNAL_ERRORS()
26 #undef x
27         NULL
28 };
29
30 static inline bool journal_seq_unwritten(struct journal *j, u64 seq)
31 {
32         return seq > j->seq_ondisk;
33 }
34
35 static bool __journal_entry_is_open(union journal_res_state state)
36 {
37         return state.cur_entry_offset < JOURNAL_ENTRY_CLOSED_VAL;
38 }
39
40 static inline unsigned nr_unwritten_journal_entries(struct journal *j)
41 {
42         return atomic64_read(&j->seq) - j->seq_ondisk;
43 }
44
45 static bool journal_entry_is_open(struct journal *j)
46 {
47         return __journal_entry_is_open(j->reservations);
48 }
49
50 static void bch2_journal_buf_to_text(struct printbuf *out, struct journal *j, u64 seq)
51 {
52         union journal_res_state s = READ_ONCE(j->reservations);
53         unsigned i = seq & JOURNAL_BUF_MASK;
54         struct journal_buf *buf = j->buf + i;
55
56         prt_str(out, "seq:");
57         prt_tab(out);
58         prt_printf(out, "%llu", seq);
59         prt_newline(out);
60         printbuf_indent_add(out, 2);
61
62         prt_str(out, "refcount:");
63         prt_tab(out);
64         prt_printf(out, "%u", journal_state_count(s, i));
65         prt_newline(out);
66
67         prt_str(out, "size:");
68         prt_tab(out);
69         prt_human_readable_u64(out, vstruct_bytes(buf->data));
70         prt_newline(out);
71
72         prt_str(out, "expires:");
73         prt_tab(out);
74         prt_printf(out, "%li jiffies", buf->expires - jiffies);
75         prt_newline(out);
76
77         prt_str(out, "flags:");
78         prt_tab(out);
79         if (buf->noflush)
80                 prt_str(out, "noflush ");
81         if (buf->must_flush)
82                 prt_str(out, "must_flush ");
83         if (buf->separate_flush)
84                 prt_str(out, "separate_flush ");
85         if (buf->need_flush_to_write_buffer)
86                 prt_str(out, "need_flush_to_write_buffer ");
87         if (buf->need_flush_to_write_buffer)
88                 prt_str(out, "need_flush_to_write_buffer ");
89         if (buf->write_done)
90                 prt_str(out, "write done ");
91         if (buf->write_started)
92                 prt_str(out, "write started ");
93         if (buf->write_allocated)
94                 prt_str(out, "write allocated ");
95         if (buf->write_done)
96                 prt_str(out, "write done");
97         prt_newline(out);
98
99         printbuf_indent_sub(out, 2);
100 }
101
102 static void bch2_journal_bufs_to_text(struct printbuf *out, struct journal *j)
103 {
104         if (!out->nr_tabstops)
105                 printbuf_tabstop_push(out, 24);
106
107         for (u64 seq = journal_last_unwritten_seq(j);
108              seq <= journal_cur_seq(j);
109              seq++)
110                 bch2_journal_buf_to_text(out, j, seq);
111         prt_printf(out, "last buf %s\n", journal_entry_is_open(j) ? "open" : "closed");
112 }
113
114 static inline struct journal_buf *
115 journal_seq_to_buf(struct journal *j, u64 seq)
116 {
117         struct journal_buf *buf = NULL;
118
119         EBUG_ON(seq > journal_cur_seq(j));
120
121         if (journal_seq_unwritten(j, seq)) {
122                 buf = j->buf + (seq & JOURNAL_BUF_MASK);
123                 EBUG_ON(le64_to_cpu(buf->data->seq) != seq);
124         }
125         return buf;
126 }
127
128 static void journal_pin_list_init(struct journal_entry_pin_list *p, int count)
129 {
130         unsigned i;
131
132         for (i = 0; i < ARRAY_SIZE(p->list); i++)
133                 INIT_LIST_HEAD(&p->list[i]);
134         INIT_LIST_HEAD(&p->flushed);
135         atomic_set(&p->count, count);
136         p->devs.nr = 0;
137 }
138
139 /*
140  * Detect stuck journal conditions and trigger shutdown. Technically the journal
141  * can end up stuck for a variety of reasons, such as a blocked I/O, journal
142  * reservation lockup, etc. Since this is a fatal error with potentially
143  * unpredictable characteristics, we want to be fairly conservative before we
144  * decide to shut things down.
145  *
146  * Consider the journal stuck when it appears full with no ability to commit
147  * btree transactions, to discard journal buckets, nor acquire priority
148  * (reserved watermark) reservation.
149  */
150 static inline bool
151 journal_error_check_stuck(struct journal *j, int error, unsigned flags)
152 {
153         struct bch_fs *c = container_of(j, struct bch_fs, journal);
154         bool stuck = false;
155         struct printbuf buf = PRINTBUF;
156
157         if (!(error == JOURNAL_ERR_journal_full ||
158               error == JOURNAL_ERR_journal_pin_full) ||
159             nr_unwritten_journal_entries(j) ||
160             (flags & BCH_WATERMARK_MASK) != BCH_WATERMARK_reclaim)
161                 return stuck;
162
163         spin_lock(&j->lock);
164
165         if (j->can_discard) {
166                 spin_unlock(&j->lock);
167                 return stuck;
168         }
169
170         stuck = true;
171
172         /*
173          * The journal shutdown path will set ->err_seq, but do it here first to
174          * serialize against concurrent failures and avoid duplicate error
175          * reports.
176          */
177         if (j->err_seq) {
178                 spin_unlock(&j->lock);
179                 return stuck;
180         }
181         j->err_seq = journal_cur_seq(j);
182         spin_unlock(&j->lock);
183
184         bch_err(c, "Journal stuck! Hava a pre-reservation but journal full (error %s)",
185                 bch2_journal_errors[error]);
186         bch2_journal_debug_to_text(&buf, j);
187         bch_err(c, "%s", buf.buf);
188
189         printbuf_reset(&buf);
190         bch2_journal_pins_to_text(&buf, j);
191         bch_err(c, "Journal pins:\n%s", buf.buf);
192         printbuf_exit(&buf);
193
194         bch2_fatal_error(c);
195         dump_stack();
196
197         return stuck;
198 }
199
200 void bch2_journal_do_writes(struct journal *j)
201 {
202         for (u64 seq = journal_last_unwritten_seq(j);
203              seq <= journal_cur_seq(j);
204              seq++) {
205                 unsigned idx = seq & JOURNAL_BUF_MASK;
206                 struct journal_buf *w = j->buf + idx;
207
208                 if (w->write_started && !w->write_allocated)
209                         break;
210                 if (w->write_started)
211                         continue;
212
213                 if (!journal_state_count(j->reservations, idx)) {
214                         w->write_started = true;
215                         closure_call(&w->io, bch2_journal_write, j->wq, NULL);
216                 }
217
218                 break;
219         }
220 }
221
222 /*
223  * Final processing when the last reference of a journal buffer has been
224  * dropped. Drop the pin list reference acquired at journal entry open and write
225  * the buffer, if requested.
226  */
227 void bch2_journal_buf_put_final(struct journal *j, u64 seq)
228 {
229         lockdep_assert_held(&j->lock);
230
231         if (__bch2_journal_pin_put(j, seq))
232                 bch2_journal_reclaim_fast(j);
233         bch2_journal_do_writes(j);
234 }
235
236 /*
237  * Returns true if journal entry is now closed:
238  *
239  * We don't close a journal_buf until the next journal_buf is finished writing,
240  * and can be opened again - this also initializes the next journal_buf:
241  */
242 static void __journal_entry_close(struct journal *j, unsigned closed_val, bool trace)
243 {
244         struct bch_fs *c = container_of(j, struct bch_fs, journal);
245         struct journal_buf *buf = journal_cur_buf(j);
246         union journal_res_state old, new;
247         u64 v = atomic64_read(&j->reservations.counter);
248         unsigned sectors;
249
250         BUG_ON(closed_val != JOURNAL_ENTRY_CLOSED_VAL &&
251                closed_val != JOURNAL_ENTRY_ERROR_VAL);
252
253         lockdep_assert_held(&j->lock);
254
255         do {
256                 old.v = new.v = v;
257                 new.cur_entry_offset = closed_val;
258
259                 if (old.cur_entry_offset == JOURNAL_ENTRY_ERROR_VAL ||
260                     old.cur_entry_offset == new.cur_entry_offset)
261                         return;
262         } while ((v = atomic64_cmpxchg(&j->reservations.counter,
263                                        old.v, new.v)) != old.v);
264
265         if (!__journal_entry_is_open(old))
266                 return;
267
268         /* Close out old buffer: */
269         buf->data->u64s         = cpu_to_le32(old.cur_entry_offset);
270
271         if (trace_journal_entry_close_enabled() && trace) {
272                 struct printbuf pbuf = PRINTBUF;
273                 pbuf.atomic++;
274
275                 prt_str(&pbuf, "entry size: ");
276                 prt_human_readable_u64(&pbuf, vstruct_bytes(buf->data));
277                 prt_newline(&pbuf);
278                 bch2_prt_task_backtrace(&pbuf, current, 1, GFP_NOWAIT);
279                 trace_journal_entry_close(c, pbuf.buf);
280                 printbuf_exit(&pbuf);
281         }
282
283         sectors = vstruct_blocks_plus(buf->data, c->block_bits,
284                                       buf->u64s_reserved) << c->block_bits;
285         BUG_ON(sectors > buf->sectors);
286         buf->sectors = sectors;
287
288         /*
289          * We have to set last_seq here, _before_ opening a new journal entry:
290          *
291          * A threads may replace an old pin with a new pin on their current
292          * journal reservation - the expectation being that the journal will
293          * contain either what the old pin protected or what the new pin
294          * protects.
295          *
296          * After the old pin is dropped journal_last_seq() won't include the old
297          * pin, so we can only write the updated last_seq on the entry that
298          * contains whatever the new pin protects.
299          *
300          * Restated, we can _not_ update last_seq for a given entry if there
301          * could be a newer entry open with reservations/pins that have been
302          * taken against it.
303          *
304          * Hence, we want update/set last_seq on the current journal entry right
305          * before we open a new one:
306          */
307         buf->last_seq           = journal_last_seq(j);
308         buf->data->last_seq     = cpu_to_le64(buf->last_seq);
309         BUG_ON(buf->last_seq > le64_to_cpu(buf->data->seq));
310
311         cancel_delayed_work(&j->write_work);
312
313         bch2_journal_space_available(j);
314
315         __bch2_journal_buf_put(j, old.idx, le64_to_cpu(buf->data->seq));
316 }
317
318 void bch2_journal_halt(struct journal *j)
319 {
320         spin_lock(&j->lock);
321         __journal_entry_close(j, JOURNAL_ENTRY_ERROR_VAL, true);
322         if (!j->err_seq)
323                 j->err_seq = journal_cur_seq(j);
324         journal_wake(j);
325         spin_unlock(&j->lock);
326 }
327
328 static bool journal_entry_want_write(struct journal *j)
329 {
330         bool ret = !journal_entry_is_open(j) ||
331                 journal_cur_seq(j) == journal_last_unwritten_seq(j);
332
333         /* Don't close it yet if we already have a write in flight: */
334         if (ret)
335                 __journal_entry_close(j, JOURNAL_ENTRY_CLOSED_VAL, true);
336         else if (nr_unwritten_journal_entries(j)) {
337                 struct journal_buf *buf = journal_cur_buf(j);
338
339                 if (!buf->flush_time) {
340                         buf->flush_time = local_clock() ?: 1;
341                         buf->expires = jiffies;
342                 }
343         }
344
345         return ret;
346 }
347
348 bool bch2_journal_entry_close(struct journal *j)
349 {
350         bool ret;
351
352         spin_lock(&j->lock);
353         ret = journal_entry_want_write(j);
354         spin_unlock(&j->lock);
355
356         return ret;
357 }
358
359 /*
360  * should _only_ called from journal_res_get() - when we actually want a
361  * journal reservation - journal entry is open means journal is dirty:
362  */
363 static int journal_entry_open(struct journal *j)
364 {
365         struct bch_fs *c = container_of(j, struct bch_fs, journal);
366         struct journal_buf *buf = j->buf +
367                 ((journal_cur_seq(j) + 1) & JOURNAL_BUF_MASK);
368         union journal_res_state old, new;
369         int u64s;
370         u64 v;
371
372         lockdep_assert_held(&j->lock);
373         BUG_ON(journal_entry_is_open(j));
374         BUG_ON(BCH_SB_CLEAN(c->disk_sb.sb));
375
376         if (j->blocked)
377                 return JOURNAL_ERR_blocked;
378
379         if (j->cur_entry_error)
380                 return j->cur_entry_error;
381
382         if (bch2_journal_error(j))
383                 return JOURNAL_ERR_insufficient_devices; /* -EROFS */
384
385         if (!fifo_free(&j->pin))
386                 return JOURNAL_ERR_journal_pin_full;
387
388         if (nr_unwritten_journal_entries(j) == ARRAY_SIZE(j->buf))
389                 return JOURNAL_ERR_max_in_flight;
390
391         BUG_ON(!j->cur_entry_sectors);
392
393         buf->expires            =
394                 (journal_cur_seq(j) == j->flushed_seq_ondisk
395                  ? jiffies
396                  : j->last_flush_write) +
397                 msecs_to_jiffies(c->opts.journal_flush_delay);
398
399         buf->u64s_reserved      = j->entry_u64s_reserved;
400         buf->disk_sectors       = j->cur_entry_sectors;
401         buf->sectors            = min(buf->disk_sectors, buf->buf_size >> 9);
402
403         u64s = (int) (buf->sectors << 9) / sizeof(u64) -
404                 journal_entry_overhead(j);
405         u64s = clamp_t(int, u64s, 0, JOURNAL_ENTRY_CLOSED_VAL - 1);
406
407         if (u64s <= (ssize_t) j->early_journal_entries.nr)
408                 return JOURNAL_ERR_journal_full;
409
410         if (fifo_empty(&j->pin) && j->reclaim_thread)
411                 wake_up_process(j->reclaim_thread);
412
413         /*
414          * The fifo_push() needs to happen at the same time as j->seq is
415          * incremented for journal_last_seq() to be calculated correctly
416          */
417         atomic64_inc(&j->seq);
418         journal_pin_list_init(fifo_push_ref(&j->pin), 1);
419
420         BUG_ON(j->pin.back - 1 != atomic64_read(&j->seq));
421
422         BUG_ON(j->buf + (journal_cur_seq(j) & JOURNAL_BUF_MASK) != buf);
423
424         bkey_extent_init(&buf->key);
425         buf->noflush            = false;
426         buf->must_flush         = false;
427         buf->separate_flush     = false;
428         buf->flush_time         = 0;
429         buf->need_flush_to_write_buffer = true;
430         buf->write_started      = false;
431         buf->write_allocated    = false;
432         buf->write_done         = false;
433
434         memset(buf->data, 0, sizeof(*buf->data));
435         buf->data->seq  = cpu_to_le64(journal_cur_seq(j));
436         buf->data->u64s = 0;
437
438         if (j->early_journal_entries.nr) {
439                 memcpy(buf->data->_data, j->early_journal_entries.data,
440                        j->early_journal_entries.nr * sizeof(u64));
441                 le32_add_cpu(&buf->data->u64s, j->early_journal_entries.nr);
442         }
443
444         /*
445          * Must be set before marking the journal entry as open:
446          */
447         j->cur_entry_u64s = u64s;
448
449         v = atomic64_read(&j->reservations.counter);
450         do {
451                 old.v = new.v = v;
452
453                 BUG_ON(old.cur_entry_offset == JOURNAL_ENTRY_ERROR_VAL);
454
455                 new.idx++;
456                 BUG_ON(journal_state_count(new, new.idx));
457                 BUG_ON(new.idx != (journal_cur_seq(j) & JOURNAL_BUF_MASK));
458
459                 journal_state_inc(&new);
460
461                 /* Handle any already added entries */
462                 new.cur_entry_offset = le32_to_cpu(buf->data->u64s);
463         } while ((v = atomic64_cmpxchg(&j->reservations.counter,
464                                        old.v, new.v)) != old.v);
465
466         if (nr_unwritten_journal_entries(j) == 1)
467                 mod_delayed_work(j->wq,
468                                  &j->write_work,
469                                  msecs_to_jiffies(c->opts.journal_flush_delay));
470         journal_wake(j);
471
472         if (j->early_journal_entries.nr)
473                 darray_exit(&j->early_journal_entries);
474         return 0;
475 }
476
477 static bool journal_quiesced(struct journal *j)
478 {
479         bool ret = atomic64_read(&j->seq) == j->seq_ondisk;
480
481         if (!ret)
482                 bch2_journal_entry_close(j);
483         return ret;
484 }
485
486 static void journal_quiesce(struct journal *j)
487 {
488         wait_event(j->wait, journal_quiesced(j));
489 }
490
491 static void journal_write_work(struct work_struct *work)
492 {
493         struct journal *j = container_of(work, struct journal, write_work.work);
494
495         spin_lock(&j->lock);
496         if (__journal_entry_is_open(j->reservations)) {
497                 long delta = journal_cur_buf(j)->expires - jiffies;
498
499                 if (delta > 0)
500                         mod_delayed_work(j->wq, &j->write_work, delta);
501                 else
502                         __journal_entry_close(j, JOURNAL_ENTRY_CLOSED_VAL, true);
503         }
504         spin_unlock(&j->lock);
505 }
506
507 static int __journal_res_get(struct journal *j, struct journal_res *res,
508                              unsigned flags)
509 {
510         struct bch_fs *c = container_of(j, struct bch_fs, journal);
511         struct journal_buf *buf;
512         bool can_discard;
513         int ret;
514 retry:
515         if (journal_res_get_fast(j, res, flags))
516                 return 0;
517
518         if ((flags & BCH_WATERMARK_MASK) < j->watermark) {
519                 ret = JOURNAL_ERR_journal_full;
520                 can_discard = j->can_discard;
521                 goto out;
522         }
523
524         if (j->blocked)
525                 return -BCH_ERR_journal_res_get_blocked;
526
527         if (bch2_journal_error(j))
528                 return -BCH_ERR_erofs_journal_err;
529
530         if (nr_unwritten_journal_entries(j) == ARRAY_SIZE(j->buf) && !journal_entry_is_open(j)) {
531                 ret = JOURNAL_ERR_max_in_flight;
532                 goto out;
533         }
534
535         spin_lock(&j->lock);
536
537         /*
538          * Recheck after taking the lock, so we don't race with another thread
539          * that just did journal_entry_open() and call bch2_journal_entry_close()
540          * unnecessarily
541          */
542         if (journal_res_get_fast(j, res, flags)) {
543                 ret = 0;
544                 goto unlock;
545         }
546
547         /*
548          * If we couldn't get a reservation because the current buf filled up,
549          * and we had room for a bigger entry on disk, signal that we want to
550          * realloc the journal bufs:
551          */
552         buf = journal_cur_buf(j);
553         if (journal_entry_is_open(j) &&
554             buf->buf_size >> 9 < buf->disk_sectors &&
555             buf->buf_size < JOURNAL_ENTRY_SIZE_MAX)
556                 j->buf_size_want = max(j->buf_size_want, buf->buf_size << 1);
557
558         __journal_entry_close(j, JOURNAL_ENTRY_CLOSED_VAL, false);
559         ret = journal_entry_open(j) ?: JOURNAL_ERR_retry;
560 unlock:
561         can_discard = j->can_discard;
562         spin_unlock(&j->lock);
563 out:
564         if (ret == JOURNAL_ERR_retry)
565                 goto retry;
566         if (!ret)
567                 return 0;
568
569         if (journal_error_check_stuck(j, ret, flags))
570                 ret = -BCH_ERR_journal_res_get_blocked;
571
572         if (ret == JOURNAL_ERR_max_in_flight &&
573             track_event_change(&c->times[BCH_TIME_blocked_journal_max_in_flight], true)) {
574
575                 struct printbuf buf = PRINTBUF;
576                 prt_printf(&buf, "seq %llu\n", journal_cur_seq(j));
577                 bch2_journal_bufs_to_text(&buf, j);
578                 trace_journal_entry_full(c, buf.buf);
579                 printbuf_exit(&buf);
580                 count_event(c, journal_entry_full);
581         }
582
583         /*
584          * Journal is full - can't rely on reclaim from work item due to
585          * freezing:
586          */
587         if ((ret == JOURNAL_ERR_journal_full ||
588              ret == JOURNAL_ERR_journal_pin_full) &&
589             !(flags & JOURNAL_RES_GET_NONBLOCK)) {
590                 if (can_discard) {
591                         bch2_journal_do_discards(j);
592                         goto retry;
593                 }
594
595                 if (mutex_trylock(&j->reclaim_lock)) {
596                         bch2_journal_reclaim(j);
597                         mutex_unlock(&j->reclaim_lock);
598                 }
599         }
600
601         return ret == JOURNAL_ERR_insufficient_devices
602                 ? -BCH_ERR_erofs_journal_err
603                 : -BCH_ERR_journal_res_get_blocked;
604 }
605
606 /*
607  * Essentially the entry function to the journaling code. When bcachefs is doing
608  * a btree insert, it calls this function to get the current journal write.
609  * Journal write is the structure used set up journal writes. The calling
610  * function will then add its keys to the structure, queuing them for the next
611  * write.
612  *
613  * To ensure forward progress, the current task must not be holding any
614  * btree node write locks.
615  */
616 int bch2_journal_res_get_slowpath(struct journal *j, struct journal_res *res,
617                                   unsigned flags)
618 {
619         int ret;
620
621         closure_wait_event(&j->async_wait,
622                    (ret = __journal_res_get(j, res, flags)) != -BCH_ERR_journal_res_get_blocked ||
623                    (flags & JOURNAL_RES_GET_NONBLOCK));
624         return ret;
625 }
626
627 /* journal_entry_res: */
628
629 void bch2_journal_entry_res_resize(struct journal *j,
630                                    struct journal_entry_res *res,
631                                    unsigned new_u64s)
632 {
633         union journal_res_state state;
634         int d = new_u64s - res->u64s;
635
636         spin_lock(&j->lock);
637
638         j->entry_u64s_reserved += d;
639         if (d <= 0)
640                 goto out;
641
642         j->cur_entry_u64s = max_t(int, 0, j->cur_entry_u64s - d);
643         smp_mb();
644         state = READ_ONCE(j->reservations);
645
646         if (state.cur_entry_offset < JOURNAL_ENTRY_CLOSED_VAL &&
647             state.cur_entry_offset > j->cur_entry_u64s) {
648                 j->cur_entry_u64s += d;
649                 /*
650                  * Not enough room in current journal entry, have to flush it:
651                  */
652                 __journal_entry_close(j, JOURNAL_ENTRY_CLOSED_VAL, true);
653         } else {
654                 journal_cur_buf(j)->u64s_reserved += d;
655         }
656 out:
657         spin_unlock(&j->lock);
658         res->u64s += d;
659 }
660
661 /* journal flushing: */
662
663 /**
664  * bch2_journal_flush_seq_async - wait for a journal entry to be written
665  * @j:          journal object
666  * @seq:        seq to flush
667  * @parent:     closure object to wait with
668  * Returns:     1 if @seq has already been flushed, 0 if @seq is being flushed,
669  *              -EIO if @seq will never be flushed
670  *
671  * Like bch2_journal_wait_on_seq, except that it triggers a write immediately if
672  * necessary
673  */
674 int bch2_journal_flush_seq_async(struct journal *j, u64 seq,
675                                  struct closure *parent)
676 {
677         struct journal_buf *buf;
678         int ret = 0;
679
680         if (seq <= j->flushed_seq_ondisk)
681                 return 1;
682
683         spin_lock(&j->lock);
684
685         if (WARN_ONCE(seq > journal_cur_seq(j),
686                       "requested to flush journal seq %llu, but currently at %llu",
687                       seq, journal_cur_seq(j)))
688                 goto out;
689
690         /* Recheck under lock: */
691         if (j->err_seq && seq >= j->err_seq) {
692                 ret = -EIO;
693                 goto out;
694         }
695
696         if (seq <= j->flushed_seq_ondisk) {
697                 ret = 1;
698                 goto out;
699         }
700
701         /* if seq was written, but not flushed - flush a newer one instead */
702         seq = max(seq, journal_last_unwritten_seq(j));
703
704 recheck_need_open:
705         if (seq > journal_cur_seq(j)) {
706                 struct journal_res res = { 0 };
707
708                 if (journal_entry_is_open(j))
709                         __journal_entry_close(j, JOURNAL_ENTRY_CLOSED_VAL, true);
710
711                 spin_unlock(&j->lock);
712
713                 ret = bch2_journal_res_get(j, &res, jset_u64s(0), 0);
714                 if (ret)
715                         return ret;
716
717                 seq = res.seq;
718                 buf = j->buf + (seq & JOURNAL_BUF_MASK);
719                 buf->must_flush = true;
720
721                 if (!buf->flush_time) {
722                         buf->flush_time = local_clock() ?: 1;
723                         buf->expires = jiffies;
724                 }
725
726                 if (parent && !closure_wait(&buf->wait, parent))
727                         BUG();
728
729                 bch2_journal_res_put(j, &res);
730
731                 spin_lock(&j->lock);
732                 goto want_write;
733         }
734
735         /*
736          * if write was kicked off without a flush, flush the next sequence
737          * number instead
738          */
739         buf = journal_seq_to_buf(j, seq);
740         if (buf->noflush) {
741                 seq++;
742                 goto recheck_need_open;
743         }
744
745         buf->must_flush = true;
746
747         if (parent && !closure_wait(&buf->wait, parent))
748                 BUG();
749 want_write:
750         if (seq == journal_cur_seq(j))
751                 journal_entry_want_write(j);
752 out:
753         spin_unlock(&j->lock);
754         return ret;
755 }
756
757 int bch2_journal_flush_seq(struct journal *j, u64 seq)
758 {
759         u64 start_time = local_clock();
760         int ret, ret2;
761
762         /*
763          * Don't update time_stats when @seq is already flushed:
764          */
765         if (seq <= j->flushed_seq_ondisk)
766                 return 0;
767
768         ret = wait_event_interruptible(j->wait, (ret2 = bch2_journal_flush_seq_async(j, seq, NULL)));
769
770         if (!ret)
771                 time_stats_update(j->flush_seq_time, start_time);
772
773         return ret ?: ret2 < 0 ? ret2 : 0;
774 }
775
776 /*
777  * bch2_journal_flush_async - if there is an open journal entry, or a journal
778  * still being written, write it and wait for the write to complete
779  */
780 void bch2_journal_flush_async(struct journal *j, struct closure *parent)
781 {
782         bch2_journal_flush_seq_async(j, atomic64_read(&j->seq), parent);
783 }
784
785 int bch2_journal_flush(struct journal *j)
786 {
787         return bch2_journal_flush_seq(j, atomic64_read(&j->seq));
788 }
789
790 /*
791  * bch2_journal_noflush_seq - tell the journal not to issue any flushes before
792  * @seq
793  */
794 bool bch2_journal_noflush_seq(struct journal *j, u64 seq)
795 {
796         struct bch_fs *c = container_of(j, struct bch_fs, journal);
797         u64 unwritten_seq;
798         bool ret = false;
799
800         if (!(c->sb.features & (1ULL << BCH_FEATURE_journal_no_flush)))
801                 return false;
802
803         if (seq <= c->journal.flushed_seq_ondisk)
804                 return false;
805
806         spin_lock(&j->lock);
807         if (seq <= c->journal.flushed_seq_ondisk)
808                 goto out;
809
810         for (unwritten_seq = journal_last_unwritten_seq(j);
811              unwritten_seq < seq;
812              unwritten_seq++) {
813                 struct journal_buf *buf = journal_seq_to_buf(j, unwritten_seq);
814
815                 /* journal write is already in flight, and was a flush write: */
816                 if (unwritten_seq == journal_last_unwritten_seq(j) && !buf->noflush)
817                         goto out;
818
819                 buf->noflush = true;
820         }
821
822         ret = true;
823 out:
824         spin_unlock(&j->lock);
825         return ret;
826 }
827
828 int bch2_journal_meta(struct journal *j)
829 {
830         struct journal_buf *buf;
831         struct journal_res res;
832         int ret;
833
834         memset(&res, 0, sizeof(res));
835
836         ret = bch2_journal_res_get(j, &res, jset_u64s(0), 0);
837         if (ret)
838                 return ret;
839
840         buf = j->buf + (res.seq & JOURNAL_BUF_MASK);
841         buf->must_flush = true;
842
843         if (!buf->flush_time) {
844                 buf->flush_time = local_clock() ?: 1;
845                 buf->expires = jiffies;
846         }
847
848         bch2_journal_res_put(j, &res);
849
850         return bch2_journal_flush_seq(j, res.seq);
851 }
852
853 /* block/unlock the journal: */
854
855 void bch2_journal_unblock(struct journal *j)
856 {
857         spin_lock(&j->lock);
858         j->blocked--;
859         spin_unlock(&j->lock);
860
861         journal_wake(j);
862 }
863
864 void bch2_journal_block(struct journal *j)
865 {
866         spin_lock(&j->lock);
867         j->blocked++;
868         spin_unlock(&j->lock);
869
870         journal_quiesce(j);
871 }
872
873 static struct journal_buf *__bch2_next_write_buffer_flush_journal_buf(struct journal *j, u64 max_seq)
874 {
875         struct journal_buf *ret = NULL;
876
877         mutex_lock(&j->buf_lock);
878         spin_lock(&j->lock);
879         max_seq = min(max_seq, journal_cur_seq(j));
880
881         for (u64 seq = journal_last_unwritten_seq(j);
882              seq <= max_seq;
883              seq++) {
884                 unsigned idx = seq & JOURNAL_BUF_MASK;
885                 struct journal_buf *buf = j->buf + idx;
886
887                 if (buf->need_flush_to_write_buffer) {
888                         if (seq == journal_cur_seq(j))
889                                 __journal_entry_close(j, JOURNAL_ENTRY_CLOSED_VAL, true);
890
891                         union journal_res_state s;
892                         s.v = atomic64_read_acquire(&j->reservations.counter);
893
894                         ret = journal_state_count(s, idx)
895                                 ? ERR_PTR(-EAGAIN)
896                                 : buf;
897                         break;
898                 }
899         }
900
901         spin_unlock(&j->lock);
902         if (IS_ERR_OR_NULL(ret))
903                 mutex_unlock(&j->buf_lock);
904         return ret;
905 }
906
907 struct journal_buf *bch2_next_write_buffer_flush_journal_buf(struct journal *j, u64 max_seq)
908 {
909         struct journal_buf *ret;
910
911         wait_event(j->wait, (ret = __bch2_next_write_buffer_flush_journal_buf(j, max_seq)) != ERR_PTR(-EAGAIN));
912         return ret;
913 }
914
915 /* allocate journal on a device: */
916
917 static int __bch2_set_nr_journal_buckets(struct bch_dev *ca, unsigned nr,
918                                          bool new_fs, struct closure *cl)
919 {
920         struct bch_fs *c = ca->fs;
921         struct journal_device *ja = &ca->journal;
922         u64 *new_bucket_seq = NULL, *new_buckets = NULL;
923         struct open_bucket **ob = NULL;
924         long *bu = NULL;
925         unsigned i, pos, nr_got = 0, nr_want = nr - ja->nr;
926         int ret = 0;
927
928         BUG_ON(nr <= ja->nr);
929
930         bu              = kcalloc(nr_want, sizeof(*bu), GFP_KERNEL);
931         ob              = kcalloc(nr_want, sizeof(*ob), GFP_KERNEL);
932         new_buckets     = kcalloc(nr, sizeof(u64), GFP_KERNEL);
933         new_bucket_seq  = kcalloc(nr, sizeof(u64), GFP_KERNEL);
934         if (!bu || !ob || !new_buckets || !new_bucket_seq) {
935                 ret = -BCH_ERR_ENOMEM_set_nr_journal_buckets;
936                 goto err_free;
937         }
938
939         for (nr_got = 0; nr_got < nr_want; nr_got++) {
940                 if (new_fs) {
941                         bu[nr_got] = bch2_bucket_alloc_new_fs(ca);
942                         if (bu[nr_got] < 0) {
943                                 ret = -BCH_ERR_ENOSPC_bucket_alloc;
944                                 break;
945                         }
946                 } else {
947                         ob[nr_got] = bch2_bucket_alloc(c, ca, BCH_WATERMARK_normal, cl);
948                         ret = PTR_ERR_OR_ZERO(ob[nr_got]);
949                         if (ret)
950                                 break;
951
952                         ret = bch2_trans_run(c,
953                                 bch2_trans_mark_metadata_bucket(trans, ca,
954                                                 ob[nr_got]->bucket, BCH_DATA_journal,
955                                                 ca->mi.bucket_size));
956                         if (ret) {
957                                 bch2_open_bucket_put(c, ob[nr_got]);
958                                 bch_err_msg(c, ret, "marking new journal buckets");
959                                 break;
960                         }
961
962                         bu[nr_got] = ob[nr_got]->bucket;
963                 }
964         }
965
966         if (!nr_got)
967                 goto err_free;
968
969         /* Don't return an error if we successfully allocated some buckets: */
970         ret = 0;
971
972         if (c) {
973                 bch2_journal_flush_all_pins(&c->journal);
974                 bch2_journal_block(&c->journal);
975                 mutex_lock(&c->sb_lock);
976         }
977
978         memcpy(new_buckets,     ja->buckets,    ja->nr * sizeof(u64));
979         memcpy(new_bucket_seq,  ja->bucket_seq, ja->nr * sizeof(u64));
980
981         BUG_ON(ja->discard_idx > ja->nr);
982
983         pos = ja->discard_idx ?: ja->nr;
984
985         memmove(new_buckets + pos + nr_got,
986                 new_buckets + pos,
987                 sizeof(new_buckets[0]) * (ja->nr - pos));
988         memmove(new_bucket_seq + pos + nr_got,
989                 new_bucket_seq + pos,
990                 sizeof(new_bucket_seq[0]) * (ja->nr - pos));
991
992         for (i = 0; i < nr_got; i++) {
993                 new_buckets[pos + i] = bu[i];
994                 new_bucket_seq[pos + i] = 0;
995         }
996
997         nr = ja->nr + nr_got;
998
999         ret = bch2_journal_buckets_to_sb(c, ca, new_buckets, nr);
1000         if (ret)
1001                 goto err_unblock;
1002
1003         if (!new_fs)
1004                 bch2_write_super(c);
1005
1006         /* Commit: */
1007         if (c)
1008                 spin_lock(&c->journal.lock);
1009
1010         swap(new_buckets,       ja->buckets);
1011         swap(new_bucket_seq,    ja->bucket_seq);
1012         ja->nr = nr;
1013
1014         if (pos <= ja->discard_idx)
1015                 ja->discard_idx = (ja->discard_idx + nr_got) % ja->nr;
1016         if (pos <= ja->dirty_idx_ondisk)
1017                 ja->dirty_idx_ondisk = (ja->dirty_idx_ondisk + nr_got) % ja->nr;
1018         if (pos <= ja->dirty_idx)
1019                 ja->dirty_idx = (ja->dirty_idx + nr_got) % ja->nr;
1020         if (pos <= ja->cur_idx)
1021                 ja->cur_idx = (ja->cur_idx + nr_got) % ja->nr;
1022
1023         if (c)
1024                 spin_unlock(&c->journal.lock);
1025 err_unblock:
1026         if (c) {
1027                 bch2_journal_unblock(&c->journal);
1028                 mutex_unlock(&c->sb_lock);
1029         }
1030
1031         if (ret && !new_fs)
1032                 for (i = 0; i < nr_got; i++)
1033                         bch2_trans_run(c,
1034                                 bch2_trans_mark_metadata_bucket(trans, ca,
1035                                                 bu[i], BCH_DATA_free, 0));
1036 err_free:
1037         if (!new_fs)
1038                 for (i = 0; i < nr_got; i++)
1039                         bch2_open_bucket_put(c, ob[i]);
1040
1041         kfree(new_bucket_seq);
1042         kfree(new_buckets);
1043         kfree(ob);
1044         kfree(bu);
1045         return ret;
1046 }
1047
1048 /*
1049  * Allocate more journal space at runtime - not currently making use if it, but
1050  * the code works:
1051  */
1052 int bch2_set_nr_journal_buckets(struct bch_fs *c, struct bch_dev *ca,
1053                                 unsigned nr)
1054 {
1055         struct journal_device *ja = &ca->journal;
1056         struct closure cl;
1057         int ret = 0;
1058
1059         closure_init_stack(&cl);
1060
1061         down_write(&c->state_lock);
1062
1063         /* don't handle reducing nr of buckets yet: */
1064         if (nr < ja->nr)
1065                 goto unlock;
1066
1067         while (ja->nr < nr) {
1068                 struct disk_reservation disk_res = { 0, 0, 0 };
1069
1070                 /*
1071                  * note: journal buckets aren't really counted as _sectors_ used yet, so
1072                  * we don't need the disk reservation to avoid the BUG_ON() in buckets.c
1073                  * when space used goes up without a reservation - but we do need the
1074                  * reservation to ensure we'll actually be able to allocate:
1075                  *
1076                  * XXX: that's not right, disk reservations only ensure a
1077                  * filesystem-wide allocation will succeed, this is a device
1078                  * specific allocation - we can hang here:
1079                  */
1080
1081                 ret = bch2_disk_reservation_get(c, &disk_res,
1082                                                 bucket_to_sector(ca, nr - ja->nr), 1, 0);
1083                 if (ret)
1084                         break;
1085
1086                 ret = __bch2_set_nr_journal_buckets(ca, nr, false, &cl);
1087
1088                 bch2_disk_reservation_put(c, &disk_res);
1089
1090                 closure_sync(&cl);
1091
1092                 if (ret && ret != -BCH_ERR_bucket_alloc_blocked)
1093                         break;
1094         }
1095
1096         bch_err_fn(c, ret);
1097 unlock:
1098         up_write(&c->state_lock);
1099         return ret;
1100 }
1101
1102 int bch2_dev_journal_alloc(struct bch_dev *ca)
1103 {
1104         unsigned nr;
1105         int ret;
1106
1107         if (dynamic_fault("bcachefs:add:journal_alloc")) {
1108                 ret = -BCH_ERR_ENOMEM_set_nr_journal_buckets;
1109                 goto err;
1110         }
1111
1112         /* 1/128th of the device by default: */
1113         nr = ca->mi.nbuckets >> 7;
1114
1115         /*
1116          * clamp journal size to 8192 buckets or 8GB (in sectors), whichever
1117          * is smaller:
1118          */
1119         nr = clamp_t(unsigned, nr,
1120                      BCH_JOURNAL_BUCKETS_MIN,
1121                      min(1 << 13,
1122                          (1 << 24) / ca->mi.bucket_size));
1123
1124         ret = __bch2_set_nr_journal_buckets(ca, nr, true, NULL);
1125 err:
1126         bch_err_fn(ca, ret);
1127         return ret;
1128 }
1129
1130 int bch2_fs_journal_alloc(struct bch_fs *c)
1131 {
1132         for_each_online_member(c, ca) {
1133                 if (ca->journal.nr)
1134                         continue;
1135
1136                 int ret = bch2_dev_journal_alloc(ca);
1137                 if (ret) {
1138                         percpu_ref_put(&ca->io_ref);
1139                         return ret;
1140                 }
1141         }
1142
1143         return 0;
1144 }
1145
1146 /* startup/shutdown: */
1147
1148 static bool bch2_journal_writing_to_device(struct journal *j, unsigned dev_idx)
1149 {
1150         bool ret = false;
1151         u64 seq;
1152
1153         spin_lock(&j->lock);
1154         for (seq = journal_last_unwritten_seq(j);
1155              seq <= journal_cur_seq(j) && !ret;
1156              seq++) {
1157                 struct journal_buf *buf = journal_seq_to_buf(j, seq);
1158
1159                 if (bch2_bkey_has_device_c(bkey_i_to_s_c(&buf->key), dev_idx))
1160                         ret = true;
1161         }
1162         spin_unlock(&j->lock);
1163
1164         return ret;
1165 }
1166
1167 void bch2_dev_journal_stop(struct journal *j, struct bch_dev *ca)
1168 {
1169         wait_event(j->wait, !bch2_journal_writing_to_device(j, ca->dev_idx));
1170 }
1171
1172 void bch2_fs_journal_stop(struct journal *j)
1173 {
1174         bch2_journal_reclaim_stop(j);
1175         bch2_journal_flush_all_pins(j);
1176
1177         wait_event(j->wait, bch2_journal_entry_close(j));
1178
1179         /*
1180          * Always write a new journal entry, to make sure the clock hands are up
1181          * to date (and match the superblock)
1182          */
1183         bch2_journal_meta(j);
1184
1185         journal_quiesce(j);
1186
1187         BUG_ON(!bch2_journal_error(j) &&
1188                test_bit(JOURNAL_REPLAY_DONE, &j->flags) &&
1189                j->last_empty_seq != journal_cur_seq(j));
1190
1191         cancel_delayed_work_sync(&j->write_work);
1192 }
1193
1194 int bch2_fs_journal_start(struct journal *j, u64 cur_seq)
1195 {
1196         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1197         struct journal_entry_pin_list *p;
1198         struct journal_replay *i, **_i;
1199         struct genradix_iter iter;
1200         bool had_entries = false;
1201         u64 last_seq = cur_seq, nr, seq;
1202
1203         genradix_for_each_reverse(&c->journal_entries, iter, _i) {
1204                 i = *_i;
1205
1206                 if (!i || i->ignore)
1207                         continue;
1208
1209                 last_seq = le64_to_cpu(i->j.last_seq);
1210                 break;
1211         }
1212
1213         nr = cur_seq - last_seq;
1214
1215         if (nr + 1 > j->pin.size) {
1216                 free_fifo(&j->pin);
1217                 init_fifo(&j->pin, roundup_pow_of_two(nr + 1), GFP_KERNEL);
1218                 if (!j->pin.data) {
1219                         bch_err(c, "error reallocating journal fifo (%llu open entries)", nr);
1220                         return -BCH_ERR_ENOMEM_journal_pin_fifo;
1221                 }
1222         }
1223
1224         j->replay_journal_seq   = last_seq;
1225         j->replay_journal_seq_end = cur_seq;
1226         j->last_seq_ondisk      = last_seq;
1227         j->flushed_seq_ondisk   = cur_seq - 1;
1228         j->seq_ondisk           = cur_seq - 1;
1229         j->pin.front            = last_seq;
1230         j->pin.back             = cur_seq;
1231         atomic64_set(&j->seq, cur_seq - 1);
1232
1233         fifo_for_each_entry_ptr(p, &j->pin, seq)
1234                 journal_pin_list_init(p, 1);
1235
1236         genradix_for_each(&c->journal_entries, iter, _i) {
1237                 i = *_i;
1238
1239                 if (!i || i->ignore)
1240                         continue;
1241
1242                 seq = le64_to_cpu(i->j.seq);
1243                 BUG_ON(seq >= cur_seq);
1244
1245                 if (seq < last_seq)
1246                         continue;
1247
1248                 if (journal_entry_empty(&i->j))
1249                         j->last_empty_seq = le64_to_cpu(i->j.seq);
1250
1251                 p = journal_seq_pin(j, seq);
1252
1253                 p->devs.nr = 0;
1254                 darray_for_each(i->ptrs, ptr)
1255                         bch2_dev_list_add_dev(&p->devs, ptr->dev);
1256
1257                 had_entries = true;
1258         }
1259
1260         if (!had_entries)
1261                 j->last_empty_seq = cur_seq;
1262
1263         spin_lock(&j->lock);
1264
1265         set_bit(JOURNAL_STARTED, &j->flags);
1266         j->last_flush_write = jiffies;
1267
1268         j->reservations.idx = j->reservations.unwritten_idx = journal_cur_seq(j);
1269         j->reservations.unwritten_idx++;
1270
1271         c->last_bucket_seq_cleanup = journal_cur_seq(j);
1272
1273         bch2_journal_space_available(j);
1274         spin_unlock(&j->lock);
1275
1276         return bch2_journal_reclaim_start(j);
1277 }
1278
1279 /* init/exit: */
1280
1281 void bch2_dev_journal_exit(struct bch_dev *ca)
1282 {
1283         struct journal_device *ja = &ca->journal;
1284
1285         for (unsigned i = 0; i < ARRAY_SIZE(ja->bio); i++) {
1286                 kfree(ja->bio[i]);
1287                 ja->bio[i] = NULL;
1288         }
1289
1290         kfree(ja->buckets);
1291         kfree(ja->bucket_seq);
1292         ja->buckets     = NULL;
1293         ja->bucket_seq  = NULL;
1294 }
1295
1296 int bch2_dev_journal_init(struct bch_dev *ca, struct bch_sb *sb)
1297 {
1298         struct journal_device *ja = &ca->journal;
1299         struct bch_sb_field_journal *journal_buckets =
1300                 bch2_sb_field_get(sb, journal);
1301         struct bch_sb_field_journal_v2 *journal_buckets_v2 =
1302                 bch2_sb_field_get(sb, journal_v2);
1303
1304         ja->nr = 0;
1305
1306         if (journal_buckets_v2) {
1307                 unsigned nr = bch2_sb_field_journal_v2_nr_entries(journal_buckets_v2);
1308
1309                 for (unsigned i = 0; i < nr; i++)
1310                         ja->nr += le64_to_cpu(journal_buckets_v2->d[i].nr);
1311         } else if (journal_buckets) {
1312                 ja->nr = bch2_nr_journal_buckets(journal_buckets);
1313         }
1314
1315         ja->bucket_seq = kcalloc(ja->nr, sizeof(u64), GFP_KERNEL);
1316         if (!ja->bucket_seq)
1317                 return -BCH_ERR_ENOMEM_dev_journal_init;
1318
1319         unsigned nr_bvecs = DIV_ROUND_UP(JOURNAL_ENTRY_SIZE_MAX, PAGE_SIZE);
1320
1321         for (unsigned i = 0; i < ARRAY_SIZE(ja->bio); i++) {
1322                 ja->bio[i] = kmalloc(struct_size(ja->bio[i], bio.bi_inline_vecs,
1323                                      nr_bvecs), GFP_KERNEL);
1324                 if (!ja->bio[i])
1325                         return -BCH_ERR_ENOMEM_dev_journal_init;
1326
1327                 ja->bio[i]->ca = ca;
1328                 ja->bio[i]->buf_idx = i;
1329                 bio_init(&ja->bio[i]->bio, NULL, ja->bio[i]->bio.bi_inline_vecs, nr_bvecs, 0);
1330         }
1331
1332         ja->buckets = kcalloc(ja->nr, sizeof(u64), GFP_KERNEL);
1333         if (!ja->buckets)
1334                 return -BCH_ERR_ENOMEM_dev_journal_init;
1335
1336         if (journal_buckets_v2) {
1337                 unsigned nr = bch2_sb_field_journal_v2_nr_entries(journal_buckets_v2);
1338                 unsigned dst = 0;
1339
1340                 for (unsigned i = 0; i < nr; i++)
1341                         for (unsigned j = 0; j < le64_to_cpu(journal_buckets_v2->d[i].nr); j++)
1342                                 ja->buckets[dst++] =
1343                                         le64_to_cpu(journal_buckets_v2->d[i].start) + j;
1344         } else if (journal_buckets) {
1345                 for (unsigned i = 0; i < ja->nr; i++)
1346                         ja->buckets[i] = le64_to_cpu(journal_buckets->buckets[i]);
1347         }
1348
1349         return 0;
1350 }
1351
1352 void bch2_fs_journal_exit(struct journal *j)
1353 {
1354         if (j->wq)
1355                 destroy_workqueue(j->wq);
1356
1357         darray_exit(&j->early_journal_entries);
1358
1359         for (unsigned i = 0; i < ARRAY_SIZE(j->buf); i++)
1360                 kvfree(j->buf[i].data);
1361         free_fifo(&j->pin);
1362 }
1363
1364 int bch2_fs_journal_init(struct journal *j)
1365 {
1366         static struct lock_class_key res_key;
1367
1368         mutex_init(&j->buf_lock);
1369         spin_lock_init(&j->lock);
1370         spin_lock_init(&j->err_lock);
1371         init_waitqueue_head(&j->wait);
1372         INIT_DELAYED_WORK(&j->write_work, journal_write_work);
1373         init_waitqueue_head(&j->reclaim_wait);
1374         init_waitqueue_head(&j->pin_flush_wait);
1375         mutex_init(&j->reclaim_lock);
1376         mutex_init(&j->discard_lock);
1377
1378         lockdep_init_map(&j->res_map, "journal res", &res_key, 0);
1379
1380         atomic64_set(&j->reservations.counter,
1381                 ((union journal_res_state)
1382                  { .cur_entry_offset = JOURNAL_ENTRY_CLOSED_VAL }).v);
1383
1384         if (!(init_fifo(&j->pin, JOURNAL_PIN, GFP_KERNEL)))
1385                 return -BCH_ERR_ENOMEM_journal_pin_fifo;
1386
1387         for (unsigned i = 0; i < ARRAY_SIZE(j->buf); i++) {
1388                 j->buf[i].buf_size = JOURNAL_ENTRY_SIZE_MIN;
1389                 j->buf[i].data = kvmalloc(j->buf[i].buf_size, GFP_KERNEL);
1390                 if (!j->buf[i].data)
1391                         return -BCH_ERR_ENOMEM_journal_buf;
1392                 j->buf[i].idx = i;
1393         }
1394
1395         j->pin.front = j->pin.back = 1;
1396
1397         j->wq = alloc_workqueue("bcachefs_journal",
1398                                 WQ_HIGHPRI|WQ_FREEZABLE|WQ_UNBOUND|WQ_MEM_RECLAIM, 512);
1399         if (!j->wq)
1400                 return -BCH_ERR_ENOMEM_fs_other_alloc;
1401         return 0;
1402 }
1403
1404 /* debug: */
1405
1406 void __bch2_journal_debug_to_text(struct printbuf *out, struct journal *j)
1407 {
1408         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1409         union journal_res_state s;
1410         unsigned long now = jiffies;
1411         u64 nr_writes = j->nr_flush_writes + j->nr_noflush_writes;
1412
1413         if (!out->nr_tabstops)
1414                 printbuf_tabstop_push(out, 24);
1415         out->atomic++;
1416
1417         rcu_read_lock();
1418         s = READ_ONCE(j->reservations);
1419
1420         prt_printf(out, "dirty journal entries:\t%llu/%llu\n",  fifo_used(&j->pin), j->pin.size);
1421         prt_printf(out, "seq:\t\t\t%llu\n",                     journal_cur_seq(j));
1422         prt_printf(out, "seq_ondisk:\t\t%llu\n",                j->seq_ondisk);
1423         prt_printf(out, "last_seq:\t\t%llu\n",                  journal_last_seq(j));
1424         prt_printf(out, "last_seq_ondisk:\t%llu\n",             j->last_seq_ondisk);
1425         prt_printf(out, "flushed_seq_ondisk:\t%llu\n",          j->flushed_seq_ondisk);
1426         prt_printf(out, "watermark:\t\t%s\n",                   bch2_watermarks[j->watermark]);
1427         prt_printf(out, "each entry reserved:\t%u\n",           j->entry_u64s_reserved);
1428         prt_printf(out, "nr flush writes:\t%llu\n",             j->nr_flush_writes);
1429         prt_printf(out, "nr noflush writes:\t%llu\n",           j->nr_noflush_writes);
1430         prt_printf(out, "average write size:\t");
1431         prt_human_readable_u64(out, nr_writes ? div64_u64(j->entry_bytes_written, nr_writes) : 0);
1432         prt_newline(out);
1433         prt_printf(out, "nr direct reclaim:\t%llu\n",           j->nr_direct_reclaim);
1434         prt_printf(out, "nr background reclaim:\t%llu\n",       j->nr_background_reclaim);
1435         prt_printf(out, "reclaim kicked:\t\t%u\n",              j->reclaim_kicked);
1436         prt_printf(out, "reclaim runs in:\t%u ms\n",            time_after(j->next_reclaim, now)
1437                ? jiffies_to_msecs(j->next_reclaim - jiffies) : 0);
1438         prt_printf(out, "blocked:\t\t%u\n",                     j->blocked);
1439         prt_printf(out, "current entry sectors:\t%u\n",         j->cur_entry_sectors);
1440         prt_printf(out, "current entry error:\t%s\n",           bch2_journal_errors[j->cur_entry_error]);
1441         prt_printf(out, "current entry:\t\t");
1442
1443         switch (s.cur_entry_offset) {
1444         case JOURNAL_ENTRY_ERROR_VAL:
1445                 prt_printf(out, "error");
1446                 break;
1447         case JOURNAL_ENTRY_CLOSED_VAL:
1448                 prt_printf(out, "closed");
1449                 break;
1450         default:
1451                 prt_printf(out, "%u/%u", s.cur_entry_offset, j->cur_entry_u64s);
1452                 break;
1453         }
1454
1455         prt_newline(out);
1456         prt_printf(out, "unwritten entries:");
1457         prt_newline(out);
1458         bch2_journal_bufs_to_text(out, j);
1459
1460         prt_printf(out,
1461                "replay done:\t\t%i\n",
1462                test_bit(JOURNAL_REPLAY_DONE,    &j->flags));
1463
1464         prt_printf(out, "space:\n");
1465         prt_printf(out, "\tdiscarded\t%u:%u\n",
1466                j->space[journal_space_discarded].next_entry,
1467                j->space[journal_space_discarded].total);
1468         prt_printf(out, "\tclean ondisk\t%u:%u\n",
1469                j->space[journal_space_clean_ondisk].next_entry,
1470                j->space[journal_space_clean_ondisk].total);
1471         prt_printf(out, "\tclean\t\t%u:%u\n",
1472                j->space[journal_space_clean].next_entry,
1473                j->space[journal_space_clean].total);
1474         prt_printf(out, "\ttotal\t\t%u:%u\n",
1475                j->space[journal_space_total].next_entry,
1476                j->space[journal_space_total].total);
1477
1478         for_each_member_device_rcu(c, ca, &c->rw_devs[BCH_DATA_journal]) {
1479                 struct journal_device *ja = &ca->journal;
1480
1481                 if (!test_bit(ca->dev_idx, c->rw_devs[BCH_DATA_journal].d))
1482                         continue;
1483
1484                 if (!ja->nr)
1485                         continue;
1486
1487                 prt_printf(out, "dev %u:\n",            ca->dev_idx);
1488                 prt_printf(out, "\tnr\t\t%u\n",         ja->nr);
1489                 prt_printf(out, "\tbucket size\t%u\n",  ca->mi.bucket_size);
1490                 prt_printf(out, "\tavailable\t%u:%u\n", bch2_journal_dev_buckets_available(j, ja, journal_space_discarded), ja->sectors_free);
1491                 prt_printf(out, "\tdiscard_idx\t%u\n",  ja->discard_idx);
1492                 prt_printf(out, "\tdirty_ondisk\t%u (seq %llu)\n", ja->dirty_idx_ondisk,        ja->bucket_seq[ja->dirty_idx_ondisk]);
1493                 prt_printf(out, "\tdirty_idx\t%u (seq %llu)\n", ja->dirty_idx,          ja->bucket_seq[ja->dirty_idx]);
1494                 prt_printf(out, "\tcur_idx\t\t%u (seq %llu)\n", ja->cur_idx,            ja->bucket_seq[ja->cur_idx]);
1495         }
1496
1497         rcu_read_unlock();
1498
1499         --out->atomic;
1500 }
1501
1502 void bch2_journal_debug_to_text(struct printbuf *out, struct journal *j)
1503 {
1504         spin_lock(&j->lock);
1505         __bch2_journal_debug_to_text(out, j);
1506         spin_unlock(&j->lock);
1507 }
1508
1509 bool bch2_journal_seq_pins_to_text(struct printbuf *out, struct journal *j, u64 *seq)
1510 {
1511         struct journal_entry_pin_list *pin_list;
1512         struct journal_entry_pin *pin;
1513
1514         spin_lock(&j->lock);
1515         *seq = max(*seq, j->pin.front);
1516
1517         if (*seq >= j->pin.back) {
1518                 spin_unlock(&j->lock);
1519                 return true;
1520         }
1521
1522         out->atomic++;
1523
1524         pin_list = journal_seq_pin(j, *seq);
1525
1526         prt_printf(out, "%llu: count %u", *seq, atomic_read(&pin_list->count));
1527         prt_newline(out);
1528         printbuf_indent_add(out, 2);
1529
1530         for (unsigned i = 0; i < ARRAY_SIZE(pin_list->list); i++)
1531                 list_for_each_entry(pin, &pin_list->list[i], list) {
1532                         prt_printf(out, "\t%px %ps", pin, pin->flush);
1533                         prt_newline(out);
1534                 }
1535
1536         if (!list_empty(&pin_list->flushed)) {
1537                 prt_printf(out, "flushed:");
1538                 prt_newline(out);
1539         }
1540
1541         list_for_each_entry(pin, &pin_list->flushed, list) {
1542                 prt_printf(out, "\t%px %ps", pin, pin->flush);
1543                 prt_newline(out);
1544         }
1545
1546         printbuf_indent_sub(out, 2);
1547
1548         --out->atomic;
1549         spin_unlock(&j->lock);
1550
1551         return false;
1552 }
1553
1554 void bch2_journal_pins_to_text(struct printbuf *out, struct journal *j)
1555 {
1556         u64 seq = 0;
1557
1558         while (!bch2_journal_seq_pins_to_text(out, j, &seq))
1559                 seq++;
1560 }