xref: /linux/drivers/md/bcache/journal.c (revision 6dfafbd0299a60bfb5d5e277fdf100037c7ded07)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * bcache journalling code, for btree insertions
4  *
5  * Copyright 2012 Google, Inc.
6  */
7 
8 #include "bcache.h"
9 #include "btree.h"
10 #include "debug.h"
11 #include "extents.h"
12 
13 #include <trace/events/bcache.h>
14 
15 /*
16  * Journal replay/recovery:
17  *
18  * This code is all driven from run_cache_set(); we first read the journal
19  * entries, do some other stuff, then we mark all the keys in the journal
20  * entries (same as garbage collection would), then we replay them - reinserting
21  * them into the cache in precisely the same order as they appear in the
22  * journal.
23  *
24  * We only journal keys that go in leaf nodes, which simplifies things quite a
25  * bit.
26  */
27 
28 static void journal_read_endio(struct bio *bio)
29 {
30 	struct closure *cl = bio->bi_private;
31 
32 	closure_put(cl);
33 }
34 
35 static int journal_read_bucket(struct cache *ca, struct list_head *list,
36 			       unsigned int bucket_index)
37 {
38 	struct journal_device *ja = &ca->journal;
39 	struct bio *bio = &ja->bio;
40 
41 	struct journal_replay *i;
42 	struct jset *j, *data = ca->set->journal.w[0].data;
43 	struct closure cl;
44 	unsigned int len, left, offset = 0;
45 	int ret = 0;
46 	sector_t bucket = bucket_to_sector(ca->set, ca->sb.d[bucket_index]);
47 
48 	closure_init_stack(&cl);
49 
50 	pr_debug("reading %u\n", bucket_index);
51 
52 	while (offset < ca->sb.bucket_size) {
53 reread:		left = ca->sb.bucket_size - offset;
54 		len = min_t(unsigned int, left, PAGE_SECTORS << JSET_BITS);
55 
56 		bio_reset(bio, ca->bdev, REQ_OP_READ);
57 		bio->bi_iter.bi_sector	= bucket + offset;
58 		bio->bi_iter.bi_size	= len << 9;
59 
60 		bio->bi_end_io	= journal_read_endio;
61 		bio->bi_private = &cl;
62 		bch_bio_map(bio, data);
63 
64 		closure_bio_submit(ca->set, bio, &cl);
65 		closure_sync(&cl);
66 
67 		/* This function could be simpler now since we no longer write
68 		 * journal entries that overlap bucket boundaries; this means
69 		 * the start of a bucket will always have a valid journal entry
70 		 * if it has any journal entries at all.
71 		 */
72 
73 		j = data;
74 		while (len) {
75 			struct list_head *where;
76 			size_t blocks, bytes = set_bytes(j);
77 
78 			if (j->magic != jset_magic(&ca->sb)) {
79 				pr_debug("%u: bad magic\n", bucket_index);
80 				return ret;
81 			}
82 
83 			if (bytes > left << 9 ||
84 			    bytes > PAGE_SIZE << JSET_BITS) {
85 				pr_info("%u: too big, %zu bytes, offset %u\n",
86 					bucket_index, bytes, offset);
87 				return ret;
88 			}
89 
90 			if (bytes > len << 9)
91 				goto reread;
92 
93 			if (j->csum != csum_set(j)) {
94 				pr_info("%u: bad csum, %zu bytes, offset %u\n",
95 					bucket_index, bytes, offset);
96 				return ret;
97 			}
98 
99 			blocks = set_blocks(j, block_bytes(ca));
100 
101 			/*
102 			 * Nodes in 'list' are in linear increasing order of
103 			 * i->j.seq, the node on head has the smallest (oldest)
104 			 * journal seq, the node on tail has the biggest
105 			 * (latest) journal seq.
106 			 */
107 
108 			/*
109 			 * Check from the oldest jset for last_seq. If
110 			 * i->j.seq < j->last_seq, it means the oldest jset
111 			 * in list is expired and useless, remove it from
112 			 * this list. Otherwise, j is a candidate jset for
113 			 * further following checks.
114 			 */
115 			while (!list_empty(list)) {
116 				i = list_first_entry(list,
117 					struct journal_replay, list);
118 				if (i->j.seq >= j->last_seq)
119 					break;
120 				list_del(&i->list);
121 				kfree(i);
122 			}
123 
124 			/* iterate list in reverse order (from latest jset) */
125 			list_for_each_entry_reverse(i, list, list) {
126 				if (j->seq == i->j.seq)
127 					goto next_set;
128 
129 				/*
130 				 * if j->seq is less than any i->j.last_seq
131 				 * in list, j is an expired and useless jset.
132 				 */
133 				if (j->seq < i->j.last_seq)
134 					goto next_set;
135 
136 				/*
137 				 * 'where' points to first jset in list which
138 				 * is elder then j.
139 				 */
140 				if (j->seq > i->j.seq) {
141 					where = &i->list;
142 					goto add;
143 				}
144 			}
145 
146 			where = list;
147 add:
148 			i = kmalloc(offsetof(struct journal_replay, j) +
149 				    bytes, GFP_KERNEL);
150 			if (!i)
151 				return -ENOMEM;
152 			unsafe_memcpy(&i->j, j, bytes,
153 				/* "bytes" was calculated by set_bytes() above */);
154 			/* Add to the location after 'where' points to */
155 			list_add(&i->list, where);
156 			ret = 1;
157 
158 			if (j->seq > ja->seq[bucket_index])
159 				ja->seq[bucket_index] = j->seq;
160 next_set:
161 			offset	+= blocks * ca->sb.block_size;
162 			len	-= blocks * ca->sb.block_size;
163 			j = ((void *) j) + blocks * block_bytes(ca);
164 		}
165 	}
166 
167 	return ret;
168 }
169 
170 int bch_journal_read(struct cache_set *c, struct list_head *list)
171 {
172 #define read_bucket(b)							\
173 	({								\
174 		ret = journal_read_bucket(ca, list, b);			\
175 		__set_bit(b, bitmap);					\
176 		if (ret < 0)						\
177 			return ret;					\
178 		ret;							\
179 	})
180 
181 	struct cache *ca = c->cache;
182 	int ret = 0;
183 	struct journal_device *ja = &ca->journal;
184 	DECLARE_BITMAP(bitmap, SB_JOURNAL_BUCKETS);
185 	unsigned int i, l, r, m;
186 	uint64_t seq;
187 
188 	bitmap_zero(bitmap, SB_JOURNAL_BUCKETS);
189 	pr_debug("%u journal buckets\n", ca->sb.njournal_buckets);
190 
191 	/*
192 	 * Read journal buckets ordered by golden ratio hash to quickly
193 	 * find a sequence of buckets with valid journal entries
194 	 */
195 	for (i = 0; i < ca->sb.njournal_buckets; i++) {
196 		/*
197 		 * We must try the index l with ZERO first for
198 		 * correctness due to the scenario that the journal
199 		 * bucket is circular buffer which might have wrapped
200 		 */
201 		l = (i * 2654435769U) % ca->sb.njournal_buckets;
202 
203 		if (test_bit(l, bitmap))
204 			break;
205 
206 		if (read_bucket(l))
207 			goto bsearch;
208 	}
209 
210 	/*
211 	 * If that fails, check all the buckets we haven't checked
212 	 * already
213 	 */
214 	pr_debug("falling back to linear search\n");
215 
216 	for_each_clear_bit(l, bitmap, ca->sb.njournal_buckets)
217 		if (read_bucket(l))
218 			goto bsearch;
219 
220 	/* no journal entries on this device? */
221 	if (l == ca->sb.njournal_buckets)
222 		goto out;
223 bsearch:
224 	BUG_ON(list_empty(list));
225 
226 	/* Binary search */
227 	m = l;
228 	r = find_next_bit(bitmap, ca->sb.njournal_buckets, l + 1);
229 	pr_debug("starting binary search, l %u r %u\n", l, r);
230 
231 	while (l + 1 < r) {
232 		seq = list_entry(list->prev, struct journal_replay,
233 				 list)->j.seq;
234 
235 		m = (l + r) >> 1;
236 		read_bucket(m);
237 
238 		if (seq != list_entry(list->prev, struct journal_replay,
239 				      list)->j.seq)
240 			l = m;
241 		else
242 			r = m;
243 	}
244 
245 	/*
246 	 * Read buckets in reverse order until we stop finding more
247 	 * journal entries
248 	 */
249 	pr_debug("finishing up: m %u njournal_buckets %u\n",
250 		 m, ca->sb.njournal_buckets);
251 	l = m;
252 
253 	while (1) {
254 		if (!l--)
255 			l = ca->sb.njournal_buckets - 1;
256 
257 		if (l == m)
258 			break;
259 
260 		if (test_bit(l, bitmap))
261 			continue;
262 
263 		if (!read_bucket(l))
264 			break;
265 	}
266 
267 	seq = 0;
268 
269 	for (i = 0; i < ca->sb.njournal_buckets; i++)
270 		if (ja->seq[i] > seq) {
271 			seq = ja->seq[i];
272 			/*
273 			 * When journal_reclaim() goes to allocate for
274 			 * the first time, it'll use the bucket after
275 			 * ja->cur_idx
276 			 */
277 			ja->cur_idx = i;
278 			ja->last_idx = (i + 1) % ca->sb.njournal_buckets;
279 
280 		}
281 
282 out:
283 	if (!list_empty(list))
284 		c->journal.seq = list_entry(list->prev,
285 					    struct journal_replay,
286 					    list)->j.seq;
287 
288 	return 0;
289 #undef read_bucket
290 }
291 
292 void bch_journal_mark(struct cache_set *c, struct list_head *list)
293 {
294 	atomic_t p = { 0 };
295 	struct bkey *k;
296 	struct journal_replay *i;
297 	struct journal *j = &c->journal;
298 	uint64_t last = j->seq;
299 
300 	/*
301 	 * journal.pin should never fill up - we never write a journal
302 	 * entry when it would fill up. But if for some reason it does, we
303 	 * iterate over the list in reverse order so that we can just skip that
304 	 * refcount instead of bugging.
305 	 */
306 
307 	list_for_each_entry_reverse(i, list, list) {
308 		BUG_ON(last < i->j.seq);
309 		i->pin = NULL;
310 
311 		while (last-- != i->j.seq)
312 			if (fifo_free(&j->pin) > 1) {
313 				fifo_push_front(&j->pin, p);
314 				atomic_set(&fifo_front(&j->pin), 0);
315 			}
316 
317 		if (fifo_free(&j->pin) > 1) {
318 			fifo_push_front(&j->pin, p);
319 			i->pin = &fifo_front(&j->pin);
320 			atomic_set(i->pin, 1);
321 		}
322 
323 		for (k = i->j.start;
324 		     k < bset_bkey_last(&i->j);
325 		     k = bkey_next(k))
326 			if (!__bch_extent_invalid(c, k)) {
327 				unsigned int j;
328 
329 				for (j = 0; j < KEY_PTRS(k); j++)
330 					if (ptr_available(c, k, j))
331 						atomic_inc(&PTR_BUCKET(c, k, j)->pin);
332 
333 				bch_initial_mark_key(c, 0, k);
334 			}
335 	}
336 }
337 
338 int bch_journal_replay(struct cache_set *s, struct list_head *list)
339 {
340 	int ret = 0, keys = 0, entries = 0;
341 	struct bkey *k;
342 	struct journal_replay *i =
343 		list_entry(list->prev, struct journal_replay, list);
344 
345 	uint64_t start = i->j.last_seq, end = i->j.seq, n = start;
346 	struct keylist keylist;
347 
348 	list_for_each_entry(i, list, list) {
349 		BUG_ON(i->pin && atomic_read(i->pin) != 1);
350 
351 		if (n != i->j.seq) {
352 			pr_err("journal entries %llu-%llu missing! (replaying %llu-%llu)\n",
353 				n, i->j.seq - 1, start, end);
354 			ret = -EIO;
355 			goto err;
356 		}
357 
358 		for (k = i->j.start;
359 		     k < bset_bkey_last(&i->j);
360 		     k = bkey_next(k)) {
361 			trace_bcache_journal_replay_key(k);
362 
363 			bch_keylist_init_single(&keylist, k);
364 
365 			ret = bch_btree_insert(s, &keylist, i->pin, NULL);
366 			if (ret)
367 				goto err;
368 
369 			BUG_ON(!bch_keylist_empty(&keylist));
370 			keys++;
371 
372 			cond_resched();
373 		}
374 
375 		if (i->pin)
376 			atomic_dec(i->pin);
377 		n = i->j.seq + 1;
378 		entries++;
379 	}
380 
381 	pr_info("journal replay done, %i keys in %i entries, seq %llu\n",
382 		keys, entries, end);
383 err:
384 	while (!list_empty(list)) {
385 		i = list_first_entry(list, struct journal_replay, list);
386 		list_del(&i->list);
387 		kfree(i);
388 	}
389 
390 	return ret;
391 }
392 
393 void bch_journal_space_reserve(struct journal *j)
394 {
395 	j->do_reserve = true;
396 }
397 
398 /* Journalling */
399 
400 static void btree_flush_write(struct cache_set *c)
401 {
402 	struct btree *b, *t, *btree_nodes[BTREE_FLUSH_NR];
403 	unsigned int i, nr;
404 	int ref_nr;
405 	atomic_t *fifo_front_p, *now_fifo_front_p;
406 	size_t mask;
407 
408 	if (c->journal.btree_flushing)
409 		return;
410 
411 	spin_lock(&c->journal.flush_write_lock);
412 	if (c->journal.btree_flushing) {
413 		spin_unlock(&c->journal.flush_write_lock);
414 		return;
415 	}
416 	c->journal.btree_flushing = true;
417 	spin_unlock(&c->journal.flush_write_lock);
418 
419 	/* get the oldest journal entry and check its refcount */
420 	spin_lock(&c->journal.lock);
421 	fifo_front_p = &fifo_front(&c->journal.pin);
422 	ref_nr = atomic_read(fifo_front_p);
423 	if (ref_nr <= 0) {
424 		/*
425 		 * do nothing if no btree node references
426 		 * the oldest journal entry
427 		 */
428 		spin_unlock(&c->journal.lock);
429 		goto out;
430 	}
431 	spin_unlock(&c->journal.lock);
432 
433 	mask = c->journal.pin.mask;
434 	nr = 0;
435 	atomic_long_inc(&c->flush_write);
436 	memset(btree_nodes, 0, sizeof(btree_nodes));
437 
438 	mutex_lock(&c->bucket_lock);
439 	list_for_each_entry_safe_reverse(b, t, &c->btree_cache, list) {
440 		/*
441 		 * It is safe to get now_fifo_front_p without holding
442 		 * c->journal.lock here, because we don't need to know
443 		 * the exactly accurate value, just check whether the
444 		 * front pointer of c->journal.pin is changed.
445 		 */
446 		now_fifo_front_p = &fifo_front(&c->journal.pin);
447 		/*
448 		 * If the oldest journal entry is reclaimed and front
449 		 * pointer of c->journal.pin changes, it is unnecessary
450 		 * to scan c->btree_cache anymore, just quit the loop and
451 		 * flush out what we have already.
452 		 */
453 		if (now_fifo_front_p != fifo_front_p)
454 			break;
455 		/*
456 		 * quit this loop if all matching btree nodes are
457 		 * scanned and record in btree_nodes[] already.
458 		 */
459 		ref_nr = atomic_read(fifo_front_p);
460 		if (nr >= ref_nr)
461 			break;
462 
463 		if (btree_node_journal_flush(b))
464 			pr_err("BUG: flush_write bit should not be set here!\n");
465 
466 		mutex_lock(&b->write_lock);
467 
468 		if (!btree_node_dirty(b)) {
469 			mutex_unlock(&b->write_lock);
470 			continue;
471 		}
472 
473 		if (!btree_current_write(b)->journal) {
474 			mutex_unlock(&b->write_lock);
475 			continue;
476 		}
477 
478 		/*
479 		 * Only select the btree node which exactly references
480 		 * the oldest journal entry.
481 		 *
482 		 * If the journal entry pointed by fifo_front_p is
483 		 * reclaimed in parallel, don't worry:
484 		 * - the list_for_each_xxx loop will quit when checking
485 		 *   next now_fifo_front_p.
486 		 * - If there are matched nodes recorded in btree_nodes[],
487 		 *   they are clean now (this is why and how the oldest
488 		 *   journal entry can be reclaimed). These selected nodes
489 		 *   will be ignored and skipped in the following for-loop.
490 		 */
491 		if (((btree_current_write(b)->journal - fifo_front_p) &
492 		     mask) != 0) {
493 			mutex_unlock(&b->write_lock);
494 			continue;
495 		}
496 
497 		set_btree_node_journal_flush(b);
498 
499 		mutex_unlock(&b->write_lock);
500 
501 		btree_nodes[nr++] = b;
502 		/*
503 		 * To avoid holding c->bucket_lock too long time,
504 		 * only scan for BTREE_FLUSH_NR matched btree nodes
505 		 * at most. If there are more btree nodes reference
506 		 * the oldest journal entry, try to flush them next
507 		 * time when btree_flush_write() is called.
508 		 */
509 		if (nr == BTREE_FLUSH_NR)
510 			break;
511 	}
512 	mutex_unlock(&c->bucket_lock);
513 
514 	for (i = 0; i < nr; i++) {
515 		b = btree_nodes[i];
516 		if (!b) {
517 			pr_err("BUG: btree_nodes[%d] is NULL\n", i);
518 			continue;
519 		}
520 
521 		/* safe to check without holding b->write_lock */
522 		if (!btree_node_journal_flush(b)) {
523 			pr_err("BUG: bnode %p: journal_flush bit cleaned\n", b);
524 			continue;
525 		}
526 
527 		mutex_lock(&b->write_lock);
528 		if (!btree_current_write(b)->journal) {
529 			clear_bit(BTREE_NODE_journal_flush, &b->flags);
530 			mutex_unlock(&b->write_lock);
531 			pr_debug("bnode %p: written by others\n", b);
532 			continue;
533 		}
534 
535 		if (!btree_node_dirty(b)) {
536 			clear_bit(BTREE_NODE_journal_flush, &b->flags);
537 			mutex_unlock(&b->write_lock);
538 			pr_debug("bnode %p: dirty bit cleaned by others\n", b);
539 			continue;
540 		}
541 
542 		__bch_btree_node_write(b, NULL);
543 		clear_bit(BTREE_NODE_journal_flush, &b->flags);
544 		mutex_unlock(&b->write_lock);
545 	}
546 
547 out:
548 	spin_lock(&c->journal.flush_write_lock);
549 	c->journal.btree_flushing = false;
550 	spin_unlock(&c->journal.flush_write_lock);
551 }
552 
553 #define last_seq(j)	((j)->seq - fifo_used(&(j)->pin) + 1)
554 
555 static unsigned int free_journal_buckets(struct cache_set *c)
556 {
557 	struct journal *j = &c->journal;
558 	struct cache *ca = c->cache;
559 	struct journal_device *ja = &c->cache->journal;
560 	unsigned int n;
561 
562 	/* In case njournal_buckets is not power of 2 */
563 	if (ja->cur_idx >= ja->last_idx)
564 		n = ca->sb.njournal_buckets + ja->last_idx - ja->cur_idx;
565 	else
566 		n = ja->last_idx - ja->cur_idx;
567 
568 	if (n > (1 + j->do_reserve))
569 		return n - (1 + j->do_reserve);
570 
571 	return 0;
572 }
573 
574 static void journal_reclaim(struct cache_set *c)
575 {
576 	struct bkey *k = &c->journal.key;
577 	struct cache *ca = c->cache;
578 	uint64_t last_seq;
579 	struct journal_device *ja = &ca->journal;
580 	atomic_t p __maybe_unused;
581 
582 	atomic_long_inc(&c->reclaim);
583 
584 	while (!atomic_read(&fifo_front(&c->journal.pin)))
585 		fifo_pop(&c->journal.pin, p);
586 
587 	last_seq = last_seq(&c->journal);
588 
589 	/* Update last_idx */
590 
591 	while (ja->last_idx != ja->cur_idx &&
592 	       ja->seq[ja->last_idx] < last_seq)
593 		ja->last_idx = (ja->last_idx + 1) %
594 			ca->sb.njournal_buckets;
595 
596 	if (c->journal.blocks_free)
597 		goto out;
598 
599 	if (!free_journal_buckets(c))
600 		goto out;
601 
602 	ja->cur_idx = (ja->cur_idx + 1) % ca->sb.njournal_buckets;
603 	k->ptr[0] = MAKE_PTR(0,
604 			     bucket_to_sector(c, ca->sb.d[ja->cur_idx]),
605 			     ca->sb.nr_this_dev);
606 	atomic_long_inc(&c->reclaimed_journal_buckets);
607 
608 	bkey_init(k);
609 	SET_KEY_PTRS(k, 1);
610 	c->journal.blocks_free = ca->sb.bucket_size >> c->block_bits;
611 
612 out:
613 	if (!journal_full(&c->journal))
614 		__closure_wake_up(&c->journal.wait);
615 }
616 
617 void bch_journal_next(struct journal *j)
618 {
619 	atomic_t p = { 1 };
620 
621 	j->cur = (j->cur == j->w)
622 		? &j->w[1]
623 		: &j->w[0];
624 
625 	/*
626 	 * The fifo_push() needs to happen at the same time as j->seq is
627 	 * incremented for last_seq() to be calculated correctly
628 	 */
629 	BUG_ON(!fifo_push(&j->pin, p));
630 	atomic_set(&fifo_back(&j->pin), 1);
631 
632 	j->cur->data->seq	= ++j->seq;
633 	j->cur->dirty		= false;
634 	j->cur->need_write	= false;
635 	j->cur->data->keys	= 0;
636 
637 	if (fifo_full(&j->pin))
638 		pr_debug("journal_pin full (%zu)\n", fifo_used(&j->pin));
639 }
640 
641 static void journal_write_endio(struct bio *bio)
642 {
643 	struct journal_write *w = bio->bi_private;
644 
645 	cache_set_err_on(bio->bi_status, w->c, "journal io error");
646 	closure_put(&w->c->journal.io);
647 }
648 
649 static CLOSURE_CALLBACK(journal_write);
650 
651 static CLOSURE_CALLBACK(journal_write_done)
652 {
653 	closure_type(j, struct journal, io);
654 	struct journal_write *w = (j->cur == j->w)
655 		? &j->w[1]
656 		: &j->w[0];
657 
658 	__closure_wake_up(&w->wait);
659 	continue_at_nobarrier(cl, journal_write, bch_journal_wq);
660 }
661 
662 static CLOSURE_CALLBACK(journal_write_unlock)
663 	__releases(&c->journal.lock)
664 {
665 	closure_type(c, struct cache_set, journal.io);
666 
667 	c->journal.io_in_flight = 0;
668 	spin_unlock(&c->journal.lock);
669 }
670 
671 static CLOSURE_CALLBACK(journal_write_unlocked)
672 	__releases(c->journal.lock)
673 {
674 	closure_type(c, struct cache_set, journal.io);
675 	struct cache *ca = c->cache;
676 	struct journal_write *w = c->journal.cur;
677 	struct bkey *k = &c->journal.key;
678 	unsigned int i, sectors = set_blocks(w->data, block_bytes(ca)) *
679 		ca->sb.block_size;
680 
681 	struct bio *bio;
682 	struct bio_list list;
683 
684 	bio_list_init(&list);
685 
686 	if (!w->need_write) {
687 		closure_return_with_destructor(cl, journal_write_unlock);
688 		return;
689 	} else if (journal_full(&c->journal)) {
690 		journal_reclaim(c);
691 		spin_unlock(&c->journal.lock);
692 
693 		btree_flush_write(c);
694 		continue_at(cl, journal_write, bch_journal_wq);
695 		return;
696 	}
697 
698 	c->journal.blocks_free -= set_blocks(w->data, block_bytes(ca));
699 
700 	w->data->btree_level = c->root->level;
701 
702 	bkey_copy(&w->data->btree_root, &c->root->key);
703 	bkey_copy(&w->data->uuid_bucket, &c->uuid_bucket);
704 
705 	w->data->prio_bucket[ca->sb.nr_this_dev] = ca->prio_buckets[0];
706 	w->data->magic		= jset_magic(&ca->sb);
707 	w->data->version	= BCACHE_JSET_VERSION;
708 	w->data->last_seq	= last_seq(&c->journal);
709 	w->data->csum		= csum_set(w->data);
710 
711 	for (i = 0; i < KEY_PTRS(k); i++) {
712 		ca = c->cache;
713 		bio = &ca->journal.bio;
714 
715 		atomic_long_add(sectors, &ca->meta_sectors_written);
716 
717 		bio_reset(bio, ca->bdev, REQ_OP_WRITE |
718 			  REQ_SYNC | REQ_META | REQ_PREFLUSH | REQ_FUA);
719 		bio->bi_iter.bi_sector	= PTR_OFFSET(k, i);
720 		bio->bi_iter.bi_size = sectors << 9;
721 
722 		bio->bi_end_io	= journal_write_endio;
723 		bio->bi_private = w;
724 		bch_bio_map(bio, w->data);
725 
726 		trace_bcache_journal_write(bio, w->data->keys);
727 		bio_list_add(&list, bio);
728 
729 		SET_PTR_OFFSET(k, i, PTR_OFFSET(k, i) + sectors);
730 
731 		ca->journal.seq[ca->journal.cur_idx] = w->data->seq;
732 	}
733 
734 	/* If KEY_PTRS(k) == 0, this jset gets lost in air */
735 	BUG_ON(i == 0);
736 
737 	atomic_dec_bug(&fifo_back(&c->journal.pin));
738 	bch_journal_next(&c->journal);
739 	journal_reclaim(c);
740 
741 	spin_unlock(&c->journal.lock);
742 
743 	while ((bio = bio_list_pop(&list)))
744 		closure_bio_submit(c, bio, cl);
745 
746 	continue_at(cl, journal_write_done, NULL);
747 }
748 
749 static CLOSURE_CALLBACK(journal_write)
750 {
751 	closure_type(c, struct cache_set, journal.io);
752 
753 	spin_lock(&c->journal.lock);
754 	journal_write_unlocked(&cl->work);
755 }
756 
757 static void journal_try_write(struct cache_set *c)
758 	__releases(c->journal.lock)
759 {
760 	struct closure *cl = &c->journal.io;
761 	struct journal_write *w = c->journal.cur;
762 
763 	w->need_write = true;
764 
765 	if (!c->journal.io_in_flight) {
766 		c->journal.io_in_flight = 1;
767 		closure_call(cl, journal_write_unlocked, NULL, &c->cl);
768 	} else {
769 		spin_unlock(&c->journal.lock);
770 	}
771 }
772 
773 static struct journal_write *journal_wait_for_write(struct cache_set *c,
774 						    unsigned int nkeys)
775 	__acquires(&c->journal.lock)
776 {
777 	size_t sectors;
778 	struct closure cl;
779 	bool wait = false;
780 	struct cache *ca = c->cache;
781 
782 	closure_init_stack(&cl);
783 
784 	spin_lock(&c->journal.lock);
785 
786 	while (1) {
787 		struct journal_write *w = c->journal.cur;
788 
789 		sectors = __set_blocks(w->data, w->data->keys + nkeys,
790 				       block_bytes(ca)) * ca->sb.block_size;
791 
792 		if (sectors <= min_t(size_t,
793 				     c->journal.blocks_free * ca->sb.block_size,
794 				     PAGE_SECTORS << JSET_BITS))
795 			return w;
796 
797 		if (wait)
798 			closure_wait(&c->journal.wait, &cl);
799 
800 		if (!journal_full(&c->journal)) {
801 			if (wait)
802 				trace_bcache_journal_entry_full(c);
803 
804 			/*
805 			 * XXX: If we were inserting so many keys that they
806 			 * won't fit in an _empty_ journal write, we'll
807 			 * deadlock. For now, handle this in
808 			 * bch_keylist_realloc() - but something to think about.
809 			 */
810 			BUG_ON(!w->data->keys);
811 
812 			journal_try_write(c); /* unlocks */
813 		} else {
814 			if (wait)
815 				trace_bcache_journal_full(c);
816 
817 			journal_reclaim(c);
818 			spin_unlock(&c->journal.lock);
819 
820 			btree_flush_write(c);
821 		}
822 
823 		closure_sync(&cl);
824 		spin_lock(&c->journal.lock);
825 		wait = true;
826 	}
827 }
828 
829 static void journal_write_work(struct work_struct *work)
830 {
831 	struct cache_set *c = container_of(to_delayed_work(work),
832 					   struct cache_set,
833 					   journal.work);
834 	spin_lock(&c->journal.lock);
835 	if (c->journal.cur->dirty)
836 		journal_try_write(c);
837 	else
838 		spin_unlock(&c->journal.lock);
839 }
840 
841 /*
842  * Entry point to the journalling code - bio_insert() and btree_invalidate()
843  * pass bch_journal() a list of keys to be journalled, and then
844  * bch_journal() hands those same keys off to btree_insert_async()
845  */
846 
847 atomic_t *bch_journal(struct cache_set *c,
848 		      struct keylist *keys,
849 		      struct closure *parent)
850 {
851 	struct journal_write *w;
852 	atomic_t *ret;
853 
854 	/* No journaling if CACHE_SET_IO_DISABLE set already */
855 	if (unlikely(test_bit(CACHE_SET_IO_DISABLE, &c->flags)))
856 		return NULL;
857 
858 	if (!CACHE_SYNC(&c->cache->sb))
859 		return NULL;
860 
861 	w = journal_wait_for_write(c, bch_keylist_nkeys(keys));
862 
863 	memcpy(bset_bkey_last(w->data), keys->keys, bch_keylist_bytes(keys));
864 	w->data->keys += bch_keylist_nkeys(keys);
865 
866 	ret = &fifo_back(&c->journal.pin);
867 	atomic_inc(ret);
868 
869 	if (parent) {
870 		closure_wait(&w->wait, parent);
871 		journal_try_write(c);
872 	} else if (!w->dirty) {
873 		w->dirty = true;
874 		queue_delayed_work(bch_flush_wq, &c->journal.work,
875 				   msecs_to_jiffies(c->journal_delay_ms));
876 		spin_unlock(&c->journal.lock);
877 	} else {
878 		spin_unlock(&c->journal.lock);
879 	}
880 
881 
882 	return ret;
883 }
884 
885 void bch_journal_meta(struct cache_set *c, struct closure *cl)
886 {
887 	struct keylist keys;
888 	atomic_t *ref;
889 
890 	bch_keylist_init(&keys);
891 
892 	ref = bch_journal(c, &keys, cl);
893 	if (ref)
894 		atomic_dec_bug(ref);
895 }
896 
897 void bch_journal_free(struct cache_set *c)
898 {
899 	free_pages((unsigned long) c->journal.w[1].data, JSET_BITS);
900 	free_pages((unsigned long) c->journal.w[0].data, JSET_BITS);
901 	free_fifo(&c->journal.pin);
902 }
903 
904 int bch_journal_alloc(struct cache_set *c)
905 {
906 	struct journal *j = &c->journal;
907 
908 	spin_lock_init(&j->lock);
909 	spin_lock_init(&j->flush_write_lock);
910 	INIT_DELAYED_WORK(&j->work, journal_write_work);
911 
912 	c->journal_delay_ms = 100;
913 
914 	j->w[0].c = c;
915 	j->w[1].c = c;
916 
917 	if (!(init_fifo(&j->pin, JOURNAL_PIN, GFP_KERNEL)) ||
918 	    !(j->w[0].data = (void *) __get_free_pages(GFP_KERNEL|__GFP_COMP, JSET_BITS)) ||
919 	    !(j->w[1].data = (void *) __get_free_pages(GFP_KERNEL|__GFP_COMP, JSET_BITS)))
920 		return -ENOMEM;
921 
922 	return 0;
923 }
924