xref: /linux/drivers/md/bcache/btree.c (revision 4fc012daf9c074772421c904357abf586336b1ca)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
4  *
5  * Uses a block device as cache for other block devices; optimized for SSDs.
6  * All allocation is done in buckets, which should match the erase block size
7  * of the device.
8  *
9  * Buckets containing cached data are kept on a heap sorted by priority;
10  * bucket priority is increased on cache hit, and periodically all the buckets
11  * on the heap have their priority scaled down. This currently is just used as
12  * an LRU but in the future should allow for more intelligent heuristics.
13  *
14  * Buckets have an 8 bit counter; freeing is accomplished by incrementing the
15  * counter. Garbage collection is used to remove stale pointers.
16  *
17  * Indexing is done via a btree; nodes are not necessarily fully sorted, rather
18  * as keys are inserted we only sort the pages that have not yet been written.
19  * When garbage collection is run, we resort the entire node.
20  *
21  * All configuration is done via sysfs; see Documentation/admin-guide/bcache.rst.
22  */
23 
24 #include "bcache.h"
25 #include "btree.h"
26 #include "debug.h"
27 #include "extents.h"
28 
29 #include <linux/slab.h>
30 #include <linux/bitops.h>
31 #include <linux/hash.h>
32 #include <linux/kthread.h>
33 #include <linux/prefetch.h>
34 #include <linux/random.h>
35 #include <linux/rcupdate.h>
36 #include <linux/sched/clock.h>
37 #include <linux/rculist.h>
38 #include <linux/delay.h>
39 #include <linux/sort.h>
40 #include <trace/events/bcache.h>
41 
42 /*
43  * Todo:
44  * register_bcache: Return errors out to userspace correctly
45  *
46  * Writeback: don't undirty key until after a cache flush
47  *
48  * Create an iterator for key pointers
49  *
50  * On btree write error, mark bucket such that it won't be freed from the cache
51  *
52  * Journalling:
53  *   Check for bad keys in replay
54  *   Propagate barriers
55  *   Refcount journal entries in journal_replay
56  *
57  * Garbage collection:
58  *   Finish incremental gc
59  *   Gc should free old UUIDs, data for invalid UUIDs
60  *
61  * Provide a way to list backing device UUIDs we have data cached for, and
62  * probably how long it's been since we've seen them, and a way to invalidate
63  * dirty data for devices that will never be attached again
64  *
65  * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
66  * that based on that and how much dirty data we have we can keep writeback
67  * from being starved
68  *
69  * Add a tracepoint or somesuch to watch for writeback starvation
70  *
71  * When btree depth > 1 and splitting an interior node, we have to make sure
72  * alloc_bucket() cannot fail. This should be true but is not completely
73  * obvious.
74  *
75  * Plugging?
76  *
77  * If data write is less than hard sector size of ssd, round up offset in open
78  * bucket to the next whole sector
79  *
80  * Superblock needs to be fleshed out for multiple cache devices
81  *
82  * Add a sysfs tunable for the number of writeback IOs in flight
83  *
84  * Add a sysfs tunable for the number of open data buckets
85  *
86  * IO tracking: Can we track when one process is doing io on behalf of another?
87  * IO tracking: Don't use just an average, weigh more recent stuff higher
88  *
89  * Test module load/unload
90  */
91 
92 #define MAX_NEED_GC		64
93 #define MAX_SAVE_PRIO		72
94 #define MAX_GC_TIMES		100
95 #define MIN_GC_NODES		100
96 #define GC_SLEEP_MS		100
97 
98 #define PTR_DIRTY_BIT		(((uint64_t) 1 << 36))
99 
100 #define PTR_HASH(c, k)							\
101 	(((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
102 
103 static struct workqueue_struct *btree_io_wq;
104 
105 #define insert_lock(s, b)	((b)->level <= (s)->lock)
106 
107 
108 static inline struct bset *write_block(struct btree *b)
109 {
110 	return ((void *) btree_bset_first(b)) + b->written * block_bytes(b->c->cache);
111 }
112 
113 static void bch_btree_init_next(struct btree *b)
114 {
115 	/* If not a leaf node, always sort */
116 	if (b->level && b->keys.nsets)
117 		bch_btree_sort(&b->keys, &b->c->sort);
118 	else
119 		bch_btree_sort_lazy(&b->keys, &b->c->sort);
120 
121 	if (b->written < btree_blocks(b))
122 		bch_bset_init_next(&b->keys, write_block(b),
123 				   bset_magic(&b->c->cache->sb));
124 
125 }
126 
127 /* Btree key manipulation */
128 
129 void bkey_put(struct cache_set *c, struct bkey *k)
130 {
131 	unsigned int i;
132 
133 	for (i = 0; i < KEY_PTRS(k); i++)
134 		if (ptr_available(c, k, i))
135 			atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
136 }
137 
138 /* Btree IO */
139 
140 static uint64_t btree_csum_set(struct btree *b, struct bset *i)
141 {
142 	uint64_t crc = b->key.ptr[0];
143 	void *data = (void *) i + 8, *end = bset_bkey_last(i);
144 
145 	crc = crc64_be(crc, data, end - data);
146 	return crc ^ 0xffffffffffffffffULL;
147 }
148 
149 void bch_btree_node_read_done(struct btree *b)
150 {
151 	const char *err = "bad btree header";
152 	struct bset *i = btree_bset_first(b);
153 	struct btree_iter iter;
154 
155 	/*
156 	 * c->fill_iter can allocate an iterator with more memory space
157 	 * than static MAX_BSETS.
158 	 * See the comment arount cache_set->fill_iter.
159 	 */
160 	iter.heap.data = mempool_alloc(&b->c->fill_iter, GFP_NOIO);
161 	iter.heap.size = b->c->cache->sb.bucket_size / b->c->cache->sb.block_size;
162 	iter.heap.nr = 0;
163 
164 #ifdef CONFIG_BCACHE_DEBUG
165 	iter.b = &b->keys;
166 #endif
167 
168 	if (!i->seq)
169 		goto err;
170 
171 	for (;
172 	     b->written < btree_blocks(b) && i->seq == b->keys.set[0].data->seq;
173 	     i = write_block(b)) {
174 		err = "unsupported bset version";
175 		if (i->version > BCACHE_BSET_VERSION)
176 			goto err;
177 
178 		err = "bad btree header";
179 		if (b->written + set_blocks(i, block_bytes(b->c->cache)) >
180 		    btree_blocks(b))
181 			goto err;
182 
183 		err = "bad magic";
184 		if (i->magic != bset_magic(&b->c->cache->sb))
185 			goto err;
186 
187 		err = "bad checksum";
188 		switch (i->version) {
189 		case 0:
190 			if (i->csum != csum_set(i))
191 				goto err;
192 			break;
193 		case BCACHE_BSET_VERSION:
194 			if (i->csum != btree_csum_set(b, i))
195 				goto err;
196 			break;
197 		}
198 
199 		err = "empty set";
200 		if (i != b->keys.set[0].data && !i->keys)
201 			goto err;
202 
203 		bch_btree_iter_push(&iter, i->start, bset_bkey_last(i));
204 
205 		b->written += set_blocks(i, block_bytes(b->c->cache));
206 	}
207 
208 	err = "corrupted btree";
209 	for (i = write_block(b);
210 	     bset_sector_offset(&b->keys, i) < KEY_SIZE(&b->key);
211 	     i = ((void *) i) + block_bytes(b->c->cache))
212 		if (i->seq == b->keys.set[0].data->seq)
213 			goto err;
214 
215 	bch_btree_sort_and_fix_extents(&b->keys, &iter, &b->c->sort);
216 
217 	i = b->keys.set[0].data;
218 	err = "short btree key";
219 	if (b->keys.set[0].size &&
220 	    bkey_cmp(&b->key, &b->keys.set[0].end) < 0)
221 		goto err;
222 
223 	if (b->written < btree_blocks(b))
224 		bch_bset_init_next(&b->keys, write_block(b),
225 				   bset_magic(&b->c->cache->sb));
226 out:
227 	mempool_free(iter.heap.data, &b->c->fill_iter);
228 	return;
229 err:
230 	set_btree_node_io_error(b);
231 	bch_cache_set_error(b->c, "%s at bucket %zu, block %u, %u keys",
232 			    err, PTR_BUCKET_NR(b->c, &b->key, 0),
233 			    bset_block_offset(b, i), i->keys);
234 	goto out;
235 }
236 
237 static void btree_node_read_endio(struct bio *bio)
238 {
239 	struct closure *cl = bio->bi_private;
240 
241 	closure_put(cl);
242 }
243 
244 static void bch_btree_node_read(struct btree *b)
245 {
246 	uint64_t start_time = local_clock();
247 	struct closure cl;
248 	struct bio *bio;
249 
250 	trace_bcache_btree_read(b);
251 
252 	closure_init_stack(&cl);
253 
254 	bio = bch_bbio_alloc(b->c);
255 	bio->bi_iter.bi_size = KEY_SIZE(&b->key) << 9;
256 	bio->bi_end_io	= btree_node_read_endio;
257 	bio->bi_private	= &cl;
258 	bio->bi_opf = REQ_OP_READ | REQ_META;
259 
260 	bch_bio_map(bio, b->keys.set[0].data);
261 
262 	bch_submit_bbio(bio, b->c, &b->key, 0);
263 	closure_sync(&cl);
264 
265 	if (bio->bi_status)
266 		set_btree_node_io_error(b);
267 
268 	bch_bbio_free(bio, b->c);
269 
270 	if (btree_node_io_error(b))
271 		goto err;
272 
273 	bch_btree_node_read_done(b);
274 	bch_time_stats_update(&b->c->btree_read_time, start_time);
275 
276 	return;
277 err:
278 	bch_cache_set_error(b->c, "io error reading bucket %zu",
279 			    PTR_BUCKET_NR(b->c, &b->key, 0));
280 }
281 
282 static void btree_complete_write(struct btree *b, struct btree_write *w)
283 {
284 	if (w->prio_blocked &&
285 	    !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
286 		wake_up_allocators(b->c);
287 
288 	if (w->journal) {
289 		atomic_dec_bug(w->journal);
290 		__closure_wake_up(&b->c->journal.wait);
291 	}
292 
293 	w->prio_blocked	= 0;
294 	w->journal	= NULL;
295 }
296 
297 static CLOSURE_CALLBACK(btree_node_write_unlock)
298 {
299 	closure_type(b, struct btree, io);
300 
301 	up(&b->io_mutex);
302 }
303 
304 static CLOSURE_CALLBACK(__btree_node_write_done)
305 {
306 	closure_type(b, struct btree, io);
307 	struct btree_write *w = btree_prev_write(b);
308 
309 	bch_bbio_free(b->bio, b->c);
310 	b->bio = NULL;
311 	btree_complete_write(b, w);
312 
313 	if (btree_node_dirty(b))
314 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
315 
316 	closure_return_with_destructor(cl, btree_node_write_unlock);
317 }
318 
319 static CLOSURE_CALLBACK(btree_node_write_done)
320 {
321 	closure_type(b, struct btree, io);
322 
323 	bio_free_pages(b->bio);
324 	__btree_node_write_done(&cl->work);
325 }
326 
327 static void btree_node_write_endio(struct bio *bio)
328 {
329 	struct closure *cl = bio->bi_private;
330 	struct btree *b = container_of(cl, struct btree, io);
331 
332 	if (bio->bi_status)
333 		set_btree_node_io_error(b);
334 
335 	bch_bbio_count_io_errors(b->c, bio, bio->bi_status, "writing btree");
336 	closure_put(cl);
337 }
338 
339 static void do_btree_node_write(struct btree *b)
340 {
341 	struct closure *cl = &b->io;
342 	struct bset *i = btree_bset_last(b);
343 	BKEY_PADDED(key) k;
344 
345 	i->version	= BCACHE_BSET_VERSION;
346 	i->csum		= btree_csum_set(b, i);
347 
348 	BUG_ON(b->bio);
349 	b->bio = bch_bbio_alloc(b->c);
350 
351 	b->bio->bi_end_io	= btree_node_write_endio;
352 	b->bio->bi_private	= cl;
353 	b->bio->bi_iter.bi_size	= roundup(set_bytes(i), block_bytes(b->c->cache));
354 	b->bio->bi_opf		= REQ_OP_WRITE | REQ_META | REQ_FUA;
355 	bch_bio_map(b->bio, i);
356 
357 	/*
358 	 * If we're appending to a leaf node, we don't technically need FUA -
359 	 * this write just needs to be persisted before the next journal write,
360 	 * which will be marked FLUSH|FUA.
361 	 *
362 	 * Similarly if we're writing a new btree root - the pointer is going to
363 	 * be in the next journal entry.
364 	 *
365 	 * But if we're writing a new btree node (that isn't a root) or
366 	 * appending to a non leaf btree node, we need either FUA or a flush
367 	 * when we write the parent with the new pointer. FUA is cheaper than a
368 	 * flush, and writes appending to leaf nodes aren't blocking anything so
369 	 * just make all btree node writes FUA to keep things sane.
370 	 */
371 
372 	bkey_copy(&k.key, &b->key);
373 	SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) +
374 		       bset_sector_offset(&b->keys, i));
375 
376 	if (!bch_bio_alloc_pages(b->bio, __GFP_NOWARN|GFP_NOWAIT)) {
377 		struct bio_vec *bv;
378 		void *addr = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
379 		struct bvec_iter_all iter_all;
380 
381 		bio_for_each_segment_all(bv, b->bio, iter_all) {
382 			memcpy(page_address(bv->bv_page), addr, PAGE_SIZE);
383 			addr += PAGE_SIZE;
384 		}
385 
386 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
387 
388 		continue_at(cl, btree_node_write_done, NULL);
389 	} else {
390 		/*
391 		 * No problem for multipage bvec since the bio is
392 		 * just allocated
393 		 */
394 		b->bio->bi_vcnt = 0;
395 		bch_bio_map(b->bio, i);
396 
397 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
398 
399 		closure_sync(cl);
400 		continue_at_nobarrier(cl, __btree_node_write_done, NULL);
401 	}
402 }
403 
404 void __bch_btree_node_write(struct btree *b, struct closure *parent)
405 {
406 	struct bset *i = btree_bset_last(b);
407 
408 	lockdep_assert_held(&b->write_lock);
409 
410 	trace_bcache_btree_write(b);
411 
412 	BUG_ON(current->bio_list);
413 	BUG_ON(b->written >= btree_blocks(b));
414 	BUG_ON(b->written && !i->keys);
415 	BUG_ON(btree_bset_first(b)->seq != i->seq);
416 	bch_check_keys(&b->keys, "writing");
417 
418 	cancel_delayed_work(&b->work);
419 
420 	/* If caller isn't waiting for write, parent refcount is cache set */
421 	down(&b->io_mutex);
422 	closure_init(&b->io, parent ?: &b->c->cl);
423 
424 	clear_bit(BTREE_NODE_dirty,	 &b->flags);
425 	change_bit(BTREE_NODE_write_idx, &b->flags);
426 
427 	do_btree_node_write(b);
428 
429 	atomic_long_add(set_blocks(i, block_bytes(b->c->cache)) * b->c->cache->sb.block_size,
430 			&b->c->cache->btree_sectors_written);
431 
432 	b->written += set_blocks(i, block_bytes(b->c->cache));
433 }
434 
435 void bch_btree_node_write(struct btree *b, struct closure *parent)
436 {
437 	unsigned int nsets = b->keys.nsets;
438 
439 	lockdep_assert_held(&b->lock);
440 
441 	__bch_btree_node_write(b, parent);
442 
443 	/*
444 	 * do verify if there was more than one set initially (i.e. we did a
445 	 * sort) and we sorted down to a single set:
446 	 */
447 	if (nsets && !b->keys.nsets)
448 		bch_btree_verify(b);
449 
450 	bch_btree_init_next(b);
451 }
452 
453 static void bch_btree_node_write_sync(struct btree *b)
454 {
455 	struct closure cl;
456 
457 	closure_init_stack(&cl);
458 
459 	mutex_lock(&b->write_lock);
460 	bch_btree_node_write(b, &cl);
461 	mutex_unlock(&b->write_lock);
462 
463 	closure_sync(&cl);
464 }
465 
466 static void btree_node_write_work(struct work_struct *w)
467 {
468 	struct btree *b = container_of(to_delayed_work(w), struct btree, work);
469 
470 	mutex_lock(&b->write_lock);
471 	if (btree_node_dirty(b))
472 		__bch_btree_node_write(b, NULL);
473 	mutex_unlock(&b->write_lock);
474 }
475 
476 static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
477 {
478 	struct bset *i = btree_bset_last(b);
479 	struct btree_write *w = btree_current_write(b);
480 
481 	lockdep_assert_held(&b->write_lock);
482 
483 	BUG_ON(!b->written);
484 	BUG_ON(!i->keys);
485 
486 	if (!btree_node_dirty(b))
487 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
488 
489 	set_btree_node_dirty(b);
490 
491 	/*
492 	 * w->journal is always the oldest journal pin of all bkeys
493 	 * in the leaf node, to make sure the oldest jset seq won't
494 	 * be increased before this btree node is flushed.
495 	 */
496 	if (journal_ref) {
497 		if (w->journal &&
498 		    journal_pin_cmp(b->c, w->journal, journal_ref)) {
499 			atomic_dec_bug(w->journal);
500 			w->journal = NULL;
501 		}
502 
503 		if (!w->journal) {
504 			w->journal = journal_ref;
505 			atomic_inc(w->journal);
506 		}
507 	}
508 
509 	/* Force write if set is too big */
510 	if (set_bytes(i) > PAGE_SIZE - 48 &&
511 	    !current->bio_list)
512 		bch_btree_node_write(b, NULL);
513 }
514 
515 /*
516  * Btree in memory cache - allocation/freeing
517  * mca -> memory cache
518  */
519 
520 #define mca_reserve(c)	(((!IS_ERR_OR_NULL(c->root) && c->root->level) \
521 			  ? c->root->level : 1) * 8 + 16)
522 #define mca_can_free(c)						\
523 	max_t(int, 0, c->btree_cache_used - mca_reserve(c))
524 
525 static void mca_data_free(struct btree *b)
526 {
527 	BUG_ON(b->io_mutex.count != 1);
528 
529 	bch_btree_keys_free(&b->keys);
530 
531 	b->c->btree_cache_used--;
532 	list_move(&b->list, &b->c->btree_cache_freed);
533 }
534 
535 static void mca_bucket_free(struct btree *b)
536 {
537 	BUG_ON(btree_node_dirty(b));
538 
539 	b->key.ptr[0] = 0;
540 	hlist_del_init_rcu(&b->hash);
541 	list_move(&b->list, &b->c->btree_cache_freeable);
542 }
543 
544 static unsigned int btree_order(struct bkey *k)
545 {
546 	return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
547 }
548 
549 static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
550 {
551 	if (!bch_btree_keys_alloc(&b->keys,
552 				  max_t(unsigned int,
553 					ilog2(b->c->btree_pages),
554 					btree_order(k)),
555 				  gfp)) {
556 		b->c->btree_cache_used++;
557 		list_move(&b->list, &b->c->btree_cache);
558 	} else {
559 		list_move(&b->list, &b->c->btree_cache_freed);
560 	}
561 }
562 
563 #ifdef CONFIG_PROVE_LOCKING
564 static int btree_lock_cmp_fn(const struct lockdep_map *_a,
565 			     const struct lockdep_map *_b)
566 {
567 	const struct btree *a = container_of(_a, struct btree, lock.dep_map);
568 	const struct btree *b = container_of(_b, struct btree, lock.dep_map);
569 
570 	return -cmp_int(a->level, b->level) ?: bkey_cmp(&a->key, &b->key);
571 }
572 
573 static void btree_lock_print_fn(const struct lockdep_map *map)
574 {
575 	const struct btree *b = container_of(map, struct btree, lock.dep_map);
576 
577 	printk(KERN_CONT " l=%u %llu:%llu", b->level,
578 	       KEY_INODE(&b->key), KEY_OFFSET(&b->key));
579 }
580 #endif
581 
582 static struct btree *mca_bucket_alloc(struct cache_set *c,
583 				      struct bkey *k, gfp_t gfp)
584 {
585 	/*
586 	 * kzalloc() is necessary here for initialization,
587 	 * see code comments in bch_btree_keys_init().
588 	 */
589 	struct btree *b = kzalloc(sizeof(struct btree), gfp);
590 
591 	if (!b)
592 		return NULL;
593 
594 	init_rwsem(&b->lock);
595 	lock_set_cmp_fn(&b->lock, btree_lock_cmp_fn, btree_lock_print_fn);
596 	mutex_init(&b->write_lock);
597 	lockdep_set_novalidate_class(&b->write_lock);
598 	INIT_LIST_HEAD(&b->list);
599 	INIT_DELAYED_WORK(&b->work, btree_node_write_work);
600 	b->c = c;
601 	sema_init(&b->io_mutex, 1);
602 
603 	mca_data_alloc(b, k, gfp);
604 	return b;
605 }
606 
607 static int mca_reap(struct btree *b, unsigned int min_order, bool flush)
608 {
609 	struct closure cl;
610 
611 	closure_init_stack(&cl);
612 	lockdep_assert_held(&b->c->bucket_lock);
613 
614 	if (!down_write_trylock(&b->lock))
615 		return -ENOMEM;
616 
617 	BUG_ON(btree_node_dirty(b) && !b->keys.set[0].data);
618 
619 	if (b->keys.page_order < min_order)
620 		goto out_unlock;
621 
622 	if (!flush) {
623 		if (btree_node_dirty(b))
624 			goto out_unlock;
625 
626 		if (down_trylock(&b->io_mutex))
627 			goto out_unlock;
628 		up(&b->io_mutex);
629 	}
630 
631 retry:
632 	/*
633 	 * BTREE_NODE_dirty might be cleared in btree_flush_btree() by
634 	 * __bch_btree_node_write(). To avoid an extra flush, acquire
635 	 * b->write_lock before checking BTREE_NODE_dirty bit.
636 	 */
637 	mutex_lock(&b->write_lock);
638 	/*
639 	 * If this btree node is selected in btree_flush_write() by journal
640 	 * code, delay and retry until the node is flushed by journal code
641 	 * and BTREE_NODE_journal_flush bit cleared by btree_flush_write().
642 	 */
643 	if (btree_node_journal_flush(b)) {
644 		pr_debug("bnode %p is flushing by journal, retry\n", b);
645 		mutex_unlock(&b->write_lock);
646 		udelay(1);
647 		goto retry;
648 	}
649 
650 	if (btree_node_dirty(b))
651 		__bch_btree_node_write(b, &cl);
652 	mutex_unlock(&b->write_lock);
653 
654 	closure_sync(&cl);
655 
656 	/* wait for any in flight btree write */
657 	down(&b->io_mutex);
658 	up(&b->io_mutex);
659 
660 	return 0;
661 out_unlock:
662 	rw_unlock(true, b);
663 	return -ENOMEM;
664 }
665 
666 static unsigned long bch_mca_scan(struct shrinker *shrink,
667 				  struct shrink_control *sc)
668 {
669 	struct cache_set *c = shrink->private_data;
670 	struct btree *b, *t;
671 	unsigned long i, nr = sc->nr_to_scan;
672 	unsigned long freed = 0;
673 	unsigned int btree_cache_used;
674 
675 	if (c->shrinker_disabled)
676 		return SHRINK_STOP;
677 
678 	if (c->btree_cache_alloc_lock)
679 		return SHRINK_STOP;
680 
681 	/* Return -1 if we can't do anything right now */
682 	if (sc->gfp_mask & __GFP_IO)
683 		mutex_lock(&c->bucket_lock);
684 	else if (!mutex_trylock(&c->bucket_lock))
685 		return -1;
686 
687 	/*
688 	 * It's _really_ critical that we don't free too many btree nodes - we
689 	 * have to always leave ourselves a reserve. The reserve is how we
690 	 * guarantee that allocating memory for a new btree node can always
691 	 * succeed, so that inserting keys into the btree can always succeed and
692 	 * IO can always make forward progress:
693 	 */
694 	nr /= c->btree_pages;
695 	if (nr == 0)
696 		nr = 1;
697 	nr = min_t(unsigned long, nr, mca_can_free(c));
698 
699 	i = 0;
700 	btree_cache_used = c->btree_cache_used;
701 	list_for_each_entry_safe_reverse(b, t, &c->btree_cache_freeable, list) {
702 		if (nr <= 0)
703 			goto out;
704 
705 		if (!mca_reap(b, 0, false)) {
706 			mca_data_free(b);
707 			rw_unlock(true, b);
708 			freed++;
709 		}
710 		nr--;
711 		i++;
712 	}
713 
714 	list_for_each_entry_safe_reverse(b, t, &c->btree_cache, list) {
715 		if (nr <= 0 || i >= btree_cache_used)
716 			goto out;
717 
718 		if (!mca_reap(b, 0, false)) {
719 			mca_bucket_free(b);
720 			mca_data_free(b);
721 			rw_unlock(true, b);
722 			freed++;
723 		}
724 
725 		nr--;
726 		i++;
727 	}
728 out:
729 	mutex_unlock(&c->bucket_lock);
730 	return freed * c->btree_pages;
731 }
732 
733 static unsigned long bch_mca_count(struct shrinker *shrink,
734 				   struct shrink_control *sc)
735 {
736 	struct cache_set *c = shrink->private_data;
737 
738 	if (c->shrinker_disabled)
739 		return 0;
740 
741 	if (c->btree_cache_alloc_lock)
742 		return 0;
743 
744 	return mca_can_free(c) * c->btree_pages;
745 }
746 
747 void bch_btree_cache_free(struct cache_set *c)
748 {
749 	struct btree *b;
750 	struct closure cl;
751 
752 	closure_init_stack(&cl);
753 
754 	if (c->shrink)
755 		shrinker_free(c->shrink);
756 
757 	mutex_lock(&c->bucket_lock);
758 
759 #ifdef CONFIG_BCACHE_DEBUG
760 	if (c->verify_data)
761 		list_move(&c->verify_data->list, &c->btree_cache);
762 
763 	free_pages((unsigned long) c->verify_ondisk, ilog2(meta_bucket_pages(&c->cache->sb)));
764 #endif
765 
766 	list_splice(&c->btree_cache_freeable,
767 		    &c->btree_cache);
768 
769 	while (!list_empty(&c->btree_cache)) {
770 		b = list_first_entry(&c->btree_cache, struct btree, list);
771 
772 		/*
773 		 * This function is called by cache_set_free(), no I/O
774 		 * request on cache now, it is unnecessary to acquire
775 		 * b->write_lock before clearing BTREE_NODE_dirty anymore.
776 		 */
777 		if (btree_node_dirty(b)) {
778 			btree_complete_write(b, btree_current_write(b));
779 			clear_bit(BTREE_NODE_dirty, &b->flags);
780 		}
781 		mca_data_free(b);
782 	}
783 
784 	while (!list_empty(&c->btree_cache_freed)) {
785 		b = list_first_entry(&c->btree_cache_freed,
786 				     struct btree, list);
787 		list_del(&b->list);
788 		cancel_delayed_work_sync(&b->work);
789 		kfree(b);
790 	}
791 
792 	mutex_unlock(&c->bucket_lock);
793 }
794 
795 int bch_btree_cache_alloc(struct cache_set *c)
796 {
797 	unsigned int i;
798 
799 	for (i = 0; i < mca_reserve(c); i++)
800 		if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
801 			return -ENOMEM;
802 
803 	list_splice_init(&c->btree_cache,
804 			 &c->btree_cache_freeable);
805 
806 #ifdef CONFIG_BCACHE_DEBUG
807 	mutex_init(&c->verify_lock);
808 
809 	c->verify_ondisk = (void *)
810 		__get_free_pages(GFP_KERNEL|__GFP_COMP,
811 				 ilog2(meta_bucket_pages(&c->cache->sb)));
812 	if (!c->verify_ondisk) {
813 		/*
814 		 * Don't worry about the mca_rereserve buckets
815 		 * allocated in previous for-loop, they will be
816 		 * handled properly in bch_cache_set_unregister().
817 		 */
818 		return -ENOMEM;
819 	}
820 
821 	c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
822 
823 	if (c->verify_data &&
824 	    c->verify_data->keys.set->data)
825 		list_del_init(&c->verify_data->list);
826 	else
827 		c->verify_data = NULL;
828 #endif
829 
830 	c->shrink = shrinker_alloc(0, "md-bcache:%pU", c->set_uuid);
831 	if (!c->shrink) {
832 		pr_warn("bcache: %s: could not allocate shrinker\n", __func__);
833 		return 0;
834 	}
835 
836 	c->shrink->count_objects = bch_mca_count;
837 	c->shrink->scan_objects = bch_mca_scan;
838 	c->shrink->seeks = 4;
839 	c->shrink->batch = c->btree_pages * 2;
840 	c->shrink->private_data = c;
841 
842 	shrinker_register(c->shrink);
843 
844 	return 0;
845 }
846 
847 /* Btree in memory cache - hash table */
848 
849 static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
850 {
851 	return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
852 }
853 
854 static struct btree *mca_find(struct cache_set *c, struct bkey *k)
855 {
856 	struct btree *b;
857 
858 	rcu_read_lock();
859 	hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
860 		if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
861 			goto out;
862 	b = NULL;
863 out:
864 	rcu_read_unlock();
865 	return b;
866 }
867 
868 static int mca_cannibalize_lock(struct cache_set *c, struct btree_op *op)
869 {
870 	spin_lock(&c->btree_cannibalize_lock);
871 	if (likely(c->btree_cache_alloc_lock == NULL)) {
872 		c->btree_cache_alloc_lock = current;
873 	} else if (c->btree_cache_alloc_lock != current) {
874 		if (op)
875 			prepare_to_wait(&c->btree_cache_wait, &op->wait,
876 					TASK_UNINTERRUPTIBLE);
877 		spin_unlock(&c->btree_cannibalize_lock);
878 		return -EINTR;
879 	}
880 	spin_unlock(&c->btree_cannibalize_lock);
881 
882 	return 0;
883 }
884 
885 static struct btree *mca_cannibalize(struct cache_set *c, struct btree_op *op,
886 				     struct bkey *k)
887 {
888 	struct btree *b;
889 
890 	trace_bcache_btree_cache_cannibalize(c);
891 
892 	if (mca_cannibalize_lock(c, op))
893 		return ERR_PTR(-EINTR);
894 
895 	list_for_each_entry_reverse(b, &c->btree_cache, list)
896 		if (!mca_reap(b, btree_order(k), false))
897 			return b;
898 
899 	list_for_each_entry_reverse(b, &c->btree_cache, list)
900 		if (!mca_reap(b, btree_order(k), true))
901 			return b;
902 
903 	WARN(1, "btree cache cannibalize failed\n");
904 	return ERR_PTR(-ENOMEM);
905 }
906 
907 /*
908  * We can only have one thread cannibalizing other cached btree nodes at a time,
909  * or we'll deadlock. We use an open coded mutex to ensure that, which a
910  * cannibalize_bucket() will take. This means every time we unlock the root of
911  * the btree, we need to release this lock if we have it held.
912  */
913 void bch_cannibalize_unlock(struct cache_set *c)
914 {
915 	spin_lock(&c->btree_cannibalize_lock);
916 	if (c->btree_cache_alloc_lock == current) {
917 		c->btree_cache_alloc_lock = NULL;
918 		wake_up(&c->btree_cache_wait);
919 	}
920 	spin_unlock(&c->btree_cannibalize_lock);
921 }
922 
923 static struct btree *mca_alloc(struct cache_set *c, struct btree_op *op,
924 			       struct bkey *k, int level)
925 {
926 	struct btree *b;
927 
928 	BUG_ON(current->bio_list);
929 
930 	lockdep_assert_held(&c->bucket_lock);
931 
932 	if (mca_find(c, k))
933 		return NULL;
934 
935 	/* btree_free() doesn't free memory; it sticks the node on the end of
936 	 * the list. Check if there's any freed nodes there:
937 	 */
938 	list_for_each_entry(b, &c->btree_cache_freeable, list)
939 		if (!mca_reap(b, btree_order(k), false))
940 			goto out;
941 
942 	/* We never free struct btree itself, just the memory that holds the on
943 	 * disk node. Check the freed list before allocating a new one:
944 	 */
945 	list_for_each_entry(b, &c->btree_cache_freed, list)
946 		if (!mca_reap(b, 0, false)) {
947 			mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
948 			if (!b->keys.set[0].data)
949 				goto err;
950 			else
951 				goto out;
952 		}
953 
954 	b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
955 	if (!b)
956 		goto err;
957 
958 	BUG_ON(!down_write_trylock(&b->lock));
959 	if (!b->keys.set->data)
960 		goto err;
961 out:
962 	BUG_ON(b->io_mutex.count != 1);
963 
964 	bkey_copy(&b->key, k);
965 	list_move(&b->list, &c->btree_cache);
966 	hlist_del_init_rcu(&b->hash);
967 	hlist_add_head_rcu(&b->hash, mca_hash(c, k));
968 
969 	lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
970 	b->parent	= (void *) ~0UL;
971 	b->flags	= 0;
972 	b->written	= 0;
973 	b->level	= level;
974 
975 	if (!b->level)
976 		bch_btree_keys_init(&b->keys, &bch_extent_keys_ops,
977 				    &b->c->expensive_debug_checks);
978 	else
979 		bch_btree_keys_init(&b->keys, &bch_btree_keys_ops,
980 				    &b->c->expensive_debug_checks);
981 
982 	return b;
983 err:
984 	if (b)
985 		rw_unlock(true, b);
986 
987 	b = mca_cannibalize(c, op, k);
988 	if (!IS_ERR(b))
989 		goto out;
990 
991 	return b;
992 }
993 
994 /*
995  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
996  * in from disk if necessary.
997  *
998  * If IO is necessary and running under submit_bio_noacct, returns -EAGAIN.
999  *
1000  * The btree node will have either a read or a write lock held, depending on
1001  * level and op->lock.
1002  *
1003  * Note: Only error code or btree pointer will be returned, it is unncessary
1004  *       for callers to check NULL pointer.
1005  */
1006 struct btree *bch_btree_node_get(struct cache_set *c, struct btree_op *op,
1007 				 struct bkey *k, int level, bool write,
1008 				 struct btree *parent)
1009 {
1010 	int i = 0;
1011 	struct btree *b;
1012 
1013 	BUG_ON(level < 0);
1014 retry:
1015 	b = mca_find(c, k);
1016 
1017 	if (!b) {
1018 		if (current->bio_list)
1019 			return ERR_PTR(-EAGAIN);
1020 
1021 		mutex_lock(&c->bucket_lock);
1022 		b = mca_alloc(c, op, k, level);
1023 		mutex_unlock(&c->bucket_lock);
1024 
1025 		if (!b)
1026 			goto retry;
1027 		if (IS_ERR(b))
1028 			return b;
1029 
1030 		bch_btree_node_read(b);
1031 
1032 		if (!write)
1033 			downgrade_write(&b->lock);
1034 	} else {
1035 		rw_lock(write, b, level);
1036 		if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
1037 			rw_unlock(write, b);
1038 			goto retry;
1039 		}
1040 		BUG_ON(b->level != level);
1041 	}
1042 
1043 	if (btree_node_io_error(b)) {
1044 		rw_unlock(write, b);
1045 		return ERR_PTR(-EIO);
1046 	}
1047 
1048 	BUG_ON(!b->written);
1049 
1050 	b->parent = parent;
1051 
1052 	for (; i <= b->keys.nsets && b->keys.set[i].size; i++) {
1053 		prefetch(b->keys.set[i].tree);
1054 		prefetch(b->keys.set[i].data);
1055 	}
1056 
1057 	for (; i <= b->keys.nsets; i++)
1058 		prefetch(b->keys.set[i].data);
1059 
1060 	return b;
1061 }
1062 
1063 static void btree_node_prefetch(struct btree *parent, struct bkey *k)
1064 {
1065 	struct btree *b;
1066 
1067 	mutex_lock(&parent->c->bucket_lock);
1068 	b = mca_alloc(parent->c, NULL, k, parent->level - 1);
1069 	mutex_unlock(&parent->c->bucket_lock);
1070 
1071 	if (!IS_ERR_OR_NULL(b)) {
1072 		b->parent = parent;
1073 		bch_btree_node_read(b);
1074 		rw_unlock(true, b);
1075 	}
1076 }
1077 
1078 /* Btree alloc */
1079 
1080 static void btree_node_free(struct btree *b)
1081 {
1082 	trace_bcache_btree_node_free(b);
1083 
1084 	BUG_ON(b == b->c->root);
1085 
1086 retry:
1087 	mutex_lock(&b->write_lock);
1088 	/*
1089 	 * If the btree node is selected and flushing in btree_flush_write(),
1090 	 * delay and retry until the BTREE_NODE_journal_flush bit cleared,
1091 	 * then it is safe to free the btree node here. Otherwise this btree
1092 	 * node will be in race condition.
1093 	 */
1094 	if (btree_node_journal_flush(b)) {
1095 		mutex_unlock(&b->write_lock);
1096 		pr_debug("bnode %p journal_flush set, retry\n", b);
1097 		udelay(1);
1098 		goto retry;
1099 	}
1100 
1101 	if (btree_node_dirty(b)) {
1102 		btree_complete_write(b, btree_current_write(b));
1103 		clear_bit(BTREE_NODE_dirty, &b->flags);
1104 	}
1105 
1106 	mutex_unlock(&b->write_lock);
1107 
1108 	cancel_delayed_work(&b->work);
1109 
1110 	mutex_lock(&b->c->bucket_lock);
1111 	bch_bucket_free(b->c, &b->key);
1112 	mca_bucket_free(b);
1113 	mutex_unlock(&b->c->bucket_lock);
1114 }
1115 
1116 /*
1117  * Only error code or btree pointer will be returned, it is unncessary for
1118  * callers to check NULL pointer.
1119  */
1120 struct btree *__bch_btree_node_alloc(struct cache_set *c, struct btree_op *op,
1121 				     int level, bool wait,
1122 				     struct btree *parent)
1123 {
1124 	BKEY_PADDED(key) k;
1125 	struct btree *b;
1126 
1127 	mutex_lock(&c->bucket_lock);
1128 retry:
1129 	/* return ERR_PTR(-EAGAIN) when it fails */
1130 	b = ERR_PTR(-EAGAIN);
1131 	if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, wait))
1132 		goto err;
1133 
1134 	bkey_put(c, &k.key);
1135 	SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1136 
1137 	b = mca_alloc(c, op, &k.key, level);
1138 	if (IS_ERR(b))
1139 		goto err_free;
1140 
1141 	if (!b) {
1142 		cache_bug(c,
1143 			"Tried to allocate bucket that was in btree cache");
1144 		goto retry;
1145 	}
1146 
1147 	b->parent = parent;
1148 	bch_bset_init_next(&b->keys, b->keys.set->data, bset_magic(&b->c->cache->sb));
1149 
1150 	mutex_unlock(&c->bucket_lock);
1151 
1152 	trace_bcache_btree_node_alloc(b);
1153 	return b;
1154 err_free:
1155 	bch_bucket_free(c, &k.key);
1156 err:
1157 	mutex_unlock(&c->bucket_lock);
1158 
1159 	trace_bcache_btree_node_alloc_fail(c);
1160 	return b;
1161 }
1162 
1163 static struct btree *bch_btree_node_alloc(struct cache_set *c,
1164 					  struct btree_op *op, int level,
1165 					  struct btree *parent)
1166 {
1167 	return __bch_btree_node_alloc(c, op, level, op != NULL, parent);
1168 }
1169 
1170 static struct btree *btree_node_alloc_replacement(struct btree *b,
1171 						  struct btree_op *op)
1172 {
1173 	struct btree *n = bch_btree_node_alloc(b->c, op, b->level, b->parent);
1174 
1175 	if (!IS_ERR(n)) {
1176 		mutex_lock(&n->write_lock);
1177 		bch_btree_sort_into(&b->keys, &n->keys, &b->c->sort);
1178 		bkey_copy_key(&n->key, &b->key);
1179 		mutex_unlock(&n->write_lock);
1180 	}
1181 
1182 	return n;
1183 }
1184 
1185 static void make_btree_freeing_key(struct btree *b, struct bkey *k)
1186 {
1187 	unsigned int i;
1188 
1189 	mutex_lock(&b->c->bucket_lock);
1190 
1191 	atomic_inc(&b->c->prio_blocked);
1192 
1193 	bkey_copy(k, &b->key);
1194 	bkey_copy_key(k, &ZERO_KEY);
1195 
1196 	for (i = 0; i < KEY_PTRS(k); i++)
1197 		SET_PTR_GEN(k, i,
1198 			    bch_inc_gen(b->c->cache,
1199 					PTR_BUCKET(b->c, &b->key, i)));
1200 
1201 	mutex_unlock(&b->c->bucket_lock);
1202 }
1203 
1204 static int btree_check_reserve(struct btree *b, struct btree_op *op)
1205 {
1206 	struct cache_set *c = b->c;
1207 	struct cache *ca = c->cache;
1208 	unsigned int reserve = (c->root->level - b->level) * 2 + 1;
1209 
1210 	mutex_lock(&c->bucket_lock);
1211 
1212 	if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
1213 		if (op)
1214 			prepare_to_wait(&c->btree_cache_wait, &op->wait,
1215 					TASK_UNINTERRUPTIBLE);
1216 		mutex_unlock(&c->bucket_lock);
1217 		return -EINTR;
1218 	}
1219 
1220 	mutex_unlock(&c->bucket_lock);
1221 
1222 	return mca_cannibalize_lock(b->c, op);
1223 }
1224 
1225 /* Garbage collection */
1226 
1227 static uint8_t __bch_btree_mark_key(struct cache_set *c, int level,
1228 				    struct bkey *k)
1229 {
1230 	uint8_t stale = 0;
1231 	unsigned int i;
1232 	struct bucket *g;
1233 
1234 	/*
1235 	 * ptr_invalid() can't return true for the keys that mark btree nodes as
1236 	 * freed, but since ptr_bad() returns true we'll never actually use them
1237 	 * for anything and thus we don't want mark their pointers here
1238 	 */
1239 	if (!bkey_cmp(k, &ZERO_KEY))
1240 		return stale;
1241 
1242 	for (i = 0; i < KEY_PTRS(k); i++) {
1243 		if (!ptr_available(c, k, i))
1244 			continue;
1245 
1246 		g = PTR_BUCKET(c, k, i);
1247 
1248 		if (gen_after(g->last_gc, PTR_GEN(k, i)))
1249 			g->last_gc = PTR_GEN(k, i);
1250 
1251 		if (ptr_stale(c, k, i)) {
1252 			stale = max(stale, ptr_stale(c, k, i));
1253 			continue;
1254 		}
1255 
1256 		cache_bug_on(GC_MARK(g) &&
1257 			     (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1258 			     c, "inconsistent ptrs: mark = %llu, level = %i",
1259 			     GC_MARK(g), level);
1260 
1261 		if (level)
1262 			SET_GC_MARK(g, GC_MARK_METADATA);
1263 		else if (KEY_DIRTY(k))
1264 			SET_GC_MARK(g, GC_MARK_DIRTY);
1265 		else if (!GC_MARK(g))
1266 			SET_GC_MARK(g, GC_MARK_RECLAIMABLE);
1267 
1268 		/* guard against overflow */
1269 		SET_GC_SECTORS_USED(g, min_t(unsigned int,
1270 					     GC_SECTORS_USED(g) + KEY_SIZE(k),
1271 					     MAX_GC_SECTORS_USED));
1272 
1273 		BUG_ON(!GC_SECTORS_USED(g));
1274 	}
1275 
1276 	return stale;
1277 }
1278 
1279 #define btree_mark_key(b, k)	__bch_btree_mark_key(b->c, b->level, k)
1280 
1281 void bch_initial_mark_key(struct cache_set *c, int level, struct bkey *k)
1282 {
1283 	unsigned int i;
1284 
1285 	for (i = 0; i < KEY_PTRS(k); i++)
1286 		if (ptr_available(c, k, i) &&
1287 		    !ptr_stale(c, k, i)) {
1288 			struct bucket *b = PTR_BUCKET(c, k, i);
1289 
1290 			b->gen = PTR_GEN(k, i);
1291 
1292 			if (level && bkey_cmp(k, &ZERO_KEY))
1293 				b->prio = BTREE_PRIO;
1294 			else if (!level && b->prio == BTREE_PRIO)
1295 				b->prio = INITIAL_PRIO;
1296 		}
1297 
1298 	__bch_btree_mark_key(c, level, k);
1299 }
1300 
1301 void bch_update_bucket_in_use(struct cache_set *c, struct gc_stat *stats)
1302 {
1303 	stats->in_use = (c->nbuckets - c->avail_nbuckets) * 100 / c->nbuckets;
1304 }
1305 
1306 static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1307 {
1308 	uint8_t stale = 0;
1309 	unsigned int keys = 0, good_keys = 0;
1310 	struct bkey *k;
1311 	struct btree_iter iter;
1312 	struct bset_tree *t;
1313 
1314 	min_heap_init(&iter.heap, NULL, MAX_BSETS);
1315 
1316 	gc->nodes++;
1317 
1318 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid) {
1319 		stale = max(stale, btree_mark_key(b, k));
1320 		keys++;
1321 
1322 		if (bch_ptr_bad(&b->keys, k))
1323 			continue;
1324 
1325 		gc->key_bytes += bkey_u64s(k);
1326 		gc->nkeys++;
1327 		good_keys++;
1328 
1329 		gc->data += KEY_SIZE(k);
1330 	}
1331 
1332 	for (t = b->keys.set; t <= &b->keys.set[b->keys.nsets]; t++)
1333 		btree_bug_on(t->size &&
1334 			     bset_written(&b->keys, t) &&
1335 			     bkey_cmp(&b->key, &t->end) < 0,
1336 			     b, "found short btree key in gc");
1337 
1338 	if (b->c->gc_always_rewrite)
1339 		return true;
1340 
1341 	if (stale > 10)
1342 		return true;
1343 
1344 	if ((keys - good_keys) * 2 > keys)
1345 		return true;
1346 
1347 	return false;
1348 }
1349 
1350 #define GC_MERGE_NODES	4U
1351 
1352 struct gc_merge_info {
1353 	struct btree	*b;
1354 	unsigned int	keys;
1355 };
1356 
1357 static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
1358 				 struct keylist *insert_keys,
1359 				 atomic_t *journal_ref,
1360 				 struct bkey *replace_key);
1361 
1362 static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
1363 			     struct gc_stat *gc, struct gc_merge_info *r)
1364 {
1365 	unsigned int i, nodes = 0, keys = 0, blocks;
1366 	struct btree *new_nodes[GC_MERGE_NODES];
1367 	struct keylist keylist;
1368 	struct closure cl;
1369 	struct bkey *k;
1370 
1371 	bch_keylist_init(&keylist);
1372 
1373 	if (btree_check_reserve(b, NULL))
1374 		return 0;
1375 
1376 	memset(new_nodes, 0, sizeof(new_nodes));
1377 	closure_init_stack(&cl);
1378 
1379 	while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1380 		keys += r[nodes++].keys;
1381 
1382 	blocks = btree_default_blocks(b->c) * 2 / 3;
1383 
1384 	if (nodes < 2 ||
1385 	    __set_blocks(b->keys.set[0].data, keys,
1386 			 block_bytes(b->c->cache)) > blocks * (nodes - 1))
1387 		return 0;
1388 
1389 	for (i = 0; i < nodes; i++) {
1390 		new_nodes[i] = btree_node_alloc_replacement(r[i].b, NULL);
1391 		if (IS_ERR(new_nodes[i]))
1392 			goto out_nocoalesce;
1393 	}
1394 
1395 	/*
1396 	 * We have to check the reserve here, after we've allocated our new
1397 	 * nodes, to make sure the insert below will succeed - we also check
1398 	 * before as an optimization to potentially avoid a bunch of expensive
1399 	 * allocs/sorts
1400 	 */
1401 	if (btree_check_reserve(b, NULL))
1402 		goto out_nocoalesce;
1403 
1404 	for (i = 0; i < nodes; i++)
1405 		mutex_lock(&new_nodes[i]->write_lock);
1406 
1407 	for (i = nodes - 1; i > 0; --i) {
1408 		struct bset *n1 = btree_bset_first(new_nodes[i]);
1409 		struct bset *n2 = btree_bset_first(new_nodes[i - 1]);
1410 		struct bkey *k, *last = NULL;
1411 
1412 		keys = 0;
1413 
1414 		if (i > 1) {
1415 			for (k = n2->start;
1416 			     k < bset_bkey_last(n2);
1417 			     k = bkey_next(k)) {
1418 				if (__set_blocks(n1, n1->keys + keys +
1419 						 bkey_u64s(k),
1420 						 block_bytes(b->c->cache)) > blocks)
1421 					break;
1422 
1423 				last = k;
1424 				keys += bkey_u64s(k);
1425 			}
1426 		} else {
1427 			/*
1428 			 * Last node we're not getting rid of - we're getting
1429 			 * rid of the node at r[0]. Have to try and fit all of
1430 			 * the remaining keys into this node; we can't ensure
1431 			 * they will always fit due to rounding and variable
1432 			 * length keys (shouldn't be possible in practice,
1433 			 * though)
1434 			 */
1435 			if (__set_blocks(n1, n1->keys + n2->keys,
1436 					 block_bytes(b->c->cache)) >
1437 			    btree_blocks(new_nodes[i]))
1438 				goto out_unlock_nocoalesce;
1439 
1440 			keys = n2->keys;
1441 			/* Take the key of the node we're getting rid of */
1442 			last = &r->b->key;
1443 		}
1444 
1445 		BUG_ON(__set_blocks(n1, n1->keys + keys, block_bytes(b->c->cache)) >
1446 		       btree_blocks(new_nodes[i]));
1447 
1448 		if (last)
1449 			bkey_copy_key(&new_nodes[i]->key, last);
1450 
1451 		memcpy(bset_bkey_last(n1),
1452 		       n2->start,
1453 		       (void *) bset_bkey_idx(n2, keys) - (void *) n2->start);
1454 
1455 		n1->keys += keys;
1456 		r[i].keys = n1->keys;
1457 
1458 		memmove(n2->start,
1459 			bset_bkey_idx(n2, keys),
1460 			(void *) bset_bkey_last(n2) -
1461 			(void *) bset_bkey_idx(n2, keys));
1462 
1463 		n2->keys -= keys;
1464 
1465 		if (__bch_keylist_realloc(&keylist,
1466 					  bkey_u64s(&new_nodes[i]->key)))
1467 			goto out_unlock_nocoalesce;
1468 
1469 		bch_btree_node_write(new_nodes[i], &cl);
1470 		bch_keylist_add(&keylist, &new_nodes[i]->key);
1471 	}
1472 
1473 	for (i = 0; i < nodes; i++)
1474 		mutex_unlock(&new_nodes[i]->write_lock);
1475 
1476 	closure_sync(&cl);
1477 
1478 	/* We emptied out this node */
1479 	BUG_ON(btree_bset_first(new_nodes[0])->keys);
1480 	btree_node_free(new_nodes[0]);
1481 	rw_unlock(true, new_nodes[0]);
1482 	new_nodes[0] = NULL;
1483 
1484 	for (i = 0; i < nodes; i++) {
1485 		if (__bch_keylist_realloc(&keylist, bkey_u64s(&r[i].b->key)))
1486 			goto out_nocoalesce;
1487 
1488 		make_btree_freeing_key(r[i].b, keylist.top);
1489 		bch_keylist_push(&keylist);
1490 	}
1491 
1492 	bch_btree_insert_node(b, op, &keylist, NULL, NULL);
1493 	BUG_ON(!bch_keylist_empty(&keylist));
1494 
1495 	for (i = 0; i < nodes; i++) {
1496 		btree_node_free(r[i].b);
1497 		rw_unlock(true, r[i].b);
1498 
1499 		r[i].b = new_nodes[i];
1500 	}
1501 
1502 	memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1503 	r[nodes - 1].b = ERR_PTR(-EINTR);
1504 
1505 	trace_bcache_btree_gc_coalesce(nodes);
1506 	gc->nodes--;
1507 
1508 	bch_keylist_free(&keylist);
1509 
1510 	/* Invalidated our iterator */
1511 	return -EINTR;
1512 
1513 out_unlock_nocoalesce:
1514 	for (i = 0; i < nodes; i++)
1515 		mutex_unlock(&new_nodes[i]->write_lock);
1516 
1517 out_nocoalesce:
1518 	closure_sync(&cl);
1519 
1520 	while ((k = bch_keylist_pop(&keylist)))
1521 		if (!bkey_cmp(k, &ZERO_KEY))
1522 			atomic_dec(&b->c->prio_blocked);
1523 	bch_keylist_free(&keylist);
1524 
1525 	for (i = 0; i < nodes; i++)
1526 		if (!IS_ERR_OR_NULL(new_nodes[i])) {
1527 			btree_node_free(new_nodes[i]);
1528 			rw_unlock(true, new_nodes[i]);
1529 		}
1530 	return 0;
1531 }
1532 
1533 static int btree_gc_rewrite_node(struct btree *b, struct btree_op *op,
1534 				 struct btree *replace)
1535 {
1536 	struct keylist keys;
1537 	struct btree *n;
1538 
1539 	if (btree_check_reserve(b, NULL))
1540 		return 0;
1541 
1542 	n = btree_node_alloc_replacement(replace, NULL);
1543 	if (IS_ERR(n))
1544 		return 0;
1545 
1546 	/* recheck reserve after allocating replacement node */
1547 	if (btree_check_reserve(b, NULL)) {
1548 		btree_node_free(n);
1549 		rw_unlock(true, n);
1550 		return 0;
1551 	}
1552 
1553 	bch_btree_node_write_sync(n);
1554 
1555 	bch_keylist_init(&keys);
1556 	bch_keylist_add(&keys, &n->key);
1557 
1558 	make_btree_freeing_key(replace, keys.top);
1559 	bch_keylist_push(&keys);
1560 
1561 	bch_btree_insert_node(b, op, &keys, NULL, NULL);
1562 	BUG_ON(!bch_keylist_empty(&keys));
1563 
1564 	btree_node_free(replace);
1565 	rw_unlock(true, n);
1566 
1567 	/* Invalidated our iterator */
1568 	return -EINTR;
1569 }
1570 
1571 static unsigned int btree_gc_count_keys(struct btree *b)
1572 {
1573 	struct bkey *k;
1574 	struct btree_iter iter;
1575 	unsigned int ret = 0;
1576 
1577 	min_heap_init(&iter.heap, NULL, MAX_BSETS);
1578 
1579 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_bad)
1580 		ret += bkey_u64s(k);
1581 
1582 	return ret;
1583 }
1584 
1585 static size_t btree_gc_min_nodes(struct cache_set *c)
1586 {
1587 	size_t min_nodes;
1588 
1589 	/*
1590 	 * Since incremental GC would stop 100ms when front
1591 	 * side I/O comes, so when there are many btree nodes,
1592 	 * if GC only processes constant (100) nodes each time,
1593 	 * GC would last a long time, and the front side I/Os
1594 	 * would run out of the buckets (since no new bucket
1595 	 * can be allocated during GC), and be blocked again.
1596 	 * So GC should not process constant nodes, but varied
1597 	 * nodes according to the number of btree nodes, which
1598 	 * realized by dividing GC into constant(100) times,
1599 	 * so when there are many btree nodes, GC can process
1600 	 * more nodes each time, otherwise, GC will process less
1601 	 * nodes each time (but no less than MIN_GC_NODES)
1602 	 */
1603 	min_nodes = c->gc_stats.nodes / MAX_GC_TIMES;
1604 	if (min_nodes < MIN_GC_NODES)
1605 		min_nodes = MIN_GC_NODES;
1606 
1607 	return min_nodes;
1608 }
1609 
1610 
1611 static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1612 			    struct closure *writes, struct gc_stat *gc)
1613 {
1614 	int ret = 0;
1615 	bool should_rewrite;
1616 	struct bkey *k;
1617 	struct btree_iter iter;
1618 	struct gc_merge_info r[GC_MERGE_NODES];
1619 	struct gc_merge_info *i, *last = r + ARRAY_SIZE(r) - 1;
1620 
1621 	min_heap_init(&iter.heap, NULL, MAX_BSETS);
1622 	bch_btree_iter_init(&b->keys, &iter, &b->c->gc_done);
1623 
1624 	for (i = r; i < r + ARRAY_SIZE(r); i++)
1625 		i->b = ERR_PTR(-EINTR);
1626 
1627 	while (1) {
1628 		k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad);
1629 		if (k) {
1630 			r->b = bch_btree_node_get(b->c, op, k, b->level - 1,
1631 						  true, b);
1632 			if (IS_ERR(r->b)) {
1633 				ret = PTR_ERR(r->b);
1634 				break;
1635 			}
1636 
1637 			r->keys = btree_gc_count_keys(r->b);
1638 
1639 			ret = btree_gc_coalesce(b, op, gc, r);
1640 			if (ret)
1641 				break;
1642 		}
1643 
1644 		if (!last->b)
1645 			break;
1646 
1647 		if (!IS_ERR(last->b)) {
1648 			should_rewrite = btree_gc_mark_node(last->b, gc);
1649 			if (should_rewrite) {
1650 				ret = btree_gc_rewrite_node(b, op, last->b);
1651 				if (ret)
1652 					break;
1653 			}
1654 
1655 			if (last->b->level) {
1656 				ret = btree_gc_recurse(last->b, op, writes, gc);
1657 				if (ret)
1658 					break;
1659 			}
1660 
1661 			bkey_copy_key(&b->c->gc_done, &last->b->key);
1662 
1663 			/*
1664 			 * Must flush leaf nodes before gc ends, since replace
1665 			 * operations aren't journalled
1666 			 */
1667 			mutex_lock(&last->b->write_lock);
1668 			if (btree_node_dirty(last->b))
1669 				bch_btree_node_write(last->b, writes);
1670 			mutex_unlock(&last->b->write_lock);
1671 			rw_unlock(true, last->b);
1672 		}
1673 
1674 		memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1675 		r->b = NULL;
1676 
1677 		if (atomic_read(&b->c->search_inflight) &&
1678 		    gc->nodes >= gc->nodes_pre + btree_gc_min_nodes(b->c)) {
1679 			gc->nodes_pre =  gc->nodes;
1680 			ret = -EAGAIN;
1681 			break;
1682 		}
1683 
1684 		if (need_resched()) {
1685 			ret = -EAGAIN;
1686 			break;
1687 		}
1688 	}
1689 
1690 	for (i = r; i < r + ARRAY_SIZE(r); i++)
1691 		if (!IS_ERR_OR_NULL(i->b)) {
1692 			mutex_lock(&i->b->write_lock);
1693 			if (btree_node_dirty(i->b))
1694 				bch_btree_node_write(i->b, writes);
1695 			mutex_unlock(&i->b->write_lock);
1696 			rw_unlock(true, i->b);
1697 		}
1698 
1699 	return ret;
1700 }
1701 
1702 static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1703 			     struct closure *writes, struct gc_stat *gc)
1704 {
1705 	struct btree *n = NULL;
1706 	int ret = 0;
1707 	bool should_rewrite;
1708 
1709 	should_rewrite = btree_gc_mark_node(b, gc);
1710 	if (should_rewrite) {
1711 		n = btree_node_alloc_replacement(b, NULL);
1712 
1713 		if (!IS_ERR(n)) {
1714 			bch_btree_node_write_sync(n);
1715 
1716 			bch_btree_set_root(n);
1717 			btree_node_free(b);
1718 			rw_unlock(true, n);
1719 
1720 			return -EINTR;
1721 		}
1722 	}
1723 
1724 	__bch_btree_mark_key(b->c, b->level + 1, &b->key);
1725 
1726 	if (b->level) {
1727 		ret = btree_gc_recurse(b, op, writes, gc);
1728 		if (ret)
1729 			return ret;
1730 	}
1731 
1732 	bkey_copy_key(&b->c->gc_done, &b->key);
1733 
1734 	return ret;
1735 }
1736 
1737 static void btree_gc_start(struct cache_set *c)
1738 {
1739 	struct cache *ca;
1740 	struct bucket *b;
1741 
1742 	if (!c->gc_mark_valid)
1743 		return;
1744 
1745 	mutex_lock(&c->bucket_lock);
1746 
1747 	c->gc_done = ZERO_KEY;
1748 
1749 	ca = c->cache;
1750 	for_each_bucket(b, ca) {
1751 		b->last_gc = b->gen;
1752 		if (bch_can_invalidate_bucket(ca, b))
1753 			b->reclaimable_in_gc = 1;
1754 		if (!atomic_read(&b->pin)) {
1755 			SET_GC_MARK(b, 0);
1756 			SET_GC_SECTORS_USED(b, 0);
1757 		}
1758 	}
1759 
1760 	c->gc_mark_valid = 0;
1761 	mutex_unlock(&c->bucket_lock);
1762 }
1763 
1764 static void bch_btree_gc_finish(struct cache_set *c)
1765 {
1766 	struct bucket *b;
1767 	struct cache *ca;
1768 	unsigned int i, j;
1769 	uint64_t *k;
1770 
1771 	mutex_lock(&c->bucket_lock);
1772 
1773 	set_gc_sectors(c);
1774 	c->gc_mark_valid = 1;
1775 	c->need_gc	= 0;
1776 
1777 	for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1778 		SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1779 			    GC_MARK_METADATA);
1780 
1781 	/* don't reclaim buckets to which writeback keys point */
1782 	rcu_read_lock();
1783 	for (i = 0; i < c->devices_max_used; i++) {
1784 		struct bcache_device *d = c->devices[i];
1785 		struct cached_dev *dc;
1786 		struct keybuf_key *w, *n;
1787 
1788 		if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
1789 			continue;
1790 		dc = container_of(d, struct cached_dev, disk);
1791 
1792 		spin_lock(&dc->writeback_keys.lock);
1793 		rbtree_postorder_for_each_entry_safe(w, n,
1794 					&dc->writeback_keys.keys, node)
1795 			for (j = 0; j < KEY_PTRS(&w->key); j++)
1796 				SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
1797 					    GC_MARK_DIRTY);
1798 		spin_unlock(&dc->writeback_keys.lock);
1799 	}
1800 	rcu_read_unlock();
1801 
1802 	c->avail_nbuckets = 0;
1803 
1804 	ca = c->cache;
1805 	ca->invalidate_needs_gc = 0;
1806 
1807 	for (k = ca->sb.d; k < ca->sb.d + ca->sb.keys; k++)
1808 		SET_GC_MARK(ca->buckets + *k, GC_MARK_METADATA);
1809 
1810 	for (k = ca->prio_buckets;
1811 	     k < ca->prio_buckets + prio_buckets(ca) * 2; k++)
1812 		SET_GC_MARK(ca->buckets + *k, GC_MARK_METADATA);
1813 
1814 	for_each_bucket(b, ca) {
1815 		c->need_gc	= max(c->need_gc, bucket_gc_gen(b));
1816 
1817 		if (b->reclaimable_in_gc)
1818 			b->reclaimable_in_gc = 0;
1819 
1820 		if (atomic_read(&b->pin))
1821 			continue;
1822 
1823 		BUG_ON(!GC_MARK(b) && GC_SECTORS_USED(b));
1824 
1825 		if (!GC_MARK(b) || GC_MARK(b) == GC_MARK_RECLAIMABLE)
1826 			c->avail_nbuckets++;
1827 	}
1828 
1829 	mutex_unlock(&c->bucket_lock);
1830 }
1831 
1832 static void bch_btree_gc(struct cache_set *c)
1833 {
1834 	int ret;
1835 	struct gc_stat stats;
1836 	struct closure writes;
1837 	struct btree_op op;
1838 	uint64_t start_time = local_clock();
1839 
1840 	trace_bcache_gc_start(c);
1841 
1842 	memset(&stats, 0, sizeof(struct gc_stat));
1843 	closure_init_stack(&writes);
1844 	bch_btree_op_init(&op, SHRT_MAX);
1845 
1846 	btree_gc_start(c);
1847 
1848 	/* if CACHE_SET_IO_DISABLE set, gc thread should stop too */
1849 	do {
1850 		ret = bcache_btree_root(gc_root, c, &op, &writes, &stats);
1851 		closure_sync(&writes);
1852 		cond_resched();
1853 
1854 		if (ret == -EAGAIN)
1855 			schedule_timeout_interruptible(msecs_to_jiffies
1856 						       (GC_SLEEP_MS));
1857 		else if (ret)
1858 			pr_warn("gc failed!\n");
1859 	} while (ret && !test_bit(CACHE_SET_IO_DISABLE, &c->flags));
1860 
1861 	bch_btree_gc_finish(c);
1862 	wake_up_allocators(c);
1863 
1864 	bch_time_stats_update(&c->btree_gc_time, start_time);
1865 
1866 	stats.key_bytes *= sizeof(uint64_t);
1867 	stats.data	<<= 9;
1868 	bch_update_bucket_in_use(c, &stats);
1869 	memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1870 
1871 	trace_bcache_gc_end(c);
1872 
1873 	bch_moving_gc(c);
1874 }
1875 
1876 static bool gc_should_run(struct cache_set *c)
1877 {
1878 	struct cache *ca = c->cache;
1879 
1880 	if (ca->invalidate_needs_gc)
1881 		return true;
1882 
1883 	if (atomic_read(&c->sectors_to_gc) < 0)
1884 		return true;
1885 
1886 	return false;
1887 }
1888 
1889 static int bch_gc_thread(void *arg)
1890 {
1891 	struct cache_set *c = arg;
1892 
1893 	while (1) {
1894 		wait_event_interruptible(c->gc_wait,
1895 			   kthread_should_stop() ||
1896 			   test_bit(CACHE_SET_IO_DISABLE, &c->flags) ||
1897 			   gc_should_run(c));
1898 
1899 		if (kthread_should_stop() ||
1900 		    test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1901 			break;
1902 
1903 		set_gc_sectors(c);
1904 		bch_btree_gc(c);
1905 	}
1906 
1907 	wait_for_kthread_stop();
1908 	return 0;
1909 }
1910 
1911 int bch_gc_thread_start(struct cache_set *c)
1912 {
1913 	c->gc_thread = kthread_run(bch_gc_thread, c, "bcache_gc");
1914 	return PTR_ERR_OR_ZERO(c->gc_thread);
1915 }
1916 
1917 /* Initial partial gc */
1918 
1919 static int bch_btree_check_recurse(struct btree *b, struct btree_op *op)
1920 {
1921 	int ret = 0;
1922 	struct bkey *k, *p = NULL;
1923 	struct btree_iter iter;
1924 
1925 	min_heap_init(&iter.heap, NULL, MAX_BSETS);
1926 
1927 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid)
1928 		bch_initial_mark_key(b->c, b->level, k);
1929 
1930 	bch_initial_mark_key(b->c, b->level + 1, &b->key);
1931 
1932 	if (b->level) {
1933 		bch_btree_iter_init(&b->keys, &iter, NULL);
1934 
1935 		do {
1936 			k = bch_btree_iter_next_filter(&iter, &b->keys,
1937 						       bch_ptr_bad);
1938 			if (k) {
1939 				btree_node_prefetch(b, k);
1940 				/*
1941 				 * initiallize c->gc_stats.nodes
1942 				 * for incremental GC
1943 				 */
1944 				b->c->gc_stats.nodes++;
1945 			}
1946 
1947 			if (p)
1948 				ret = bcache_btree(check_recurse, p, b, op);
1949 
1950 			p = k;
1951 		} while (p && !ret);
1952 	}
1953 
1954 	return ret;
1955 }
1956 
1957 
1958 static int bch_btree_check_thread(void *arg)
1959 {
1960 	int ret;
1961 	struct btree_check_info *info = arg;
1962 	struct btree_check_state *check_state = info->state;
1963 	struct cache_set *c = check_state->c;
1964 	struct btree_iter iter;
1965 	struct bkey *k, *p;
1966 	int cur_idx, prev_idx, skip_nr;
1967 
1968 	k = p = NULL;
1969 	cur_idx = prev_idx = 0;
1970 	ret = 0;
1971 
1972 	min_heap_init(&iter.heap, NULL, MAX_BSETS);
1973 
1974 	/* root node keys are checked before thread created */
1975 	bch_btree_iter_init(&c->root->keys, &iter, NULL);
1976 	k = bch_btree_iter_next_filter(&iter, &c->root->keys, bch_ptr_bad);
1977 	BUG_ON(!k);
1978 
1979 	p = k;
1980 	while (k) {
1981 		/*
1982 		 * Fetch a root node key index, skip the keys which
1983 		 * should be fetched by other threads, then check the
1984 		 * sub-tree indexed by the fetched key.
1985 		 */
1986 		spin_lock(&check_state->idx_lock);
1987 		cur_idx = check_state->key_idx;
1988 		check_state->key_idx++;
1989 		spin_unlock(&check_state->idx_lock);
1990 
1991 		skip_nr = cur_idx - prev_idx;
1992 
1993 		while (skip_nr) {
1994 			k = bch_btree_iter_next_filter(&iter,
1995 						       &c->root->keys,
1996 						       bch_ptr_bad);
1997 			if (k)
1998 				p = k;
1999 			else {
2000 				/*
2001 				 * No more keys to check in root node,
2002 				 * current checking threads are enough,
2003 				 * stop creating more.
2004 				 */
2005 				atomic_set(&check_state->enough, 1);
2006 				/* Update check_state->enough earlier */
2007 				smp_mb__after_atomic();
2008 				goto out;
2009 			}
2010 			skip_nr--;
2011 			cond_resched();
2012 		}
2013 
2014 		if (p) {
2015 			struct btree_op op;
2016 
2017 			btree_node_prefetch(c->root, p);
2018 			c->gc_stats.nodes++;
2019 			bch_btree_op_init(&op, 0);
2020 			ret = bcache_btree(check_recurse, p, c->root, &op);
2021 			/*
2022 			 * The op may be added to cache_set's btree_cache_wait
2023 			 * in mca_cannibalize(), must ensure it is removed from
2024 			 * the list and release btree_cache_alloc_lock before
2025 			 * free op memory.
2026 			 * Otherwise, the btree_cache_wait will be damaged.
2027 			 */
2028 			bch_cannibalize_unlock(c);
2029 			finish_wait(&c->btree_cache_wait, &(&op)->wait);
2030 			if (ret)
2031 				goto out;
2032 		}
2033 		p = NULL;
2034 		prev_idx = cur_idx;
2035 		cond_resched();
2036 	}
2037 
2038 out:
2039 	info->result = ret;
2040 	/* update check_state->started among all CPUs */
2041 	smp_mb__before_atomic();
2042 	if (atomic_dec_and_test(&check_state->started))
2043 		wake_up(&check_state->wait);
2044 
2045 	return ret;
2046 }
2047 
2048 
2049 
2050 static int bch_btree_chkthread_nr(void)
2051 {
2052 	int n = num_online_cpus()/2;
2053 
2054 	if (n == 0)
2055 		n = 1;
2056 	else if (n > BCH_BTR_CHKTHREAD_MAX)
2057 		n = BCH_BTR_CHKTHREAD_MAX;
2058 
2059 	return n;
2060 }
2061 
2062 int bch_btree_check(struct cache_set *c)
2063 {
2064 	int ret = 0;
2065 	int i;
2066 	struct bkey *k = NULL;
2067 	struct btree_iter iter;
2068 	struct btree_check_state check_state;
2069 
2070 	min_heap_init(&iter.heap, NULL, MAX_BSETS);
2071 
2072 	/* check and mark root node keys */
2073 	for_each_key_filter(&c->root->keys, k, &iter, bch_ptr_invalid)
2074 		bch_initial_mark_key(c, c->root->level, k);
2075 
2076 	bch_initial_mark_key(c, c->root->level + 1, &c->root->key);
2077 
2078 	if (c->root->level == 0)
2079 		return 0;
2080 
2081 	memset(&check_state, 0, sizeof(struct btree_check_state));
2082 	check_state.c = c;
2083 	check_state.total_threads = bch_btree_chkthread_nr();
2084 	check_state.key_idx = 0;
2085 	spin_lock_init(&check_state.idx_lock);
2086 	atomic_set(&check_state.started, 0);
2087 	atomic_set(&check_state.enough, 0);
2088 	init_waitqueue_head(&check_state.wait);
2089 
2090 	rw_lock(0, c->root, c->root->level);
2091 	/*
2092 	 * Run multiple threads to check btree nodes in parallel,
2093 	 * if check_state.enough is non-zero, it means current
2094 	 * running check threads are enough, unncessary to create
2095 	 * more.
2096 	 */
2097 	for (i = 0; i < check_state.total_threads; i++) {
2098 		/* fetch latest check_state.enough earlier */
2099 		smp_mb__before_atomic();
2100 		if (atomic_read(&check_state.enough))
2101 			break;
2102 
2103 		check_state.infos[i].result = 0;
2104 		check_state.infos[i].state = &check_state;
2105 
2106 		check_state.infos[i].thread =
2107 			kthread_run(bch_btree_check_thread,
2108 				    &check_state.infos[i],
2109 				    "bch_btrchk[%d]", i);
2110 		if (IS_ERR(check_state.infos[i].thread)) {
2111 			pr_err("fails to run thread bch_btrchk[%d]\n", i);
2112 			for (--i; i >= 0; i--)
2113 				kthread_stop(check_state.infos[i].thread);
2114 			ret = -ENOMEM;
2115 			goto out;
2116 		}
2117 		atomic_inc(&check_state.started);
2118 	}
2119 
2120 	/*
2121 	 * Must wait for all threads to stop.
2122 	 */
2123 	wait_event(check_state.wait, atomic_read(&check_state.started) == 0);
2124 
2125 	for (i = 0; i < check_state.total_threads; i++) {
2126 		if (check_state.infos[i].result) {
2127 			ret = check_state.infos[i].result;
2128 			goto out;
2129 		}
2130 	}
2131 
2132 out:
2133 	rw_unlock(0, c->root);
2134 	return ret;
2135 }
2136 
2137 void bch_initial_gc_finish(struct cache_set *c)
2138 {
2139 	struct cache *ca = c->cache;
2140 	struct bucket *b;
2141 
2142 	bch_btree_gc_finish(c);
2143 
2144 	mutex_lock(&c->bucket_lock);
2145 
2146 	/*
2147 	 * We need to put some unused buckets directly on the prio freelist in
2148 	 * order to get the allocator thread started - it needs freed buckets in
2149 	 * order to rewrite the prios and gens, and it needs to rewrite prios
2150 	 * and gens in order to free buckets.
2151 	 *
2152 	 * This is only safe for buckets that have no live data in them, which
2153 	 * there should always be some of.
2154 	 */
2155 	for_each_bucket(b, ca) {
2156 		if (fifo_full(&ca->free[RESERVE_PRIO]) &&
2157 		    fifo_full(&ca->free[RESERVE_BTREE]))
2158 			break;
2159 
2160 		if (bch_can_invalidate_bucket(ca, b) &&
2161 		    !GC_MARK(b)) {
2162 			__bch_invalidate_one_bucket(ca, b);
2163 			if (!fifo_push(&ca->free[RESERVE_PRIO],
2164 			   b - ca->buckets))
2165 				fifo_push(&ca->free[RESERVE_BTREE],
2166 					  b - ca->buckets);
2167 		}
2168 	}
2169 
2170 	mutex_unlock(&c->bucket_lock);
2171 }
2172 
2173 /* Btree insertion */
2174 
2175 static bool btree_insert_key(struct btree *b, struct bkey *k,
2176 			     struct bkey *replace_key)
2177 {
2178 	unsigned int status;
2179 
2180 	BUG_ON(bkey_cmp(k, &b->key) > 0);
2181 
2182 	status = bch_btree_insert_key(&b->keys, k, replace_key);
2183 	if (status != BTREE_INSERT_STATUS_NO_INSERT) {
2184 		bch_check_keys(&b->keys, "%u for %s", status,
2185 			       replace_key ? "replace" : "insert");
2186 
2187 		trace_bcache_btree_insert_key(b, k, replace_key != NULL,
2188 					      status);
2189 		return true;
2190 	} else
2191 		return false;
2192 }
2193 
2194 static size_t insert_u64s_remaining(struct btree *b)
2195 {
2196 	long ret = bch_btree_keys_u64s_remaining(&b->keys);
2197 
2198 	/*
2199 	 * Might land in the middle of an existing extent and have to split it
2200 	 */
2201 	if (b->keys.ops->is_extents)
2202 		ret -= KEY_MAX_U64S;
2203 
2204 	return max(ret, 0L);
2205 }
2206 
2207 static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
2208 				  struct keylist *insert_keys,
2209 				  struct bkey *replace_key)
2210 {
2211 	bool ret = false;
2212 	int oldsize = bch_count_data(&b->keys);
2213 
2214 	while (!bch_keylist_empty(insert_keys)) {
2215 		struct bkey *k = insert_keys->keys;
2216 
2217 		if (bkey_u64s(k) > insert_u64s_remaining(b))
2218 			break;
2219 
2220 		if (bkey_cmp(k, &b->key) <= 0) {
2221 			if (!b->level)
2222 				bkey_put(b->c, k);
2223 
2224 			ret |= btree_insert_key(b, k, replace_key);
2225 			bch_keylist_pop_front(insert_keys);
2226 		} else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
2227 			BKEY_PADDED(key) temp;
2228 			bkey_copy(&temp.key, insert_keys->keys);
2229 
2230 			bch_cut_back(&b->key, &temp.key);
2231 			bch_cut_front(&b->key, insert_keys->keys);
2232 
2233 			ret |= btree_insert_key(b, &temp.key, replace_key);
2234 			break;
2235 		} else {
2236 			break;
2237 		}
2238 	}
2239 
2240 	if (!ret)
2241 		op->insert_collision = true;
2242 
2243 	BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
2244 
2245 	BUG_ON(bch_count_data(&b->keys) < oldsize);
2246 	return ret;
2247 }
2248 
2249 static int btree_split(struct btree *b, struct btree_op *op,
2250 		       struct keylist *insert_keys,
2251 		       struct bkey *replace_key)
2252 {
2253 	bool split;
2254 	struct btree *n1, *n2 = NULL, *n3 = NULL;
2255 	uint64_t start_time = local_clock();
2256 	struct closure cl;
2257 	struct keylist parent_keys;
2258 
2259 	closure_init_stack(&cl);
2260 	bch_keylist_init(&parent_keys);
2261 
2262 	if (btree_check_reserve(b, op)) {
2263 		if (!b->level)
2264 			return -EINTR;
2265 		else
2266 			WARN(1, "insufficient reserve for split\n");
2267 	}
2268 
2269 	n1 = btree_node_alloc_replacement(b, op);
2270 	if (IS_ERR(n1))
2271 		goto err;
2272 
2273 	split = set_blocks(btree_bset_first(n1),
2274 			   block_bytes(n1->c->cache)) > (btree_blocks(b) * 4) / 5;
2275 
2276 	if (split) {
2277 		unsigned int keys = 0;
2278 
2279 		trace_bcache_btree_node_split(b, btree_bset_first(n1)->keys);
2280 
2281 		n2 = bch_btree_node_alloc(b->c, op, b->level, b->parent);
2282 		if (IS_ERR(n2))
2283 			goto err_free1;
2284 
2285 		if (!b->parent) {
2286 			n3 = bch_btree_node_alloc(b->c, op, b->level + 1, NULL);
2287 			if (IS_ERR(n3))
2288 				goto err_free2;
2289 		}
2290 
2291 		mutex_lock(&n1->write_lock);
2292 		mutex_lock(&n2->write_lock);
2293 
2294 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2295 
2296 		/*
2297 		 * Has to be a linear search because we don't have an auxiliary
2298 		 * search tree yet
2299 		 */
2300 
2301 		while (keys < (btree_bset_first(n1)->keys * 3) / 5)
2302 			keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1),
2303 							keys));
2304 
2305 		bkey_copy_key(&n1->key,
2306 			      bset_bkey_idx(btree_bset_first(n1), keys));
2307 		keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1), keys));
2308 
2309 		btree_bset_first(n2)->keys = btree_bset_first(n1)->keys - keys;
2310 		btree_bset_first(n1)->keys = keys;
2311 
2312 		memcpy(btree_bset_first(n2)->start,
2313 		       bset_bkey_last(btree_bset_first(n1)),
2314 		       btree_bset_first(n2)->keys * sizeof(uint64_t));
2315 
2316 		bkey_copy_key(&n2->key, &b->key);
2317 
2318 		bch_keylist_add(&parent_keys, &n2->key);
2319 		bch_btree_node_write(n2, &cl);
2320 		mutex_unlock(&n2->write_lock);
2321 		rw_unlock(true, n2);
2322 	} else {
2323 		trace_bcache_btree_node_compact(b, btree_bset_first(n1)->keys);
2324 
2325 		mutex_lock(&n1->write_lock);
2326 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2327 	}
2328 
2329 	bch_keylist_add(&parent_keys, &n1->key);
2330 	bch_btree_node_write(n1, &cl);
2331 	mutex_unlock(&n1->write_lock);
2332 
2333 	if (n3) {
2334 		/* Depth increases, make a new root */
2335 		mutex_lock(&n3->write_lock);
2336 		bkey_copy_key(&n3->key, &MAX_KEY);
2337 		bch_btree_insert_keys(n3, op, &parent_keys, NULL);
2338 		bch_btree_node_write(n3, &cl);
2339 		mutex_unlock(&n3->write_lock);
2340 
2341 		closure_sync(&cl);
2342 		bch_btree_set_root(n3);
2343 		rw_unlock(true, n3);
2344 	} else if (!b->parent) {
2345 		/* Root filled up but didn't need to be split */
2346 		closure_sync(&cl);
2347 		bch_btree_set_root(n1);
2348 	} else {
2349 		/* Split a non root node */
2350 		closure_sync(&cl);
2351 		make_btree_freeing_key(b, parent_keys.top);
2352 		bch_keylist_push(&parent_keys);
2353 
2354 		bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
2355 		BUG_ON(!bch_keylist_empty(&parent_keys));
2356 	}
2357 
2358 	btree_node_free(b);
2359 	rw_unlock(true, n1);
2360 
2361 	bch_time_stats_update(&b->c->btree_split_time, start_time);
2362 
2363 	return 0;
2364 err_free2:
2365 	bkey_put(b->c, &n2->key);
2366 	btree_node_free(n2);
2367 	rw_unlock(true, n2);
2368 err_free1:
2369 	bkey_put(b->c, &n1->key);
2370 	btree_node_free(n1);
2371 	rw_unlock(true, n1);
2372 err:
2373 	WARN(1, "bcache: btree split failed (level %u)", b->level);
2374 
2375 	if (n3 == ERR_PTR(-EAGAIN) ||
2376 	    n2 == ERR_PTR(-EAGAIN) ||
2377 	    n1 == ERR_PTR(-EAGAIN))
2378 		return -EAGAIN;
2379 
2380 	return -ENOMEM;
2381 }
2382 
2383 static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
2384 				 struct keylist *insert_keys,
2385 				 atomic_t *journal_ref,
2386 				 struct bkey *replace_key)
2387 {
2388 	struct closure cl;
2389 
2390 	BUG_ON(b->level && replace_key);
2391 
2392 	closure_init_stack(&cl);
2393 
2394 	mutex_lock(&b->write_lock);
2395 
2396 	if (write_block(b) != btree_bset_last(b) &&
2397 	    b->keys.last_set_unwritten)
2398 		bch_btree_init_next(b); /* just wrote a set */
2399 
2400 	if (bch_keylist_nkeys(insert_keys) > insert_u64s_remaining(b)) {
2401 		mutex_unlock(&b->write_lock);
2402 		goto split;
2403 	}
2404 
2405 	BUG_ON(write_block(b) != btree_bset_last(b));
2406 
2407 	if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
2408 		if (!b->level)
2409 			bch_btree_leaf_dirty(b, journal_ref);
2410 		else
2411 			bch_btree_node_write(b, &cl);
2412 	}
2413 
2414 	mutex_unlock(&b->write_lock);
2415 
2416 	/* wait for btree node write if necessary, after unlock */
2417 	closure_sync(&cl);
2418 
2419 	return 0;
2420 split:
2421 	if (current->bio_list) {
2422 		op->lock = b->c->root->level + 1;
2423 		return -EAGAIN;
2424 	} else if (op->lock <= b->c->root->level) {
2425 		op->lock = b->c->root->level + 1;
2426 		return -EINTR;
2427 	} else {
2428 		/* Invalidated all iterators */
2429 		int ret = btree_split(b, op, insert_keys, replace_key);
2430 
2431 		if (bch_keylist_empty(insert_keys))
2432 			return 0;
2433 		else if (!ret)
2434 			return -EINTR;
2435 		return ret;
2436 	}
2437 }
2438 
2439 int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2440 			       struct bkey *check_key)
2441 {
2442 	int ret = -EINTR;
2443 	uint64_t btree_ptr = b->key.ptr[0];
2444 	unsigned long seq = b->seq;
2445 	struct keylist insert;
2446 	bool upgrade = op->lock == -1;
2447 
2448 	bch_keylist_init(&insert);
2449 
2450 	if (upgrade) {
2451 		rw_unlock(false, b);
2452 		rw_lock(true, b, b->level);
2453 
2454 		if (b->key.ptr[0] != btree_ptr ||
2455 		    b->seq != seq + 1) {
2456 			op->lock = b->level;
2457 			goto out;
2458 		}
2459 	}
2460 
2461 	SET_KEY_PTRS(check_key, 1);
2462 	get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2463 
2464 	SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2465 
2466 	bch_keylist_add(&insert, check_key);
2467 
2468 	ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2469 
2470 	BUG_ON(!ret && !bch_keylist_empty(&insert));
2471 out:
2472 	if (upgrade)
2473 		downgrade_write(&b->lock);
2474 	return ret;
2475 }
2476 
2477 struct btree_insert_op {
2478 	struct btree_op	op;
2479 	struct keylist	*keys;
2480 	atomic_t	*journal_ref;
2481 	struct bkey	*replace_key;
2482 };
2483 
2484 static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2485 {
2486 	struct btree_insert_op *op = container_of(b_op,
2487 					struct btree_insert_op, op);
2488 
2489 	int ret = bch_btree_insert_node(b, &op->op, op->keys,
2490 					op->journal_ref, op->replace_key);
2491 	if (ret && !bch_keylist_empty(op->keys))
2492 		return ret;
2493 	else
2494 		return MAP_DONE;
2495 }
2496 
2497 int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2498 		     atomic_t *journal_ref, struct bkey *replace_key)
2499 {
2500 	struct btree_insert_op op;
2501 	int ret = 0;
2502 
2503 	BUG_ON(current->bio_list);
2504 	BUG_ON(bch_keylist_empty(keys));
2505 
2506 	bch_btree_op_init(&op.op, 0);
2507 	op.keys		= keys;
2508 	op.journal_ref	= journal_ref;
2509 	op.replace_key	= replace_key;
2510 
2511 	while (!ret && !bch_keylist_empty(keys)) {
2512 		op.op.lock = 0;
2513 		ret = bch_btree_map_leaf_nodes(&op.op, c,
2514 					       &START_KEY(keys->keys),
2515 					       btree_insert_fn);
2516 	}
2517 
2518 	if (ret) {
2519 		struct bkey *k;
2520 
2521 		pr_err("error %i\n", ret);
2522 
2523 		while ((k = bch_keylist_pop(keys)))
2524 			bkey_put(c, k);
2525 	} else if (op.op.insert_collision)
2526 		ret = -ESRCH;
2527 
2528 	return ret;
2529 }
2530 
2531 void bch_btree_set_root(struct btree *b)
2532 {
2533 	unsigned int i;
2534 	struct closure cl;
2535 
2536 	closure_init_stack(&cl);
2537 
2538 	trace_bcache_btree_set_root(b);
2539 
2540 	BUG_ON(!b->written);
2541 
2542 	for (i = 0; i < KEY_PTRS(&b->key); i++)
2543 		BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2544 
2545 	mutex_lock(&b->c->bucket_lock);
2546 	list_del_init(&b->list);
2547 	mutex_unlock(&b->c->bucket_lock);
2548 
2549 	b->c->root = b;
2550 
2551 	bch_journal_meta(b->c, &cl);
2552 	closure_sync(&cl);
2553 }
2554 
2555 /* Map across nodes or keys */
2556 
2557 static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
2558 				       struct bkey *from,
2559 				       btree_map_nodes_fn *fn, int flags)
2560 {
2561 	int ret = MAP_CONTINUE;
2562 
2563 	if (b->level) {
2564 		struct bkey *k;
2565 		struct btree_iter iter;
2566 
2567 		min_heap_init(&iter.heap, NULL, MAX_BSETS);
2568 		bch_btree_iter_init(&b->keys, &iter, from);
2569 
2570 		while ((k = bch_btree_iter_next_filter(&iter, &b->keys,
2571 						       bch_ptr_bad))) {
2572 			ret = bcache_btree(map_nodes_recurse, k, b,
2573 				    op, from, fn, flags);
2574 			from = NULL;
2575 
2576 			if (ret != MAP_CONTINUE)
2577 				return ret;
2578 		}
2579 	}
2580 
2581 	if (!b->level || flags == MAP_ALL_NODES)
2582 		ret = fn(op, b);
2583 
2584 	return ret;
2585 }
2586 
2587 int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
2588 			  struct bkey *from, btree_map_nodes_fn *fn, int flags)
2589 {
2590 	return bcache_btree_root(map_nodes_recurse, c, op, from, fn, flags);
2591 }
2592 
2593 int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
2594 				      struct bkey *from, btree_map_keys_fn *fn,
2595 				      int flags)
2596 {
2597 	int ret = MAP_CONTINUE;
2598 	struct bkey *k;
2599 	struct btree_iter iter;
2600 
2601 	min_heap_init(&iter.heap, NULL, MAX_BSETS);
2602 	bch_btree_iter_init(&b->keys, &iter, from);
2603 
2604 	while ((k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad))) {
2605 		ret = !b->level
2606 			? fn(op, b, k)
2607 			: bcache_btree(map_keys_recurse, k,
2608 				       b, op, from, fn, flags);
2609 		from = NULL;
2610 
2611 		if (ret != MAP_CONTINUE)
2612 			return ret;
2613 	}
2614 
2615 	if (!b->level && (flags & MAP_END_KEY))
2616 		ret = fn(op, b, &KEY(KEY_INODE(&b->key),
2617 				     KEY_OFFSET(&b->key), 0));
2618 
2619 	return ret;
2620 }
2621 
2622 int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
2623 		       struct bkey *from, btree_map_keys_fn *fn, int flags)
2624 {
2625 	return bcache_btree_root(map_keys_recurse, c, op, from, fn, flags);
2626 }
2627 
2628 /* Keybuf code */
2629 
2630 static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2631 {
2632 	/* Overlapping keys compare equal */
2633 	if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2634 		return -1;
2635 	if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2636 		return 1;
2637 	return 0;
2638 }
2639 
2640 static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2641 					    struct keybuf_key *r)
2642 {
2643 	return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2644 }
2645 
2646 struct refill {
2647 	struct btree_op	op;
2648 	unsigned int	nr_found;
2649 	struct keybuf	*buf;
2650 	struct bkey	*end;
2651 	keybuf_pred_fn	*pred;
2652 };
2653 
2654 static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
2655 			    struct bkey *k)
2656 {
2657 	struct refill *refill = container_of(op, struct refill, op);
2658 	struct keybuf *buf = refill->buf;
2659 	int ret = MAP_CONTINUE;
2660 
2661 	if (bkey_cmp(k, refill->end) > 0) {
2662 		ret = MAP_DONE;
2663 		goto out;
2664 	}
2665 
2666 	if (!KEY_SIZE(k)) /* end key */
2667 		goto out;
2668 
2669 	if (refill->pred(buf, k)) {
2670 		struct keybuf_key *w;
2671 
2672 		spin_lock(&buf->lock);
2673 
2674 		w = array_alloc(&buf->freelist);
2675 		if (!w) {
2676 			spin_unlock(&buf->lock);
2677 			return MAP_DONE;
2678 		}
2679 
2680 		w->private = NULL;
2681 		bkey_copy(&w->key, k);
2682 
2683 		if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2684 			array_free(&buf->freelist, w);
2685 		else
2686 			refill->nr_found++;
2687 
2688 		if (array_freelist_empty(&buf->freelist))
2689 			ret = MAP_DONE;
2690 
2691 		spin_unlock(&buf->lock);
2692 	}
2693 out:
2694 	buf->last_scanned = *k;
2695 	return ret;
2696 }
2697 
2698 void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
2699 		       struct bkey *end, keybuf_pred_fn *pred)
2700 {
2701 	struct bkey start = buf->last_scanned;
2702 	struct refill refill;
2703 
2704 	cond_resched();
2705 
2706 	bch_btree_op_init(&refill.op, -1);
2707 	refill.nr_found	= 0;
2708 	refill.buf	= buf;
2709 	refill.end	= end;
2710 	refill.pred	= pred;
2711 
2712 	bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
2713 			   refill_keybuf_fn, MAP_END_KEY);
2714 
2715 	trace_bcache_keyscan(refill.nr_found,
2716 			     KEY_INODE(&start), KEY_OFFSET(&start),
2717 			     KEY_INODE(&buf->last_scanned),
2718 			     KEY_OFFSET(&buf->last_scanned));
2719 
2720 	spin_lock(&buf->lock);
2721 
2722 	if (!RB_EMPTY_ROOT(&buf->keys)) {
2723 		struct keybuf_key *w;
2724 
2725 		w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2726 		buf->start	= START_KEY(&w->key);
2727 
2728 		w = RB_LAST(&buf->keys, struct keybuf_key, node);
2729 		buf->end	= w->key;
2730 	} else {
2731 		buf->start	= MAX_KEY;
2732 		buf->end	= MAX_KEY;
2733 	}
2734 
2735 	spin_unlock(&buf->lock);
2736 }
2737 
2738 static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2739 {
2740 	rb_erase(&w->node, &buf->keys);
2741 	array_free(&buf->freelist, w);
2742 }
2743 
2744 void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2745 {
2746 	spin_lock(&buf->lock);
2747 	__bch_keybuf_del(buf, w);
2748 	spin_unlock(&buf->lock);
2749 }
2750 
2751 bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2752 				  struct bkey *end)
2753 {
2754 	bool ret = false;
2755 	struct keybuf_key *p, *w, s;
2756 
2757 	s.key = *start;
2758 
2759 	if (bkey_cmp(end, &buf->start) <= 0 ||
2760 	    bkey_cmp(start, &buf->end) >= 0)
2761 		return false;
2762 
2763 	spin_lock(&buf->lock);
2764 	w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2765 
2766 	while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2767 		p = w;
2768 		w = RB_NEXT(w, node);
2769 
2770 		if (p->private)
2771 			ret = true;
2772 		else
2773 			__bch_keybuf_del(buf, p);
2774 	}
2775 
2776 	spin_unlock(&buf->lock);
2777 	return ret;
2778 }
2779 
2780 struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2781 {
2782 	struct keybuf_key *w;
2783 
2784 	spin_lock(&buf->lock);
2785 
2786 	w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2787 
2788 	while (w && w->private)
2789 		w = RB_NEXT(w, node);
2790 
2791 	if (w)
2792 		w->private = ERR_PTR(-EINTR);
2793 
2794 	spin_unlock(&buf->lock);
2795 	return w;
2796 }
2797 
2798 struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2799 					  struct keybuf *buf,
2800 					  struct bkey *end,
2801 					  keybuf_pred_fn *pred)
2802 {
2803 	struct keybuf_key *ret;
2804 
2805 	while (1) {
2806 		ret = bch_keybuf_next(buf);
2807 		if (ret)
2808 			break;
2809 
2810 		if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2811 			pr_debug("scan finished\n");
2812 			break;
2813 		}
2814 
2815 		bch_refill_keybuf(c, buf, end, pred);
2816 	}
2817 
2818 	return ret;
2819 }
2820 
2821 void bch_keybuf_init(struct keybuf *buf)
2822 {
2823 	buf->last_scanned	= MAX_KEY;
2824 	buf->keys		= RB_ROOT;
2825 
2826 	spin_lock_init(&buf->lock);
2827 	array_allocator_init(&buf->freelist);
2828 }
2829 
2830 void bch_btree_exit(void)
2831 {
2832 	if (btree_io_wq)
2833 		destroy_workqueue(btree_io_wq);
2834 }
2835 
2836 int __init bch_btree_init(void)
2837 {
2838 	btree_io_wq = alloc_workqueue("bch_btree_io", WQ_MEM_RECLAIM, 0);
2839 	if (!btree_io_wq)
2840 		return -ENOMEM;
2841 
2842 	return 0;
2843 }
2844