xref: /openbmc/linux/drivers/md/bcache/journal.c (revision 1fae7cf05293d3a2c9e59c1bc59372322386467c)
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", 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);
57 		bio->bi_iter.bi_sector	= bucket + offset;
58 		bio_set_dev(bio, ca->bdev);
59 		bio->bi_iter.bi_size	= len << 9;
60 
61 		bio->bi_end_io	= journal_read_endio;
62 		bio->bi_private = &cl;
63 		bio_set_op_attrs(bio, REQ_OP_READ, 0);
64 		bch_bio_map(bio, data);
65 
66 		closure_bio_submit(ca->set, bio, &cl);
67 		closure_sync(&cl);
68 
69 		/* This function could be simpler now since we no longer write
70 		 * journal entries that overlap bucket boundaries; this means
71 		 * the start of a bucket will always have a valid journal entry
72 		 * if it has any journal entries at all.
73 		 */
74 
75 		j = data;
76 		while (len) {
77 			struct list_head *where;
78 			size_t blocks, bytes = set_bytes(j);
79 
80 			if (j->magic != jset_magic(&ca->sb)) {
81 				pr_debug("%u: bad magic", bucket_index);
82 				return ret;
83 			}
84 
85 			if (bytes > left << 9 ||
86 			    bytes > PAGE_SIZE << JSET_BITS) {
87 				pr_info("%u: too big, %zu bytes, offset %u",
88 					bucket_index, bytes, offset);
89 				return ret;
90 			}
91 
92 			if (bytes > len << 9)
93 				goto reread;
94 
95 			if (j->csum != csum_set(j)) {
96 				pr_info("%u: bad csum, %zu bytes, offset %u",
97 					bucket_index, bytes, offset);
98 				return ret;
99 			}
100 
101 			blocks = set_blocks(j, block_bytes(ca->set));
102 
103 			while (!list_empty(list)) {
104 				i = list_first_entry(list,
105 					struct journal_replay, list);
106 				if (i->j.seq >= j->last_seq)
107 					break;
108 				list_del(&i->list);
109 				kfree(i);
110 			}
111 
112 			list_for_each_entry_reverse(i, list, list) {
113 				if (j->seq == i->j.seq)
114 					goto next_set;
115 
116 				if (j->seq < i->j.last_seq)
117 					goto next_set;
118 
119 				if (j->seq > i->j.seq) {
120 					where = &i->list;
121 					goto add;
122 				}
123 			}
124 
125 			where = list;
126 add:
127 			i = kmalloc(offsetof(struct journal_replay, j) +
128 				    bytes, GFP_KERNEL);
129 			if (!i)
130 				return -ENOMEM;
131 			memcpy(&i->j, j, bytes);
132 			list_add(&i->list, where);
133 			ret = 1;
134 
135 			ja->seq[bucket_index] = j->seq;
136 next_set:
137 			offset	+= blocks * ca->sb.block_size;
138 			len	-= blocks * ca->sb.block_size;
139 			j = ((void *) j) + blocks * block_bytes(ca);
140 		}
141 	}
142 
143 	return ret;
144 }
145 
146 int bch_journal_read(struct cache_set *c, struct list_head *list)
147 {
148 #define read_bucket(b)							\
149 	({								\
150 		int ret = journal_read_bucket(ca, list, b);		\
151 		__set_bit(b, bitmap);					\
152 		if (ret < 0)						\
153 			return ret;					\
154 		ret;							\
155 	})
156 
157 	struct cache *ca;
158 	unsigned int iter;
159 
160 	for_each_cache(ca, c, iter) {
161 		struct journal_device *ja = &ca->journal;
162 		DECLARE_BITMAP(bitmap, SB_JOURNAL_BUCKETS);
163 		unsigned int i, l, r, m;
164 		uint64_t seq;
165 
166 		bitmap_zero(bitmap, SB_JOURNAL_BUCKETS);
167 		pr_debug("%u journal buckets", ca->sb.njournal_buckets);
168 
169 		/*
170 		 * Read journal buckets ordered by golden ratio hash to quickly
171 		 * find a sequence of buckets with valid journal entries
172 		 */
173 		for (i = 0; i < ca->sb.njournal_buckets; i++) {
174 			/*
175 			 * We must try the index l with ZERO first for
176 			 * correctness due to the scenario that the journal
177 			 * bucket is circular buffer which might have wrapped
178 			 */
179 			l = (i * 2654435769U) % ca->sb.njournal_buckets;
180 
181 			if (test_bit(l, bitmap))
182 				break;
183 
184 			if (read_bucket(l))
185 				goto bsearch;
186 		}
187 
188 		/*
189 		 * If that fails, check all the buckets we haven't checked
190 		 * already
191 		 */
192 		pr_debug("falling back to linear search");
193 
194 		for (l = find_first_zero_bit(bitmap, ca->sb.njournal_buckets);
195 		     l < ca->sb.njournal_buckets;
196 		     l = find_next_zero_bit(bitmap, ca->sb.njournal_buckets, l + 1))
197 			if (read_bucket(l))
198 				goto bsearch;
199 
200 		/* no journal entries on this device? */
201 		if (l == ca->sb.njournal_buckets)
202 			continue;
203 bsearch:
204 		BUG_ON(list_empty(list));
205 
206 		/* Binary search */
207 		m = l;
208 		r = find_next_bit(bitmap, ca->sb.njournal_buckets, l + 1);
209 		pr_debug("starting binary search, l %u r %u", l, r);
210 
211 		while (l + 1 < r) {
212 			seq = list_entry(list->prev, struct journal_replay,
213 					 list)->j.seq;
214 
215 			m = (l + r) >> 1;
216 			read_bucket(m);
217 
218 			if (seq != list_entry(list->prev, struct journal_replay,
219 					      list)->j.seq)
220 				l = m;
221 			else
222 				r = m;
223 		}
224 
225 		/*
226 		 * Read buckets in reverse order until we stop finding more
227 		 * journal entries
228 		 */
229 		pr_debug("finishing up: m %u njournal_buckets %u",
230 			 m, ca->sb.njournal_buckets);
231 		l = m;
232 
233 		while (1) {
234 			if (!l--)
235 				l = ca->sb.njournal_buckets - 1;
236 
237 			if (l == m)
238 				break;
239 
240 			if (test_bit(l, bitmap))
241 				continue;
242 
243 			if (!read_bucket(l))
244 				break;
245 		}
246 
247 		seq = 0;
248 
249 		for (i = 0; i < ca->sb.njournal_buckets; i++)
250 			if (ja->seq[i] > seq) {
251 				seq = ja->seq[i];
252 				/*
253 				 * When journal_reclaim() goes to allocate for
254 				 * the first time, it'll use the bucket after
255 				 * ja->cur_idx
256 				 */
257 				ja->cur_idx = i;
258 				ja->last_idx = ja->discard_idx = (i + 1) %
259 					ca->sb.njournal_buckets;
260 
261 			}
262 	}
263 
264 	if (!list_empty(list))
265 		c->journal.seq = list_entry(list->prev,
266 					    struct journal_replay,
267 					    list)->j.seq;
268 
269 	return 0;
270 #undef read_bucket
271 }
272 
273 void bch_journal_mark(struct cache_set *c, struct list_head *list)
274 {
275 	atomic_t p = { 0 };
276 	struct bkey *k;
277 	struct journal_replay *i;
278 	struct journal *j = &c->journal;
279 	uint64_t last = j->seq;
280 
281 	/*
282 	 * journal.pin should never fill up - we never write a journal
283 	 * entry when it would fill up. But if for some reason it does, we
284 	 * iterate over the list in reverse order so that we can just skip that
285 	 * refcount instead of bugging.
286 	 */
287 
288 	list_for_each_entry_reverse(i, list, list) {
289 		BUG_ON(last < i->j.seq);
290 		i->pin = NULL;
291 
292 		while (last-- != i->j.seq)
293 			if (fifo_free(&j->pin) > 1) {
294 				fifo_push_front(&j->pin, p);
295 				atomic_set(&fifo_front(&j->pin), 0);
296 			}
297 
298 		if (fifo_free(&j->pin) > 1) {
299 			fifo_push_front(&j->pin, p);
300 			i->pin = &fifo_front(&j->pin);
301 			atomic_set(i->pin, 1);
302 		}
303 
304 		for (k = i->j.start;
305 		     k < bset_bkey_last(&i->j);
306 		     k = bkey_next(k))
307 			if (!__bch_extent_invalid(c, k)) {
308 				unsigned int j;
309 
310 				for (j = 0; j < KEY_PTRS(k); j++)
311 					if (ptr_available(c, k, j))
312 						atomic_inc(&PTR_BUCKET(c, k, j)->pin);
313 
314 				bch_initial_mark_key(c, 0, k);
315 			}
316 	}
317 }
318 
319 int bch_journal_replay(struct cache_set *s, struct list_head *list)
320 {
321 	int ret = 0, keys = 0, entries = 0;
322 	struct bkey *k;
323 	struct journal_replay *i =
324 		list_entry(list->prev, struct journal_replay, list);
325 
326 	uint64_t start = i->j.last_seq, end = i->j.seq, n = start;
327 	struct keylist keylist;
328 
329 	list_for_each_entry(i, list, list) {
330 		BUG_ON(i->pin && atomic_read(i->pin) != 1);
331 
332 		cache_set_err_on(n != i->j.seq, s,
333 "bcache: journal entries %llu-%llu missing! (replaying %llu-%llu)",
334 				 n, i->j.seq - 1, start, end);
335 
336 		for (k = i->j.start;
337 		     k < bset_bkey_last(&i->j);
338 		     k = bkey_next(k)) {
339 			trace_bcache_journal_replay_key(k);
340 
341 			bch_keylist_init_single(&keylist, k);
342 
343 			ret = bch_btree_insert(s, &keylist, i->pin, NULL);
344 			if (ret)
345 				goto err;
346 
347 			BUG_ON(!bch_keylist_empty(&keylist));
348 			keys++;
349 
350 			cond_resched();
351 		}
352 
353 		if (i->pin)
354 			atomic_dec(i->pin);
355 		n = i->j.seq + 1;
356 		entries++;
357 	}
358 
359 	pr_info("journal replay done, %i keys in %i entries, seq %llu",
360 		keys, entries, end);
361 err:
362 	while (!list_empty(list)) {
363 		i = list_first_entry(list, struct journal_replay, list);
364 		list_del(&i->list);
365 		kfree(i);
366 	}
367 
368 	return ret;
369 }
370 
371 /* Journalling */
372 #define journal_max_cmp(l, r) \
373 	(fifo_idx(&c->journal.pin, btree_current_write(l)->journal) < \
374 	 fifo_idx(&(c)->journal.pin, btree_current_write(r)->journal))
375 #define journal_min_cmp(l, r) \
376 	(fifo_idx(&c->journal.pin, btree_current_write(l)->journal) > \
377 	 fifo_idx(&(c)->journal.pin, btree_current_write(r)->journal))
378 
379 static void btree_flush_write(struct cache_set *c)
380 {
381 	/*
382 	 * Try to find the btree node with that references the oldest journal
383 	 * entry, best is our current candidate and is locked if non NULL:
384 	 */
385 	struct btree *b;
386 	int i;
387 
388 	atomic_long_inc(&c->flush_write);
389 
390 retry:
391 	spin_lock(&c->journal.lock);
392 	if (heap_empty(&c->flush_btree)) {
393 		for_each_cached_btree(b, c, i)
394 			if (btree_current_write(b)->journal) {
395 				if (!heap_full(&c->flush_btree))
396 					heap_add(&c->flush_btree, b,
397 						 journal_max_cmp);
398 				else if (journal_max_cmp(b,
399 					 heap_peek(&c->flush_btree))) {
400 					c->flush_btree.data[0] = b;
401 					heap_sift(&c->flush_btree, 0,
402 						  journal_max_cmp);
403 				}
404 			}
405 
406 		for (i = c->flush_btree.used / 2 - 1; i >= 0; --i)
407 			heap_sift(&c->flush_btree, i, journal_min_cmp);
408 	}
409 
410 	b = NULL;
411 	heap_pop(&c->flush_btree, b, journal_min_cmp);
412 	spin_unlock(&c->journal.lock);
413 
414 	if (b) {
415 		mutex_lock(&b->write_lock);
416 		if (!btree_current_write(b)->journal) {
417 			mutex_unlock(&b->write_lock);
418 			/* We raced */
419 			atomic_long_inc(&c->retry_flush_write);
420 			goto retry;
421 		}
422 
423 		__bch_btree_node_write(b, NULL);
424 		mutex_unlock(&b->write_lock);
425 	}
426 }
427 
428 #define last_seq(j)	((j)->seq - fifo_used(&(j)->pin) + 1)
429 
430 static void journal_discard_endio(struct bio *bio)
431 {
432 	struct journal_device *ja =
433 		container_of(bio, struct journal_device, discard_bio);
434 	struct cache *ca = container_of(ja, struct cache, journal);
435 
436 	atomic_set(&ja->discard_in_flight, DISCARD_DONE);
437 
438 	closure_wake_up(&ca->set->journal.wait);
439 	closure_put(&ca->set->cl);
440 }
441 
442 static void journal_discard_work(struct work_struct *work)
443 {
444 	struct journal_device *ja =
445 		container_of(work, struct journal_device, discard_work);
446 
447 	submit_bio(&ja->discard_bio);
448 }
449 
450 static void do_journal_discard(struct cache *ca)
451 {
452 	struct journal_device *ja = &ca->journal;
453 	struct bio *bio = &ja->discard_bio;
454 
455 	if (!ca->discard) {
456 		ja->discard_idx = ja->last_idx;
457 		return;
458 	}
459 
460 	switch (atomic_read(&ja->discard_in_flight)) {
461 	case DISCARD_IN_FLIGHT:
462 		return;
463 
464 	case DISCARD_DONE:
465 		ja->discard_idx = (ja->discard_idx + 1) %
466 			ca->sb.njournal_buckets;
467 
468 		atomic_set(&ja->discard_in_flight, DISCARD_READY);
469 		/* fallthrough */
470 
471 	case DISCARD_READY:
472 		if (ja->discard_idx == ja->last_idx)
473 			return;
474 
475 		atomic_set(&ja->discard_in_flight, DISCARD_IN_FLIGHT);
476 
477 		bio_init(bio, bio->bi_inline_vecs, 1);
478 		bio_set_op_attrs(bio, REQ_OP_DISCARD, 0);
479 		bio->bi_iter.bi_sector	= bucket_to_sector(ca->set,
480 						ca->sb.d[ja->discard_idx]);
481 		bio_set_dev(bio, ca->bdev);
482 		bio->bi_iter.bi_size	= bucket_bytes(ca);
483 		bio->bi_end_io		= journal_discard_endio;
484 
485 		closure_get(&ca->set->cl);
486 		INIT_WORK(&ja->discard_work, journal_discard_work);
487 		schedule_work(&ja->discard_work);
488 	}
489 }
490 
491 static void journal_reclaim(struct cache_set *c)
492 {
493 	struct bkey *k = &c->journal.key;
494 	struct cache *ca;
495 	uint64_t last_seq;
496 	unsigned int iter, n = 0;
497 	atomic_t p __maybe_unused;
498 
499 	atomic_long_inc(&c->reclaim);
500 
501 	while (!atomic_read(&fifo_front(&c->journal.pin)))
502 		fifo_pop(&c->journal.pin, p);
503 
504 	last_seq = last_seq(&c->journal);
505 
506 	/* Update last_idx */
507 
508 	for_each_cache(ca, c, iter) {
509 		struct journal_device *ja = &ca->journal;
510 
511 		while (ja->last_idx != ja->cur_idx &&
512 		       ja->seq[ja->last_idx] < last_seq)
513 			ja->last_idx = (ja->last_idx + 1) %
514 				ca->sb.njournal_buckets;
515 	}
516 
517 	for_each_cache(ca, c, iter)
518 		do_journal_discard(ca);
519 
520 	if (c->journal.blocks_free)
521 		goto out;
522 
523 	/*
524 	 * Allocate:
525 	 * XXX: Sort by free journal space
526 	 */
527 
528 	for_each_cache(ca, c, iter) {
529 		struct journal_device *ja = &ca->journal;
530 		unsigned int next = (ja->cur_idx + 1) % ca->sb.njournal_buckets;
531 
532 		/* No space available on this device */
533 		if (next == ja->discard_idx)
534 			continue;
535 
536 		ja->cur_idx = next;
537 		k->ptr[n++] = MAKE_PTR(0,
538 				  bucket_to_sector(c, ca->sb.d[ja->cur_idx]),
539 				  ca->sb.nr_this_dev);
540 	}
541 
542 	bkey_init(k);
543 	SET_KEY_PTRS(k, n);
544 
545 	if (n)
546 		c->journal.blocks_free = c->sb.bucket_size >> c->block_bits;
547 out:
548 	if (!journal_full(&c->journal))
549 		__closure_wake_up(&c->journal.wait);
550 }
551 
552 void bch_journal_next(struct journal *j)
553 {
554 	atomic_t p = { 1 };
555 
556 	j->cur = (j->cur == j->w)
557 		? &j->w[1]
558 		: &j->w[0];
559 
560 	/*
561 	 * The fifo_push() needs to happen at the same time as j->seq is
562 	 * incremented for last_seq() to be calculated correctly
563 	 */
564 	BUG_ON(!fifo_push(&j->pin, p));
565 	atomic_set(&fifo_back(&j->pin), 1);
566 
567 	j->cur->data->seq	= ++j->seq;
568 	j->cur->dirty		= false;
569 	j->cur->need_write	= false;
570 	j->cur->data->keys	= 0;
571 
572 	if (fifo_full(&j->pin))
573 		pr_debug("journal_pin full (%zu)", fifo_used(&j->pin));
574 }
575 
576 static void journal_write_endio(struct bio *bio)
577 {
578 	struct journal_write *w = bio->bi_private;
579 
580 	cache_set_err_on(bio->bi_status, w->c, "journal io error");
581 	closure_put(&w->c->journal.io);
582 }
583 
584 static void journal_write(struct closure *);
585 
586 static void journal_write_done(struct closure *cl)
587 {
588 	struct journal *j = container_of(cl, struct journal, io);
589 	struct journal_write *w = (j->cur == j->w)
590 		? &j->w[1]
591 		: &j->w[0];
592 
593 	__closure_wake_up(&w->wait);
594 	continue_at_nobarrier(cl, journal_write, system_wq);
595 }
596 
597 static void journal_write_unlock(struct closure *cl)
598 	__releases(&c->journal.lock)
599 {
600 	struct cache_set *c = container_of(cl, struct cache_set, journal.io);
601 
602 	c->journal.io_in_flight = 0;
603 	spin_unlock(&c->journal.lock);
604 }
605 
606 static void journal_write_unlocked(struct closure *cl)
607 	__releases(c->journal.lock)
608 {
609 	struct cache_set *c = container_of(cl, struct cache_set, journal.io);
610 	struct cache *ca;
611 	struct journal_write *w = c->journal.cur;
612 	struct bkey *k = &c->journal.key;
613 	unsigned int i, sectors = set_blocks(w->data, block_bytes(c)) *
614 		c->sb.block_size;
615 
616 	struct bio *bio;
617 	struct bio_list list;
618 
619 	bio_list_init(&list);
620 
621 	if (!w->need_write) {
622 		closure_return_with_destructor(cl, journal_write_unlock);
623 		return;
624 	} else if (journal_full(&c->journal)) {
625 		journal_reclaim(c);
626 		spin_unlock(&c->journal.lock);
627 
628 		btree_flush_write(c);
629 		continue_at(cl, journal_write, system_wq);
630 		return;
631 	}
632 
633 	c->journal.blocks_free -= set_blocks(w->data, block_bytes(c));
634 
635 	w->data->btree_level = c->root->level;
636 
637 	bkey_copy(&w->data->btree_root, &c->root->key);
638 	bkey_copy(&w->data->uuid_bucket, &c->uuid_bucket);
639 
640 	for_each_cache(ca, c, i)
641 		w->data->prio_bucket[ca->sb.nr_this_dev] = ca->prio_buckets[0];
642 
643 	w->data->magic		= jset_magic(&c->sb);
644 	w->data->version	= BCACHE_JSET_VERSION;
645 	w->data->last_seq	= last_seq(&c->journal);
646 	w->data->csum		= csum_set(w->data);
647 
648 	for (i = 0; i < KEY_PTRS(k); i++) {
649 		ca = PTR_CACHE(c, k, i);
650 		bio = &ca->journal.bio;
651 
652 		atomic_long_add(sectors, &ca->meta_sectors_written);
653 
654 		bio_reset(bio);
655 		bio->bi_iter.bi_sector	= PTR_OFFSET(k, i);
656 		bio_set_dev(bio, ca->bdev);
657 		bio->bi_iter.bi_size = sectors << 9;
658 
659 		bio->bi_end_io	= journal_write_endio;
660 		bio->bi_private = w;
661 		bio_set_op_attrs(bio, REQ_OP_WRITE,
662 				 REQ_SYNC|REQ_META|REQ_PREFLUSH|REQ_FUA);
663 		bch_bio_map(bio, w->data);
664 
665 		trace_bcache_journal_write(bio);
666 		bio_list_add(&list, bio);
667 
668 		SET_PTR_OFFSET(k, i, PTR_OFFSET(k, i) + sectors);
669 
670 		ca->journal.seq[ca->journal.cur_idx] = w->data->seq;
671 	}
672 
673 	atomic_dec_bug(&fifo_back(&c->journal.pin));
674 	bch_journal_next(&c->journal);
675 	journal_reclaim(c);
676 
677 	spin_unlock(&c->journal.lock);
678 
679 	while ((bio = bio_list_pop(&list)))
680 		closure_bio_submit(c, bio, cl);
681 
682 	continue_at(cl, journal_write_done, NULL);
683 }
684 
685 static void journal_write(struct closure *cl)
686 {
687 	struct cache_set *c = container_of(cl, struct cache_set, journal.io);
688 
689 	spin_lock(&c->journal.lock);
690 	journal_write_unlocked(cl);
691 }
692 
693 static void journal_try_write(struct cache_set *c)
694 	__releases(c->journal.lock)
695 {
696 	struct closure *cl = &c->journal.io;
697 	struct journal_write *w = c->journal.cur;
698 
699 	w->need_write = true;
700 
701 	if (!c->journal.io_in_flight) {
702 		c->journal.io_in_flight = 1;
703 		closure_call(cl, journal_write_unlocked, NULL, &c->cl);
704 	} else {
705 		spin_unlock(&c->journal.lock);
706 	}
707 }
708 
709 static struct journal_write *journal_wait_for_write(struct cache_set *c,
710 						    unsigned int nkeys)
711 	__acquires(&c->journal.lock)
712 {
713 	size_t sectors;
714 	struct closure cl;
715 	bool wait = false;
716 
717 	closure_init_stack(&cl);
718 
719 	spin_lock(&c->journal.lock);
720 
721 	while (1) {
722 		struct journal_write *w = c->journal.cur;
723 
724 		sectors = __set_blocks(w->data, w->data->keys + nkeys,
725 				       block_bytes(c)) * c->sb.block_size;
726 
727 		if (sectors <= min_t(size_t,
728 				     c->journal.blocks_free * c->sb.block_size,
729 				     PAGE_SECTORS << JSET_BITS))
730 			return w;
731 
732 		if (wait)
733 			closure_wait(&c->journal.wait, &cl);
734 
735 		if (!journal_full(&c->journal)) {
736 			if (wait)
737 				trace_bcache_journal_entry_full(c);
738 
739 			/*
740 			 * XXX: If we were inserting so many keys that they
741 			 * won't fit in an _empty_ journal write, we'll
742 			 * deadlock. For now, handle this in
743 			 * bch_keylist_realloc() - but something to think about.
744 			 */
745 			BUG_ON(!w->data->keys);
746 
747 			journal_try_write(c); /* unlocks */
748 		} else {
749 			if (wait)
750 				trace_bcache_journal_full(c);
751 
752 			journal_reclaim(c);
753 			spin_unlock(&c->journal.lock);
754 
755 			btree_flush_write(c);
756 		}
757 
758 		closure_sync(&cl);
759 		spin_lock(&c->journal.lock);
760 		wait = true;
761 	}
762 }
763 
764 static void journal_write_work(struct work_struct *work)
765 {
766 	struct cache_set *c = container_of(to_delayed_work(work),
767 					   struct cache_set,
768 					   journal.work);
769 	spin_lock(&c->journal.lock);
770 	if (c->journal.cur->dirty)
771 		journal_try_write(c);
772 	else
773 		spin_unlock(&c->journal.lock);
774 }
775 
776 /*
777  * Entry point to the journalling code - bio_insert() and btree_invalidate()
778  * pass bch_journal() a list of keys to be journalled, and then
779  * bch_journal() hands those same keys off to btree_insert_async()
780  */
781 
782 atomic_t *bch_journal(struct cache_set *c,
783 		      struct keylist *keys,
784 		      struct closure *parent)
785 {
786 	struct journal_write *w;
787 	atomic_t *ret;
788 
789 	if (!CACHE_SYNC(&c->sb))
790 		return NULL;
791 
792 	w = journal_wait_for_write(c, bch_keylist_nkeys(keys));
793 
794 	memcpy(bset_bkey_last(w->data), keys->keys, bch_keylist_bytes(keys));
795 	w->data->keys += bch_keylist_nkeys(keys);
796 
797 	ret = &fifo_back(&c->journal.pin);
798 	atomic_inc(ret);
799 
800 	if (parent) {
801 		closure_wait(&w->wait, parent);
802 		journal_try_write(c);
803 	} else if (!w->dirty) {
804 		w->dirty = true;
805 		schedule_delayed_work(&c->journal.work,
806 				      msecs_to_jiffies(c->journal_delay_ms));
807 		spin_unlock(&c->journal.lock);
808 	} else {
809 		spin_unlock(&c->journal.lock);
810 	}
811 
812 
813 	return ret;
814 }
815 
816 void bch_journal_meta(struct cache_set *c, struct closure *cl)
817 {
818 	struct keylist keys;
819 	atomic_t *ref;
820 
821 	bch_keylist_init(&keys);
822 
823 	ref = bch_journal(c, &keys, cl);
824 	if (ref)
825 		atomic_dec_bug(ref);
826 }
827 
828 void bch_journal_free(struct cache_set *c)
829 {
830 	free_pages((unsigned long) c->journal.w[1].data, JSET_BITS);
831 	free_pages((unsigned long) c->journal.w[0].data, JSET_BITS);
832 	free_fifo(&c->journal.pin);
833 	free_heap(&c->flush_btree);
834 }
835 
836 int bch_journal_alloc(struct cache_set *c)
837 {
838 	struct journal *j = &c->journal;
839 
840 	spin_lock_init(&j->lock);
841 	INIT_DELAYED_WORK(&j->work, journal_write_work);
842 
843 	c->journal_delay_ms = 100;
844 
845 	j->w[0].c = c;
846 	j->w[1].c = c;
847 
848 	if (!(init_heap(&c->flush_btree, 128, GFP_KERNEL)) ||
849 	    !(init_fifo(&j->pin, JOURNAL_PIN, GFP_KERNEL)) ||
850 	    !(j->w[0].data = (void *) __get_free_pages(GFP_KERNEL, JSET_BITS)) ||
851 	    !(j->w[1].data = (void *) __get_free_pages(GFP_KERNEL, JSET_BITS)))
852 		return -ENOMEM;
853 
854 	return 0;
855 }
856