xref: /linux/drivers/md/bcache/btree.c (revision 085d2a3dd4d65b7bce1dead987c647dbbc014281)
1cafe5635SKent Overstreet /*
2cafe5635SKent Overstreet  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
3cafe5635SKent Overstreet  *
4cafe5635SKent Overstreet  * Uses a block device as cache for other block devices; optimized for SSDs.
5cafe5635SKent Overstreet  * All allocation is done in buckets, which should match the erase block size
6cafe5635SKent Overstreet  * of the device.
7cafe5635SKent Overstreet  *
8cafe5635SKent Overstreet  * Buckets containing cached data are kept on a heap sorted by priority;
9cafe5635SKent Overstreet  * bucket priority is increased on cache hit, and periodically all the buckets
10cafe5635SKent Overstreet  * on the heap have their priority scaled down. This currently is just used as
11cafe5635SKent Overstreet  * an LRU but in the future should allow for more intelligent heuristics.
12cafe5635SKent Overstreet  *
13cafe5635SKent Overstreet  * Buckets have an 8 bit counter; freeing is accomplished by incrementing the
14cafe5635SKent Overstreet  * counter. Garbage collection is used to remove stale pointers.
15cafe5635SKent Overstreet  *
16cafe5635SKent Overstreet  * Indexing is done via a btree; nodes are not necessarily fully sorted, rather
17cafe5635SKent Overstreet  * as keys are inserted we only sort the pages that have not yet been written.
18cafe5635SKent Overstreet  * When garbage collection is run, we resort the entire node.
19cafe5635SKent Overstreet  *
20cafe5635SKent Overstreet  * All configuration is done via sysfs; see Documentation/bcache.txt.
21cafe5635SKent Overstreet  */
22cafe5635SKent Overstreet 
23cafe5635SKent Overstreet #include "bcache.h"
24cafe5635SKent Overstreet #include "btree.h"
25cafe5635SKent Overstreet #include "debug.h"
26279afbadSKent Overstreet #include "writeback.h"
27cafe5635SKent Overstreet 
28cafe5635SKent Overstreet #include <linux/slab.h>
29cafe5635SKent Overstreet #include <linux/bitops.h>
3072a44517SKent Overstreet #include <linux/freezer.h>
31cafe5635SKent Overstreet #include <linux/hash.h>
3272a44517SKent Overstreet #include <linux/kthread.h>
33cd953ed0SGeert Uytterhoeven #include <linux/prefetch.h>
34cafe5635SKent Overstreet #include <linux/random.h>
35cafe5635SKent Overstreet #include <linux/rcupdate.h>
36cafe5635SKent Overstreet #include <trace/events/bcache.h>
37cafe5635SKent Overstreet 
38cafe5635SKent Overstreet /*
39cafe5635SKent Overstreet  * Todo:
40cafe5635SKent Overstreet  * register_bcache: Return errors out to userspace correctly
41cafe5635SKent Overstreet  *
42cafe5635SKent Overstreet  * Writeback: don't undirty key until after a cache flush
43cafe5635SKent Overstreet  *
44cafe5635SKent Overstreet  * Create an iterator for key pointers
45cafe5635SKent Overstreet  *
46cafe5635SKent Overstreet  * On btree write error, mark bucket such that it won't be freed from the cache
47cafe5635SKent Overstreet  *
48cafe5635SKent Overstreet  * Journalling:
49cafe5635SKent Overstreet  *   Check for bad keys in replay
50cafe5635SKent Overstreet  *   Propagate barriers
51cafe5635SKent Overstreet  *   Refcount journal entries in journal_replay
52cafe5635SKent Overstreet  *
53cafe5635SKent Overstreet  * Garbage collection:
54cafe5635SKent Overstreet  *   Finish incremental gc
55cafe5635SKent Overstreet  *   Gc should free old UUIDs, data for invalid UUIDs
56cafe5635SKent Overstreet  *
57cafe5635SKent Overstreet  * Provide a way to list backing device UUIDs we have data cached for, and
58cafe5635SKent Overstreet  * probably how long it's been since we've seen them, and a way to invalidate
59cafe5635SKent Overstreet  * dirty data for devices that will never be attached again
60cafe5635SKent Overstreet  *
61cafe5635SKent Overstreet  * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
62cafe5635SKent Overstreet  * that based on that and how much dirty data we have we can keep writeback
63cafe5635SKent Overstreet  * from being starved
64cafe5635SKent Overstreet  *
65cafe5635SKent Overstreet  * Add a tracepoint or somesuch to watch for writeback starvation
66cafe5635SKent Overstreet  *
67cafe5635SKent Overstreet  * When btree depth > 1 and splitting an interior node, we have to make sure
68cafe5635SKent Overstreet  * alloc_bucket() cannot fail. This should be true but is not completely
69cafe5635SKent Overstreet  * obvious.
70cafe5635SKent Overstreet  *
71cafe5635SKent Overstreet  * Make sure all allocations get charged to the root cgroup
72cafe5635SKent Overstreet  *
73cafe5635SKent Overstreet  * Plugging?
74cafe5635SKent Overstreet  *
75cafe5635SKent Overstreet  * If data write is less than hard sector size of ssd, round up offset in open
76cafe5635SKent Overstreet  * bucket to the next whole sector
77cafe5635SKent Overstreet  *
78cafe5635SKent Overstreet  * Also lookup by cgroup in get_open_bucket()
79cafe5635SKent Overstreet  *
80cafe5635SKent Overstreet  * Superblock needs to be fleshed out for multiple cache devices
81cafe5635SKent Overstreet  *
82cafe5635SKent Overstreet  * Add a sysfs tunable for the number of writeback IOs in flight
83cafe5635SKent Overstreet  *
84cafe5635SKent Overstreet  * Add a sysfs tunable for the number of open data buckets
85cafe5635SKent Overstreet  *
86cafe5635SKent Overstreet  * IO tracking: Can we track when one process is doing io on behalf of another?
87cafe5635SKent Overstreet  * IO tracking: Don't use just an average, weigh more recent stuff higher
88cafe5635SKent Overstreet  *
89cafe5635SKent Overstreet  * Test module load/unload
90cafe5635SKent Overstreet  */
91cafe5635SKent Overstreet 
92df8e8970SKent Overstreet enum {
93df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_INSERT,
94df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_BACK_MERGE,
95df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_OVERWROTE,
96df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_FRONT_MERGE,
97df8e8970SKent Overstreet };
98df8e8970SKent Overstreet 
99cafe5635SKent Overstreet #define MAX_NEED_GC		64
100cafe5635SKent Overstreet #define MAX_SAVE_PRIO		72
101cafe5635SKent Overstreet 
102cafe5635SKent Overstreet #define PTR_DIRTY_BIT		(((uint64_t) 1 << 36))
103cafe5635SKent Overstreet 
104cafe5635SKent Overstreet #define PTR_HASH(c, k)							\
105cafe5635SKent Overstreet 	(((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
106cafe5635SKent Overstreet 
107cafe5635SKent Overstreet static struct workqueue_struct *btree_io_wq;
108cafe5635SKent Overstreet 
109df8e8970SKent Overstreet static inline bool should_split(struct btree *b)
110df8e8970SKent Overstreet {
111df8e8970SKent Overstreet 	struct bset *i = write_block(b);
112df8e8970SKent Overstreet 	return b->written >= btree_blocks(b) ||
113df8e8970SKent Overstreet 		(b->written + __set_blocks(i, i->keys + 15, b->c)
114df8e8970SKent Overstreet 		 > btree_blocks(b));
115df8e8970SKent Overstreet }
116df8e8970SKent Overstreet 
117df8e8970SKent Overstreet #define insert_lock(s, b)	((b)->level <= (s)->lock)
118df8e8970SKent Overstreet 
119df8e8970SKent Overstreet /*
120df8e8970SKent Overstreet  * These macros are for recursing down the btree - they handle the details of
121df8e8970SKent Overstreet  * locking and looking up nodes in the cache for you. They're best treated as
122df8e8970SKent Overstreet  * mere syntax when reading code that uses them.
123df8e8970SKent Overstreet  *
124df8e8970SKent Overstreet  * op->lock determines whether we take a read or a write lock at a given depth.
125df8e8970SKent Overstreet  * If you've got a read lock and find that you need a write lock (i.e. you're
126df8e8970SKent Overstreet  * going to have to split), set op->lock and return -EINTR; btree_root() will
127df8e8970SKent Overstreet  * call you again and you'll have the correct lock.
128df8e8970SKent Overstreet  */
129df8e8970SKent Overstreet 
130df8e8970SKent Overstreet /**
131df8e8970SKent Overstreet  * btree - recurse down the btree on a specified key
132df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
133df8e8970SKent Overstreet  * @key:	key to recurse on
134df8e8970SKent Overstreet  * @b:		parent btree node
135df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
136df8e8970SKent Overstreet  */
137df8e8970SKent Overstreet #define btree(fn, key, b, op, ...)					\
138df8e8970SKent Overstreet ({									\
139df8e8970SKent Overstreet 	int _r, l = (b)->level - 1;					\
140df8e8970SKent Overstreet 	bool _w = l <= (op)->lock;					\
141df8e8970SKent Overstreet 	struct btree *_child = bch_btree_node_get((b)->c, key, l, _w);	\
142df8e8970SKent Overstreet 	if (!IS_ERR(_child)) {						\
143df8e8970SKent Overstreet 		_child->parent = (b);					\
144df8e8970SKent Overstreet 		_r = bch_btree_ ## fn(_child, op, ##__VA_ARGS__);	\
145df8e8970SKent Overstreet 		rw_unlock(_w, _child);					\
146df8e8970SKent Overstreet 	} else								\
147df8e8970SKent Overstreet 		_r = PTR_ERR(_child);					\
148df8e8970SKent Overstreet 	_r;								\
149df8e8970SKent Overstreet })
150df8e8970SKent Overstreet 
151df8e8970SKent Overstreet /**
152df8e8970SKent Overstreet  * btree_root - call a function on the root of the btree
153df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
154df8e8970SKent Overstreet  * @c:		cache set
155df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
156df8e8970SKent Overstreet  */
157df8e8970SKent Overstreet #define btree_root(fn, c, op, ...)					\
158df8e8970SKent Overstreet ({									\
159df8e8970SKent Overstreet 	int _r = -EINTR;						\
160df8e8970SKent Overstreet 	do {								\
161df8e8970SKent Overstreet 		struct btree *_b = (c)->root;				\
162df8e8970SKent Overstreet 		bool _w = insert_lock(op, _b);				\
163df8e8970SKent Overstreet 		rw_lock(_w, _b, _b->level);				\
164df8e8970SKent Overstreet 		if (_b == (c)->root &&					\
165df8e8970SKent Overstreet 		    _w == insert_lock(op, _b)) {			\
166df8e8970SKent Overstreet 			_b->parent = NULL;				\
167df8e8970SKent Overstreet 			_r = bch_btree_ ## fn(_b, op, ##__VA_ARGS__);	\
168df8e8970SKent Overstreet 		}							\
169df8e8970SKent Overstreet 		rw_unlock(_w, _b);					\
17078365411SKent Overstreet 		if (_r == -EINTR)					\
17178365411SKent Overstreet 			schedule();					\
172df8e8970SKent Overstreet 		bch_cannibalize_unlock(c);				\
173df8e8970SKent Overstreet 		if (_r == -ENOSPC) {					\
174df8e8970SKent Overstreet 			wait_event((c)->try_wait,			\
175df8e8970SKent Overstreet 				   !(c)->try_harder);			\
176df8e8970SKent Overstreet 			_r = -EINTR;					\
177df8e8970SKent Overstreet 		}							\
178df8e8970SKent Overstreet 	} while (_r == -EINTR);						\
179df8e8970SKent Overstreet 									\
18078365411SKent Overstreet 	finish_wait(&(c)->bucket_wait, &(op)->wait);			\
181df8e8970SKent Overstreet 	_r;								\
182df8e8970SKent Overstreet })
183df8e8970SKent Overstreet 
184cafe5635SKent Overstreet /* Btree key manipulation */
185cafe5635SKent Overstreet 
1863a3b6a4eSKent Overstreet void bkey_put(struct cache_set *c, struct bkey *k)
187e7c590ebSKent Overstreet {
188e7c590ebSKent Overstreet 	unsigned i;
189e7c590ebSKent Overstreet 
190e7c590ebSKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
191e7c590ebSKent Overstreet 		if (ptr_available(c, k, i))
192e7c590ebSKent Overstreet 			atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
193e7c590ebSKent Overstreet }
194e7c590ebSKent Overstreet 
195cafe5635SKent Overstreet /* Btree IO */
196cafe5635SKent Overstreet 
197cafe5635SKent Overstreet static uint64_t btree_csum_set(struct btree *b, struct bset *i)
198cafe5635SKent Overstreet {
199cafe5635SKent Overstreet 	uint64_t crc = b->key.ptr[0];
200cafe5635SKent Overstreet 	void *data = (void *) i + 8, *end = end(i);
201cafe5635SKent Overstreet 
202169ef1cfSKent Overstreet 	crc = bch_crc64_update(crc, data, end - data);
203c19ed23aSKent Overstreet 	return crc ^ 0xffffffffffffffffULL;
204cafe5635SKent Overstreet }
205cafe5635SKent Overstreet 
20678b77bf8SKent Overstreet void bch_btree_node_read_done(struct btree *b)
207cafe5635SKent Overstreet {
208cafe5635SKent Overstreet 	const char *err = "bad btree header";
20957943511SKent Overstreet 	struct bset *i = b->sets[0].data;
21057943511SKent Overstreet 	struct btree_iter *iter;
211cafe5635SKent Overstreet 
21257943511SKent Overstreet 	iter = mempool_alloc(b->c->fill_iter, GFP_NOWAIT);
21357943511SKent Overstreet 	iter->size = b->c->sb.bucket_size / b->c->sb.block_size;
214cafe5635SKent Overstreet 	iter->used = 0;
215cafe5635SKent Overstreet 
216280481d0SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
217280481d0SKent Overstreet 	iter->b = b;
218280481d0SKent Overstreet #endif
219280481d0SKent Overstreet 
22057943511SKent Overstreet 	if (!i->seq)
221cafe5635SKent Overstreet 		goto err;
222cafe5635SKent Overstreet 
223cafe5635SKent Overstreet 	for (;
224cafe5635SKent Overstreet 	     b->written < btree_blocks(b) && i->seq == b->sets[0].data->seq;
225cafe5635SKent Overstreet 	     i = write_block(b)) {
226cafe5635SKent Overstreet 		err = "unsupported bset version";
227cafe5635SKent Overstreet 		if (i->version > BCACHE_BSET_VERSION)
228cafe5635SKent Overstreet 			goto err;
229cafe5635SKent Overstreet 
230cafe5635SKent Overstreet 		err = "bad btree header";
231cafe5635SKent Overstreet 		if (b->written + set_blocks(i, b->c) > btree_blocks(b))
232cafe5635SKent Overstreet 			goto err;
233cafe5635SKent Overstreet 
234cafe5635SKent Overstreet 		err = "bad magic";
23581ab4190SKent Overstreet 		if (i->magic != bset_magic(&b->c->sb))
236cafe5635SKent Overstreet 			goto err;
237cafe5635SKent Overstreet 
238cafe5635SKent Overstreet 		err = "bad checksum";
239cafe5635SKent Overstreet 		switch (i->version) {
240cafe5635SKent Overstreet 		case 0:
241cafe5635SKent Overstreet 			if (i->csum != csum_set(i))
242cafe5635SKent Overstreet 				goto err;
243cafe5635SKent Overstreet 			break;
244cafe5635SKent Overstreet 		case BCACHE_BSET_VERSION:
245cafe5635SKent Overstreet 			if (i->csum != btree_csum_set(b, i))
246cafe5635SKent Overstreet 				goto err;
247cafe5635SKent Overstreet 			break;
248cafe5635SKent Overstreet 		}
249cafe5635SKent Overstreet 
250cafe5635SKent Overstreet 		err = "empty set";
251cafe5635SKent Overstreet 		if (i != b->sets[0].data && !i->keys)
252cafe5635SKent Overstreet 			goto err;
253cafe5635SKent Overstreet 
254cafe5635SKent Overstreet 		bch_btree_iter_push(iter, i->start, end(i));
255cafe5635SKent Overstreet 
256cafe5635SKent Overstreet 		b->written += set_blocks(i, b->c);
257cafe5635SKent Overstreet 	}
258cafe5635SKent Overstreet 
259cafe5635SKent Overstreet 	err = "corrupted btree";
260cafe5635SKent Overstreet 	for (i = write_block(b);
26188b9f8c4SKent Overstreet 	     bset_sector_offset(b, i) < KEY_SIZE(&b->key);
262cafe5635SKent Overstreet 	     i = ((void *) i) + block_bytes(b->c))
263cafe5635SKent Overstreet 		if (i->seq == b->sets[0].data->seq)
264cafe5635SKent Overstreet 			goto err;
265cafe5635SKent Overstreet 
266cafe5635SKent Overstreet 	bch_btree_sort_and_fix_extents(b, iter);
267cafe5635SKent Overstreet 
268cafe5635SKent Overstreet 	i = b->sets[0].data;
269cafe5635SKent Overstreet 	err = "short btree key";
270cafe5635SKent Overstreet 	if (b->sets[0].size &&
271cafe5635SKent Overstreet 	    bkey_cmp(&b->key, &b->sets[0].end) < 0)
272cafe5635SKent Overstreet 		goto err;
273cafe5635SKent Overstreet 
274cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
275cafe5635SKent Overstreet 		bch_bset_init_next(b);
276cafe5635SKent Overstreet out:
27757943511SKent Overstreet 	mempool_free(iter, b->c->fill_iter);
27857943511SKent Overstreet 	return;
279cafe5635SKent Overstreet err:
280cafe5635SKent Overstreet 	set_btree_node_io_error(b);
28188b9f8c4SKent Overstreet 	bch_cache_set_error(b->c, "%s at bucket %zu, block %u, %u keys",
282cafe5635SKent Overstreet 			    err, PTR_BUCKET_NR(b->c, &b->key, 0),
28388b9f8c4SKent Overstreet 			    bset_block_offset(b, i), i->keys);
284cafe5635SKent Overstreet 	goto out;
285cafe5635SKent Overstreet }
286cafe5635SKent Overstreet 
28757943511SKent Overstreet static void btree_node_read_endio(struct bio *bio, int error)
288cafe5635SKent Overstreet {
28957943511SKent Overstreet 	struct closure *cl = bio->bi_private;
29057943511SKent Overstreet 	closure_put(cl);
29157943511SKent Overstreet }
292cafe5635SKent Overstreet 
29378b77bf8SKent Overstreet static void bch_btree_node_read(struct btree *b)
29457943511SKent Overstreet {
29557943511SKent Overstreet 	uint64_t start_time = local_clock();
29657943511SKent Overstreet 	struct closure cl;
29757943511SKent Overstreet 	struct bio *bio;
298cafe5635SKent Overstreet 
299c37511b8SKent Overstreet 	trace_bcache_btree_read(b);
300c37511b8SKent Overstreet 
30157943511SKent Overstreet 	closure_init_stack(&cl);
302cafe5635SKent Overstreet 
30357943511SKent Overstreet 	bio = bch_bbio_alloc(b->c);
30457943511SKent Overstreet 	bio->bi_rw	= REQ_META|READ_SYNC;
3054f024f37SKent Overstreet 	bio->bi_iter.bi_size = KEY_SIZE(&b->key) << 9;
30657943511SKent Overstreet 	bio->bi_end_io	= btree_node_read_endio;
30757943511SKent Overstreet 	bio->bi_private	= &cl;
30857943511SKent Overstreet 
30957943511SKent Overstreet 	bch_bio_map(bio, b->sets[0].data);
31057943511SKent Overstreet 
31157943511SKent Overstreet 	bch_submit_bbio(bio, b->c, &b->key, 0);
31257943511SKent Overstreet 	closure_sync(&cl);
31357943511SKent Overstreet 
31457943511SKent Overstreet 	if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
31557943511SKent Overstreet 		set_btree_node_io_error(b);
31657943511SKent Overstreet 
31757943511SKent Overstreet 	bch_bbio_free(bio, b->c);
31857943511SKent Overstreet 
31957943511SKent Overstreet 	if (btree_node_io_error(b))
32057943511SKent Overstreet 		goto err;
32157943511SKent Overstreet 
32257943511SKent Overstreet 	bch_btree_node_read_done(b);
32357943511SKent Overstreet 	bch_time_stats_update(&b->c->btree_read_time, start_time);
32457943511SKent Overstreet 
32557943511SKent Overstreet 	return;
32657943511SKent Overstreet err:
32761cbd250SGeert Uytterhoeven 	bch_cache_set_error(b->c, "io error reading bucket %zu",
32857943511SKent Overstreet 			    PTR_BUCKET_NR(b->c, &b->key, 0));
329cafe5635SKent Overstreet }
330cafe5635SKent Overstreet 
331cafe5635SKent Overstreet static void btree_complete_write(struct btree *b, struct btree_write *w)
332cafe5635SKent Overstreet {
333cafe5635SKent Overstreet 	if (w->prio_blocked &&
334cafe5635SKent Overstreet 	    !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
335119ba0f8SKent Overstreet 		wake_up_allocators(b->c);
336cafe5635SKent Overstreet 
337cafe5635SKent Overstreet 	if (w->journal) {
338cafe5635SKent Overstreet 		atomic_dec_bug(w->journal);
339cafe5635SKent Overstreet 		__closure_wake_up(&b->c->journal.wait);
340cafe5635SKent Overstreet 	}
341cafe5635SKent Overstreet 
342cafe5635SKent Overstreet 	w->prio_blocked	= 0;
343cafe5635SKent Overstreet 	w->journal	= NULL;
344cafe5635SKent Overstreet }
345cafe5635SKent Overstreet 
346cb7a583eSKent Overstreet static void btree_node_write_unlock(struct closure *cl)
347cb7a583eSKent Overstreet {
348cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
349cb7a583eSKent Overstreet 
350cb7a583eSKent Overstreet 	up(&b->io_mutex);
351cb7a583eSKent Overstreet }
352cb7a583eSKent Overstreet 
35357943511SKent Overstreet static void __btree_node_write_done(struct closure *cl)
354cafe5635SKent Overstreet {
355cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
356cafe5635SKent Overstreet 	struct btree_write *w = btree_prev_write(b);
357cafe5635SKent Overstreet 
358cafe5635SKent Overstreet 	bch_bbio_free(b->bio, b->c);
359cafe5635SKent Overstreet 	b->bio = NULL;
360cafe5635SKent Overstreet 	btree_complete_write(b, w);
361cafe5635SKent Overstreet 
362cafe5635SKent Overstreet 	if (btree_node_dirty(b))
363cafe5635SKent Overstreet 		queue_delayed_work(btree_io_wq, &b->work,
364cafe5635SKent Overstreet 				   msecs_to_jiffies(30000));
365cafe5635SKent Overstreet 
366cb7a583eSKent Overstreet 	closure_return_with_destructor(cl, btree_node_write_unlock);
367cafe5635SKent Overstreet }
368cafe5635SKent Overstreet 
36957943511SKent Overstreet static void btree_node_write_done(struct closure *cl)
370cafe5635SKent Overstreet {
371cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
372cafe5635SKent Overstreet 	struct bio_vec *bv;
373cafe5635SKent Overstreet 	int n;
374cafe5635SKent Overstreet 
3757988613bSKent Overstreet 	bio_for_each_segment_all(bv, b->bio, n)
376cafe5635SKent Overstreet 		__free_page(bv->bv_page);
377cafe5635SKent Overstreet 
37857943511SKent Overstreet 	__btree_node_write_done(cl);
379cafe5635SKent Overstreet }
380cafe5635SKent Overstreet 
38157943511SKent Overstreet static void btree_node_write_endio(struct bio *bio, int error)
38257943511SKent Overstreet {
38357943511SKent Overstreet 	struct closure *cl = bio->bi_private;
384cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
38557943511SKent Overstreet 
38657943511SKent Overstreet 	if (error)
38757943511SKent Overstreet 		set_btree_node_io_error(b);
38857943511SKent Overstreet 
38957943511SKent Overstreet 	bch_bbio_count_io_errors(b->c, bio, error, "writing btree");
39057943511SKent Overstreet 	closure_put(cl);
39157943511SKent Overstreet }
39257943511SKent Overstreet 
39357943511SKent Overstreet static void do_btree_node_write(struct btree *b)
394cafe5635SKent Overstreet {
395cb7a583eSKent Overstreet 	struct closure *cl = &b->io;
396cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
397cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
398cafe5635SKent Overstreet 
399cafe5635SKent Overstreet 	i->version	= BCACHE_BSET_VERSION;
400cafe5635SKent Overstreet 	i->csum		= btree_csum_set(b, i);
401cafe5635SKent Overstreet 
40257943511SKent Overstreet 	BUG_ON(b->bio);
40357943511SKent Overstreet 	b->bio = bch_bbio_alloc(b->c);
40457943511SKent Overstreet 
40557943511SKent Overstreet 	b->bio->bi_end_io	= btree_node_write_endio;
406faadf0c9SKent Overstreet 	b->bio->bi_private	= cl;
407e49c7c37SKent Overstreet 	b->bio->bi_rw		= REQ_META|WRITE_SYNC|REQ_FUA;
4084f024f37SKent Overstreet 	b->bio->bi_iter.bi_size	= set_blocks(i, b->c) * block_bytes(b->c);
409169ef1cfSKent Overstreet 	bch_bio_map(b->bio, i);
410cafe5635SKent Overstreet 
411e49c7c37SKent Overstreet 	/*
412e49c7c37SKent Overstreet 	 * If we're appending to a leaf node, we don't technically need FUA -
413e49c7c37SKent Overstreet 	 * this write just needs to be persisted before the next journal write,
414e49c7c37SKent Overstreet 	 * which will be marked FLUSH|FUA.
415e49c7c37SKent Overstreet 	 *
416e49c7c37SKent Overstreet 	 * Similarly if we're writing a new btree root - the pointer is going to
417e49c7c37SKent Overstreet 	 * be in the next journal entry.
418e49c7c37SKent Overstreet 	 *
419e49c7c37SKent Overstreet 	 * But if we're writing a new btree node (that isn't a root) or
420e49c7c37SKent Overstreet 	 * appending to a non leaf btree node, we need either FUA or a flush
421e49c7c37SKent Overstreet 	 * when we write the parent with the new pointer. FUA is cheaper than a
422e49c7c37SKent Overstreet 	 * flush, and writes appending to leaf nodes aren't blocking anything so
423e49c7c37SKent Overstreet 	 * just make all btree node writes FUA to keep things sane.
424e49c7c37SKent Overstreet 	 */
425e49c7c37SKent Overstreet 
426cafe5635SKent Overstreet 	bkey_copy(&k.key, &b->key);
427cafe5635SKent Overstreet 	SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) + bset_offset(b, i));
428cafe5635SKent Overstreet 
4298e51e414SKent Overstreet 	if (!bio_alloc_pages(b->bio, GFP_NOIO)) {
430cafe5635SKent Overstreet 		int j;
431cafe5635SKent Overstreet 		struct bio_vec *bv;
432cafe5635SKent Overstreet 		void *base = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
433cafe5635SKent Overstreet 
4347988613bSKent Overstreet 		bio_for_each_segment_all(bv, b->bio, j)
435cafe5635SKent Overstreet 			memcpy(page_address(bv->bv_page),
436cafe5635SKent Overstreet 			       base + j * PAGE_SIZE, PAGE_SIZE);
437cafe5635SKent Overstreet 
438cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
439cafe5635SKent Overstreet 
44057943511SKent Overstreet 		continue_at(cl, btree_node_write_done, NULL);
441cafe5635SKent Overstreet 	} else {
442cafe5635SKent Overstreet 		b->bio->bi_vcnt = 0;
443169ef1cfSKent Overstreet 		bch_bio_map(b->bio, i);
444cafe5635SKent Overstreet 
445cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
446cafe5635SKent Overstreet 
447cafe5635SKent Overstreet 		closure_sync(cl);
448cb7a583eSKent Overstreet 		continue_at_nobarrier(cl, __btree_node_write_done, NULL);
449cafe5635SKent Overstreet 	}
450cafe5635SKent Overstreet }
451cafe5635SKent Overstreet 
45257943511SKent Overstreet void bch_btree_node_write(struct btree *b, struct closure *parent)
453cafe5635SKent Overstreet {
454cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
455cafe5635SKent Overstreet 
456c37511b8SKent Overstreet 	trace_bcache_btree_write(b);
457c37511b8SKent Overstreet 
458cafe5635SKent Overstreet 	BUG_ON(current->bio_list);
45957943511SKent Overstreet 	BUG_ON(b->written >= btree_blocks(b));
46057943511SKent Overstreet 	BUG_ON(b->written && !i->keys);
46157943511SKent Overstreet 	BUG_ON(b->sets->data->seq != i->seq);
462280481d0SKent Overstreet 	bch_check_keys(b, "writing");
463cafe5635SKent Overstreet 
464cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
465cafe5635SKent Overstreet 
46657943511SKent Overstreet 	/* If caller isn't waiting for write, parent refcount is cache set */
467cb7a583eSKent Overstreet 	down(&b->io_mutex);
468cb7a583eSKent Overstreet 	closure_init(&b->io, parent ?: &b->c->cl);
46957943511SKent Overstreet 
470cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty,	 &b->flags);
471cafe5635SKent Overstreet 	change_bit(BTREE_NODE_write_idx, &b->flags);
472cafe5635SKent Overstreet 
47357943511SKent Overstreet 	do_btree_node_write(b);
474cafe5635SKent Overstreet 
475cafe5635SKent Overstreet 	b->written += set_blocks(i, b->c);
476cafe5635SKent Overstreet 	atomic_long_add(set_blocks(i, b->c) * b->c->sb.block_size,
477cafe5635SKent Overstreet 			&PTR_CACHE(b->c, &b->key, 0)->btree_sectors_written);
478cafe5635SKent Overstreet 
479cafe5635SKent Overstreet 	bch_btree_sort_lazy(b);
480cafe5635SKent Overstreet 
48178b77bf8SKent Overstreet 	/*
48278b77bf8SKent Overstreet 	 * do verify if there was more than one set initially (i.e. we did a
48378b77bf8SKent Overstreet 	 * sort) and we sorted down to a single set:
48478b77bf8SKent Overstreet 	 */
48578b77bf8SKent Overstreet 	if (i != b->sets->data && !b->nsets)
48678b77bf8SKent Overstreet 		bch_btree_verify(b);
48778b77bf8SKent Overstreet 
488cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
489cafe5635SKent Overstreet 		bch_bset_init_next(b);
490cafe5635SKent Overstreet }
491cafe5635SKent Overstreet 
492f269af5aSKent Overstreet static void bch_btree_node_write_sync(struct btree *b)
493f269af5aSKent Overstreet {
494f269af5aSKent Overstreet 	struct closure cl;
495f269af5aSKent Overstreet 
496f269af5aSKent Overstreet 	closure_init_stack(&cl);
497f269af5aSKent Overstreet 	bch_btree_node_write(b, &cl);
498f269af5aSKent Overstreet 	closure_sync(&cl);
499f269af5aSKent Overstreet }
500f269af5aSKent Overstreet 
50157943511SKent Overstreet static void btree_node_write_work(struct work_struct *w)
502cafe5635SKent Overstreet {
503cafe5635SKent Overstreet 	struct btree *b = container_of(to_delayed_work(w), struct btree, work);
504cafe5635SKent Overstreet 
50557943511SKent Overstreet 	rw_lock(true, b, b->level);
506cafe5635SKent Overstreet 
507cafe5635SKent Overstreet 	if (btree_node_dirty(b))
50857943511SKent Overstreet 		bch_btree_node_write(b, NULL);
50957943511SKent Overstreet 	rw_unlock(true, b);
510cafe5635SKent Overstreet }
511cafe5635SKent Overstreet 
512c18536a7SKent Overstreet static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
513cafe5635SKent Overstreet {
514cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
515cafe5635SKent Overstreet 	struct btree_write *w = btree_current_write(b);
516cafe5635SKent Overstreet 
51757943511SKent Overstreet 	BUG_ON(!b->written);
51857943511SKent Overstreet 	BUG_ON(!i->keys);
519cafe5635SKent Overstreet 
52057943511SKent Overstreet 	if (!btree_node_dirty(b))
52157943511SKent Overstreet 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
52257943511SKent Overstreet 
523cafe5635SKent Overstreet 	set_btree_node_dirty(b);
524cafe5635SKent Overstreet 
525c18536a7SKent Overstreet 	if (journal_ref) {
526cafe5635SKent Overstreet 		if (w->journal &&
527c18536a7SKent Overstreet 		    journal_pin_cmp(b->c, w->journal, journal_ref)) {
528cafe5635SKent Overstreet 			atomic_dec_bug(w->journal);
529cafe5635SKent Overstreet 			w->journal = NULL;
530cafe5635SKent Overstreet 		}
531cafe5635SKent Overstreet 
532cafe5635SKent Overstreet 		if (!w->journal) {
533c18536a7SKent Overstreet 			w->journal = journal_ref;
534cafe5635SKent Overstreet 			atomic_inc(w->journal);
535cafe5635SKent Overstreet 		}
536cafe5635SKent Overstreet 	}
537cafe5635SKent Overstreet 
538cafe5635SKent Overstreet 	/* Force write if set is too big */
53957943511SKent Overstreet 	if (set_bytes(i) > PAGE_SIZE - 48 &&
54057943511SKent Overstreet 	    !current->bio_list)
54157943511SKent Overstreet 		bch_btree_node_write(b, NULL);
542cafe5635SKent Overstreet }
543cafe5635SKent Overstreet 
544cafe5635SKent Overstreet /*
545cafe5635SKent Overstreet  * Btree in memory cache - allocation/freeing
546cafe5635SKent Overstreet  * mca -> memory cache
547cafe5635SKent Overstreet  */
548cafe5635SKent Overstreet 
549cafe5635SKent Overstreet static void mca_reinit(struct btree *b)
550cafe5635SKent Overstreet {
551cafe5635SKent Overstreet 	unsigned i;
552cafe5635SKent Overstreet 
553cafe5635SKent Overstreet 	b->flags	= 0;
554cafe5635SKent Overstreet 	b->written	= 0;
555cafe5635SKent Overstreet 	b->nsets	= 0;
556cafe5635SKent Overstreet 
557cafe5635SKent Overstreet 	for (i = 0; i < MAX_BSETS; i++)
558cafe5635SKent Overstreet 		b->sets[i].size = 0;
559cafe5635SKent Overstreet 	/*
560cafe5635SKent Overstreet 	 * Second loop starts at 1 because b->sets[0]->data is the memory we
561cafe5635SKent Overstreet 	 * allocated
562cafe5635SKent Overstreet 	 */
563cafe5635SKent Overstreet 	for (i = 1; i < MAX_BSETS; i++)
564cafe5635SKent Overstreet 		b->sets[i].data = NULL;
565cafe5635SKent Overstreet }
566cafe5635SKent Overstreet 
567cafe5635SKent Overstreet #define mca_reserve(c)	(((c->root && c->root->level)		\
568cafe5635SKent Overstreet 			  ? c->root->level : 1) * 8 + 16)
569cafe5635SKent Overstreet #define mca_can_free(c)						\
570cafe5635SKent Overstreet 	max_t(int, 0, c->bucket_cache_used - mca_reserve(c))
571cafe5635SKent Overstreet 
572cafe5635SKent Overstreet static void mca_data_free(struct btree *b)
573cafe5635SKent Overstreet {
574cafe5635SKent Overstreet 	struct bset_tree *t = b->sets;
575cb7a583eSKent Overstreet 
576cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
577cafe5635SKent Overstreet 
578cafe5635SKent Overstreet 	if (bset_prev_bytes(b) < PAGE_SIZE)
579cafe5635SKent Overstreet 		kfree(t->prev);
580cafe5635SKent Overstreet 	else
581cafe5635SKent Overstreet 		free_pages((unsigned long) t->prev,
582cafe5635SKent Overstreet 			   get_order(bset_prev_bytes(b)));
583cafe5635SKent Overstreet 
584cafe5635SKent Overstreet 	if (bset_tree_bytes(b) < PAGE_SIZE)
585cafe5635SKent Overstreet 		kfree(t->tree);
586cafe5635SKent Overstreet 	else
587cafe5635SKent Overstreet 		free_pages((unsigned long) t->tree,
588cafe5635SKent Overstreet 			   get_order(bset_tree_bytes(b)));
589cafe5635SKent Overstreet 
590cafe5635SKent Overstreet 	free_pages((unsigned long) t->data, b->page_order);
591cafe5635SKent Overstreet 
592cafe5635SKent Overstreet 	t->prev = NULL;
593cafe5635SKent Overstreet 	t->tree = NULL;
594cafe5635SKent Overstreet 	t->data = NULL;
595cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freed);
596cafe5635SKent Overstreet 	b->c->bucket_cache_used--;
597cafe5635SKent Overstreet }
598cafe5635SKent Overstreet 
599cafe5635SKent Overstreet static void mca_bucket_free(struct btree *b)
600cafe5635SKent Overstreet {
601cafe5635SKent Overstreet 	BUG_ON(btree_node_dirty(b));
602cafe5635SKent Overstreet 
603cafe5635SKent Overstreet 	b->key.ptr[0] = 0;
604cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
605cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freeable);
606cafe5635SKent Overstreet }
607cafe5635SKent Overstreet 
608cafe5635SKent Overstreet static unsigned btree_order(struct bkey *k)
609cafe5635SKent Overstreet {
610cafe5635SKent Overstreet 	return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
611cafe5635SKent Overstreet }
612cafe5635SKent Overstreet 
613cafe5635SKent Overstreet static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
614cafe5635SKent Overstreet {
615cafe5635SKent Overstreet 	struct bset_tree *t = b->sets;
616cafe5635SKent Overstreet 	BUG_ON(t->data);
617cafe5635SKent Overstreet 
618cafe5635SKent Overstreet 	b->page_order = max_t(unsigned,
619cafe5635SKent Overstreet 			      ilog2(b->c->btree_pages),
620cafe5635SKent Overstreet 			      btree_order(k));
621cafe5635SKent Overstreet 
622cafe5635SKent Overstreet 	t->data = (void *) __get_free_pages(gfp, b->page_order);
623cafe5635SKent Overstreet 	if (!t->data)
624cafe5635SKent Overstreet 		goto err;
625cafe5635SKent Overstreet 
626cafe5635SKent Overstreet 	t->tree = bset_tree_bytes(b) < PAGE_SIZE
627cafe5635SKent Overstreet 		? kmalloc(bset_tree_bytes(b), gfp)
628cafe5635SKent Overstreet 		: (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
629cafe5635SKent Overstreet 	if (!t->tree)
630cafe5635SKent Overstreet 		goto err;
631cafe5635SKent Overstreet 
632cafe5635SKent Overstreet 	t->prev = bset_prev_bytes(b) < PAGE_SIZE
633cafe5635SKent Overstreet 		? kmalloc(bset_prev_bytes(b), gfp)
634cafe5635SKent Overstreet 		: (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
635cafe5635SKent Overstreet 	if (!t->prev)
636cafe5635SKent Overstreet 		goto err;
637cafe5635SKent Overstreet 
638cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache);
639cafe5635SKent Overstreet 	b->c->bucket_cache_used++;
640cafe5635SKent Overstreet 	return;
641cafe5635SKent Overstreet err:
642cafe5635SKent Overstreet 	mca_data_free(b);
643cafe5635SKent Overstreet }
644cafe5635SKent Overstreet 
645cafe5635SKent Overstreet static struct btree *mca_bucket_alloc(struct cache_set *c,
646cafe5635SKent Overstreet 				      struct bkey *k, gfp_t gfp)
647cafe5635SKent Overstreet {
648cafe5635SKent Overstreet 	struct btree *b = kzalloc(sizeof(struct btree), gfp);
649cafe5635SKent Overstreet 	if (!b)
650cafe5635SKent Overstreet 		return NULL;
651cafe5635SKent Overstreet 
652cafe5635SKent Overstreet 	init_rwsem(&b->lock);
653cafe5635SKent Overstreet 	lockdep_set_novalidate_class(&b->lock);
654cafe5635SKent Overstreet 	INIT_LIST_HEAD(&b->list);
65557943511SKent Overstreet 	INIT_DELAYED_WORK(&b->work, btree_node_write_work);
656cafe5635SKent Overstreet 	b->c = c;
657cb7a583eSKent Overstreet 	sema_init(&b->io_mutex, 1);
658cafe5635SKent Overstreet 
659cafe5635SKent Overstreet 	mca_data_alloc(b, k, gfp);
660cafe5635SKent Overstreet 	return b;
661cafe5635SKent Overstreet }
662cafe5635SKent Overstreet 
663e8e1d468SKent Overstreet static int mca_reap(struct btree *b, unsigned min_order, bool flush)
664cafe5635SKent Overstreet {
665e8e1d468SKent Overstreet 	struct closure cl;
666e8e1d468SKent Overstreet 
667e8e1d468SKent Overstreet 	closure_init_stack(&cl);
668cafe5635SKent Overstreet 	lockdep_assert_held(&b->c->bucket_lock);
669cafe5635SKent Overstreet 
670cafe5635SKent Overstreet 	if (!down_write_trylock(&b->lock))
671cafe5635SKent Overstreet 		return -ENOMEM;
672cafe5635SKent Overstreet 
673e8e1d468SKent Overstreet 	BUG_ON(btree_node_dirty(b) && !b->sets[0].data);
674e8e1d468SKent Overstreet 
675cb7a583eSKent Overstreet 	if (b->page_order < min_order)
676cb7a583eSKent Overstreet 		goto out_unlock;
677cb7a583eSKent Overstreet 
678cb7a583eSKent Overstreet 	if (!flush) {
679cb7a583eSKent Overstreet 		if (btree_node_dirty(b))
680cb7a583eSKent Overstreet 			goto out_unlock;
681cb7a583eSKent Overstreet 
682cb7a583eSKent Overstreet 		if (down_trylock(&b->io_mutex))
683cb7a583eSKent Overstreet 			goto out_unlock;
684cb7a583eSKent Overstreet 		up(&b->io_mutex);
685cafe5635SKent Overstreet 	}
686cafe5635SKent Overstreet 
687f269af5aSKent Overstreet 	if (btree_node_dirty(b))
688f269af5aSKent Overstreet 		bch_btree_node_write_sync(b);
689cafe5635SKent Overstreet 
690e8e1d468SKent Overstreet 	/* wait for any in flight btree write */
691cb7a583eSKent Overstreet 	down(&b->io_mutex);
692cb7a583eSKent Overstreet 	up(&b->io_mutex);
693e8e1d468SKent Overstreet 
694cafe5635SKent Overstreet 	return 0;
695cb7a583eSKent Overstreet out_unlock:
696cb7a583eSKent Overstreet 	rw_unlock(true, b);
697cb7a583eSKent Overstreet 	return -ENOMEM;
698cafe5635SKent Overstreet }
699cafe5635SKent Overstreet 
7007dc19d5aSDave Chinner static unsigned long bch_mca_scan(struct shrinker *shrink,
7017dc19d5aSDave Chinner 				  struct shrink_control *sc)
702cafe5635SKent Overstreet {
703cafe5635SKent Overstreet 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
704cafe5635SKent Overstreet 	struct btree *b, *t;
705cafe5635SKent Overstreet 	unsigned long i, nr = sc->nr_to_scan;
7067dc19d5aSDave Chinner 	unsigned long freed = 0;
707cafe5635SKent Overstreet 
708cafe5635SKent Overstreet 	if (c->shrinker_disabled)
7097dc19d5aSDave Chinner 		return SHRINK_STOP;
710cafe5635SKent Overstreet 
711cafe5635SKent Overstreet 	if (c->try_harder)
7127dc19d5aSDave Chinner 		return SHRINK_STOP;
713cafe5635SKent Overstreet 
714cafe5635SKent Overstreet 	/* Return -1 if we can't do anything right now */
715a698e08cSKent Overstreet 	if (sc->gfp_mask & __GFP_IO)
716cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
717cafe5635SKent Overstreet 	else if (!mutex_trylock(&c->bucket_lock))
718cafe5635SKent Overstreet 		return -1;
719cafe5635SKent Overstreet 
72036c9ea98SKent Overstreet 	/*
72136c9ea98SKent Overstreet 	 * It's _really_ critical that we don't free too many btree nodes - we
72236c9ea98SKent Overstreet 	 * have to always leave ourselves a reserve. The reserve is how we
72336c9ea98SKent Overstreet 	 * guarantee that allocating memory for a new btree node can always
72436c9ea98SKent Overstreet 	 * succeed, so that inserting keys into the btree can always succeed and
72536c9ea98SKent Overstreet 	 * IO can always make forward progress:
72636c9ea98SKent Overstreet 	 */
727cafe5635SKent Overstreet 	nr /= c->btree_pages;
728cafe5635SKent Overstreet 	nr = min_t(unsigned long, nr, mca_can_free(c));
729cafe5635SKent Overstreet 
730cafe5635SKent Overstreet 	i = 0;
731cafe5635SKent Overstreet 	list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
7327dc19d5aSDave Chinner 		if (freed >= nr)
733cafe5635SKent Overstreet 			break;
734cafe5635SKent Overstreet 
735cafe5635SKent Overstreet 		if (++i > 3 &&
736e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
737cafe5635SKent Overstreet 			mca_data_free(b);
738cafe5635SKent Overstreet 			rw_unlock(true, b);
7397dc19d5aSDave Chinner 			freed++;
740cafe5635SKent Overstreet 		}
741cafe5635SKent Overstreet 	}
742cafe5635SKent Overstreet 
743b0f32a56SKent Overstreet 	for (i = 0; (nr--) && i < c->bucket_cache_used; i++) {
744cafe5635SKent Overstreet 		if (list_empty(&c->btree_cache))
745cafe5635SKent Overstreet 			goto out;
746cafe5635SKent Overstreet 
747cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
748cafe5635SKent Overstreet 		list_rotate_left(&c->btree_cache);
749cafe5635SKent Overstreet 
750cafe5635SKent Overstreet 		if (!b->accessed &&
751e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
752cafe5635SKent Overstreet 			mca_bucket_free(b);
753cafe5635SKent Overstreet 			mca_data_free(b);
754cafe5635SKent Overstreet 			rw_unlock(true, b);
7557dc19d5aSDave Chinner 			freed++;
756cafe5635SKent Overstreet 		} else
757cafe5635SKent Overstreet 			b->accessed = 0;
758cafe5635SKent Overstreet 	}
759cafe5635SKent Overstreet out:
760cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
7617dc19d5aSDave Chinner 	return freed;
7627dc19d5aSDave Chinner }
7637dc19d5aSDave Chinner 
7647dc19d5aSDave Chinner static unsigned long bch_mca_count(struct shrinker *shrink,
7657dc19d5aSDave Chinner 				   struct shrink_control *sc)
7667dc19d5aSDave Chinner {
7677dc19d5aSDave Chinner 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
7687dc19d5aSDave Chinner 
7697dc19d5aSDave Chinner 	if (c->shrinker_disabled)
7707dc19d5aSDave Chinner 		return 0;
7717dc19d5aSDave Chinner 
7727dc19d5aSDave Chinner 	if (c->try_harder)
7737dc19d5aSDave Chinner 		return 0;
7747dc19d5aSDave Chinner 
7757dc19d5aSDave Chinner 	return mca_can_free(c) * c->btree_pages;
776cafe5635SKent Overstreet }
777cafe5635SKent Overstreet 
778cafe5635SKent Overstreet void bch_btree_cache_free(struct cache_set *c)
779cafe5635SKent Overstreet {
780cafe5635SKent Overstreet 	struct btree *b;
781cafe5635SKent Overstreet 	struct closure cl;
782cafe5635SKent Overstreet 	closure_init_stack(&cl);
783cafe5635SKent Overstreet 
784cafe5635SKent Overstreet 	if (c->shrink.list.next)
785cafe5635SKent Overstreet 		unregister_shrinker(&c->shrink);
786cafe5635SKent Overstreet 
787cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
788cafe5635SKent Overstreet 
789cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
790cafe5635SKent Overstreet 	if (c->verify_data)
791cafe5635SKent Overstreet 		list_move(&c->verify_data->list, &c->btree_cache);
79278b77bf8SKent Overstreet 
79378b77bf8SKent Overstreet 	free_pages((unsigned long) c->verify_ondisk, ilog2(bucket_pages(c)));
794cafe5635SKent Overstreet #endif
795cafe5635SKent Overstreet 
796cafe5635SKent Overstreet 	list_splice(&c->btree_cache_freeable,
797cafe5635SKent Overstreet 		    &c->btree_cache);
798cafe5635SKent Overstreet 
799cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache)) {
800cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
801cafe5635SKent Overstreet 
802cafe5635SKent Overstreet 		if (btree_node_dirty(b))
803cafe5635SKent Overstreet 			btree_complete_write(b, btree_current_write(b));
804cafe5635SKent Overstreet 		clear_bit(BTREE_NODE_dirty, &b->flags);
805cafe5635SKent Overstreet 
806cafe5635SKent Overstreet 		mca_data_free(b);
807cafe5635SKent Overstreet 	}
808cafe5635SKent Overstreet 
809cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache_freed)) {
810cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache_freed,
811cafe5635SKent Overstreet 				     struct btree, list);
812cafe5635SKent Overstreet 		list_del(&b->list);
813cafe5635SKent Overstreet 		cancel_delayed_work_sync(&b->work);
814cafe5635SKent Overstreet 		kfree(b);
815cafe5635SKent Overstreet 	}
816cafe5635SKent Overstreet 
817cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
818cafe5635SKent Overstreet }
819cafe5635SKent Overstreet 
820cafe5635SKent Overstreet int bch_btree_cache_alloc(struct cache_set *c)
821cafe5635SKent Overstreet {
822cafe5635SKent Overstreet 	unsigned i;
823cafe5635SKent Overstreet 
824cafe5635SKent Overstreet 	for (i = 0; i < mca_reserve(c); i++)
82572a44517SKent Overstreet 		if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
82672a44517SKent Overstreet 			return -ENOMEM;
827cafe5635SKent Overstreet 
828cafe5635SKent Overstreet 	list_splice_init(&c->btree_cache,
829cafe5635SKent Overstreet 			 &c->btree_cache_freeable);
830cafe5635SKent Overstreet 
831cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
832cafe5635SKent Overstreet 	mutex_init(&c->verify_lock);
833cafe5635SKent Overstreet 
83478b77bf8SKent Overstreet 	c->verify_ondisk = (void *)
83578b77bf8SKent Overstreet 		__get_free_pages(GFP_KERNEL, ilog2(bucket_pages(c)));
83678b77bf8SKent Overstreet 
837cafe5635SKent Overstreet 	c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
838cafe5635SKent Overstreet 
839cafe5635SKent Overstreet 	if (c->verify_data &&
840cafe5635SKent Overstreet 	    c->verify_data->sets[0].data)
841cafe5635SKent Overstreet 		list_del_init(&c->verify_data->list);
842cafe5635SKent Overstreet 	else
843cafe5635SKent Overstreet 		c->verify_data = NULL;
844cafe5635SKent Overstreet #endif
845cafe5635SKent Overstreet 
8467dc19d5aSDave Chinner 	c->shrink.count_objects = bch_mca_count;
8477dc19d5aSDave Chinner 	c->shrink.scan_objects = bch_mca_scan;
848cafe5635SKent Overstreet 	c->shrink.seeks = 4;
849cafe5635SKent Overstreet 	c->shrink.batch = c->btree_pages * 2;
850cafe5635SKent Overstreet 	register_shrinker(&c->shrink);
851cafe5635SKent Overstreet 
852cafe5635SKent Overstreet 	return 0;
853cafe5635SKent Overstreet }
854cafe5635SKent Overstreet 
855cafe5635SKent Overstreet /* Btree in memory cache - hash table */
856cafe5635SKent Overstreet 
857cafe5635SKent Overstreet static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
858cafe5635SKent Overstreet {
859cafe5635SKent Overstreet 	return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
860cafe5635SKent Overstreet }
861cafe5635SKent Overstreet 
862cafe5635SKent Overstreet static struct btree *mca_find(struct cache_set *c, struct bkey *k)
863cafe5635SKent Overstreet {
864cafe5635SKent Overstreet 	struct btree *b;
865cafe5635SKent Overstreet 
866cafe5635SKent Overstreet 	rcu_read_lock();
867cafe5635SKent Overstreet 	hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
868cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
869cafe5635SKent Overstreet 			goto out;
870cafe5635SKent Overstreet 	b = NULL;
871cafe5635SKent Overstreet out:
872cafe5635SKent Overstreet 	rcu_read_unlock();
873cafe5635SKent Overstreet 	return b;
874cafe5635SKent Overstreet }
875cafe5635SKent Overstreet 
876e8e1d468SKent Overstreet static struct btree *mca_cannibalize(struct cache_set *c, struct bkey *k)
877cafe5635SKent Overstreet {
878e8e1d468SKent Overstreet 	struct btree *b;
879cafe5635SKent Overstreet 
880c37511b8SKent Overstreet 	trace_bcache_btree_cache_cannibalize(c);
881c37511b8SKent Overstreet 
882e8e1d468SKent Overstreet 	if (!c->try_harder) {
883e8e1d468SKent Overstreet 		c->try_harder = current;
884cafe5635SKent Overstreet 		c->try_harder_start = local_clock();
885e8e1d468SKent Overstreet 	} else if (c->try_harder != current)
886e8e1d468SKent Overstreet 		return ERR_PTR(-ENOSPC);
887cafe5635SKent Overstreet 
888e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
889e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
890e8e1d468SKent Overstreet 			return b;
891cafe5635SKent Overstreet 
892e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
893e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), true))
894e8e1d468SKent Overstreet 			return b;
895e8e1d468SKent Overstreet 
896e8e1d468SKent Overstreet 	return ERR_PTR(-ENOMEM);
897cafe5635SKent Overstreet }
898cafe5635SKent Overstreet 
899cafe5635SKent Overstreet /*
900cafe5635SKent Overstreet  * We can only have one thread cannibalizing other cached btree nodes at a time,
901cafe5635SKent Overstreet  * or we'll deadlock. We use an open coded mutex to ensure that, which a
902cafe5635SKent Overstreet  * cannibalize_bucket() will take. This means every time we unlock the root of
903cafe5635SKent Overstreet  * the btree, we need to release this lock if we have it held.
904cafe5635SKent Overstreet  */
905df8e8970SKent Overstreet static void bch_cannibalize_unlock(struct cache_set *c)
906cafe5635SKent Overstreet {
907e8e1d468SKent Overstreet 	if (c->try_harder == current) {
908169ef1cfSKent Overstreet 		bch_time_stats_update(&c->try_harder_time, c->try_harder_start);
909cafe5635SKent Overstreet 		c->try_harder = NULL;
910e8e1d468SKent Overstreet 		wake_up(&c->try_wait);
911cafe5635SKent Overstreet 	}
912cafe5635SKent Overstreet }
913cafe5635SKent Overstreet 
914e8e1d468SKent Overstreet static struct btree *mca_alloc(struct cache_set *c, struct bkey *k, int level)
915cafe5635SKent Overstreet {
916cafe5635SKent Overstreet 	struct btree *b;
917cafe5635SKent Overstreet 
918e8e1d468SKent Overstreet 	BUG_ON(current->bio_list);
919e8e1d468SKent Overstreet 
920cafe5635SKent Overstreet 	lockdep_assert_held(&c->bucket_lock);
921cafe5635SKent Overstreet 
922cafe5635SKent Overstreet 	if (mca_find(c, k))
923cafe5635SKent Overstreet 		return NULL;
924cafe5635SKent Overstreet 
925cafe5635SKent Overstreet 	/* btree_free() doesn't free memory; it sticks the node on the end of
926cafe5635SKent Overstreet 	 * the list. Check if there's any freed nodes there:
927cafe5635SKent Overstreet 	 */
928cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freeable, list)
929e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
930cafe5635SKent Overstreet 			goto out;
931cafe5635SKent Overstreet 
932cafe5635SKent Overstreet 	/* We never free struct btree itself, just the memory that holds the on
933cafe5635SKent Overstreet 	 * disk node. Check the freed list before allocating a new one:
934cafe5635SKent Overstreet 	 */
935cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freed, list)
936e8e1d468SKent Overstreet 		if (!mca_reap(b, 0, false)) {
937cafe5635SKent Overstreet 			mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
938cafe5635SKent Overstreet 			if (!b->sets[0].data)
939cafe5635SKent Overstreet 				goto err;
940cafe5635SKent Overstreet 			else
941cafe5635SKent Overstreet 				goto out;
942cafe5635SKent Overstreet 		}
943cafe5635SKent Overstreet 
944cafe5635SKent Overstreet 	b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
945cafe5635SKent Overstreet 	if (!b)
946cafe5635SKent Overstreet 		goto err;
947cafe5635SKent Overstreet 
948cafe5635SKent Overstreet 	BUG_ON(!down_write_trylock(&b->lock));
949cafe5635SKent Overstreet 	if (!b->sets->data)
950cafe5635SKent Overstreet 		goto err;
951cafe5635SKent Overstreet out:
952cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
953cafe5635SKent Overstreet 
954cafe5635SKent Overstreet 	bkey_copy(&b->key, k);
955cafe5635SKent Overstreet 	list_move(&b->list, &c->btree_cache);
956cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
957cafe5635SKent Overstreet 	hlist_add_head_rcu(&b->hash, mca_hash(c, k));
958cafe5635SKent Overstreet 
959cafe5635SKent Overstreet 	lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
960cafe5635SKent Overstreet 	b->level	= level;
961d6fd3b11SKent Overstreet 	b->parent	= (void *) ~0UL;
962cafe5635SKent Overstreet 
963cafe5635SKent Overstreet 	mca_reinit(b);
964cafe5635SKent Overstreet 
965cafe5635SKent Overstreet 	return b;
966cafe5635SKent Overstreet err:
967cafe5635SKent Overstreet 	if (b)
968cafe5635SKent Overstreet 		rw_unlock(true, b);
969cafe5635SKent Overstreet 
970e8e1d468SKent Overstreet 	b = mca_cannibalize(c, k);
971cafe5635SKent Overstreet 	if (!IS_ERR(b))
972cafe5635SKent Overstreet 		goto out;
973cafe5635SKent Overstreet 
974cafe5635SKent Overstreet 	return b;
975cafe5635SKent Overstreet }
976cafe5635SKent Overstreet 
977cafe5635SKent Overstreet /**
978cafe5635SKent Overstreet  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
979cafe5635SKent Overstreet  * in from disk if necessary.
980cafe5635SKent Overstreet  *
981b54d6934SKent Overstreet  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
982cafe5635SKent Overstreet  *
983cafe5635SKent Overstreet  * The btree node will have either a read or a write lock held, depending on
984cafe5635SKent Overstreet  * level and op->lock.
985cafe5635SKent Overstreet  */
986cafe5635SKent Overstreet struct btree *bch_btree_node_get(struct cache_set *c, struct bkey *k,
987e8e1d468SKent Overstreet 				 int level, bool write)
988cafe5635SKent Overstreet {
989cafe5635SKent Overstreet 	int i = 0;
990cafe5635SKent Overstreet 	struct btree *b;
991cafe5635SKent Overstreet 
992cafe5635SKent Overstreet 	BUG_ON(level < 0);
993cafe5635SKent Overstreet retry:
994cafe5635SKent Overstreet 	b = mca_find(c, k);
995cafe5635SKent Overstreet 
996cafe5635SKent Overstreet 	if (!b) {
99757943511SKent Overstreet 		if (current->bio_list)
99857943511SKent Overstreet 			return ERR_PTR(-EAGAIN);
99957943511SKent Overstreet 
1000cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
1001e8e1d468SKent Overstreet 		b = mca_alloc(c, k, level);
1002cafe5635SKent Overstreet 		mutex_unlock(&c->bucket_lock);
1003cafe5635SKent Overstreet 
1004cafe5635SKent Overstreet 		if (!b)
1005cafe5635SKent Overstreet 			goto retry;
1006cafe5635SKent Overstreet 		if (IS_ERR(b))
1007cafe5635SKent Overstreet 			return b;
1008cafe5635SKent Overstreet 
100957943511SKent Overstreet 		bch_btree_node_read(b);
1010cafe5635SKent Overstreet 
1011cafe5635SKent Overstreet 		if (!write)
1012cafe5635SKent Overstreet 			downgrade_write(&b->lock);
1013cafe5635SKent Overstreet 	} else {
1014cafe5635SKent Overstreet 		rw_lock(write, b, level);
1015cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
1016cafe5635SKent Overstreet 			rw_unlock(write, b);
1017cafe5635SKent Overstreet 			goto retry;
1018cafe5635SKent Overstreet 		}
1019cafe5635SKent Overstreet 		BUG_ON(b->level != level);
1020cafe5635SKent Overstreet 	}
1021cafe5635SKent Overstreet 
1022cafe5635SKent Overstreet 	b->accessed = 1;
1023cafe5635SKent Overstreet 
1024cafe5635SKent Overstreet 	for (; i <= b->nsets && b->sets[i].size; i++) {
1025cafe5635SKent Overstreet 		prefetch(b->sets[i].tree);
1026cafe5635SKent Overstreet 		prefetch(b->sets[i].data);
1027cafe5635SKent Overstreet 	}
1028cafe5635SKent Overstreet 
1029cafe5635SKent Overstreet 	for (; i <= b->nsets; i++)
1030cafe5635SKent Overstreet 		prefetch(b->sets[i].data);
1031cafe5635SKent Overstreet 
103257943511SKent Overstreet 	if (btree_node_io_error(b)) {
1033cafe5635SKent Overstreet 		rw_unlock(write, b);
103457943511SKent Overstreet 		return ERR_PTR(-EIO);
103557943511SKent Overstreet 	}
103657943511SKent Overstreet 
1037cafe5635SKent Overstreet 	BUG_ON(!b->written);
1038cafe5635SKent Overstreet 
1039cafe5635SKent Overstreet 	return b;
1040cafe5635SKent Overstreet }
1041cafe5635SKent Overstreet 
1042cafe5635SKent Overstreet static void btree_node_prefetch(struct cache_set *c, struct bkey *k, int level)
1043cafe5635SKent Overstreet {
1044cafe5635SKent Overstreet 	struct btree *b;
1045cafe5635SKent Overstreet 
1046cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1047e8e1d468SKent Overstreet 	b = mca_alloc(c, k, level);
1048cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1049cafe5635SKent Overstreet 
1050cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(b)) {
105157943511SKent Overstreet 		bch_btree_node_read(b);
1052cafe5635SKent Overstreet 		rw_unlock(true, b);
1053cafe5635SKent Overstreet 	}
1054cafe5635SKent Overstreet }
1055cafe5635SKent Overstreet 
1056cafe5635SKent Overstreet /* Btree alloc */
1057cafe5635SKent Overstreet 
1058e8e1d468SKent Overstreet static void btree_node_free(struct btree *b)
1059cafe5635SKent Overstreet {
1060cafe5635SKent Overstreet 	unsigned i;
1061cafe5635SKent Overstreet 
1062c37511b8SKent Overstreet 	trace_bcache_btree_node_free(b);
1063c37511b8SKent Overstreet 
1064cafe5635SKent Overstreet 	BUG_ON(b == b->c->root);
1065cafe5635SKent Overstreet 
1066cafe5635SKent Overstreet 	if (btree_node_dirty(b))
1067cafe5635SKent Overstreet 		btree_complete_write(b, btree_current_write(b));
1068cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty, &b->flags);
1069cafe5635SKent Overstreet 
1070cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
1071cafe5635SKent Overstreet 
1072cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
1073cafe5635SKent Overstreet 
1074cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++) {
1075cafe5635SKent Overstreet 		BUG_ON(atomic_read(&PTR_BUCKET(b->c, &b->key, i)->pin));
1076cafe5635SKent Overstreet 
1077cafe5635SKent Overstreet 		bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
1078cafe5635SKent Overstreet 			    PTR_BUCKET(b->c, &b->key, i));
1079cafe5635SKent Overstreet 	}
1080cafe5635SKent Overstreet 
1081cafe5635SKent Overstreet 	bch_bucket_free(b->c, &b->key);
1082cafe5635SKent Overstreet 	mca_bucket_free(b);
1083cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
1084cafe5635SKent Overstreet }
1085cafe5635SKent Overstreet 
1086bc9389eeSKent Overstreet struct btree *bch_btree_node_alloc(struct cache_set *c, int level, bool wait)
1087cafe5635SKent Overstreet {
1088cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
1089cafe5635SKent Overstreet 	struct btree *b = ERR_PTR(-EAGAIN);
1090cafe5635SKent Overstreet 
1091cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1092cafe5635SKent Overstreet retry:
109378365411SKent Overstreet 	if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, wait))
1094cafe5635SKent Overstreet 		goto err;
1095cafe5635SKent Overstreet 
10963a3b6a4eSKent Overstreet 	bkey_put(c, &k.key);
1097cafe5635SKent Overstreet 	SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1098cafe5635SKent Overstreet 
1099e8e1d468SKent Overstreet 	b = mca_alloc(c, &k.key, level);
1100cafe5635SKent Overstreet 	if (IS_ERR(b))
1101cafe5635SKent Overstreet 		goto err_free;
1102cafe5635SKent Overstreet 
1103cafe5635SKent Overstreet 	if (!b) {
1104b1a67b0fSKent Overstreet 		cache_bug(c,
1105b1a67b0fSKent Overstreet 			"Tried to allocate bucket that was in btree cache");
1106cafe5635SKent Overstreet 		goto retry;
1107cafe5635SKent Overstreet 	}
1108cafe5635SKent Overstreet 
1109cafe5635SKent Overstreet 	b->accessed = 1;
1110cafe5635SKent Overstreet 	bch_bset_init_next(b);
1111cafe5635SKent Overstreet 
1112cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1113c37511b8SKent Overstreet 
1114c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc(b);
1115cafe5635SKent Overstreet 	return b;
1116cafe5635SKent Overstreet err_free:
1117cafe5635SKent Overstreet 	bch_bucket_free(c, &k.key);
1118cafe5635SKent Overstreet err:
1119cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1120c37511b8SKent Overstreet 
1121c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc_fail(b);
1122cafe5635SKent Overstreet 	return b;
1123cafe5635SKent Overstreet }
1124cafe5635SKent Overstreet 
1125bc9389eeSKent Overstreet static struct btree *btree_node_alloc_replacement(struct btree *b, bool wait)
1126cafe5635SKent Overstreet {
1127bc9389eeSKent Overstreet 	struct btree *n = bch_btree_node_alloc(b->c, b->level, wait);
1128cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(n))
1129cafe5635SKent Overstreet 		bch_btree_sort_into(b, n);
1130cafe5635SKent Overstreet 
1131cafe5635SKent Overstreet 	return n;
1132cafe5635SKent Overstreet }
1133cafe5635SKent Overstreet 
11348835c123SKent Overstreet static void make_btree_freeing_key(struct btree *b, struct bkey *k)
11358835c123SKent Overstreet {
11368835c123SKent Overstreet 	unsigned i;
11378835c123SKent Overstreet 
11388835c123SKent Overstreet 	bkey_copy(k, &b->key);
11398835c123SKent Overstreet 	bkey_copy_key(k, &ZERO_KEY);
11408835c123SKent Overstreet 
11418835c123SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
11428835c123SKent Overstreet 		uint8_t g = PTR_BUCKET(b->c, k, i)->gen + 1;
11438835c123SKent Overstreet 
11448835c123SKent Overstreet 		SET_PTR_GEN(k, i, g);
11458835c123SKent Overstreet 	}
11468835c123SKent Overstreet 
11478835c123SKent Overstreet 	atomic_inc(&b->c->prio_blocked);
11488835c123SKent Overstreet }
11498835c123SKent Overstreet 
115078365411SKent Overstreet static int btree_check_reserve(struct btree *b, struct btree_op *op)
115178365411SKent Overstreet {
115278365411SKent Overstreet 	struct cache_set *c = b->c;
115378365411SKent Overstreet 	struct cache *ca;
115478365411SKent Overstreet 	unsigned i, reserve = c->root->level * 2 + 1;
115578365411SKent Overstreet 	int ret = 0;
115678365411SKent Overstreet 
115778365411SKent Overstreet 	mutex_lock(&c->bucket_lock);
115878365411SKent Overstreet 
115978365411SKent Overstreet 	for_each_cache(ca, c, i)
116078365411SKent Overstreet 		if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
116178365411SKent Overstreet 			if (op)
116278365411SKent Overstreet 				prepare_to_wait(&c->bucket_wait, &op->wait,
116378365411SKent Overstreet 						TASK_UNINTERRUPTIBLE);
116478365411SKent Overstreet 			ret = -EINTR;
116578365411SKent Overstreet 			break;
116678365411SKent Overstreet 		}
116778365411SKent Overstreet 
116878365411SKent Overstreet 	mutex_unlock(&c->bucket_lock);
116978365411SKent Overstreet 	return ret;
117078365411SKent Overstreet }
117178365411SKent Overstreet 
1172cafe5635SKent Overstreet /* Garbage collection */
1173cafe5635SKent Overstreet 
1174cafe5635SKent Overstreet uint8_t __bch_btree_mark_key(struct cache_set *c, int level, struct bkey *k)
1175cafe5635SKent Overstreet {
1176cafe5635SKent Overstreet 	uint8_t stale = 0;
1177cafe5635SKent Overstreet 	unsigned i;
1178cafe5635SKent Overstreet 	struct bucket *g;
1179cafe5635SKent Overstreet 
1180cafe5635SKent Overstreet 	/*
1181cafe5635SKent Overstreet 	 * ptr_invalid() can't return true for the keys that mark btree nodes as
1182cafe5635SKent Overstreet 	 * freed, but since ptr_bad() returns true we'll never actually use them
1183cafe5635SKent Overstreet 	 * for anything and thus we don't want mark their pointers here
1184cafe5635SKent Overstreet 	 */
1185cafe5635SKent Overstreet 	if (!bkey_cmp(k, &ZERO_KEY))
1186cafe5635SKent Overstreet 		return stale;
1187cafe5635SKent Overstreet 
1188cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
1189cafe5635SKent Overstreet 		if (!ptr_available(c, k, i))
1190cafe5635SKent Overstreet 			continue;
1191cafe5635SKent Overstreet 
1192cafe5635SKent Overstreet 		g = PTR_BUCKET(c, k, i);
1193cafe5635SKent Overstreet 
1194cafe5635SKent Overstreet 		if (gen_after(g->gc_gen, PTR_GEN(k, i)))
1195cafe5635SKent Overstreet 			g->gc_gen = PTR_GEN(k, i);
1196cafe5635SKent Overstreet 
1197cafe5635SKent Overstreet 		if (ptr_stale(c, k, i)) {
1198cafe5635SKent Overstreet 			stale = max(stale, ptr_stale(c, k, i));
1199cafe5635SKent Overstreet 			continue;
1200cafe5635SKent Overstreet 		}
1201cafe5635SKent Overstreet 
1202cafe5635SKent Overstreet 		cache_bug_on(GC_MARK(g) &&
1203cafe5635SKent Overstreet 			     (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1204cafe5635SKent Overstreet 			     c, "inconsistent ptrs: mark = %llu, level = %i",
1205cafe5635SKent Overstreet 			     GC_MARK(g), level);
1206cafe5635SKent Overstreet 
1207cafe5635SKent Overstreet 		if (level)
1208cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_METADATA);
1209cafe5635SKent Overstreet 		else if (KEY_DIRTY(k))
1210cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_DIRTY);
1211cafe5635SKent Overstreet 
1212cafe5635SKent Overstreet 		/* guard against overflow */
1213cafe5635SKent Overstreet 		SET_GC_SECTORS_USED(g, min_t(unsigned,
1214cafe5635SKent Overstreet 					     GC_SECTORS_USED(g) + KEY_SIZE(k),
1215cafe5635SKent Overstreet 					     (1 << 14) - 1));
1216cafe5635SKent Overstreet 
1217cafe5635SKent Overstreet 		BUG_ON(!GC_SECTORS_USED(g));
1218cafe5635SKent Overstreet 	}
1219cafe5635SKent Overstreet 
1220cafe5635SKent Overstreet 	return stale;
1221cafe5635SKent Overstreet }
1222cafe5635SKent Overstreet 
1223cafe5635SKent Overstreet #define btree_mark_key(b, k)	__bch_btree_mark_key(b->c, b->level, k)
1224cafe5635SKent Overstreet 
1225a1f0358bSKent Overstreet static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1226cafe5635SKent Overstreet {
1227cafe5635SKent Overstreet 	uint8_t stale = 0;
1228a1f0358bSKent Overstreet 	unsigned keys = 0, good_keys = 0;
1229cafe5635SKent Overstreet 	struct bkey *k;
1230cafe5635SKent Overstreet 	struct btree_iter iter;
1231cafe5635SKent Overstreet 	struct bset_tree *t;
1232cafe5635SKent Overstreet 
1233cafe5635SKent Overstreet 	gc->nodes++;
1234cafe5635SKent Overstreet 
1235cafe5635SKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1236cafe5635SKent Overstreet 		stale = max(stale, btree_mark_key(b, k));
1237a1f0358bSKent Overstreet 		keys++;
1238cafe5635SKent Overstreet 
1239cafe5635SKent Overstreet 		if (bch_ptr_bad(b, k))
1240cafe5635SKent Overstreet 			continue;
1241cafe5635SKent Overstreet 
1242cafe5635SKent Overstreet 		gc->key_bytes += bkey_u64s(k);
1243cafe5635SKent Overstreet 		gc->nkeys++;
1244a1f0358bSKent Overstreet 		good_keys++;
1245cafe5635SKent Overstreet 
1246cafe5635SKent Overstreet 		gc->data += KEY_SIZE(k);
1247cafe5635SKent Overstreet 	}
1248cafe5635SKent Overstreet 
1249cafe5635SKent Overstreet 	for (t = b->sets; t <= &b->sets[b->nsets]; t++)
1250cafe5635SKent Overstreet 		btree_bug_on(t->size &&
1251cafe5635SKent Overstreet 			     bset_written(b, t) &&
1252cafe5635SKent Overstreet 			     bkey_cmp(&b->key, &t->end) < 0,
1253cafe5635SKent Overstreet 			     b, "found short btree key in gc");
1254cafe5635SKent Overstreet 
1255a1f0358bSKent Overstreet 	if (b->c->gc_always_rewrite)
1256a1f0358bSKent Overstreet 		return true;
1257a1f0358bSKent Overstreet 
1258a1f0358bSKent Overstreet 	if (stale > 10)
1259a1f0358bSKent Overstreet 		return true;
1260a1f0358bSKent Overstreet 
1261a1f0358bSKent Overstreet 	if ((keys - good_keys) * 2 > keys)
1262a1f0358bSKent Overstreet 		return true;
1263a1f0358bSKent Overstreet 
1264a1f0358bSKent Overstreet 	return false;
1265cafe5635SKent Overstreet }
1266cafe5635SKent Overstreet 
1267a1f0358bSKent Overstreet #define GC_MERGE_NODES	4U
1268cafe5635SKent Overstreet 
1269cafe5635SKent Overstreet struct gc_merge_info {
1270cafe5635SKent Overstreet 	struct btree	*b;
1271cafe5635SKent Overstreet 	unsigned	keys;
1272cafe5635SKent Overstreet };
1273cafe5635SKent Overstreet 
1274a1f0358bSKent Overstreet static int bch_btree_insert_node(struct btree *, struct btree_op *,
1275a1f0358bSKent Overstreet 				 struct keylist *, atomic_t *, struct bkey *);
1276a1f0358bSKent Overstreet 
1277a1f0358bSKent Overstreet static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
1278a1f0358bSKent Overstreet 			     struct keylist *keylist, struct gc_stat *gc,
1279e8e1d468SKent Overstreet 			     struct gc_merge_info *r)
1280cafe5635SKent Overstreet {
1281a1f0358bSKent Overstreet 	unsigned i, nodes = 0, keys = 0, blocks;
1282a1f0358bSKent Overstreet 	struct btree *new_nodes[GC_MERGE_NODES];
1283b54d6934SKent Overstreet 	struct closure cl;
1284a1f0358bSKent Overstreet 	struct bkey *k;
1285b54d6934SKent Overstreet 
1286a1f0358bSKent Overstreet 	memset(new_nodes, 0, sizeof(new_nodes));
1287b54d6934SKent Overstreet 	closure_init_stack(&cl);
1288cafe5635SKent Overstreet 
1289a1f0358bSKent Overstreet 	while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1290cafe5635SKent Overstreet 		keys += r[nodes++].keys;
1291cafe5635SKent Overstreet 
1292cafe5635SKent Overstreet 	blocks = btree_default_blocks(b->c) * 2 / 3;
1293cafe5635SKent Overstreet 
1294cafe5635SKent Overstreet 	if (nodes < 2 ||
1295cafe5635SKent Overstreet 	    __set_blocks(b->sets[0].data, keys, b->c) > blocks * (nodes - 1))
1296a1f0358bSKent Overstreet 		return 0;
1297cafe5635SKent Overstreet 
1298a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1299bc9389eeSKent Overstreet 		new_nodes[i] = btree_node_alloc_replacement(r[i].b, false);
1300a1f0358bSKent Overstreet 		if (IS_ERR_OR_NULL(new_nodes[i]))
1301a1f0358bSKent Overstreet 			goto out_nocoalesce;
1302cafe5635SKent Overstreet 	}
1303cafe5635SKent Overstreet 
1304cafe5635SKent Overstreet 	for (i = nodes - 1; i > 0; --i) {
1305a1f0358bSKent Overstreet 		struct bset *n1 = new_nodes[i]->sets->data;
1306a1f0358bSKent Overstreet 		struct bset *n2 = new_nodes[i - 1]->sets->data;
1307cafe5635SKent Overstreet 		struct bkey *k, *last = NULL;
1308cafe5635SKent Overstreet 
1309cafe5635SKent Overstreet 		keys = 0;
1310cafe5635SKent Overstreet 
1311a1f0358bSKent Overstreet 		if (i > 1) {
1312cafe5635SKent Overstreet 			for (k = n2->start;
1313cafe5635SKent Overstreet 			     k < end(n2);
1314cafe5635SKent Overstreet 			     k = bkey_next(k)) {
1315cafe5635SKent Overstreet 				if (__set_blocks(n1, n1->keys + keys +
1316cafe5635SKent Overstreet 						 bkey_u64s(k), b->c) > blocks)
1317cafe5635SKent Overstreet 					break;
1318cafe5635SKent Overstreet 
1319cafe5635SKent Overstreet 				last = k;
1320cafe5635SKent Overstreet 				keys += bkey_u64s(k);
1321cafe5635SKent Overstreet 			}
1322a1f0358bSKent Overstreet 		} else {
1323a1f0358bSKent Overstreet 			/*
1324a1f0358bSKent Overstreet 			 * Last node we're not getting rid of - we're getting
1325a1f0358bSKent Overstreet 			 * rid of the node at r[0]. Have to try and fit all of
1326a1f0358bSKent Overstreet 			 * the remaining keys into this node; we can't ensure
1327a1f0358bSKent Overstreet 			 * they will always fit due to rounding and variable
1328a1f0358bSKent Overstreet 			 * length keys (shouldn't be possible in practice,
1329a1f0358bSKent Overstreet 			 * though)
1330a1f0358bSKent Overstreet 			 */
1331a1f0358bSKent Overstreet 			if (__set_blocks(n1, n1->keys + n2->keys,
1332a1f0358bSKent Overstreet 					 b->c) > btree_blocks(new_nodes[i]))
1333a1f0358bSKent Overstreet 				goto out_nocoalesce;
1334a1f0358bSKent Overstreet 
1335a1f0358bSKent Overstreet 			keys = n2->keys;
1336a1f0358bSKent Overstreet 			/* Take the key of the node we're getting rid of */
1337a1f0358bSKent Overstreet 			last = &r->b->key;
1338a1f0358bSKent Overstreet 		}
1339cafe5635SKent Overstreet 
1340cafe5635SKent Overstreet 		BUG_ON(__set_blocks(n1, n1->keys + keys,
1341a1f0358bSKent Overstreet 				    b->c) > btree_blocks(new_nodes[i]));
1342cafe5635SKent Overstreet 
1343a1f0358bSKent Overstreet 		if (last)
1344a1f0358bSKent Overstreet 			bkey_copy_key(&new_nodes[i]->key, last);
1345cafe5635SKent Overstreet 
1346cafe5635SKent Overstreet 		memcpy(end(n1),
1347cafe5635SKent Overstreet 		       n2->start,
1348cafe5635SKent Overstreet 		       (void *) node(n2, keys) - (void *) n2->start);
1349cafe5635SKent Overstreet 
1350cafe5635SKent Overstreet 		n1->keys += keys;
1351a1f0358bSKent Overstreet 		r[i].keys = n1->keys;
1352cafe5635SKent Overstreet 
1353cafe5635SKent Overstreet 		memmove(n2->start,
1354cafe5635SKent Overstreet 			node(n2, keys),
1355cafe5635SKent Overstreet 			(void *) end(n2) - (void *) node(n2, keys));
1356cafe5635SKent Overstreet 
1357cafe5635SKent Overstreet 		n2->keys -= keys;
1358cafe5635SKent Overstreet 
1359*085d2a3dSKent Overstreet 		if (__bch_keylist_realloc(keylist,
1360*085d2a3dSKent Overstreet 					  bkey_u64s(&new_nodes[i]->key)))
1361a1f0358bSKent Overstreet 			goto out_nocoalesce;
1362a1f0358bSKent Overstreet 
1363a1f0358bSKent Overstreet 		bch_btree_node_write(new_nodes[i], &cl);
1364a1f0358bSKent Overstreet 		bch_keylist_add(keylist, &new_nodes[i]->key);
1365cafe5635SKent Overstreet 	}
1366cafe5635SKent Overstreet 
1367a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1368*085d2a3dSKent Overstreet 		if (__bch_keylist_realloc(keylist, bkey_u64s(&r[i].b->key)))
1369a1f0358bSKent Overstreet 			goto out_nocoalesce;
1370a1f0358bSKent Overstreet 
1371a1f0358bSKent Overstreet 		make_btree_freeing_key(r[i].b, keylist->top);
1372a1f0358bSKent Overstreet 		bch_keylist_push(keylist);
1373a1f0358bSKent Overstreet 	}
1374a1f0358bSKent Overstreet 
1375a1f0358bSKent Overstreet 	/* We emptied out this node */
1376a1f0358bSKent Overstreet 	BUG_ON(new_nodes[0]->sets->data->keys);
1377a1f0358bSKent Overstreet 	btree_node_free(new_nodes[0]);
1378a1f0358bSKent Overstreet 	rw_unlock(true, new_nodes[0]);
1379a1f0358bSKent Overstreet 
1380a1f0358bSKent Overstreet 	closure_sync(&cl);
1381a1f0358bSKent Overstreet 
1382a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1383a1f0358bSKent Overstreet 		btree_node_free(r[i].b);
1384a1f0358bSKent Overstreet 		rw_unlock(true, r[i].b);
1385a1f0358bSKent Overstreet 
1386a1f0358bSKent Overstreet 		r[i].b = new_nodes[i];
1387a1f0358bSKent Overstreet 	}
1388a1f0358bSKent Overstreet 
1389a1f0358bSKent Overstreet 	bch_btree_insert_node(b, op, keylist, NULL, NULL);
1390a1f0358bSKent Overstreet 	BUG_ON(!bch_keylist_empty(keylist));
1391a1f0358bSKent Overstreet 
1392a1f0358bSKent Overstreet 	memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1393a1f0358bSKent Overstreet 	r[nodes - 1].b = ERR_PTR(-EINTR);
1394cafe5635SKent Overstreet 
1395c37511b8SKent Overstreet 	trace_bcache_btree_gc_coalesce(nodes);
1396cafe5635SKent Overstreet 	gc->nodes--;
1397cafe5635SKent Overstreet 
1398a1f0358bSKent Overstreet 	/* Invalidated our iterator */
1399a1f0358bSKent Overstreet 	return -EINTR;
1400a1f0358bSKent Overstreet 
1401a1f0358bSKent Overstreet out_nocoalesce:
1402a1f0358bSKent Overstreet 	closure_sync(&cl);
1403a1f0358bSKent Overstreet 
1404a1f0358bSKent Overstreet 	while ((k = bch_keylist_pop(keylist)))
1405a1f0358bSKent Overstreet 		if (!bkey_cmp(k, &ZERO_KEY))
1406a1f0358bSKent Overstreet 			atomic_dec(&b->c->prio_blocked);
1407a1f0358bSKent Overstreet 
1408a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++)
1409a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(new_nodes[i])) {
1410a1f0358bSKent Overstreet 			btree_node_free(new_nodes[i]);
1411a1f0358bSKent Overstreet 			rw_unlock(true, new_nodes[i]);
1412a1f0358bSKent Overstreet 		}
1413a1f0358bSKent Overstreet 	return 0;
1414a1f0358bSKent Overstreet }
1415a1f0358bSKent Overstreet 
1416a1f0358bSKent Overstreet static unsigned btree_gc_count_keys(struct btree *b)
1417a1f0358bSKent Overstreet {
1418a1f0358bSKent Overstreet 	struct bkey *k;
1419a1f0358bSKent Overstreet 	struct btree_iter iter;
1420a1f0358bSKent Overstreet 	unsigned ret = 0;
1421a1f0358bSKent Overstreet 
1422a1f0358bSKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_bad)
1423a1f0358bSKent Overstreet 		ret += bkey_u64s(k);
1424a1f0358bSKent Overstreet 
1425a1f0358bSKent Overstreet 	return ret;
1426cafe5635SKent Overstreet }
1427cafe5635SKent Overstreet 
1428cafe5635SKent Overstreet static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1429cafe5635SKent Overstreet 			    struct closure *writes, struct gc_stat *gc)
1430cafe5635SKent Overstreet {
1431cafe5635SKent Overstreet 	unsigned i;
1432a1f0358bSKent Overstreet 	int ret = 0;
1433a1f0358bSKent Overstreet 	bool should_rewrite;
1434a1f0358bSKent Overstreet 	struct btree *n;
1435a1f0358bSKent Overstreet 	struct bkey *k;
1436a1f0358bSKent Overstreet 	struct keylist keys;
1437a1f0358bSKent Overstreet 	struct btree_iter iter;
1438cafe5635SKent Overstreet 	struct gc_merge_info r[GC_MERGE_NODES];
1439a1f0358bSKent Overstreet 	struct gc_merge_info *last = r + GC_MERGE_NODES - 1;
1440cafe5635SKent Overstreet 
1441a1f0358bSKent Overstreet 	bch_keylist_init(&keys);
1442a1f0358bSKent Overstreet 	bch_btree_iter_init(b, &iter, &b->c->gc_done);
1443cafe5635SKent Overstreet 
1444a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1445a1f0358bSKent Overstreet 		r[i].b = ERR_PTR(-EINTR);
1446cafe5635SKent Overstreet 
1447a1f0358bSKent Overstreet 	while (1) {
1448a1f0358bSKent Overstreet 		k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad);
1449a1f0358bSKent Overstreet 		if (k) {
1450a1f0358bSKent Overstreet 			r->b = bch_btree_node_get(b->c, k, b->level - 1, true);
1451cafe5635SKent Overstreet 			if (IS_ERR(r->b)) {
1452cafe5635SKent Overstreet 				ret = PTR_ERR(r->b);
1453cafe5635SKent Overstreet 				break;
1454cafe5635SKent Overstreet 			}
1455cafe5635SKent Overstreet 
1456a1f0358bSKent Overstreet 			r->keys = btree_gc_count_keys(r->b);
1457cafe5635SKent Overstreet 
1458a1f0358bSKent Overstreet 			ret = btree_gc_coalesce(b, op, &keys, gc, r);
1459a1f0358bSKent Overstreet 			if (ret)
1460cafe5635SKent Overstreet 				break;
1461cafe5635SKent Overstreet 		}
1462cafe5635SKent Overstreet 
1463a1f0358bSKent Overstreet 		if (!last->b)
1464a1f0358bSKent Overstreet 			break;
1465cafe5635SKent Overstreet 
1466a1f0358bSKent Overstreet 		if (!IS_ERR(last->b)) {
1467a1f0358bSKent Overstreet 			should_rewrite = btree_gc_mark_node(last->b, gc);
146878365411SKent Overstreet 			if (should_rewrite &&
146978365411SKent Overstreet 			    !btree_check_reserve(b, NULL)) {
1470bc9389eeSKent Overstreet 				n = btree_node_alloc_replacement(last->b,
1471bc9389eeSKent Overstreet 								 false);
1472cafe5635SKent Overstreet 
1473a1f0358bSKent Overstreet 				if (!IS_ERR_OR_NULL(n)) {
1474a1f0358bSKent Overstreet 					bch_btree_node_write_sync(n);
1475a1f0358bSKent Overstreet 					bch_keylist_add(&keys, &n->key);
1476cafe5635SKent Overstreet 
1477a1f0358bSKent Overstreet 					make_btree_freeing_key(last->b,
1478a1f0358bSKent Overstreet 							       keys.top);
1479a1f0358bSKent Overstreet 					bch_keylist_push(&keys);
1480cafe5635SKent Overstreet 
1481a1f0358bSKent Overstreet 					btree_node_free(last->b);
1482a1f0358bSKent Overstreet 
1483a1f0358bSKent Overstreet 					bch_btree_insert_node(b, op, &keys,
1484a1f0358bSKent Overstreet 							      NULL, NULL);
1485a1f0358bSKent Overstreet 					BUG_ON(!bch_keylist_empty(&keys));
1486a1f0358bSKent Overstreet 
1487a1f0358bSKent Overstreet 					rw_unlock(true, last->b);
1488a1f0358bSKent Overstreet 					last->b = n;
1489a1f0358bSKent Overstreet 
1490a1f0358bSKent Overstreet 					/* Invalidated our iterator */
1491a1f0358bSKent Overstreet 					ret = -EINTR;
1492a1f0358bSKent Overstreet 					break;
1493a1f0358bSKent Overstreet 				}
1494a1f0358bSKent Overstreet 			}
1495a1f0358bSKent Overstreet 
1496a1f0358bSKent Overstreet 			if (last->b->level) {
1497a1f0358bSKent Overstreet 				ret = btree_gc_recurse(last->b, op, writes, gc);
1498a1f0358bSKent Overstreet 				if (ret)
1499a1f0358bSKent Overstreet 					break;
1500a1f0358bSKent Overstreet 			}
1501a1f0358bSKent Overstreet 
1502a1f0358bSKent Overstreet 			bkey_copy_key(&b->c->gc_done, &last->b->key);
1503a1f0358bSKent Overstreet 
1504a1f0358bSKent Overstreet 			/*
1505a1f0358bSKent Overstreet 			 * Must flush leaf nodes before gc ends, since replace
1506a1f0358bSKent Overstreet 			 * operations aren't journalled
1507cafe5635SKent Overstreet 			 */
1508a1f0358bSKent Overstreet 			if (btree_node_dirty(last->b))
1509a1f0358bSKent Overstreet 				bch_btree_node_write(last->b, writes);
1510a1f0358bSKent Overstreet 			rw_unlock(true, last->b);
1511a1f0358bSKent Overstreet 		}
1512a1f0358bSKent Overstreet 
1513a1f0358bSKent Overstreet 		memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1514a1f0358bSKent Overstreet 		r->b = NULL;
1515a1f0358bSKent Overstreet 
1516cafe5635SKent Overstreet 		if (need_resched()) {
1517cafe5635SKent Overstreet 			ret = -EAGAIN;
1518cafe5635SKent Overstreet 			break;
1519cafe5635SKent Overstreet 		}
1520cafe5635SKent Overstreet 	}
1521cafe5635SKent Overstreet 
1522a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1523a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(r[i].b)) {
1524a1f0358bSKent Overstreet 			if (btree_node_dirty(r[i].b))
1525a1f0358bSKent Overstreet 				bch_btree_node_write(r[i].b, writes);
1526a1f0358bSKent Overstreet 			rw_unlock(true, r[i].b);
1527a1f0358bSKent Overstreet 		}
1528cafe5635SKent Overstreet 
1529a1f0358bSKent Overstreet 	bch_keylist_free(&keys);
1530cafe5635SKent Overstreet 
1531cafe5635SKent Overstreet 	return ret;
1532cafe5635SKent Overstreet }
1533cafe5635SKent Overstreet 
1534cafe5635SKent Overstreet static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1535cafe5635SKent Overstreet 			     struct closure *writes, struct gc_stat *gc)
1536cafe5635SKent Overstreet {
1537cafe5635SKent Overstreet 	struct btree *n = NULL;
1538a1f0358bSKent Overstreet 	int ret = 0;
1539a1f0358bSKent Overstreet 	bool should_rewrite;
1540cafe5635SKent Overstreet 
1541a1f0358bSKent Overstreet 	should_rewrite = btree_gc_mark_node(b, gc);
1542a1f0358bSKent Overstreet 	if (should_rewrite) {
1543bc9389eeSKent Overstreet 		n = btree_node_alloc_replacement(b, false);
1544cafe5635SKent Overstreet 
1545cafe5635SKent Overstreet 		if (!IS_ERR_OR_NULL(n)) {
1546a1f0358bSKent Overstreet 			bch_btree_node_write_sync(n);
1547a1f0358bSKent Overstreet 			bch_btree_set_root(n);
1548a1f0358bSKent Overstreet 			btree_node_free(b);
1549a1f0358bSKent Overstreet 			rw_unlock(true, n);
1550a1f0358bSKent Overstreet 
1551a1f0358bSKent Overstreet 			return -EINTR;
1552cafe5635SKent Overstreet 		}
1553a1f0358bSKent Overstreet 	}
1554a1f0358bSKent Overstreet 
1555a1f0358bSKent Overstreet 	if (b->level) {
1556a1f0358bSKent Overstreet 		ret = btree_gc_recurse(b, op, writes, gc);
1557a1f0358bSKent Overstreet 		if (ret)
1558a1f0358bSKent Overstreet 			return ret;
1559a1f0358bSKent Overstreet 	}
1560a1f0358bSKent Overstreet 
1561a1f0358bSKent Overstreet 	bkey_copy_key(&b->c->gc_done, &b->key);
1562cafe5635SKent Overstreet 
1563cafe5635SKent Overstreet 	return ret;
1564cafe5635SKent Overstreet }
1565cafe5635SKent Overstreet 
1566cafe5635SKent Overstreet static void btree_gc_start(struct cache_set *c)
1567cafe5635SKent Overstreet {
1568cafe5635SKent Overstreet 	struct cache *ca;
1569cafe5635SKent Overstreet 	struct bucket *b;
1570cafe5635SKent Overstreet 	unsigned i;
1571cafe5635SKent Overstreet 
1572cafe5635SKent Overstreet 	if (!c->gc_mark_valid)
1573cafe5635SKent Overstreet 		return;
1574cafe5635SKent Overstreet 
1575cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1576cafe5635SKent Overstreet 
1577cafe5635SKent Overstreet 	c->gc_mark_valid = 0;
1578cafe5635SKent Overstreet 	c->gc_done = ZERO_KEY;
1579cafe5635SKent Overstreet 
1580cafe5635SKent Overstreet 	for_each_cache(ca, c, i)
1581cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1582cafe5635SKent Overstreet 			b->gc_gen = b->gen;
158329ebf465SKent Overstreet 			if (!atomic_read(&b->pin)) {
1584cafe5635SKent Overstreet 				SET_GC_MARK(b, GC_MARK_RECLAIMABLE);
158529ebf465SKent Overstreet 				SET_GC_SECTORS_USED(b, 0);
158629ebf465SKent Overstreet 			}
1587cafe5635SKent Overstreet 		}
1588cafe5635SKent Overstreet 
1589cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1590cafe5635SKent Overstreet }
1591cafe5635SKent Overstreet 
1592cafe5635SKent Overstreet size_t bch_btree_gc_finish(struct cache_set *c)
1593cafe5635SKent Overstreet {
1594cafe5635SKent Overstreet 	size_t available = 0;
1595cafe5635SKent Overstreet 	struct bucket *b;
1596cafe5635SKent Overstreet 	struct cache *ca;
1597cafe5635SKent Overstreet 	unsigned i;
1598cafe5635SKent Overstreet 
1599cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1600cafe5635SKent Overstreet 
1601cafe5635SKent Overstreet 	set_gc_sectors(c);
1602cafe5635SKent Overstreet 	c->gc_mark_valid = 1;
1603cafe5635SKent Overstreet 	c->need_gc	= 0;
1604cafe5635SKent Overstreet 
1605cafe5635SKent Overstreet 	if (c->root)
1606cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(&c->root->key); i++)
1607cafe5635SKent Overstreet 			SET_GC_MARK(PTR_BUCKET(c, &c->root->key, i),
1608cafe5635SKent Overstreet 				    GC_MARK_METADATA);
1609cafe5635SKent Overstreet 
1610cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1611cafe5635SKent Overstreet 		SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1612cafe5635SKent Overstreet 			    GC_MARK_METADATA);
1613cafe5635SKent Overstreet 
1614bf0a628aSNicholas Swenson 	/* don't reclaim buckets to which writeback keys point */
1615bf0a628aSNicholas Swenson 	rcu_read_lock();
1616bf0a628aSNicholas Swenson 	for (i = 0; i < c->nr_uuids; i++) {
1617bf0a628aSNicholas Swenson 		struct bcache_device *d = c->devices[i];
1618bf0a628aSNicholas Swenson 		struct cached_dev *dc;
1619bf0a628aSNicholas Swenson 		struct keybuf_key *w, *n;
1620bf0a628aSNicholas Swenson 		unsigned j;
1621bf0a628aSNicholas Swenson 
1622bf0a628aSNicholas Swenson 		if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
1623bf0a628aSNicholas Swenson 			continue;
1624bf0a628aSNicholas Swenson 		dc = container_of(d, struct cached_dev, disk);
1625bf0a628aSNicholas Swenson 
1626bf0a628aSNicholas Swenson 		spin_lock(&dc->writeback_keys.lock);
1627bf0a628aSNicholas Swenson 		rbtree_postorder_for_each_entry_safe(w, n,
1628bf0a628aSNicholas Swenson 					&dc->writeback_keys.keys, node)
1629bf0a628aSNicholas Swenson 			for (j = 0; j < KEY_PTRS(&w->key); j++)
1630bf0a628aSNicholas Swenson 				SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
1631bf0a628aSNicholas Swenson 					    GC_MARK_DIRTY);
1632bf0a628aSNicholas Swenson 		spin_unlock(&dc->writeback_keys.lock);
1633bf0a628aSNicholas Swenson 	}
1634bf0a628aSNicholas Swenson 	rcu_read_unlock();
1635bf0a628aSNicholas Swenson 
1636cafe5635SKent Overstreet 	for_each_cache(ca, c, i) {
1637cafe5635SKent Overstreet 		uint64_t *i;
1638cafe5635SKent Overstreet 
1639cafe5635SKent Overstreet 		ca->invalidate_needs_gc = 0;
1640cafe5635SKent Overstreet 
1641cafe5635SKent Overstreet 		for (i = ca->sb.d; i < ca->sb.d + ca->sb.keys; i++)
1642cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1643cafe5635SKent Overstreet 
1644cafe5635SKent Overstreet 		for (i = ca->prio_buckets;
1645cafe5635SKent Overstreet 		     i < ca->prio_buckets + prio_buckets(ca) * 2; i++)
1646cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1647cafe5635SKent Overstreet 
1648cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1649cafe5635SKent Overstreet 			b->last_gc	= b->gc_gen;
1650cafe5635SKent Overstreet 			c->need_gc	= max(c->need_gc, bucket_gc_gen(b));
1651cafe5635SKent Overstreet 
1652cafe5635SKent Overstreet 			if (!atomic_read(&b->pin) &&
1653cafe5635SKent Overstreet 			    GC_MARK(b) == GC_MARK_RECLAIMABLE) {
1654cafe5635SKent Overstreet 				available++;
1655cafe5635SKent Overstreet 				if (!GC_SECTORS_USED(b))
1656cafe5635SKent Overstreet 					bch_bucket_add_unused(ca, b);
1657cafe5635SKent Overstreet 			}
1658cafe5635SKent Overstreet 		}
1659cafe5635SKent Overstreet 	}
1660cafe5635SKent Overstreet 
1661cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1662cafe5635SKent Overstreet 	return available;
1663cafe5635SKent Overstreet }
1664cafe5635SKent Overstreet 
166572a44517SKent Overstreet static void bch_btree_gc(struct cache_set *c)
1666cafe5635SKent Overstreet {
1667cafe5635SKent Overstreet 	int ret;
1668cafe5635SKent Overstreet 	unsigned long available;
1669cafe5635SKent Overstreet 	struct gc_stat stats;
1670cafe5635SKent Overstreet 	struct closure writes;
1671cafe5635SKent Overstreet 	struct btree_op op;
1672cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
167357943511SKent Overstreet 
1674c37511b8SKent Overstreet 	trace_bcache_gc_start(c);
1675cafe5635SKent Overstreet 
1676cafe5635SKent Overstreet 	memset(&stats, 0, sizeof(struct gc_stat));
1677cafe5635SKent Overstreet 	closure_init_stack(&writes);
1678b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1679cafe5635SKent Overstreet 
1680cafe5635SKent Overstreet 	btree_gc_start(c);
1681cafe5635SKent Overstreet 
1682a1f0358bSKent Overstreet 	do {
1683cafe5635SKent Overstreet 		ret = btree_root(gc_root, c, &op, &writes, &stats);
1684cafe5635SKent Overstreet 		closure_sync(&writes);
1685cafe5635SKent Overstreet 
1686a1f0358bSKent Overstreet 		if (ret && ret != -EAGAIN)
1687cafe5635SKent Overstreet 			pr_warn("gc failed!");
1688a1f0358bSKent Overstreet 	} while (ret);
1689cafe5635SKent Overstreet 
1690cafe5635SKent Overstreet 	available = bch_btree_gc_finish(c);
169157943511SKent Overstreet 	wake_up_allocators(c);
169257943511SKent Overstreet 
1693169ef1cfSKent Overstreet 	bch_time_stats_update(&c->btree_gc_time, start_time);
1694cafe5635SKent Overstreet 
1695cafe5635SKent Overstreet 	stats.key_bytes *= sizeof(uint64_t);
1696cafe5635SKent Overstreet 	stats.data	<<= 9;
1697cafe5635SKent Overstreet 	stats.in_use	= (c->nbuckets - available) * 100 / c->nbuckets;
1698cafe5635SKent Overstreet 	memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1699cafe5635SKent Overstreet 
1700c37511b8SKent Overstreet 	trace_bcache_gc_end(c);
1701cafe5635SKent Overstreet 
170272a44517SKent Overstreet 	bch_moving_gc(c);
1703cafe5635SKent Overstreet }
1704cafe5635SKent Overstreet 
170572a44517SKent Overstreet static int bch_gc_thread(void *arg)
1706cafe5635SKent Overstreet {
170772a44517SKent Overstreet 	struct cache_set *c = arg;
1708a1f0358bSKent Overstreet 	struct cache *ca;
1709a1f0358bSKent Overstreet 	unsigned i;
171072a44517SKent Overstreet 
171172a44517SKent Overstreet 	while (1) {
1712a1f0358bSKent Overstreet again:
171372a44517SKent Overstreet 		bch_btree_gc(c);
171472a44517SKent Overstreet 
171572a44517SKent Overstreet 		set_current_state(TASK_INTERRUPTIBLE);
171672a44517SKent Overstreet 		if (kthread_should_stop())
171772a44517SKent Overstreet 			break;
171872a44517SKent Overstreet 
1719a1f0358bSKent Overstreet 		mutex_lock(&c->bucket_lock);
1720a1f0358bSKent Overstreet 
1721a1f0358bSKent Overstreet 		for_each_cache(ca, c, i)
1722a1f0358bSKent Overstreet 			if (ca->invalidate_needs_gc) {
1723a1f0358bSKent Overstreet 				mutex_unlock(&c->bucket_lock);
1724a1f0358bSKent Overstreet 				set_current_state(TASK_RUNNING);
1725a1f0358bSKent Overstreet 				goto again;
1726a1f0358bSKent Overstreet 			}
1727a1f0358bSKent Overstreet 
1728a1f0358bSKent Overstreet 		mutex_unlock(&c->bucket_lock);
1729a1f0358bSKent Overstreet 
173072a44517SKent Overstreet 		try_to_freeze();
173172a44517SKent Overstreet 		schedule();
173272a44517SKent Overstreet 	}
173372a44517SKent Overstreet 
173472a44517SKent Overstreet 	return 0;
173572a44517SKent Overstreet }
173672a44517SKent Overstreet 
173772a44517SKent Overstreet int bch_gc_thread_start(struct cache_set *c)
173872a44517SKent Overstreet {
173972a44517SKent Overstreet 	c->gc_thread = kthread_create(bch_gc_thread, c, "bcache_gc");
174072a44517SKent Overstreet 	if (IS_ERR(c->gc_thread))
174172a44517SKent Overstreet 		return PTR_ERR(c->gc_thread);
174272a44517SKent Overstreet 
174372a44517SKent Overstreet 	set_task_state(c->gc_thread, TASK_INTERRUPTIBLE);
174472a44517SKent Overstreet 	return 0;
1745cafe5635SKent Overstreet }
1746cafe5635SKent Overstreet 
1747cafe5635SKent Overstreet /* Initial partial gc */
1748cafe5635SKent Overstreet 
1749cafe5635SKent Overstreet static int bch_btree_check_recurse(struct btree *b, struct btree_op *op,
1750cafe5635SKent Overstreet 				   unsigned long **seen)
1751cafe5635SKent Overstreet {
175250310164SKent Overstreet 	int ret = 0;
1753cafe5635SKent Overstreet 	unsigned i;
175450310164SKent Overstreet 	struct bkey *k, *p = NULL;
1755cafe5635SKent Overstreet 	struct bucket *g;
1756cafe5635SKent Overstreet 	struct btree_iter iter;
1757cafe5635SKent Overstreet 
1758cafe5635SKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1759cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(k); i++) {
1760cafe5635SKent Overstreet 			if (!ptr_available(b->c, k, i))
1761cafe5635SKent Overstreet 				continue;
1762cafe5635SKent Overstreet 
1763cafe5635SKent Overstreet 			g = PTR_BUCKET(b->c, k, i);
1764cafe5635SKent Overstreet 
1765cafe5635SKent Overstreet 			if (!__test_and_set_bit(PTR_BUCKET_NR(b->c, k, i),
1766cafe5635SKent Overstreet 						seen[PTR_DEV(k, i)]) ||
1767cafe5635SKent Overstreet 			    !ptr_stale(b->c, k, i)) {
1768cafe5635SKent Overstreet 				g->gen = PTR_GEN(k, i);
1769cafe5635SKent Overstreet 
1770cafe5635SKent Overstreet 				if (b->level)
1771cafe5635SKent Overstreet 					g->prio = BTREE_PRIO;
1772cafe5635SKent Overstreet 				else if (g->prio == BTREE_PRIO)
1773cafe5635SKent Overstreet 					g->prio = INITIAL_PRIO;
1774cafe5635SKent Overstreet 			}
1775cafe5635SKent Overstreet 		}
1776cafe5635SKent Overstreet 
1777cafe5635SKent Overstreet 		btree_mark_key(b, k);
1778cafe5635SKent Overstreet 	}
1779cafe5635SKent Overstreet 
1780cafe5635SKent Overstreet 	if (b->level) {
178150310164SKent Overstreet 		bch_btree_iter_init(b, &iter, NULL);
1782cafe5635SKent Overstreet 
178350310164SKent Overstreet 		do {
178450310164SKent Overstreet 			k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad);
178550310164SKent Overstreet 			if (k)
178650310164SKent Overstreet 				btree_node_prefetch(b->c, k, b->level - 1);
178750310164SKent Overstreet 
1788cafe5635SKent Overstreet 			if (p)
178950310164SKent Overstreet 				ret = btree(check_recurse, p, b, op, seen);
1790cafe5635SKent Overstreet 
179150310164SKent Overstreet 			p = k;
179250310164SKent Overstreet 		} while (p && !ret);
1793cafe5635SKent Overstreet 	}
1794cafe5635SKent Overstreet 
1795cafe5635SKent Overstreet 	return 0;
1796cafe5635SKent Overstreet }
1797cafe5635SKent Overstreet 
1798c18536a7SKent Overstreet int bch_btree_check(struct cache_set *c)
1799cafe5635SKent Overstreet {
1800cafe5635SKent Overstreet 	int ret = -ENOMEM;
1801cafe5635SKent Overstreet 	unsigned i;
1802cafe5635SKent Overstreet 	unsigned long *seen[MAX_CACHES_PER_SET];
1803c18536a7SKent Overstreet 	struct btree_op op;
1804cafe5635SKent Overstreet 
1805cafe5635SKent Overstreet 	memset(seen, 0, sizeof(seen));
1806b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1807cafe5635SKent Overstreet 
1808cafe5635SKent Overstreet 	for (i = 0; c->cache[i]; i++) {
1809cafe5635SKent Overstreet 		size_t n = DIV_ROUND_UP(c->cache[i]->sb.nbuckets, 8);
1810cafe5635SKent Overstreet 		seen[i] = kmalloc(n, GFP_KERNEL);
1811cafe5635SKent Overstreet 		if (!seen[i])
1812cafe5635SKent Overstreet 			goto err;
1813cafe5635SKent Overstreet 
1814cafe5635SKent Overstreet 		/* Disables the seen array until prio_read() uses it too */
1815cafe5635SKent Overstreet 		memset(seen[i], 0xFF, n);
1816cafe5635SKent Overstreet 	}
1817cafe5635SKent Overstreet 
1818c18536a7SKent Overstreet 	ret = btree_root(check_recurse, c, &op, seen);
1819cafe5635SKent Overstreet err:
1820cafe5635SKent Overstreet 	for (i = 0; i < MAX_CACHES_PER_SET; i++)
1821cafe5635SKent Overstreet 		kfree(seen[i]);
1822cafe5635SKent Overstreet 	return ret;
1823cafe5635SKent Overstreet }
1824cafe5635SKent Overstreet 
1825cafe5635SKent Overstreet /* Btree insertion */
1826cafe5635SKent Overstreet 
1827cafe5635SKent Overstreet static void shift_keys(struct btree *b, struct bkey *where, struct bkey *insert)
1828cafe5635SKent Overstreet {
1829cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
1830cafe5635SKent Overstreet 
1831cafe5635SKent Overstreet 	memmove((uint64_t *) where + bkey_u64s(insert),
1832cafe5635SKent Overstreet 		where,
1833cafe5635SKent Overstreet 		(void *) end(i) - (void *) where);
1834cafe5635SKent Overstreet 
1835cafe5635SKent Overstreet 	i->keys += bkey_u64s(insert);
1836cafe5635SKent Overstreet 	bkey_copy(where, insert);
1837cafe5635SKent Overstreet 	bch_bset_fix_lookup_table(b, where);
1838cafe5635SKent Overstreet }
1839cafe5635SKent Overstreet 
18401b207d80SKent Overstreet static bool fix_overlapping_extents(struct btree *b, struct bkey *insert,
1841cafe5635SKent Overstreet 				    struct btree_iter *iter,
18421b207d80SKent Overstreet 				    struct bkey *replace_key)
1843cafe5635SKent Overstreet {
1844279afbadSKent Overstreet 	void subtract_dirty(struct bkey *k, uint64_t offset, int sectors)
1845cafe5635SKent Overstreet 	{
1846279afbadSKent Overstreet 		if (KEY_DIRTY(k))
1847279afbadSKent Overstreet 			bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
1848279afbadSKent Overstreet 						     offset, -sectors);
1849cafe5635SKent Overstreet 	}
1850cafe5635SKent Overstreet 
1851279afbadSKent Overstreet 	uint64_t old_offset;
1852cafe5635SKent Overstreet 	unsigned old_size, sectors_found = 0;
1853cafe5635SKent Overstreet 
1854cafe5635SKent Overstreet 	while (1) {
1855cafe5635SKent Overstreet 		struct bkey *k = bch_btree_iter_next(iter);
1856cafe5635SKent Overstreet 		if (!k ||
1857cafe5635SKent Overstreet 		    bkey_cmp(&START_KEY(k), insert) >= 0)
1858cafe5635SKent Overstreet 			break;
1859cafe5635SKent Overstreet 
1860cafe5635SKent Overstreet 		if (bkey_cmp(k, &START_KEY(insert)) <= 0)
1861cafe5635SKent Overstreet 			continue;
1862cafe5635SKent Overstreet 
1863279afbadSKent Overstreet 		old_offset = KEY_START(k);
1864cafe5635SKent Overstreet 		old_size = KEY_SIZE(k);
1865cafe5635SKent Overstreet 
1866cafe5635SKent Overstreet 		/*
1867cafe5635SKent Overstreet 		 * We might overlap with 0 size extents; we can't skip these
1868cafe5635SKent Overstreet 		 * because if they're in the set we're inserting to we have to
1869cafe5635SKent Overstreet 		 * adjust them so they don't overlap with the key we're
18701b207d80SKent Overstreet 		 * inserting. But we don't want to check them for replace
1871cafe5635SKent Overstreet 		 * operations.
1872cafe5635SKent Overstreet 		 */
1873cafe5635SKent Overstreet 
18741b207d80SKent Overstreet 		if (replace_key && KEY_SIZE(k)) {
1875cafe5635SKent Overstreet 			/*
1876cafe5635SKent Overstreet 			 * k might have been split since we inserted/found the
1877cafe5635SKent Overstreet 			 * key we're replacing
1878cafe5635SKent Overstreet 			 */
1879cafe5635SKent Overstreet 			unsigned i;
1880cafe5635SKent Overstreet 			uint64_t offset = KEY_START(k) -
18811b207d80SKent Overstreet 				KEY_START(replace_key);
1882cafe5635SKent Overstreet 
1883cafe5635SKent Overstreet 			/* But it must be a subset of the replace key */
18841b207d80SKent Overstreet 			if (KEY_START(k) < KEY_START(replace_key) ||
18851b207d80SKent Overstreet 			    KEY_OFFSET(k) > KEY_OFFSET(replace_key))
1886cafe5635SKent Overstreet 				goto check_failed;
1887cafe5635SKent Overstreet 
1888cafe5635SKent Overstreet 			/* We didn't find a key that we were supposed to */
1889cafe5635SKent Overstreet 			if (KEY_START(k) > KEY_START(insert) + sectors_found)
1890cafe5635SKent Overstreet 				goto check_failed;
1891cafe5635SKent Overstreet 
1892d24a6e10SKent Overstreet 			if (KEY_PTRS(k) != KEY_PTRS(replace_key) ||
1893d24a6e10SKent Overstreet 			    KEY_DIRTY(k) != KEY_DIRTY(replace_key))
1894cafe5635SKent Overstreet 				goto check_failed;
1895cafe5635SKent Overstreet 
1896cafe5635SKent Overstreet 			/* skip past gen */
1897cafe5635SKent Overstreet 			offset <<= 8;
1898cafe5635SKent Overstreet 
18991b207d80SKent Overstreet 			BUG_ON(!KEY_PTRS(replace_key));
1900cafe5635SKent Overstreet 
19011b207d80SKent Overstreet 			for (i = 0; i < KEY_PTRS(replace_key); i++)
19021b207d80SKent Overstreet 				if (k->ptr[i] != replace_key->ptr[i] + offset)
1903cafe5635SKent Overstreet 					goto check_failed;
1904cafe5635SKent Overstreet 
1905cafe5635SKent Overstreet 			sectors_found = KEY_OFFSET(k) - KEY_START(insert);
1906cafe5635SKent Overstreet 		}
1907cafe5635SKent Overstreet 
1908cafe5635SKent Overstreet 		if (bkey_cmp(insert, k) < 0 &&
1909cafe5635SKent Overstreet 		    bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0) {
1910cafe5635SKent Overstreet 			/*
1911cafe5635SKent Overstreet 			 * We overlapped in the middle of an existing key: that
1912cafe5635SKent Overstreet 			 * means we have to split the old key. But we have to do
1913cafe5635SKent Overstreet 			 * slightly different things depending on whether the
1914cafe5635SKent Overstreet 			 * old key has been written out yet.
1915cafe5635SKent Overstreet 			 */
1916cafe5635SKent Overstreet 
1917cafe5635SKent Overstreet 			struct bkey *top;
1918cafe5635SKent Overstreet 
1919279afbadSKent Overstreet 			subtract_dirty(k, KEY_START(insert), KEY_SIZE(insert));
1920cafe5635SKent Overstreet 
1921cafe5635SKent Overstreet 			if (bkey_written(b, k)) {
1922cafe5635SKent Overstreet 				/*
1923cafe5635SKent Overstreet 				 * We insert a new key to cover the top of the
1924cafe5635SKent Overstreet 				 * old key, and the old key is modified in place
1925cafe5635SKent Overstreet 				 * to represent the bottom split.
1926cafe5635SKent Overstreet 				 *
1927cafe5635SKent Overstreet 				 * It's completely arbitrary whether the new key
1928cafe5635SKent Overstreet 				 * is the top or the bottom, but it has to match
1929cafe5635SKent Overstreet 				 * up with what btree_sort_fixup() does - it
1930cafe5635SKent Overstreet 				 * doesn't check for this kind of overlap, it
1931cafe5635SKent Overstreet 				 * depends on us inserting a new key for the top
1932cafe5635SKent Overstreet 				 * here.
1933cafe5635SKent Overstreet 				 */
1934cafe5635SKent Overstreet 				top = bch_bset_search(b, &b->sets[b->nsets],
1935cafe5635SKent Overstreet 						      insert);
1936cafe5635SKent Overstreet 				shift_keys(b, top, k);
1937cafe5635SKent Overstreet 			} else {
1938cafe5635SKent Overstreet 				BKEY_PADDED(key) temp;
1939cafe5635SKent Overstreet 				bkey_copy(&temp.key, k);
1940cafe5635SKent Overstreet 				shift_keys(b, k, &temp.key);
1941cafe5635SKent Overstreet 				top = bkey_next(k);
1942cafe5635SKent Overstreet 			}
1943cafe5635SKent Overstreet 
1944cafe5635SKent Overstreet 			bch_cut_front(insert, top);
1945cafe5635SKent Overstreet 			bch_cut_back(&START_KEY(insert), k);
1946cafe5635SKent Overstreet 			bch_bset_fix_invalidated_key(b, k);
1947cafe5635SKent Overstreet 			return false;
1948cafe5635SKent Overstreet 		}
1949cafe5635SKent Overstreet 
1950cafe5635SKent Overstreet 		if (bkey_cmp(insert, k) < 0) {
1951cafe5635SKent Overstreet 			bch_cut_front(insert, k);
1952cafe5635SKent Overstreet 		} else {
19531fa8455dSKent Overstreet 			if (bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0)
19541fa8455dSKent Overstreet 				old_offset = KEY_START(insert);
19551fa8455dSKent Overstreet 
1956cafe5635SKent Overstreet 			if (bkey_written(b, k) &&
1957cafe5635SKent Overstreet 			    bkey_cmp(&START_KEY(insert), &START_KEY(k)) <= 0) {
1958cafe5635SKent Overstreet 				/*
1959cafe5635SKent Overstreet 				 * Completely overwrote, so we don't have to
1960cafe5635SKent Overstreet 				 * invalidate the binary search tree
1961cafe5635SKent Overstreet 				 */
1962cafe5635SKent Overstreet 				bch_cut_front(k, k);
1963cafe5635SKent Overstreet 			} else {
1964cafe5635SKent Overstreet 				__bch_cut_back(&START_KEY(insert), k);
1965cafe5635SKent Overstreet 				bch_bset_fix_invalidated_key(b, k);
1966cafe5635SKent Overstreet 			}
1967cafe5635SKent Overstreet 		}
1968cafe5635SKent Overstreet 
1969279afbadSKent Overstreet 		subtract_dirty(k, old_offset, old_size - KEY_SIZE(k));
1970cafe5635SKent Overstreet 	}
1971cafe5635SKent Overstreet 
1972cafe5635SKent Overstreet check_failed:
19731b207d80SKent Overstreet 	if (replace_key) {
1974cafe5635SKent Overstreet 		if (!sectors_found) {
1975cafe5635SKent Overstreet 			return true;
1976cafe5635SKent Overstreet 		} else if (sectors_found < KEY_SIZE(insert)) {
1977cafe5635SKent Overstreet 			SET_KEY_OFFSET(insert, KEY_OFFSET(insert) -
1978cafe5635SKent Overstreet 				       (KEY_SIZE(insert) - sectors_found));
1979cafe5635SKent Overstreet 			SET_KEY_SIZE(insert, sectors_found);
1980cafe5635SKent Overstreet 		}
1981cafe5635SKent Overstreet 	}
1982cafe5635SKent Overstreet 
1983cafe5635SKent Overstreet 	return false;
1984cafe5635SKent Overstreet }
1985cafe5635SKent Overstreet 
1986cafe5635SKent Overstreet static bool btree_insert_key(struct btree *b, struct btree_op *op,
19871b207d80SKent Overstreet 			     struct bkey *k, struct bkey *replace_key)
1988cafe5635SKent Overstreet {
1989cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
1990cafe5635SKent Overstreet 	struct bkey *m, *prev;
199185b1492eSKent Overstreet 	unsigned status = BTREE_INSERT_STATUS_INSERT;
1992cafe5635SKent Overstreet 
1993cafe5635SKent Overstreet 	BUG_ON(bkey_cmp(k, &b->key) > 0);
1994cafe5635SKent Overstreet 	BUG_ON(b->level && !KEY_PTRS(k));
1995cafe5635SKent Overstreet 	BUG_ON(!b->level && !KEY_OFFSET(k));
1996cafe5635SKent Overstreet 
1997cafe5635SKent Overstreet 	if (!b->level) {
1998cafe5635SKent Overstreet 		struct btree_iter iter;
1999cafe5635SKent Overstreet 
2000cafe5635SKent Overstreet 		/*
2001cafe5635SKent Overstreet 		 * bset_search() returns the first key that is strictly greater
2002cafe5635SKent Overstreet 		 * than the search key - but for back merging, we want to find
20030eacac22SKent Overstreet 		 * the previous key.
2004cafe5635SKent Overstreet 		 */
2005cafe5635SKent Overstreet 		prev = NULL;
20060eacac22SKent Overstreet 		m = bch_btree_iter_init(b, &iter, PRECEDING_KEY(&START_KEY(k)));
2007cafe5635SKent Overstreet 
20081b207d80SKent Overstreet 		if (fix_overlapping_extents(b, k, &iter, replace_key)) {
20091b207d80SKent Overstreet 			op->insert_collision = true;
2010cafe5635SKent Overstreet 			return false;
20111b207d80SKent Overstreet 		}
2012cafe5635SKent Overstreet 
20131fa8455dSKent Overstreet 		if (KEY_DIRTY(k))
20141fa8455dSKent Overstreet 			bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
20151fa8455dSKent Overstreet 						     KEY_START(k), KEY_SIZE(k));
20161fa8455dSKent Overstreet 
2017cafe5635SKent Overstreet 		while (m != end(i) &&
2018cafe5635SKent Overstreet 		       bkey_cmp(k, &START_KEY(m)) > 0)
2019cafe5635SKent Overstreet 			prev = m, m = bkey_next(m);
2020cafe5635SKent Overstreet 
2021cafe5635SKent Overstreet 		if (key_merging_disabled(b->c))
2022cafe5635SKent Overstreet 			goto insert;
2023cafe5635SKent Overstreet 
2024cafe5635SKent Overstreet 		/* prev is in the tree, if we merge we're done */
202585b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_BACK_MERGE;
2026cafe5635SKent Overstreet 		if (prev &&
2027cafe5635SKent Overstreet 		    bch_bkey_try_merge(b, prev, k))
2028cafe5635SKent Overstreet 			goto merged;
2029cafe5635SKent Overstreet 
203085b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_OVERWROTE;
2031cafe5635SKent Overstreet 		if (m != end(i) &&
2032cafe5635SKent Overstreet 		    KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
2033cafe5635SKent Overstreet 			goto copy;
2034cafe5635SKent Overstreet 
203585b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_FRONT_MERGE;
2036cafe5635SKent Overstreet 		if (m != end(i) &&
2037cafe5635SKent Overstreet 		    bch_bkey_try_merge(b, k, m))
2038cafe5635SKent Overstreet 			goto copy;
20391b207d80SKent Overstreet 	} else {
20401b207d80SKent Overstreet 		BUG_ON(replace_key);
2041cafe5635SKent Overstreet 		m = bch_bset_search(b, &b->sets[b->nsets], k);
20421b207d80SKent Overstreet 	}
2043cafe5635SKent Overstreet 
2044cafe5635SKent Overstreet insert:	shift_keys(b, m, k);
2045cafe5635SKent Overstreet copy:	bkey_copy(m, k);
2046cafe5635SKent Overstreet merged:
20471b207d80SKent Overstreet 	bch_check_keys(b, "%u for %s", status,
20481b207d80SKent Overstreet 		       replace_key ? "replace" : "insert");
2049cafe5635SKent Overstreet 
2050cafe5635SKent Overstreet 	if (b->level && !KEY_OFFSET(k))
205157943511SKent Overstreet 		btree_current_write(b)->prio_blocked++;
2052cafe5635SKent Overstreet 
20531b207d80SKent Overstreet 	trace_bcache_btree_insert_key(b, k, replace_key != NULL, status);
2054cafe5635SKent Overstreet 
2055cafe5635SKent Overstreet 	return true;
2056cafe5635SKent Overstreet }
2057cafe5635SKent Overstreet 
205826c949f8SKent Overstreet static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
20591b207d80SKent Overstreet 				  struct keylist *insert_keys,
20601b207d80SKent Overstreet 				  struct bkey *replace_key)
2061cafe5635SKent Overstreet {
2062cafe5635SKent Overstreet 	bool ret = false;
2063280481d0SKent Overstreet 	int oldsize = bch_count_data(b);
2064cafe5635SKent Overstreet 
206526c949f8SKent Overstreet 	while (!bch_keylist_empty(insert_keys)) {
2066403b6cdeSKent Overstreet 		struct bset *i = write_block(b);
2067c2f95ae2SKent Overstreet 		struct bkey *k = insert_keys->keys;
206826c949f8SKent Overstreet 
2069403b6cdeSKent Overstreet 		if (b->written + __set_blocks(i, i->keys + bkey_u64s(k), b->c)
2070403b6cdeSKent Overstreet 		    > btree_blocks(b))
2071403b6cdeSKent Overstreet 			break;
2072403b6cdeSKent Overstreet 
2073403b6cdeSKent Overstreet 		if (bkey_cmp(k, &b->key) <= 0) {
20743a3b6a4eSKent Overstreet 			if (!b->level)
20753a3b6a4eSKent Overstreet 				bkey_put(b->c, k);
207626c949f8SKent Overstreet 
20771b207d80SKent Overstreet 			ret |= btree_insert_key(b, op, k, replace_key);
207826c949f8SKent Overstreet 			bch_keylist_pop_front(insert_keys);
207926c949f8SKent Overstreet 		} else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
208026c949f8SKent Overstreet 			BKEY_PADDED(key) temp;
2081c2f95ae2SKent Overstreet 			bkey_copy(&temp.key, insert_keys->keys);
208226c949f8SKent Overstreet 
208326c949f8SKent Overstreet 			bch_cut_back(&b->key, &temp.key);
2084c2f95ae2SKent Overstreet 			bch_cut_front(&b->key, insert_keys->keys);
208526c949f8SKent Overstreet 
20861b207d80SKent Overstreet 			ret |= btree_insert_key(b, op, &temp.key, replace_key);
208726c949f8SKent Overstreet 			break;
208826c949f8SKent Overstreet 		} else {
208926c949f8SKent Overstreet 			break;
209026c949f8SKent Overstreet 		}
2091cafe5635SKent Overstreet 	}
2092cafe5635SKent Overstreet 
2093403b6cdeSKent Overstreet 	BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
2094403b6cdeSKent Overstreet 
2095cafe5635SKent Overstreet 	BUG_ON(bch_count_data(b) < oldsize);
2096cafe5635SKent Overstreet 	return ret;
2097cafe5635SKent Overstreet }
2098cafe5635SKent Overstreet 
209926c949f8SKent Overstreet static int btree_split(struct btree *b, struct btree_op *op,
210026c949f8SKent Overstreet 		       struct keylist *insert_keys,
21011b207d80SKent Overstreet 		       struct bkey *replace_key)
2102cafe5635SKent Overstreet {
2103d6fd3b11SKent Overstreet 	bool split;
2104cafe5635SKent Overstreet 	struct btree *n1, *n2 = NULL, *n3 = NULL;
2105cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
2106b54d6934SKent Overstreet 	struct closure cl;
210717e21a9fSKent Overstreet 	struct keylist parent_keys;
2108b54d6934SKent Overstreet 
2109b54d6934SKent Overstreet 	closure_init_stack(&cl);
211017e21a9fSKent Overstreet 	bch_keylist_init(&parent_keys);
2111cafe5635SKent Overstreet 
211278365411SKent Overstreet 	if (!b->level &&
211378365411SKent Overstreet 	    btree_check_reserve(b, op))
211478365411SKent Overstreet 		return -EINTR;
211578365411SKent Overstreet 
2116bc9389eeSKent Overstreet 	n1 = btree_node_alloc_replacement(b, true);
2117cafe5635SKent Overstreet 	if (IS_ERR(n1))
2118cafe5635SKent Overstreet 		goto err;
2119cafe5635SKent Overstreet 
2120cafe5635SKent Overstreet 	split = set_blocks(n1->sets[0].data, n1->c) > (btree_blocks(b) * 4) / 5;
2121cafe5635SKent Overstreet 
2122cafe5635SKent Overstreet 	if (split) {
2123cafe5635SKent Overstreet 		unsigned keys = 0;
2124cafe5635SKent Overstreet 
2125c37511b8SKent Overstreet 		trace_bcache_btree_node_split(b, n1->sets[0].data->keys);
2126c37511b8SKent Overstreet 
2127bc9389eeSKent Overstreet 		n2 = bch_btree_node_alloc(b->c, b->level, true);
2128cafe5635SKent Overstreet 		if (IS_ERR(n2))
2129cafe5635SKent Overstreet 			goto err_free1;
2130cafe5635SKent Overstreet 
2131d6fd3b11SKent Overstreet 		if (!b->parent) {
2132bc9389eeSKent Overstreet 			n3 = bch_btree_node_alloc(b->c, b->level + 1, true);
2133cafe5635SKent Overstreet 			if (IS_ERR(n3))
2134cafe5635SKent Overstreet 				goto err_free2;
2135cafe5635SKent Overstreet 		}
2136cafe5635SKent Overstreet 
21371b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2138cafe5635SKent Overstreet 
2139d6fd3b11SKent Overstreet 		/*
2140d6fd3b11SKent Overstreet 		 * Has to be a linear search because we don't have an auxiliary
2141cafe5635SKent Overstreet 		 * search tree yet
2142cafe5635SKent Overstreet 		 */
2143cafe5635SKent Overstreet 
2144cafe5635SKent Overstreet 		while (keys < (n1->sets[0].data->keys * 3) / 5)
2145cafe5635SKent Overstreet 			keys += bkey_u64s(node(n1->sets[0].data, keys));
2146cafe5635SKent Overstreet 
2147cafe5635SKent Overstreet 		bkey_copy_key(&n1->key, node(n1->sets[0].data, keys));
2148cafe5635SKent Overstreet 		keys += bkey_u64s(node(n1->sets[0].data, keys));
2149cafe5635SKent Overstreet 
2150cafe5635SKent Overstreet 		n2->sets[0].data->keys = n1->sets[0].data->keys - keys;
2151cafe5635SKent Overstreet 		n1->sets[0].data->keys = keys;
2152cafe5635SKent Overstreet 
2153cafe5635SKent Overstreet 		memcpy(n2->sets[0].data->start,
2154cafe5635SKent Overstreet 		       end(n1->sets[0].data),
2155cafe5635SKent Overstreet 		       n2->sets[0].data->keys * sizeof(uint64_t));
2156cafe5635SKent Overstreet 
2157cafe5635SKent Overstreet 		bkey_copy_key(&n2->key, &b->key);
2158cafe5635SKent Overstreet 
215917e21a9fSKent Overstreet 		bch_keylist_add(&parent_keys, &n2->key);
2160b54d6934SKent Overstreet 		bch_btree_node_write(n2, &cl);
2161cafe5635SKent Overstreet 		rw_unlock(true, n2);
2162c37511b8SKent Overstreet 	} else {
2163c37511b8SKent Overstreet 		trace_bcache_btree_node_compact(b, n1->sets[0].data->keys);
2164c37511b8SKent Overstreet 
21651b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2166c37511b8SKent Overstreet 	}
2167cafe5635SKent Overstreet 
216817e21a9fSKent Overstreet 	bch_keylist_add(&parent_keys, &n1->key);
2169b54d6934SKent Overstreet 	bch_btree_node_write(n1, &cl);
2170cafe5635SKent Overstreet 
2171cafe5635SKent Overstreet 	if (n3) {
2172d6fd3b11SKent Overstreet 		/* Depth increases, make a new root */
2173cafe5635SKent Overstreet 		bkey_copy_key(&n3->key, &MAX_KEY);
217417e21a9fSKent Overstreet 		bch_btree_insert_keys(n3, op, &parent_keys, NULL);
2175b54d6934SKent Overstreet 		bch_btree_node_write(n3, &cl);
2176cafe5635SKent Overstreet 
2177b54d6934SKent Overstreet 		closure_sync(&cl);
2178cafe5635SKent Overstreet 		bch_btree_set_root(n3);
2179cafe5635SKent Overstreet 		rw_unlock(true, n3);
218017e21a9fSKent Overstreet 
218117e21a9fSKent Overstreet 		btree_node_free(b);
2182d6fd3b11SKent Overstreet 	} else if (!b->parent) {
2183d6fd3b11SKent Overstreet 		/* Root filled up but didn't need to be split */
2184b54d6934SKent Overstreet 		closure_sync(&cl);
2185cafe5635SKent Overstreet 		bch_btree_set_root(n1);
218617e21a9fSKent Overstreet 
218717e21a9fSKent Overstreet 		btree_node_free(b);
2188cafe5635SKent Overstreet 	} else {
218917e21a9fSKent Overstreet 		/* Split a non root node */
2190b54d6934SKent Overstreet 		closure_sync(&cl);
219117e21a9fSKent Overstreet 		make_btree_freeing_key(b, parent_keys.top);
219217e21a9fSKent Overstreet 		bch_keylist_push(&parent_keys);
219317e21a9fSKent Overstreet 
219417e21a9fSKent Overstreet 		btree_node_free(b);
219517e21a9fSKent Overstreet 
219617e21a9fSKent Overstreet 		bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
219717e21a9fSKent Overstreet 		BUG_ON(!bch_keylist_empty(&parent_keys));
2198cafe5635SKent Overstreet 	}
2199cafe5635SKent Overstreet 
2200cafe5635SKent Overstreet 	rw_unlock(true, n1);
2201cafe5635SKent Overstreet 
2202169ef1cfSKent Overstreet 	bch_time_stats_update(&b->c->btree_split_time, start_time);
2203cafe5635SKent Overstreet 
2204cafe5635SKent Overstreet 	return 0;
2205cafe5635SKent Overstreet err_free2:
22065f5837d2SKent Overstreet 	bkey_put(b->c, &n2->key);
2207e8e1d468SKent Overstreet 	btree_node_free(n2);
2208cafe5635SKent Overstreet 	rw_unlock(true, n2);
2209cafe5635SKent Overstreet err_free1:
22105f5837d2SKent Overstreet 	bkey_put(b->c, &n1->key);
2211e8e1d468SKent Overstreet 	btree_node_free(n1);
2212cafe5635SKent Overstreet 	rw_unlock(true, n1);
2213cafe5635SKent Overstreet err:
22145f5837d2SKent Overstreet 	WARN(1, "bcache: btree split failed");
22155f5837d2SKent Overstreet 
2216cafe5635SKent Overstreet 	if (n3 == ERR_PTR(-EAGAIN) ||
2217cafe5635SKent Overstreet 	    n2 == ERR_PTR(-EAGAIN) ||
2218cafe5635SKent Overstreet 	    n1 == ERR_PTR(-EAGAIN))
2219cafe5635SKent Overstreet 		return -EAGAIN;
2220cafe5635SKent Overstreet 
2221cafe5635SKent Overstreet 	return -ENOMEM;
2222cafe5635SKent Overstreet }
2223cafe5635SKent Overstreet 
222426c949f8SKent Overstreet static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
2225c18536a7SKent Overstreet 				 struct keylist *insert_keys,
22261b207d80SKent Overstreet 				 atomic_t *journal_ref,
22271b207d80SKent Overstreet 				 struct bkey *replace_key)
222826c949f8SKent Overstreet {
22291b207d80SKent Overstreet 	BUG_ON(b->level && replace_key);
22301b207d80SKent Overstreet 
223126c949f8SKent Overstreet 	if (should_split(b)) {
223226c949f8SKent Overstreet 		if (current->bio_list) {
223326c949f8SKent Overstreet 			op->lock = b->c->root->level + 1;
223417e21a9fSKent Overstreet 			return -EAGAIN;
223526c949f8SKent Overstreet 		} else if (op->lock <= b->c->root->level) {
223626c949f8SKent Overstreet 			op->lock = b->c->root->level + 1;
223717e21a9fSKent Overstreet 			return -EINTR;
223826c949f8SKent Overstreet 		} else {
223917e21a9fSKent Overstreet 			/* Invalidated all iterators */
224017e21a9fSKent Overstreet 			return btree_split(b, op, insert_keys, replace_key) ?:
224117e21a9fSKent Overstreet 				-EINTR;
224226c949f8SKent Overstreet 		}
224326c949f8SKent Overstreet 	} else {
224426c949f8SKent Overstreet 		BUG_ON(write_block(b) != b->sets[b->nsets].data);
224526c949f8SKent Overstreet 
224617e21a9fSKent Overstreet 		if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
2247f269af5aSKent Overstreet 			if (!b->level)
2248c18536a7SKent Overstreet 				bch_btree_leaf_dirty(b, journal_ref);
2249f269af5aSKent Overstreet 			else
2250f269af5aSKent Overstreet 				bch_btree_node_write_sync(b);
225126c949f8SKent Overstreet 		}
225226c949f8SKent Overstreet 
225317e21a9fSKent Overstreet 		return 0;
225417e21a9fSKent Overstreet 	}
225526c949f8SKent Overstreet }
225626c949f8SKent Overstreet 
2257e7c590ebSKent Overstreet int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2258e7c590ebSKent Overstreet 			       struct bkey *check_key)
2259e7c590ebSKent Overstreet {
2260e7c590ebSKent Overstreet 	int ret = -EINTR;
2261e7c590ebSKent Overstreet 	uint64_t btree_ptr = b->key.ptr[0];
2262e7c590ebSKent Overstreet 	unsigned long seq = b->seq;
2263e7c590ebSKent Overstreet 	struct keylist insert;
2264e7c590ebSKent Overstreet 	bool upgrade = op->lock == -1;
2265e7c590ebSKent Overstreet 
2266e7c590ebSKent Overstreet 	bch_keylist_init(&insert);
2267e7c590ebSKent Overstreet 
2268e7c590ebSKent Overstreet 	if (upgrade) {
2269e7c590ebSKent Overstreet 		rw_unlock(false, b);
2270e7c590ebSKent Overstreet 		rw_lock(true, b, b->level);
2271e7c590ebSKent Overstreet 
2272e7c590ebSKent Overstreet 		if (b->key.ptr[0] != btree_ptr ||
2273e7c590ebSKent Overstreet 		    b->seq != seq + 1)
2274e7c590ebSKent Overstreet 			goto out;
2275e7c590ebSKent Overstreet 	}
2276e7c590ebSKent Overstreet 
2277e7c590ebSKent Overstreet 	SET_KEY_PTRS(check_key, 1);
2278e7c590ebSKent Overstreet 	get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2279e7c590ebSKent Overstreet 
2280e7c590ebSKent Overstreet 	SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2281e7c590ebSKent Overstreet 
2282e7c590ebSKent Overstreet 	bch_keylist_add(&insert, check_key);
2283e7c590ebSKent Overstreet 
22841b207d80SKent Overstreet 	ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2285e7c590ebSKent Overstreet 
2286e7c590ebSKent Overstreet 	BUG_ON(!ret && !bch_keylist_empty(&insert));
2287e7c590ebSKent Overstreet out:
2288e7c590ebSKent Overstreet 	if (upgrade)
2289e7c590ebSKent Overstreet 		downgrade_write(&b->lock);
2290e7c590ebSKent Overstreet 	return ret;
2291e7c590ebSKent Overstreet }
2292e7c590ebSKent Overstreet 
2293cc7b8819SKent Overstreet struct btree_insert_op {
2294cc7b8819SKent Overstreet 	struct btree_op	op;
2295cc7b8819SKent Overstreet 	struct keylist	*keys;
2296cc7b8819SKent Overstreet 	atomic_t	*journal_ref;
2297cc7b8819SKent Overstreet 	struct bkey	*replace_key;
2298cc7b8819SKent Overstreet };
2299cc7b8819SKent Overstreet 
230008239ca2SWei Yongjun static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2301cafe5635SKent Overstreet {
2302cc7b8819SKent Overstreet 	struct btree_insert_op *op = container_of(b_op,
2303cc7b8819SKent Overstreet 					struct btree_insert_op, op);
2304403b6cdeSKent Overstreet 
2305cc7b8819SKent Overstreet 	int ret = bch_btree_insert_node(b, &op->op, op->keys,
2306cc7b8819SKent Overstreet 					op->journal_ref, op->replace_key);
2307cc7b8819SKent Overstreet 	if (ret && !bch_keylist_empty(op->keys))
2308cc7b8819SKent Overstreet 		return ret;
2309cc7b8819SKent Overstreet 	else
2310cc7b8819SKent Overstreet 		return MAP_DONE;
2311cafe5635SKent Overstreet }
2312cafe5635SKent Overstreet 
2313cc7b8819SKent Overstreet int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2314cc7b8819SKent Overstreet 		     atomic_t *journal_ref, struct bkey *replace_key)
2315cafe5635SKent Overstreet {
2316cc7b8819SKent Overstreet 	struct btree_insert_op op;
2317cafe5635SKent Overstreet 	int ret = 0;
2318cafe5635SKent Overstreet 
2319cc7b8819SKent Overstreet 	BUG_ON(current->bio_list);
23204f3d4014SKent Overstreet 	BUG_ON(bch_keylist_empty(keys));
2321cafe5635SKent Overstreet 
2322cc7b8819SKent Overstreet 	bch_btree_op_init(&op.op, 0);
2323cc7b8819SKent Overstreet 	op.keys		= keys;
2324cc7b8819SKent Overstreet 	op.journal_ref	= journal_ref;
2325cc7b8819SKent Overstreet 	op.replace_key	= replace_key;
2326cafe5635SKent Overstreet 
2327cc7b8819SKent Overstreet 	while (!ret && !bch_keylist_empty(keys)) {
2328cc7b8819SKent Overstreet 		op.op.lock = 0;
2329cc7b8819SKent Overstreet 		ret = bch_btree_map_leaf_nodes(&op.op, c,
2330cc7b8819SKent Overstreet 					       &START_KEY(keys->keys),
2331cc7b8819SKent Overstreet 					       btree_insert_fn);
2332cc7b8819SKent Overstreet 	}
2333cc7b8819SKent Overstreet 
2334cc7b8819SKent Overstreet 	if (ret) {
2335cafe5635SKent Overstreet 		struct bkey *k;
2336cafe5635SKent Overstreet 
23371b207d80SKent Overstreet 		pr_err("error %i", ret);
2338cafe5635SKent Overstreet 
23394f3d4014SKent Overstreet 		while ((k = bch_keylist_pop(keys)))
23403a3b6a4eSKent Overstreet 			bkey_put(c, k);
2341cc7b8819SKent Overstreet 	} else if (op.op.insert_collision)
2342cc7b8819SKent Overstreet 		ret = -ESRCH;
23436054c6d4SKent Overstreet 
2344cafe5635SKent Overstreet 	return ret;
2345cafe5635SKent Overstreet }
2346cafe5635SKent Overstreet 
2347cafe5635SKent Overstreet void bch_btree_set_root(struct btree *b)
2348cafe5635SKent Overstreet {
2349cafe5635SKent Overstreet 	unsigned i;
2350e49c7c37SKent Overstreet 	struct closure cl;
2351e49c7c37SKent Overstreet 
2352e49c7c37SKent Overstreet 	closure_init_stack(&cl);
2353cafe5635SKent Overstreet 
2354c37511b8SKent Overstreet 	trace_bcache_btree_set_root(b);
2355c37511b8SKent Overstreet 
2356cafe5635SKent Overstreet 	BUG_ON(!b->written);
2357cafe5635SKent Overstreet 
2358cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++)
2359cafe5635SKent Overstreet 		BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2360cafe5635SKent Overstreet 
2361cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
2362cafe5635SKent Overstreet 	list_del_init(&b->list);
2363cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
2364cafe5635SKent Overstreet 
2365cafe5635SKent Overstreet 	b->c->root = b;
2366cafe5635SKent Overstreet 
2367e49c7c37SKent Overstreet 	bch_journal_meta(b->c, &cl);
2368e49c7c37SKent Overstreet 	closure_sync(&cl);
2369cafe5635SKent Overstreet }
2370cafe5635SKent Overstreet 
237148dad8baSKent Overstreet /* Map across nodes or keys */
237248dad8baSKent Overstreet 
237348dad8baSKent Overstreet static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
237448dad8baSKent Overstreet 				       struct bkey *from,
237548dad8baSKent Overstreet 				       btree_map_nodes_fn *fn, int flags)
237648dad8baSKent Overstreet {
237748dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
237848dad8baSKent Overstreet 
237948dad8baSKent Overstreet 	if (b->level) {
238048dad8baSKent Overstreet 		struct bkey *k;
238148dad8baSKent Overstreet 		struct btree_iter iter;
238248dad8baSKent Overstreet 
238348dad8baSKent Overstreet 		bch_btree_iter_init(b, &iter, from);
238448dad8baSKent Overstreet 
238548dad8baSKent Overstreet 		while ((k = bch_btree_iter_next_filter(&iter, b,
238648dad8baSKent Overstreet 						       bch_ptr_bad))) {
238748dad8baSKent Overstreet 			ret = btree(map_nodes_recurse, k, b,
238848dad8baSKent Overstreet 				    op, from, fn, flags);
238948dad8baSKent Overstreet 			from = NULL;
239048dad8baSKent Overstreet 
239148dad8baSKent Overstreet 			if (ret != MAP_CONTINUE)
239248dad8baSKent Overstreet 				return ret;
239348dad8baSKent Overstreet 		}
239448dad8baSKent Overstreet 	}
239548dad8baSKent Overstreet 
239648dad8baSKent Overstreet 	if (!b->level || flags == MAP_ALL_NODES)
239748dad8baSKent Overstreet 		ret = fn(op, b);
239848dad8baSKent Overstreet 
239948dad8baSKent Overstreet 	return ret;
240048dad8baSKent Overstreet }
240148dad8baSKent Overstreet 
240248dad8baSKent Overstreet int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
240348dad8baSKent Overstreet 			  struct bkey *from, btree_map_nodes_fn *fn, int flags)
240448dad8baSKent Overstreet {
2405b54d6934SKent Overstreet 	return btree_root(map_nodes_recurse, c, op, from, fn, flags);
240648dad8baSKent Overstreet }
240748dad8baSKent Overstreet 
240848dad8baSKent Overstreet static int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
240948dad8baSKent Overstreet 				      struct bkey *from, btree_map_keys_fn *fn,
241048dad8baSKent Overstreet 				      int flags)
241148dad8baSKent Overstreet {
241248dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
241348dad8baSKent Overstreet 	struct bkey *k;
241448dad8baSKent Overstreet 	struct btree_iter iter;
241548dad8baSKent Overstreet 
241648dad8baSKent Overstreet 	bch_btree_iter_init(b, &iter, from);
241748dad8baSKent Overstreet 
241848dad8baSKent Overstreet 	while ((k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad))) {
241948dad8baSKent Overstreet 		ret = !b->level
242048dad8baSKent Overstreet 			? fn(op, b, k)
242148dad8baSKent Overstreet 			: btree(map_keys_recurse, k, b, op, from, fn, flags);
242248dad8baSKent Overstreet 		from = NULL;
242348dad8baSKent Overstreet 
242448dad8baSKent Overstreet 		if (ret != MAP_CONTINUE)
242548dad8baSKent Overstreet 			return ret;
242648dad8baSKent Overstreet 	}
242748dad8baSKent Overstreet 
242848dad8baSKent Overstreet 	if (!b->level && (flags & MAP_END_KEY))
242948dad8baSKent Overstreet 		ret = fn(op, b, &KEY(KEY_INODE(&b->key),
243048dad8baSKent Overstreet 				     KEY_OFFSET(&b->key), 0));
243148dad8baSKent Overstreet 
243248dad8baSKent Overstreet 	return ret;
243348dad8baSKent Overstreet }
243448dad8baSKent Overstreet 
243548dad8baSKent Overstreet int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
243648dad8baSKent Overstreet 		       struct bkey *from, btree_map_keys_fn *fn, int flags)
243748dad8baSKent Overstreet {
2438b54d6934SKent Overstreet 	return btree_root(map_keys_recurse, c, op, from, fn, flags);
243948dad8baSKent Overstreet }
244048dad8baSKent Overstreet 
2441cafe5635SKent Overstreet /* Keybuf code */
2442cafe5635SKent Overstreet 
2443cafe5635SKent Overstreet static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2444cafe5635SKent Overstreet {
2445cafe5635SKent Overstreet 	/* Overlapping keys compare equal */
2446cafe5635SKent Overstreet 	if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2447cafe5635SKent Overstreet 		return -1;
2448cafe5635SKent Overstreet 	if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2449cafe5635SKent Overstreet 		return 1;
2450cafe5635SKent Overstreet 	return 0;
2451cafe5635SKent Overstreet }
2452cafe5635SKent Overstreet 
2453cafe5635SKent Overstreet static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2454cafe5635SKent Overstreet 					    struct keybuf_key *r)
2455cafe5635SKent Overstreet {
2456cafe5635SKent Overstreet 	return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2457cafe5635SKent Overstreet }
2458cafe5635SKent Overstreet 
245948dad8baSKent Overstreet struct refill {
246048dad8baSKent Overstreet 	struct btree_op	op;
246148a915a8SKent Overstreet 	unsigned	nr_found;
246248dad8baSKent Overstreet 	struct keybuf	*buf;
246348dad8baSKent Overstreet 	struct bkey	*end;
246448dad8baSKent Overstreet 	keybuf_pred_fn	*pred;
246548dad8baSKent Overstreet };
246648dad8baSKent Overstreet 
246748dad8baSKent Overstreet static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
246848dad8baSKent Overstreet 			    struct bkey *k)
2469cafe5635SKent Overstreet {
247048dad8baSKent Overstreet 	struct refill *refill = container_of(op, struct refill, op);
247148dad8baSKent Overstreet 	struct keybuf *buf = refill->buf;
247248dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
2473cafe5635SKent Overstreet 
247448dad8baSKent Overstreet 	if (bkey_cmp(k, refill->end) >= 0) {
247548dad8baSKent Overstreet 		ret = MAP_DONE;
247648dad8baSKent Overstreet 		goto out;
2477cafe5635SKent Overstreet 	}
2478cafe5635SKent Overstreet 
247948dad8baSKent Overstreet 	if (!KEY_SIZE(k)) /* end key */
248048dad8baSKent Overstreet 		goto out;
2481cafe5635SKent Overstreet 
248248dad8baSKent Overstreet 	if (refill->pred(buf, k)) {
2483cafe5635SKent Overstreet 		struct keybuf_key *w;
2484cafe5635SKent Overstreet 
2485cafe5635SKent Overstreet 		spin_lock(&buf->lock);
2486cafe5635SKent Overstreet 
2487cafe5635SKent Overstreet 		w = array_alloc(&buf->freelist);
248848dad8baSKent Overstreet 		if (!w) {
248948dad8baSKent Overstreet 			spin_unlock(&buf->lock);
249048dad8baSKent Overstreet 			return MAP_DONE;
249148dad8baSKent Overstreet 		}
2492cafe5635SKent Overstreet 
2493cafe5635SKent Overstreet 		w->private = NULL;
2494cafe5635SKent Overstreet 		bkey_copy(&w->key, k);
2495cafe5635SKent Overstreet 
2496cafe5635SKent Overstreet 		if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2497cafe5635SKent Overstreet 			array_free(&buf->freelist, w);
249848a915a8SKent Overstreet 		else
249948a915a8SKent Overstreet 			refill->nr_found++;
2500cafe5635SKent Overstreet 
250148dad8baSKent Overstreet 		if (array_freelist_empty(&buf->freelist))
250248dad8baSKent Overstreet 			ret = MAP_DONE;
250348dad8baSKent Overstreet 
2504cafe5635SKent Overstreet 		spin_unlock(&buf->lock);
2505cafe5635SKent Overstreet 	}
250648dad8baSKent Overstreet out:
250748dad8baSKent Overstreet 	buf->last_scanned = *k;
250848dad8baSKent Overstreet 	return ret;
2509cafe5635SKent Overstreet }
2510cafe5635SKent Overstreet 
2511cafe5635SKent Overstreet void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
251272c27061SKent Overstreet 		       struct bkey *end, keybuf_pred_fn *pred)
2513cafe5635SKent Overstreet {
2514cafe5635SKent Overstreet 	struct bkey start = buf->last_scanned;
251548dad8baSKent Overstreet 	struct refill refill;
2516cafe5635SKent Overstreet 
2517cafe5635SKent Overstreet 	cond_resched();
2518cafe5635SKent Overstreet 
2519b54d6934SKent Overstreet 	bch_btree_op_init(&refill.op, -1);
252048a915a8SKent Overstreet 	refill.nr_found	= 0;
252148dad8baSKent Overstreet 	refill.buf	= buf;
252248dad8baSKent Overstreet 	refill.end	= end;
252348dad8baSKent Overstreet 	refill.pred	= pred;
252448dad8baSKent Overstreet 
252548dad8baSKent Overstreet 	bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
252648dad8baSKent Overstreet 			   refill_keybuf_fn, MAP_END_KEY);
2527cafe5635SKent Overstreet 
252848a915a8SKent Overstreet 	trace_bcache_keyscan(refill.nr_found,
2529cafe5635SKent Overstreet 			     KEY_INODE(&start), KEY_OFFSET(&start),
253048a915a8SKent Overstreet 			     KEY_INODE(&buf->last_scanned),
253148a915a8SKent Overstreet 			     KEY_OFFSET(&buf->last_scanned));
2532cafe5635SKent Overstreet 
2533cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2534cafe5635SKent Overstreet 
2535cafe5635SKent Overstreet 	if (!RB_EMPTY_ROOT(&buf->keys)) {
2536cafe5635SKent Overstreet 		struct keybuf_key *w;
2537cafe5635SKent Overstreet 		w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2538cafe5635SKent Overstreet 		buf->start	= START_KEY(&w->key);
2539cafe5635SKent Overstreet 
2540cafe5635SKent Overstreet 		w = RB_LAST(&buf->keys, struct keybuf_key, node);
2541cafe5635SKent Overstreet 		buf->end	= w->key;
2542cafe5635SKent Overstreet 	} else {
2543cafe5635SKent Overstreet 		buf->start	= MAX_KEY;
2544cafe5635SKent Overstreet 		buf->end	= MAX_KEY;
2545cafe5635SKent Overstreet 	}
2546cafe5635SKent Overstreet 
2547cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2548cafe5635SKent Overstreet }
2549cafe5635SKent Overstreet 
2550cafe5635SKent Overstreet static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2551cafe5635SKent Overstreet {
2552cafe5635SKent Overstreet 	rb_erase(&w->node, &buf->keys);
2553cafe5635SKent Overstreet 	array_free(&buf->freelist, w);
2554cafe5635SKent Overstreet }
2555cafe5635SKent Overstreet 
2556cafe5635SKent Overstreet void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2557cafe5635SKent Overstreet {
2558cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2559cafe5635SKent Overstreet 	__bch_keybuf_del(buf, w);
2560cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2561cafe5635SKent Overstreet }
2562cafe5635SKent Overstreet 
2563cafe5635SKent Overstreet bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2564cafe5635SKent Overstreet 				  struct bkey *end)
2565cafe5635SKent Overstreet {
2566cafe5635SKent Overstreet 	bool ret = false;
2567cafe5635SKent Overstreet 	struct keybuf_key *p, *w, s;
2568cafe5635SKent Overstreet 	s.key = *start;
2569cafe5635SKent Overstreet 
2570cafe5635SKent Overstreet 	if (bkey_cmp(end, &buf->start) <= 0 ||
2571cafe5635SKent Overstreet 	    bkey_cmp(start, &buf->end) >= 0)
2572cafe5635SKent Overstreet 		return false;
2573cafe5635SKent Overstreet 
2574cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2575cafe5635SKent Overstreet 	w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2576cafe5635SKent Overstreet 
2577cafe5635SKent Overstreet 	while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2578cafe5635SKent Overstreet 		p = w;
2579cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2580cafe5635SKent Overstreet 
2581cafe5635SKent Overstreet 		if (p->private)
2582cafe5635SKent Overstreet 			ret = true;
2583cafe5635SKent Overstreet 		else
2584cafe5635SKent Overstreet 			__bch_keybuf_del(buf, p);
2585cafe5635SKent Overstreet 	}
2586cafe5635SKent Overstreet 
2587cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2588cafe5635SKent Overstreet 	return ret;
2589cafe5635SKent Overstreet }
2590cafe5635SKent Overstreet 
2591cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2592cafe5635SKent Overstreet {
2593cafe5635SKent Overstreet 	struct keybuf_key *w;
2594cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2595cafe5635SKent Overstreet 
2596cafe5635SKent Overstreet 	w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2597cafe5635SKent Overstreet 
2598cafe5635SKent Overstreet 	while (w && w->private)
2599cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2600cafe5635SKent Overstreet 
2601cafe5635SKent Overstreet 	if (w)
2602cafe5635SKent Overstreet 		w->private = ERR_PTR(-EINTR);
2603cafe5635SKent Overstreet 
2604cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2605cafe5635SKent Overstreet 	return w;
2606cafe5635SKent Overstreet }
2607cafe5635SKent Overstreet 
2608cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2609cafe5635SKent Overstreet 					  struct keybuf *buf,
261072c27061SKent Overstreet 					  struct bkey *end,
261172c27061SKent Overstreet 					  keybuf_pred_fn *pred)
2612cafe5635SKent Overstreet {
2613cafe5635SKent Overstreet 	struct keybuf_key *ret;
2614cafe5635SKent Overstreet 
2615cafe5635SKent Overstreet 	while (1) {
2616cafe5635SKent Overstreet 		ret = bch_keybuf_next(buf);
2617cafe5635SKent Overstreet 		if (ret)
2618cafe5635SKent Overstreet 			break;
2619cafe5635SKent Overstreet 
2620cafe5635SKent Overstreet 		if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2621cafe5635SKent Overstreet 			pr_debug("scan finished");
2622cafe5635SKent Overstreet 			break;
2623cafe5635SKent Overstreet 		}
2624cafe5635SKent Overstreet 
262572c27061SKent Overstreet 		bch_refill_keybuf(c, buf, end, pred);
2626cafe5635SKent Overstreet 	}
2627cafe5635SKent Overstreet 
2628cafe5635SKent Overstreet 	return ret;
2629cafe5635SKent Overstreet }
2630cafe5635SKent Overstreet 
263172c27061SKent Overstreet void bch_keybuf_init(struct keybuf *buf)
2632cafe5635SKent Overstreet {
2633cafe5635SKent Overstreet 	buf->last_scanned	= MAX_KEY;
2634cafe5635SKent Overstreet 	buf->keys		= RB_ROOT;
2635cafe5635SKent Overstreet 
2636cafe5635SKent Overstreet 	spin_lock_init(&buf->lock);
2637cafe5635SKent Overstreet 	array_allocator_init(&buf->freelist);
2638cafe5635SKent Overstreet }
2639cafe5635SKent Overstreet 
2640cafe5635SKent Overstreet void bch_btree_exit(void)
2641cafe5635SKent Overstreet {
2642cafe5635SKent Overstreet 	if (btree_io_wq)
2643cafe5635SKent Overstreet 		destroy_workqueue(btree_io_wq);
2644cafe5635SKent Overstreet }
2645cafe5635SKent Overstreet 
2646cafe5635SKent Overstreet int __init bch_btree_init(void)
2647cafe5635SKent Overstreet {
264872a44517SKent Overstreet 	btree_io_wq = create_singlethread_workqueue("bch_btree_io");
264972a44517SKent Overstreet 	if (!btree_io_wq)
2650cafe5635SKent Overstreet 		return -ENOMEM;
2651cafe5635SKent Overstreet 
2652cafe5635SKent Overstreet 	return 0;
2653cafe5635SKent Overstreet }
2654