xref: /linux/drivers/md/bcache/btree.c (revision 78365411b344df35a198b119133e6515c2dcfb9f)
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);					\
170*78365411SKent Overstreet 		if (_r == -EINTR)					\
171*78365411SKent 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 									\
180*78365411SKent 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 
206f3059a54SKent Overstreet static 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);
261cafe5635SKent Overstreet 	     index(i, b) < btree_blocks(b);
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);
28107e86ccbSKent Overstreet 	bch_cache_set_error(b->c, "%s at bucket %zu, block %zu, %u keys",
282cafe5635SKent Overstreet 			    err, PTR_BUCKET_NR(b->c, &b->key, 0),
283cafe5635SKent Overstreet 			    index(i, b), 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 
29357943511SKent Overstreet 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 
481cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
482cafe5635SKent Overstreet 		bch_bset_init_next(b);
483cafe5635SKent Overstreet }
484cafe5635SKent Overstreet 
485f269af5aSKent Overstreet static void bch_btree_node_write_sync(struct btree *b)
486f269af5aSKent Overstreet {
487f269af5aSKent Overstreet 	struct closure cl;
488f269af5aSKent Overstreet 
489f269af5aSKent Overstreet 	closure_init_stack(&cl);
490f269af5aSKent Overstreet 	bch_btree_node_write(b, &cl);
491f269af5aSKent Overstreet 	closure_sync(&cl);
492f269af5aSKent Overstreet }
493f269af5aSKent Overstreet 
49457943511SKent Overstreet static void btree_node_write_work(struct work_struct *w)
495cafe5635SKent Overstreet {
496cafe5635SKent Overstreet 	struct btree *b = container_of(to_delayed_work(w), struct btree, work);
497cafe5635SKent Overstreet 
49857943511SKent Overstreet 	rw_lock(true, b, b->level);
499cafe5635SKent Overstreet 
500cafe5635SKent Overstreet 	if (btree_node_dirty(b))
50157943511SKent Overstreet 		bch_btree_node_write(b, NULL);
50257943511SKent Overstreet 	rw_unlock(true, b);
503cafe5635SKent Overstreet }
504cafe5635SKent Overstreet 
505c18536a7SKent Overstreet static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
506cafe5635SKent Overstreet {
507cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
508cafe5635SKent Overstreet 	struct btree_write *w = btree_current_write(b);
509cafe5635SKent Overstreet 
51057943511SKent Overstreet 	BUG_ON(!b->written);
51157943511SKent Overstreet 	BUG_ON(!i->keys);
512cafe5635SKent Overstreet 
51357943511SKent Overstreet 	if (!btree_node_dirty(b))
51457943511SKent Overstreet 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
51557943511SKent Overstreet 
516cafe5635SKent Overstreet 	set_btree_node_dirty(b);
517cafe5635SKent Overstreet 
518c18536a7SKent Overstreet 	if (journal_ref) {
519cafe5635SKent Overstreet 		if (w->journal &&
520c18536a7SKent Overstreet 		    journal_pin_cmp(b->c, w->journal, journal_ref)) {
521cafe5635SKent Overstreet 			atomic_dec_bug(w->journal);
522cafe5635SKent Overstreet 			w->journal = NULL;
523cafe5635SKent Overstreet 		}
524cafe5635SKent Overstreet 
525cafe5635SKent Overstreet 		if (!w->journal) {
526c18536a7SKent Overstreet 			w->journal = journal_ref;
527cafe5635SKent Overstreet 			atomic_inc(w->journal);
528cafe5635SKent Overstreet 		}
529cafe5635SKent Overstreet 	}
530cafe5635SKent Overstreet 
531cafe5635SKent Overstreet 	/* Force write if set is too big */
53257943511SKent Overstreet 	if (set_bytes(i) > PAGE_SIZE - 48 &&
53357943511SKent Overstreet 	    !current->bio_list)
53457943511SKent Overstreet 		bch_btree_node_write(b, NULL);
535cafe5635SKent Overstreet }
536cafe5635SKent Overstreet 
537cafe5635SKent Overstreet /*
538cafe5635SKent Overstreet  * Btree in memory cache - allocation/freeing
539cafe5635SKent Overstreet  * mca -> memory cache
540cafe5635SKent Overstreet  */
541cafe5635SKent Overstreet 
542cafe5635SKent Overstreet static void mca_reinit(struct btree *b)
543cafe5635SKent Overstreet {
544cafe5635SKent Overstreet 	unsigned i;
545cafe5635SKent Overstreet 
546cafe5635SKent Overstreet 	b->flags	= 0;
547cafe5635SKent Overstreet 	b->written	= 0;
548cafe5635SKent Overstreet 	b->nsets	= 0;
549cafe5635SKent Overstreet 
550cafe5635SKent Overstreet 	for (i = 0; i < MAX_BSETS; i++)
551cafe5635SKent Overstreet 		b->sets[i].size = 0;
552cafe5635SKent Overstreet 	/*
553cafe5635SKent Overstreet 	 * Second loop starts at 1 because b->sets[0]->data is the memory we
554cafe5635SKent Overstreet 	 * allocated
555cafe5635SKent Overstreet 	 */
556cafe5635SKent Overstreet 	for (i = 1; i < MAX_BSETS; i++)
557cafe5635SKent Overstreet 		b->sets[i].data = NULL;
558cafe5635SKent Overstreet }
559cafe5635SKent Overstreet 
560cafe5635SKent Overstreet #define mca_reserve(c)	(((c->root && c->root->level)		\
561cafe5635SKent Overstreet 			  ? c->root->level : 1) * 8 + 16)
562cafe5635SKent Overstreet #define mca_can_free(c)						\
563cafe5635SKent Overstreet 	max_t(int, 0, c->bucket_cache_used - mca_reserve(c))
564cafe5635SKent Overstreet 
565cafe5635SKent Overstreet static void mca_data_free(struct btree *b)
566cafe5635SKent Overstreet {
567cafe5635SKent Overstreet 	struct bset_tree *t = b->sets;
568cb7a583eSKent Overstreet 
569cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
570cafe5635SKent Overstreet 
571cafe5635SKent Overstreet 	if (bset_prev_bytes(b) < PAGE_SIZE)
572cafe5635SKent Overstreet 		kfree(t->prev);
573cafe5635SKent Overstreet 	else
574cafe5635SKent Overstreet 		free_pages((unsigned long) t->prev,
575cafe5635SKent Overstreet 			   get_order(bset_prev_bytes(b)));
576cafe5635SKent Overstreet 
577cafe5635SKent Overstreet 	if (bset_tree_bytes(b) < PAGE_SIZE)
578cafe5635SKent Overstreet 		kfree(t->tree);
579cafe5635SKent Overstreet 	else
580cafe5635SKent Overstreet 		free_pages((unsigned long) t->tree,
581cafe5635SKent Overstreet 			   get_order(bset_tree_bytes(b)));
582cafe5635SKent Overstreet 
583cafe5635SKent Overstreet 	free_pages((unsigned long) t->data, b->page_order);
584cafe5635SKent Overstreet 
585cafe5635SKent Overstreet 	t->prev = NULL;
586cafe5635SKent Overstreet 	t->tree = NULL;
587cafe5635SKent Overstreet 	t->data = NULL;
588cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freed);
589cafe5635SKent Overstreet 	b->c->bucket_cache_used--;
590cafe5635SKent Overstreet }
591cafe5635SKent Overstreet 
592cafe5635SKent Overstreet static void mca_bucket_free(struct btree *b)
593cafe5635SKent Overstreet {
594cafe5635SKent Overstreet 	BUG_ON(btree_node_dirty(b));
595cafe5635SKent Overstreet 
596cafe5635SKent Overstreet 	b->key.ptr[0] = 0;
597cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
598cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freeable);
599cafe5635SKent Overstreet }
600cafe5635SKent Overstreet 
601cafe5635SKent Overstreet static unsigned btree_order(struct bkey *k)
602cafe5635SKent Overstreet {
603cafe5635SKent Overstreet 	return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
604cafe5635SKent Overstreet }
605cafe5635SKent Overstreet 
606cafe5635SKent Overstreet static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
607cafe5635SKent Overstreet {
608cafe5635SKent Overstreet 	struct bset_tree *t = b->sets;
609cafe5635SKent Overstreet 	BUG_ON(t->data);
610cafe5635SKent Overstreet 
611cafe5635SKent Overstreet 	b->page_order = max_t(unsigned,
612cafe5635SKent Overstreet 			      ilog2(b->c->btree_pages),
613cafe5635SKent Overstreet 			      btree_order(k));
614cafe5635SKent Overstreet 
615cafe5635SKent Overstreet 	t->data = (void *) __get_free_pages(gfp, b->page_order);
616cafe5635SKent Overstreet 	if (!t->data)
617cafe5635SKent Overstreet 		goto err;
618cafe5635SKent Overstreet 
619cafe5635SKent Overstreet 	t->tree = bset_tree_bytes(b) < PAGE_SIZE
620cafe5635SKent Overstreet 		? kmalloc(bset_tree_bytes(b), gfp)
621cafe5635SKent Overstreet 		: (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
622cafe5635SKent Overstreet 	if (!t->tree)
623cafe5635SKent Overstreet 		goto err;
624cafe5635SKent Overstreet 
625cafe5635SKent Overstreet 	t->prev = bset_prev_bytes(b) < PAGE_SIZE
626cafe5635SKent Overstreet 		? kmalloc(bset_prev_bytes(b), gfp)
627cafe5635SKent Overstreet 		: (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
628cafe5635SKent Overstreet 	if (!t->prev)
629cafe5635SKent Overstreet 		goto err;
630cafe5635SKent Overstreet 
631cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache);
632cafe5635SKent Overstreet 	b->c->bucket_cache_used++;
633cafe5635SKent Overstreet 	return;
634cafe5635SKent Overstreet err:
635cafe5635SKent Overstreet 	mca_data_free(b);
636cafe5635SKent Overstreet }
637cafe5635SKent Overstreet 
638cafe5635SKent Overstreet static struct btree *mca_bucket_alloc(struct cache_set *c,
639cafe5635SKent Overstreet 				      struct bkey *k, gfp_t gfp)
640cafe5635SKent Overstreet {
641cafe5635SKent Overstreet 	struct btree *b = kzalloc(sizeof(struct btree), gfp);
642cafe5635SKent Overstreet 	if (!b)
643cafe5635SKent Overstreet 		return NULL;
644cafe5635SKent Overstreet 
645cafe5635SKent Overstreet 	init_rwsem(&b->lock);
646cafe5635SKent Overstreet 	lockdep_set_novalidate_class(&b->lock);
647cafe5635SKent Overstreet 	INIT_LIST_HEAD(&b->list);
64857943511SKent Overstreet 	INIT_DELAYED_WORK(&b->work, btree_node_write_work);
649cafe5635SKent Overstreet 	b->c = c;
650cb7a583eSKent Overstreet 	sema_init(&b->io_mutex, 1);
651cafe5635SKent Overstreet 
652cafe5635SKent Overstreet 	mca_data_alloc(b, k, gfp);
653cafe5635SKent Overstreet 	return b;
654cafe5635SKent Overstreet }
655cafe5635SKent Overstreet 
656e8e1d468SKent Overstreet static int mca_reap(struct btree *b, unsigned min_order, bool flush)
657cafe5635SKent Overstreet {
658e8e1d468SKent Overstreet 	struct closure cl;
659e8e1d468SKent Overstreet 
660e8e1d468SKent Overstreet 	closure_init_stack(&cl);
661cafe5635SKent Overstreet 	lockdep_assert_held(&b->c->bucket_lock);
662cafe5635SKent Overstreet 
663cafe5635SKent Overstreet 	if (!down_write_trylock(&b->lock))
664cafe5635SKent Overstreet 		return -ENOMEM;
665cafe5635SKent Overstreet 
666e8e1d468SKent Overstreet 	BUG_ON(btree_node_dirty(b) && !b->sets[0].data);
667e8e1d468SKent Overstreet 
668cb7a583eSKent Overstreet 	if (b->page_order < min_order)
669cb7a583eSKent Overstreet 		goto out_unlock;
670cb7a583eSKent Overstreet 
671cb7a583eSKent Overstreet 	if (!flush) {
672cb7a583eSKent Overstreet 		if (btree_node_dirty(b))
673cb7a583eSKent Overstreet 			goto out_unlock;
674cb7a583eSKent Overstreet 
675cb7a583eSKent Overstreet 		if (down_trylock(&b->io_mutex))
676cb7a583eSKent Overstreet 			goto out_unlock;
677cb7a583eSKent Overstreet 		up(&b->io_mutex);
678cafe5635SKent Overstreet 	}
679cafe5635SKent Overstreet 
680f269af5aSKent Overstreet 	if (btree_node_dirty(b))
681f269af5aSKent Overstreet 		bch_btree_node_write_sync(b);
682cafe5635SKent Overstreet 
683e8e1d468SKent Overstreet 	/* wait for any in flight btree write */
684cb7a583eSKent Overstreet 	down(&b->io_mutex);
685cb7a583eSKent Overstreet 	up(&b->io_mutex);
686e8e1d468SKent Overstreet 
687cafe5635SKent Overstreet 	return 0;
688cb7a583eSKent Overstreet out_unlock:
689cb7a583eSKent Overstreet 	rw_unlock(true, b);
690cb7a583eSKent Overstreet 	return -ENOMEM;
691cafe5635SKent Overstreet }
692cafe5635SKent Overstreet 
6937dc19d5aSDave Chinner static unsigned long bch_mca_scan(struct shrinker *shrink,
6947dc19d5aSDave Chinner 				  struct shrink_control *sc)
695cafe5635SKent Overstreet {
696cafe5635SKent Overstreet 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
697cafe5635SKent Overstreet 	struct btree *b, *t;
698cafe5635SKent Overstreet 	unsigned long i, nr = sc->nr_to_scan;
6997dc19d5aSDave Chinner 	unsigned long freed = 0;
700cafe5635SKent Overstreet 
701cafe5635SKent Overstreet 	if (c->shrinker_disabled)
7027dc19d5aSDave Chinner 		return SHRINK_STOP;
703cafe5635SKent Overstreet 
704cafe5635SKent Overstreet 	if (c->try_harder)
7057dc19d5aSDave Chinner 		return SHRINK_STOP;
706cafe5635SKent Overstreet 
707cafe5635SKent Overstreet 	/* Return -1 if we can't do anything right now */
708a698e08cSKent Overstreet 	if (sc->gfp_mask & __GFP_IO)
709cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
710cafe5635SKent Overstreet 	else if (!mutex_trylock(&c->bucket_lock))
711cafe5635SKent Overstreet 		return -1;
712cafe5635SKent Overstreet 
71336c9ea98SKent Overstreet 	/*
71436c9ea98SKent Overstreet 	 * It's _really_ critical that we don't free too many btree nodes - we
71536c9ea98SKent Overstreet 	 * have to always leave ourselves a reserve. The reserve is how we
71636c9ea98SKent Overstreet 	 * guarantee that allocating memory for a new btree node can always
71736c9ea98SKent Overstreet 	 * succeed, so that inserting keys into the btree can always succeed and
71836c9ea98SKent Overstreet 	 * IO can always make forward progress:
71936c9ea98SKent Overstreet 	 */
720cafe5635SKent Overstreet 	nr /= c->btree_pages;
721cafe5635SKent Overstreet 	nr = min_t(unsigned long, nr, mca_can_free(c));
722cafe5635SKent Overstreet 
723cafe5635SKent Overstreet 	i = 0;
724cafe5635SKent Overstreet 	list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
7257dc19d5aSDave Chinner 		if (freed >= nr)
726cafe5635SKent Overstreet 			break;
727cafe5635SKent Overstreet 
728cafe5635SKent Overstreet 		if (++i > 3 &&
729e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
730cafe5635SKent Overstreet 			mca_data_free(b);
731cafe5635SKent Overstreet 			rw_unlock(true, b);
7327dc19d5aSDave Chinner 			freed++;
733cafe5635SKent Overstreet 		}
734cafe5635SKent Overstreet 	}
735cafe5635SKent Overstreet 
736b0f32a56SKent Overstreet 	for (i = 0; (nr--) && i < c->bucket_cache_used; i++) {
737cafe5635SKent Overstreet 		if (list_empty(&c->btree_cache))
738cafe5635SKent Overstreet 			goto out;
739cafe5635SKent Overstreet 
740cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
741cafe5635SKent Overstreet 		list_rotate_left(&c->btree_cache);
742cafe5635SKent Overstreet 
743cafe5635SKent Overstreet 		if (!b->accessed &&
744e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
745cafe5635SKent Overstreet 			mca_bucket_free(b);
746cafe5635SKent Overstreet 			mca_data_free(b);
747cafe5635SKent Overstreet 			rw_unlock(true, b);
7487dc19d5aSDave Chinner 			freed++;
749cafe5635SKent Overstreet 		} else
750cafe5635SKent Overstreet 			b->accessed = 0;
751cafe5635SKent Overstreet 	}
752cafe5635SKent Overstreet out:
753cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
7547dc19d5aSDave Chinner 	return freed;
7557dc19d5aSDave Chinner }
7567dc19d5aSDave Chinner 
7577dc19d5aSDave Chinner static unsigned long bch_mca_count(struct shrinker *shrink,
7587dc19d5aSDave Chinner 				   struct shrink_control *sc)
7597dc19d5aSDave Chinner {
7607dc19d5aSDave Chinner 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
7617dc19d5aSDave Chinner 
7627dc19d5aSDave Chinner 	if (c->shrinker_disabled)
7637dc19d5aSDave Chinner 		return 0;
7647dc19d5aSDave Chinner 
7657dc19d5aSDave Chinner 	if (c->try_harder)
7667dc19d5aSDave Chinner 		return 0;
7677dc19d5aSDave Chinner 
7687dc19d5aSDave Chinner 	return mca_can_free(c) * c->btree_pages;
769cafe5635SKent Overstreet }
770cafe5635SKent Overstreet 
771cafe5635SKent Overstreet void bch_btree_cache_free(struct cache_set *c)
772cafe5635SKent Overstreet {
773cafe5635SKent Overstreet 	struct btree *b;
774cafe5635SKent Overstreet 	struct closure cl;
775cafe5635SKent Overstreet 	closure_init_stack(&cl);
776cafe5635SKent Overstreet 
777cafe5635SKent Overstreet 	if (c->shrink.list.next)
778cafe5635SKent Overstreet 		unregister_shrinker(&c->shrink);
779cafe5635SKent Overstreet 
780cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
781cafe5635SKent Overstreet 
782cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
783cafe5635SKent Overstreet 	if (c->verify_data)
784cafe5635SKent Overstreet 		list_move(&c->verify_data->list, &c->btree_cache);
785cafe5635SKent Overstreet #endif
786cafe5635SKent Overstreet 
787cafe5635SKent Overstreet 	list_splice(&c->btree_cache_freeable,
788cafe5635SKent Overstreet 		    &c->btree_cache);
789cafe5635SKent Overstreet 
790cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache)) {
791cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
792cafe5635SKent Overstreet 
793cafe5635SKent Overstreet 		if (btree_node_dirty(b))
794cafe5635SKent Overstreet 			btree_complete_write(b, btree_current_write(b));
795cafe5635SKent Overstreet 		clear_bit(BTREE_NODE_dirty, &b->flags);
796cafe5635SKent Overstreet 
797cafe5635SKent Overstreet 		mca_data_free(b);
798cafe5635SKent Overstreet 	}
799cafe5635SKent Overstreet 
800cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache_freed)) {
801cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache_freed,
802cafe5635SKent Overstreet 				     struct btree, list);
803cafe5635SKent Overstreet 		list_del(&b->list);
804cafe5635SKent Overstreet 		cancel_delayed_work_sync(&b->work);
805cafe5635SKent Overstreet 		kfree(b);
806cafe5635SKent Overstreet 	}
807cafe5635SKent Overstreet 
808cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
809cafe5635SKent Overstreet }
810cafe5635SKent Overstreet 
811cafe5635SKent Overstreet int bch_btree_cache_alloc(struct cache_set *c)
812cafe5635SKent Overstreet {
813cafe5635SKent Overstreet 	unsigned i;
814cafe5635SKent Overstreet 
815cafe5635SKent Overstreet 	for (i = 0; i < mca_reserve(c); i++)
81672a44517SKent Overstreet 		if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
81772a44517SKent Overstreet 			return -ENOMEM;
818cafe5635SKent Overstreet 
819cafe5635SKent Overstreet 	list_splice_init(&c->btree_cache,
820cafe5635SKent Overstreet 			 &c->btree_cache_freeable);
821cafe5635SKent Overstreet 
822cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
823cafe5635SKent Overstreet 	mutex_init(&c->verify_lock);
824cafe5635SKent Overstreet 
825cafe5635SKent Overstreet 	c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
826cafe5635SKent Overstreet 
827cafe5635SKent Overstreet 	if (c->verify_data &&
828cafe5635SKent Overstreet 	    c->verify_data->sets[0].data)
829cafe5635SKent Overstreet 		list_del_init(&c->verify_data->list);
830cafe5635SKent Overstreet 	else
831cafe5635SKent Overstreet 		c->verify_data = NULL;
832cafe5635SKent Overstreet #endif
833cafe5635SKent Overstreet 
8347dc19d5aSDave Chinner 	c->shrink.count_objects = bch_mca_count;
8357dc19d5aSDave Chinner 	c->shrink.scan_objects = bch_mca_scan;
836cafe5635SKent Overstreet 	c->shrink.seeks = 4;
837cafe5635SKent Overstreet 	c->shrink.batch = c->btree_pages * 2;
838cafe5635SKent Overstreet 	register_shrinker(&c->shrink);
839cafe5635SKent Overstreet 
840cafe5635SKent Overstreet 	return 0;
841cafe5635SKent Overstreet }
842cafe5635SKent Overstreet 
843cafe5635SKent Overstreet /* Btree in memory cache - hash table */
844cafe5635SKent Overstreet 
845cafe5635SKent Overstreet static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
846cafe5635SKent Overstreet {
847cafe5635SKent Overstreet 	return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
848cafe5635SKent Overstreet }
849cafe5635SKent Overstreet 
850cafe5635SKent Overstreet static struct btree *mca_find(struct cache_set *c, struct bkey *k)
851cafe5635SKent Overstreet {
852cafe5635SKent Overstreet 	struct btree *b;
853cafe5635SKent Overstreet 
854cafe5635SKent Overstreet 	rcu_read_lock();
855cafe5635SKent Overstreet 	hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
856cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
857cafe5635SKent Overstreet 			goto out;
858cafe5635SKent Overstreet 	b = NULL;
859cafe5635SKent Overstreet out:
860cafe5635SKent Overstreet 	rcu_read_unlock();
861cafe5635SKent Overstreet 	return b;
862cafe5635SKent Overstreet }
863cafe5635SKent Overstreet 
864e8e1d468SKent Overstreet static struct btree *mca_cannibalize(struct cache_set *c, struct bkey *k)
865cafe5635SKent Overstreet {
866e8e1d468SKent Overstreet 	struct btree *b;
867cafe5635SKent Overstreet 
868c37511b8SKent Overstreet 	trace_bcache_btree_cache_cannibalize(c);
869c37511b8SKent Overstreet 
870e8e1d468SKent Overstreet 	if (!c->try_harder) {
871e8e1d468SKent Overstreet 		c->try_harder = current;
872cafe5635SKent Overstreet 		c->try_harder_start = local_clock();
873e8e1d468SKent Overstreet 	} else if (c->try_harder != current)
874e8e1d468SKent Overstreet 		return ERR_PTR(-ENOSPC);
875cafe5635SKent Overstreet 
876e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
877e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
878e8e1d468SKent Overstreet 			return b;
879cafe5635SKent Overstreet 
880e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
881e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), true))
882e8e1d468SKent Overstreet 			return b;
883e8e1d468SKent Overstreet 
884e8e1d468SKent Overstreet 	return ERR_PTR(-ENOMEM);
885cafe5635SKent Overstreet }
886cafe5635SKent Overstreet 
887cafe5635SKent Overstreet /*
888cafe5635SKent Overstreet  * We can only have one thread cannibalizing other cached btree nodes at a time,
889cafe5635SKent Overstreet  * or we'll deadlock. We use an open coded mutex to ensure that, which a
890cafe5635SKent Overstreet  * cannibalize_bucket() will take. This means every time we unlock the root of
891cafe5635SKent Overstreet  * the btree, we need to release this lock if we have it held.
892cafe5635SKent Overstreet  */
893df8e8970SKent Overstreet static void bch_cannibalize_unlock(struct cache_set *c)
894cafe5635SKent Overstreet {
895e8e1d468SKent Overstreet 	if (c->try_harder == current) {
896169ef1cfSKent Overstreet 		bch_time_stats_update(&c->try_harder_time, c->try_harder_start);
897cafe5635SKent Overstreet 		c->try_harder = NULL;
898e8e1d468SKent Overstreet 		wake_up(&c->try_wait);
899cafe5635SKent Overstreet 	}
900cafe5635SKent Overstreet }
901cafe5635SKent Overstreet 
902e8e1d468SKent Overstreet static struct btree *mca_alloc(struct cache_set *c, struct bkey *k, int level)
903cafe5635SKent Overstreet {
904cafe5635SKent Overstreet 	struct btree *b;
905cafe5635SKent Overstreet 
906e8e1d468SKent Overstreet 	BUG_ON(current->bio_list);
907e8e1d468SKent Overstreet 
908cafe5635SKent Overstreet 	lockdep_assert_held(&c->bucket_lock);
909cafe5635SKent Overstreet 
910cafe5635SKent Overstreet 	if (mca_find(c, k))
911cafe5635SKent Overstreet 		return NULL;
912cafe5635SKent Overstreet 
913cafe5635SKent Overstreet 	/* btree_free() doesn't free memory; it sticks the node on the end of
914cafe5635SKent Overstreet 	 * the list. Check if there's any freed nodes there:
915cafe5635SKent Overstreet 	 */
916cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freeable, list)
917e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
918cafe5635SKent Overstreet 			goto out;
919cafe5635SKent Overstreet 
920cafe5635SKent Overstreet 	/* We never free struct btree itself, just the memory that holds the on
921cafe5635SKent Overstreet 	 * disk node. Check the freed list before allocating a new one:
922cafe5635SKent Overstreet 	 */
923cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freed, list)
924e8e1d468SKent Overstreet 		if (!mca_reap(b, 0, false)) {
925cafe5635SKent Overstreet 			mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
926cafe5635SKent Overstreet 			if (!b->sets[0].data)
927cafe5635SKent Overstreet 				goto err;
928cafe5635SKent Overstreet 			else
929cafe5635SKent Overstreet 				goto out;
930cafe5635SKent Overstreet 		}
931cafe5635SKent Overstreet 
932cafe5635SKent Overstreet 	b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
933cafe5635SKent Overstreet 	if (!b)
934cafe5635SKent Overstreet 		goto err;
935cafe5635SKent Overstreet 
936cafe5635SKent Overstreet 	BUG_ON(!down_write_trylock(&b->lock));
937cafe5635SKent Overstreet 	if (!b->sets->data)
938cafe5635SKent Overstreet 		goto err;
939cafe5635SKent Overstreet out:
940cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
941cafe5635SKent Overstreet 
942cafe5635SKent Overstreet 	bkey_copy(&b->key, k);
943cafe5635SKent Overstreet 	list_move(&b->list, &c->btree_cache);
944cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
945cafe5635SKent Overstreet 	hlist_add_head_rcu(&b->hash, mca_hash(c, k));
946cafe5635SKent Overstreet 
947cafe5635SKent Overstreet 	lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
948cafe5635SKent Overstreet 	b->level	= level;
949d6fd3b11SKent Overstreet 	b->parent	= (void *) ~0UL;
950cafe5635SKent Overstreet 
951cafe5635SKent Overstreet 	mca_reinit(b);
952cafe5635SKent Overstreet 
953cafe5635SKent Overstreet 	return b;
954cafe5635SKent Overstreet err:
955cafe5635SKent Overstreet 	if (b)
956cafe5635SKent Overstreet 		rw_unlock(true, b);
957cafe5635SKent Overstreet 
958e8e1d468SKent Overstreet 	b = mca_cannibalize(c, k);
959cafe5635SKent Overstreet 	if (!IS_ERR(b))
960cafe5635SKent Overstreet 		goto out;
961cafe5635SKent Overstreet 
962cafe5635SKent Overstreet 	return b;
963cafe5635SKent Overstreet }
964cafe5635SKent Overstreet 
965cafe5635SKent Overstreet /**
966cafe5635SKent Overstreet  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
967cafe5635SKent Overstreet  * in from disk if necessary.
968cafe5635SKent Overstreet  *
969b54d6934SKent Overstreet  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
970cafe5635SKent Overstreet  *
971cafe5635SKent Overstreet  * The btree node will have either a read or a write lock held, depending on
972cafe5635SKent Overstreet  * level and op->lock.
973cafe5635SKent Overstreet  */
974cafe5635SKent Overstreet struct btree *bch_btree_node_get(struct cache_set *c, struct bkey *k,
975e8e1d468SKent Overstreet 				 int level, bool write)
976cafe5635SKent Overstreet {
977cafe5635SKent Overstreet 	int i = 0;
978cafe5635SKent Overstreet 	struct btree *b;
979cafe5635SKent Overstreet 
980cafe5635SKent Overstreet 	BUG_ON(level < 0);
981cafe5635SKent Overstreet retry:
982cafe5635SKent Overstreet 	b = mca_find(c, k);
983cafe5635SKent Overstreet 
984cafe5635SKent Overstreet 	if (!b) {
98557943511SKent Overstreet 		if (current->bio_list)
98657943511SKent Overstreet 			return ERR_PTR(-EAGAIN);
98757943511SKent Overstreet 
988cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
989e8e1d468SKent Overstreet 		b = mca_alloc(c, k, level);
990cafe5635SKent Overstreet 		mutex_unlock(&c->bucket_lock);
991cafe5635SKent Overstreet 
992cafe5635SKent Overstreet 		if (!b)
993cafe5635SKent Overstreet 			goto retry;
994cafe5635SKent Overstreet 		if (IS_ERR(b))
995cafe5635SKent Overstreet 			return b;
996cafe5635SKent Overstreet 
99757943511SKent Overstreet 		bch_btree_node_read(b);
998cafe5635SKent Overstreet 
999cafe5635SKent Overstreet 		if (!write)
1000cafe5635SKent Overstreet 			downgrade_write(&b->lock);
1001cafe5635SKent Overstreet 	} else {
1002cafe5635SKent Overstreet 		rw_lock(write, b, level);
1003cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
1004cafe5635SKent Overstreet 			rw_unlock(write, b);
1005cafe5635SKent Overstreet 			goto retry;
1006cafe5635SKent Overstreet 		}
1007cafe5635SKent Overstreet 		BUG_ON(b->level != level);
1008cafe5635SKent Overstreet 	}
1009cafe5635SKent Overstreet 
1010cafe5635SKent Overstreet 	b->accessed = 1;
1011cafe5635SKent Overstreet 
1012cafe5635SKent Overstreet 	for (; i <= b->nsets && b->sets[i].size; i++) {
1013cafe5635SKent Overstreet 		prefetch(b->sets[i].tree);
1014cafe5635SKent Overstreet 		prefetch(b->sets[i].data);
1015cafe5635SKent Overstreet 	}
1016cafe5635SKent Overstreet 
1017cafe5635SKent Overstreet 	for (; i <= b->nsets; i++)
1018cafe5635SKent Overstreet 		prefetch(b->sets[i].data);
1019cafe5635SKent Overstreet 
102057943511SKent Overstreet 	if (btree_node_io_error(b)) {
1021cafe5635SKent Overstreet 		rw_unlock(write, b);
102257943511SKent Overstreet 		return ERR_PTR(-EIO);
102357943511SKent Overstreet 	}
102457943511SKent Overstreet 
1025cafe5635SKent Overstreet 	BUG_ON(!b->written);
1026cafe5635SKent Overstreet 
1027cafe5635SKent Overstreet 	return b;
1028cafe5635SKent Overstreet }
1029cafe5635SKent Overstreet 
1030cafe5635SKent Overstreet static void btree_node_prefetch(struct cache_set *c, struct bkey *k, int level)
1031cafe5635SKent Overstreet {
1032cafe5635SKent Overstreet 	struct btree *b;
1033cafe5635SKent Overstreet 
1034cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1035e8e1d468SKent Overstreet 	b = mca_alloc(c, k, level);
1036cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1037cafe5635SKent Overstreet 
1038cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(b)) {
103957943511SKent Overstreet 		bch_btree_node_read(b);
1040cafe5635SKent Overstreet 		rw_unlock(true, b);
1041cafe5635SKent Overstreet 	}
1042cafe5635SKent Overstreet }
1043cafe5635SKent Overstreet 
1044cafe5635SKent Overstreet /* Btree alloc */
1045cafe5635SKent Overstreet 
1046e8e1d468SKent Overstreet static void btree_node_free(struct btree *b)
1047cafe5635SKent Overstreet {
1048cafe5635SKent Overstreet 	unsigned i;
1049cafe5635SKent Overstreet 
1050c37511b8SKent Overstreet 	trace_bcache_btree_node_free(b);
1051c37511b8SKent Overstreet 
1052cafe5635SKent Overstreet 	BUG_ON(b == b->c->root);
1053cafe5635SKent Overstreet 
1054cafe5635SKent Overstreet 	if (btree_node_dirty(b))
1055cafe5635SKent Overstreet 		btree_complete_write(b, btree_current_write(b));
1056cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty, &b->flags);
1057cafe5635SKent Overstreet 
1058cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
1059cafe5635SKent Overstreet 
1060cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
1061cafe5635SKent Overstreet 
1062cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++) {
1063cafe5635SKent Overstreet 		BUG_ON(atomic_read(&PTR_BUCKET(b->c, &b->key, i)->pin));
1064cafe5635SKent Overstreet 
1065cafe5635SKent Overstreet 		bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
1066cafe5635SKent Overstreet 			    PTR_BUCKET(b->c, &b->key, i));
1067cafe5635SKent Overstreet 	}
1068cafe5635SKent Overstreet 
1069cafe5635SKent Overstreet 	bch_bucket_free(b->c, &b->key);
1070cafe5635SKent Overstreet 	mca_bucket_free(b);
1071cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
1072cafe5635SKent Overstreet }
1073cafe5635SKent Overstreet 
1074bc9389eeSKent Overstreet struct btree *bch_btree_node_alloc(struct cache_set *c, int level, bool wait)
1075cafe5635SKent Overstreet {
1076cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
1077cafe5635SKent Overstreet 	struct btree *b = ERR_PTR(-EAGAIN);
1078cafe5635SKent Overstreet 
1079cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1080cafe5635SKent Overstreet retry:
1081*78365411SKent Overstreet 	if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, wait))
1082cafe5635SKent Overstreet 		goto err;
1083cafe5635SKent Overstreet 
10843a3b6a4eSKent Overstreet 	bkey_put(c, &k.key);
1085cafe5635SKent Overstreet 	SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1086cafe5635SKent Overstreet 
1087e8e1d468SKent Overstreet 	b = mca_alloc(c, &k.key, level);
1088cafe5635SKent Overstreet 	if (IS_ERR(b))
1089cafe5635SKent Overstreet 		goto err_free;
1090cafe5635SKent Overstreet 
1091cafe5635SKent Overstreet 	if (!b) {
1092b1a67b0fSKent Overstreet 		cache_bug(c,
1093b1a67b0fSKent Overstreet 			"Tried to allocate bucket that was in btree cache");
1094cafe5635SKent Overstreet 		goto retry;
1095cafe5635SKent Overstreet 	}
1096cafe5635SKent Overstreet 
1097cafe5635SKent Overstreet 	b->accessed = 1;
1098cafe5635SKent Overstreet 	bch_bset_init_next(b);
1099cafe5635SKent Overstreet 
1100cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1101c37511b8SKent Overstreet 
1102c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc(b);
1103cafe5635SKent Overstreet 	return b;
1104cafe5635SKent Overstreet err_free:
1105cafe5635SKent Overstreet 	bch_bucket_free(c, &k.key);
1106cafe5635SKent Overstreet err:
1107cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1108c37511b8SKent Overstreet 
1109c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc_fail(b);
1110cafe5635SKent Overstreet 	return b;
1111cafe5635SKent Overstreet }
1112cafe5635SKent Overstreet 
1113bc9389eeSKent Overstreet static struct btree *btree_node_alloc_replacement(struct btree *b, bool wait)
1114cafe5635SKent Overstreet {
1115bc9389eeSKent Overstreet 	struct btree *n = bch_btree_node_alloc(b->c, b->level, wait);
1116cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(n))
1117cafe5635SKent Overstreet 		bch_btree_sort_into(b, n);
1118cafe5635SKent Overstreet 
1119cafe5635SKent Overstreet 	return n;
1120cafe5635SKent Overstreet }
1121cafe5635SKent Overstreet 
11228835c123SKent Overstreet static void make_btree_freeing_key(struct btree *b, struct bkey *k)
11238835c123SKent Overstreet {
11248835c123SKent Overstreet 	unsigned i;
11258835c123SKent Overstreet 
11268835c123SKent Overstreet 	bkey_copy(k, &b->key);
11278835c123SKent Overstreet 	bkey_copy_key(k, &ZERO_KEY);
11288835c123SKent Overstreet 
11298835c123SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
11308835c123SKent Overstreet 		uint8_t g = PTR_BUCKET(b->c, k, i)->gen + 1;
11318835c123SKent Overstreet 
11328835c123SKent Overstreet 		SET_PTR_GEN(k, i, g);
11338835c123SKent Overstreet 	}
11348835c123SKent Overstreet 
11358835c123SKent Overstreet 	atomic_inc(&b->c->prio_blocked);
11368835c123SKent Overstreet }
11378835c123SKent Overstreet 
1138*78365411SKent Overstreet static int btree_check_reserve(struct btree *b, struct btree_op *op)
1139*78365411SKent Overstreet {
1140*78365411SKent Overstreet 	struct cache_set *c = b->c;
1141*78365411SKent Overstreet 	struct cache *ca;
1142*78365411SKent Overstreet 	unsigned i, reserve = c->root->level * 2 + 1;
1143*78365411SKent Overstreet 	int ret = 0;
1144*78365411SKent Overstreet 
1145*78365411SKent Overstreet 	mutex_lock(&c->bucket_lock);
1146*78365411SKent Overstreet 
1147*78365411SKent Overstreet 	for_each_cache(ca, c, i)
1148*78365411SKent Overstreet 		if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
1149*78365411SKent Overstreet 			if (op)
1150*78365411SKent Overstreet 				prepare_to_wait(&c->bucket_wait, &op->wait,
1151*78365411SKent Overstreet 						TASK_UNINTERRUPTIBLE);
1152*78365411SKent Overstreet 			ret = -EINTR;
1153*78365411SKent Overstreet 			break;
1154*78365411SKent Overstreet 		}
1155*78365411SKent Overstreet 
1156*78365411SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1157*78365411SKent Overstreet 	return ret;
1158*78365411SKent Overstreet }
1159*78365411SKent Overstreet 
1160cafe5635SKent Overstreet /* Garbage collection */
1161cafe5635SKent Overstreet 
1162cafe5635SKent Overstreet uint8_t __bch_btree_mark_key(struct cache_set *c, int level, struct bkey *k)
1163cafe5635SKent Overstreet {
1164cafe5635SKent Overstreet 	uint8_t stale = 0;
1165cafe5635SKent Overstreet 	unsigned i;
1166cafe5635SKent Overstreet 	struct bucket *g;
1167cafe5635SKent Overstreet 
1168cafe5635SKent Overstreet 	/*
1169cafe5635SKent Overstreet 	 * ptr_invalid() can't return true for the keys that mark btree nodes as
1170cafe5635SKent Overstreet 	 * freed, but since ptr_bad() returns true we'll never actually use them
1171cafe5635SKent Overstreet 	 * for anything and thus we don't want mark their pointers here
1172cafe5635SKent Overstreet 	 */
1173cafe5635SKent Overstreet 	if (!bkey_cmp(k, &ZERO_KEY))
1174cafe5635SKent Overstreet 		return stale;
1175cafe5635SKent Overstreet 
1176cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
1177cafe5635SKent Overstreet 		if (!ptr_available(c, k, i))
1178cafe5635SKent Overstreet 			continue;
1179cafe5635SKent Overstreet 
1180cafe5635SKent Overstreet 		g = PTR_BUCKET(c, k, i);
1181cafe5635SKent Overstreet 
1182cafe5635SKent Overstreet 		if (gen_after(g->gc_gen, PTR_GEN(k, i)))
1183cafe5635SKent Overstreet 			g->gc_gen = PTR_GEN(k, i);
1184cafe5635SKent Overstreet 
1185cafe5635SKent Overstreet 		if (ptr_stale(c, k, i)) {
1186cafe5635SKent Overstreet 			stale = max(stale, ptr_stale(c, k, i));
1187cafe5635SKent Overstreet 			continue;
1188cafe5635SKent Overstreet 		}
1189cafe5635SKent Overstreet 
1190cafe5635SKent Overstreet 		cache_bug_on(GC_MARK(g) &&
1191cafe5635SKent Overstreet 			     (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1192cafe5635SKent Overstreet 			     c, "inconsistent ptrs: mark = %llu, level = %i",
1193cafe5635SKent Overstreet 			     GC_MARK(g), level);
1194cafe5635SKent Overstreet 
1195cafe5635SKent Overstreet 		if (level)
1196cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_METADATA);
1197cafe5635SKent Overstreet 		else if (KEY_DIRTY(k))
1198cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_DIRTY);
1199cafe5635SKent Overstreet 
1200cafe5635SKent Overstreet 		/* guard against overflow */
1201cafe5635SKent Overstreet 		SET_GC_SECTORS_USED(g, min_t(unsigned,
1202cafe5635SKent Overstreet 					     GC_SECTORS_USED(g) + KEY_SIZE(k),
1203cafe5635SKent Overstreet 					     (1 << 14) - 1));
1204cafe5635SKent Overstreet 
1205cafe5635SKent Overstreet 		BUG_ON(!GC_SECTORS_USED(g));
1206cafe5635SKent Overstreet 	}
1207cafe5635SKent Overstreet 
1208cafe5635SKent Overstreet 	return stale;
1209cafe5635SKent Overstreet }
1210cafe5635SKent Overstreet 
1211cafe5635SKent Overstreet #define btree_mark_key(b, k)	__bch_btree_mark_key(b->c, b->level, k)
1212cafe5635SKent Overstreet 
1213a1f0358bSKent Overstreet static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1214cafe5635SKent Overstreet {
1215cafe5635SKent Overstreet 	uint8_t stale = 0;
1216a1f0358bSKent Overstreet 	unsigned keys = 0, good_keys = 0;
1217cafe5635SKent Overstreet 	struct bkey *k;
1218cafe5635SKent Overstreet 	struct btree_iter iter;
1219cafe5635SKent Overstreet 	struct bset_tree *t;
1220cafe5635SKent Overstreet 
1221cafe5635SKent Overstreet 	gc->nodes++;
1222cafe5635SKent Overstreet 
1223cafe5635SKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1224cafe5635SKent Overstreet 		stale = max(stale, btree_mark_key(b, k));
1225a1f0358bSKent Overstreet 		keys++;
1226cafe5635SKent Overstreet 
1227cafe5635SKent Overstreet 		if (bch_ptr_bad(b, k))
1228cafe5635SKent Overstreet 			continue;
1229cafe5635SKent Overstreet 
1230cafe5635SKent Overstreet 		gc->key_bytes += bkey_u64s(k);
1231cafe5635SKent Overstreet 		gc->nkeys++;
1232a1f0358bSKent Overstreet 		good_keys++;
1233cafe5635SKent Overstreet 
1234cafe5635SKent Overstreet 		gc->data += KEY_SIZE(k);
1235cafe5635SKent Overstreet 	}
1236cafe5635SKent Overstreet 
1237cafe5635SKent Overstreet 	for (t = b->sets; t <= &b->sets[b->nsets]; t++)
1238cafe5635SKent Overstreet 		btree_bug_on(t->size &&
1239cafe5635SKent Overstreet 			     bset_written(b, t) &&
1240cafe5635SKent Overstreet 			     bkey_cmp(&b->key, &t->end) < 0,
1241cafe5635SKent Overstreet 			     b, "found short btree key in gc");
1242cafe5635SKent Overstreet 
1243a1f0358bSKent Overstreet 	if (b->c->gc_always_rewrite)
1244a1f0358bSKent Overstreet 		return true;
1245a1f0358bSKent Overstreet 
1246a1f0358bSKent Overstreet 	if (stale > 10)
1247a1f0358bSKent Overstreet 		return true;
1248a1f0358bSKent Overstreet 
1249a1f0358bSKent Overstreet 	if ((keys - good_keys) * 2 > keys)
1250a1f0358bSKent Overstreet 		return true;
1251a1f0358bSKent Overstreet 
1252a1f0358bSKent Overstreet 	return false;
1253cafe5635SKent Overstreet }
1254cafe5635SKent Overstreet 
1255a1f0358bSKent Overstreet #define GC_MERGE_NODES	4U
1256cafe5635SKent Overstreet 
1257cafe5635SKent Overstreet struct gc_merge_info {
1258cafe5635SKent Overstreet 	struct btree	*b;
1259cafe5635SKent Overstreet 	unsigned	keys;
1260cafe5635SKent Overstreet };
1261cafe5635SKent Overstreet 
1262a1f0358bSKent Overstreet static int bch_btree_insert_node(struct btree *, struct btree_op *,
1263a1f0358bSKent Overstreet 				 struct keylist *, atomic_t *, struct bkey *);
1264a1f0358bSKent Overstreet 
1265a1f0358bSKent Overstreet static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
1266a1f0358bSKent Overstreet 			     struct keylist *keylist, struct gc_stat *gc,
1267e8e1d468SKent Overstreet 			     struct gc_merge_info *r)
1268cafe5635SKent Overstreet {
1269a1f0358bSKent Overstreet 	unsigned i, nodes = 0, keys = 0, blocks;
1270a1f0358bSKent Overstreet 	struct btree *new_nodes[GC_MERGE_NODES];
1271b54d6934SKent Overstreet 	struct closure cl;
1272a1f0358bSKent Overstreet 	struct bkey *k;
1273b54d6934SKent Overstreet 
1274a1f0358bSKent Overstreet 	memset(new_nodes, 0, sizeof(new_nodes));
1275b54d6934SKent Overstreet 	closure_init_stack(&cl);
1276cafe5635SKent Overstreet 
1277a1f0358bSKent Overstreet 	while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1278cafe5635SKent Overstreet 		keys += r[nodes++].keys;
1279cafe5635SKent Overstreet 
1280cafe5635SKent Overstreet 	blocks = btree_default_blocks(b->c) * 2 / 3;
1281cafe5635SKent Overstreet 
1282cafe5635SKent Overstreet 	if (nodes < 2 ||
1283cafe5635SKent Overstreet 	    __set_blocks(b->sets[0].data, keys, b->c) > blocks * (nodes - 1))
1284a1f0358bSKent Overstreet 		return 0;
1285cafe5635SKent Overstreet 
1286a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1287bc9389eeSKent Overstreet 		new_nodes[i] = btree_node_alloc_replacement(r[i].b, false);
1288a1f0358bSKent Overstreet 		if (IS_ERR_OR_NULL(new_nodes[i]))
1289a1f0358bSKent Overstreet 			goto out_nocoalesce;
1290cafe5635SKent Overstreet 	}
1291cafe5635SKent Overstreet 
1292cafe5635SKent Overstreet 	for (i = nodes - 1; i > 0; --i) {
1293a1f0358bSKent Overstreet 		struct bset *n1 = new_nodes[i]->sets->data;
1294a1f0358bSKent Overstreet 		struct bset *n2 = new_nodes[i - 1]->sets->data;
1295cafe5635SKent Overstreet 		struct bkey *k, *last = NULL;
1296cafe5635SKent Overstreet 
1297cafe5635SKent Overstreet 		keys = 0;
1298cafe5635SKent Overstreet 
1299a1f0358bSKent Overstreet 		if (i > 1) {
1300cafe5635SKent Overstreet 			for (k = n2->start;
1301cafe5635SKent Overstreet 			     k < end(n2);
1302cafe5635SKent Overstreet 			     k = bkey_next(k)) {
1303cafe5635SKent Overstreet 				if (__set_blocks(n1, n1->keys + keys +
1304cafe5635SKent Overstreet 						 bkey_u64s(k), b->c) > blocks)
1305cafe5635SKent Overstreet 					break;
1306cafe5635SKent Overstreet 
1307cafe5635SKent Overstreet 				last = k;
1308cafe5635SKent Overstreet 				keys += bkey_u64s(k);
1309cafe5635SKent Overstreet 			}
1310a1f0358bSKent Overstreet 		} else {
1311a1f0358bSKent Overstreet 			/*
1312a1f0358bSKent Overstreet 			 * Last node we're not getting rid of - we're getting
1313a1f0358bSKent Overstreet 			 * rid of the node at r[0]. Have to try and fit all of
1314a1f0358bSKent Overstreet 			 * the remaining keys into this node; we can't ensure
1315a1f0358bSKent Overstreet 			 * they will always fit due to rounding and variable
1316a1f0358bSKent Overstreet 			 * length keys (shouldn't be possible in practice,
1317a1f0358bSKent Overstreet 			 * though)
1318a1f0358bSKent Overstreet 			 */
1319a1f0358bSKent Overstreet 			if (__set_blocks(n1, n1->keys + n2->keys,
1320a1f0358bSKent Overstreet 					 b->c) > btree_blocks(new_nodes[i]))
1321a1f0358bSKent Overstreet 				goto out_nocoalesce;
1322a1f0358bSKent Overstreet 
1323a1f0358bSKent Overstreet 			keys = n2->keys;
1324a1f0358bSKent Overstreet 			/* Take the key of the node we're getting rid of */
1325a1f0358bSKent Overstreet 			last = &r->b->key;
1326a1f0358bSKent Overstreet 		}
1327cafe5635SKent Overstreet 
1328cafe5635SKent Overstreet 		BUG_ON(__set_blocks(n1, n1->keys + keys,
1329a1f0358bSKent Overstreet 				    b->c) > btree_blocks(new_nodes[i]));
1330cafe5635SKent Overstreet 
1331a1f0358bSKent Overstreet 		if (last)
1332a1f0358bSKent Overstreet 			bkey_copy_key(&new_nodes[i]->key, last);
1333cafe5635SKent Overstreet 
1334cafe5635SKent Overstreet 		memcpy(end(n1),
1335cafe5635SKent Overstreet 		       n2->start,
1336cafe5635SKent Overstreet 		       (void *) node(n2, keys) - (void *) n2->start);
1337cafe5635SKent Overstreet 
1338cafe5635SKent Overstreet 		n1->keys += keys;
1339a1f0358bSKent Overstreet 		r[i].keys = n1->keys;
1340cafe5635SKent Overstreet 
1341cafe5635SKent Overstreet 		memmove(n2->start,
1342cafe5635SKent Overstreet 			node(n2, keys),
1343cafe5635SKent Overstreet 			(void *) end(n2) - (void *) node(n2, keys));
1344cafe5635SKent Overstreet 
1345cafe5635SKent Overstreet 		n2->keys -= keys;
1346cafe5635SKent Overstreet 
1347a1f0358bSKent Overstreet 		if (bch_keylist_realloc(keylist,
1348a1f0358bSKent Overstreet 					KEY_PTRS(&new_nodes[i]->key), b->c))
1349a1f0358bSKent Overstreet 			goto out_nocoalesce;
1350a1f0358bSKent Overstreet 
1351a1f0358bSKent Overstreet 		bch_btree_node_write(new_nodes[i], &cl);
1352a1f0358bSKent Overstreet 		bch_keylist_add(keylist, &new_nodes[i]->key);
1353cafe5635SKent Overstreet 	}
1354cafe5635SKent Overstreet 
1355a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1356a1f0358bSKent Overstreet 		if (bch_keylist_realloc(keylist, KEY_PTRS(&r[i].b->key), b->c))
1357a1f0358bSKent Overstreet 			goto out_nocoalesce;
1358a1f0358bSKent Overstreet 
1359a1f0358bSKent Overstreet 		make_btree_freeing_key(r[i].b, keylist->top);
1360a1f0358bSKent Overstreet 		bch_keylist_push(keylist);
1361a1f0358bSKent Overstreet 	}
1362a1f0358bSKent Overstreet 
1363a1f0358bSKent Overstreet 	/* We emptied out this node */
1364a1f0358bSKent Overstreet 	BUG_ON(new_nodes[0]->sets->data->keys);
1365a1f0358bSKent Overstreet 	btree_node_free(new_nodes[0]);
1366a1f0358bSKent Overstreet 	rw_unlock(true, new_nodes[0]);
1367a1f0358bSKent Overstreet 
1368a1f0358bSKent Overstreet 	closure_sync(&cl);
1369a1f0358bSKent Overstreet 
1370a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1371a1f0358bSKent Overstreet 		btree_node_free(r[i].b);
1372a1f0358bSKent Overstreet 		rw_unlock(true, r[i].b);
1373a1f0358bSKent Overstreet 
1374a1f0358bSKent Overstreet 		r[i].b = new_nodes[i];
1375a1f0358bSKent Overstreet 	}
1376a1f0358bSKent Overstreet 
1377a1f0358bSKent Overstreet 	bch_btree_insert_node(b, op, keylist, NULL, NULL);
1378a1f0358bSKent Overstreet 	BUG_ON(!bch_keylist_empty(keylist));
1379a1f0358bSKent Overstreet 
1380a1f0358bSKent Overstreet 	memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1381a1f0358bSKent Overstreet 	r[nodes - 1].b = ERR_PTR(-EINTR);
1382cafe5635SKent Overstreet 
1383c37511b8SKent Overstreet 	trace_bcache_btree_gc_coalesce(nodes);
1384cafe5635SKent Overstreet 	gc->nodes--;
1385cafe5635SKent Overstreet 
1386a1f0358bSKent Overstreet 	/* Invalidated our iterator */
1387a1f0358bSKent Overstreet 	return -EINTR;
1388a1f0358bSKent Overstreet 
1389a1f0358bSKent Overstreet out_nocoalesce:
1390a1f0358bSKent Overstreet 	closure_sync(&cl);
1391a1f0358bSKent Overstreet 
1392a1f0358bSKent Overstreet 	while ((k = bch_keylist_pop(keylist)))
1393a1f0358bSKent Overstreet 		if (!bkey_cmp(k, &ZERO_KEY))
1394a1f0358bSKent Overstreet 			atomic_dec(&b->c->prio_blocked);
1395a1f0358bSKent Overstreet 
1396a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++)
1397a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(new_nodes[i])) {
1398a1f0358bSKent Overstreet 			btree_node_free(new_nodes[i]);
1399a1f0358bSKent Overstreet 			rw_unlock(true, new_nodes[i]);
1400a1f0358bSKent Overstreet 		}
1401a1f0358bSKent Overstreet 	return 0;
1402a1f0358bSKent Overstreet }
1403a1f0358bSKent Overstreet 
1404a1f0358bSKent Overstreet static unsigned btree_gc_count_keys(struct btree *b)
1405a1f0358bSKent Overstreet {
1406a1f0358bSKent Overstreet 	struct bkey *k;
1407a1f0358bSKent Overstreet 	struct btree_iter iter;
1408a1f0358bSKent Overstreet 	unsigned ret = 0;
1409a1f0358bSKent Overstreet 
1410a1f0358bSKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_bad)
1411a1f0358bSKent Overstreet 		ret += bkey_u64s(k);
1412a1f0358bSKent Overstreet 
1413a1f0358bSKent Overstreet 	return ret;
1414cafe5635SKent Overstreet }
1415cafe5635SKent Overstreet 
1416cafe5635SKent Overstreet static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1417cafe5635SKent Overstreet 			    struct closure *writes, struct gc_stat *gc)
1418cafe5635SKent Overstreet {
1419cafe5635SKent Overstreet 	unsigned i;
1420a1f0358bSKent Overstreet 	int ret = 0;
1421a1f0358bSKent Overstreet 	bool should_rewrite;
1422a1f0358bSKent Overstreet 	struct btree *n;
1423a1f0358bSKent Overstreet 	struct bkey *k;
1424a1f0358bSKent Overstreet 	struct keylist keys;
1425a1f0358bSKent Overstreet 	struct btree_iter iter;
1426cafe5635SKent Overstreet 	struct gc_merge_info r[GC_MERGE_NODES];
1427a1f0358bSKent Overstreet 	struct gc_merge_info *last = r + GC_MERGE_NODES - 1;
1428cafe5635SKent Overstreet 
1429a1f0358bSKent Overstreet 	bch_keylist_init(&keys);
1430a1f0358bSKent Overstreet 	bch_btree_iter_init(b, &iter, &b->c->gc_done);
1431cafe5635SKent Overstreet 
1432a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1433a1f0358bSKent Overstreet 		r[i].b = ERR_PTR(-EINTR);
1434cafe5635SKent Overstreet 
1435a1f0358bSKent Overstreet 	while (1) {
1436a1f0358bSKent Overstreet 		k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad);
1437a1f0358bSKent Overstreet 		if (k) {
1438a1f0358bSKent Overstreet 			r->b = bch_btree_node_get(b->c, k, b->level - 1, true);
1439cafe5635SKent Overstreet 			if (IS_ERR(r->b)) {
1440cafe5635SKent Overstreet 				ret = PTR_ERR(r->b);
1441cafe5635SKent Overstreet 				break;
1442cafe5635SKent Overstreet 			}
1443cafe5635SKent Overstreet 
1444a1f0358bSKent Overstreet 			r->keys = btree_gc_count_keys(r->b);
1445cafe5635SKent Overstreet 
1446a1f0358bSKent Overstreet 			ret = btree_gc_coalesce(b, op, &keys, gc, r);
1447a1f0358bSKent Overstreet 			if (ret)
1448cafe5635SKent Overstreet 				break;
1449cafe5635SKent Overstreet 		}
1450cafe5635SKent Overstreet 
1451a1f0358bSKent Overstreet 		if (!last->b)
1452a1f0358bSKent Overstreet 			break;
1453cafe5635SKent Overstreet 
1454a1f0358bSKent Overstreet 		if (!IS_ERR(last->b)) {
1455a1f0358bSKent Overstreet 			should_rewrite = btree_gc_mark_node(last->b, gc);
1456*78365411SKent Overstreet 			if (should_rewrite &&
1457*78365411SKent Overstreet 			    !btree_check_reserve(b, NULL)) {
1458bc9389eeSKent Overstreet 				n = btree_node_alloc_replacement(last->b,
1459bc9389eeSKent Overstreet 								 false);
1460cafe5635SKent Overstreet 
1461a1f0358bSKent Overstreet 				if (!IS_ERR_OR_NULL(n)) {
1462a1f0358bSKent Overstreet 					bch_btree_node_write_sync(n);
1463a1f0358bSKent Overstreet 					bch_keylist_add(&keys, &n->key);
1464cafe5635SKent Overstreet 
1465a1f0358bSKent Overstreet 					make_btree_freeing_key(last->b,
1466a1f0358bSKent Overstreet 							       keys.top);
1467a1f0358bSKent Overstreet 					bch_keylist_push(&keys);
1468cafe5635SKent Overstreet 
1469a1f0358bSKent Overstreet 					btree_node_free(last->b);
1470a1f0358bSKent Overstreet 
1471a1f0358bSKent Overstreet 					bch_btree_insert_node(b, op, &keys,
1472a1f0358bSKent Overstreet 							      NULL, NULL);
1473a1f0358bSKent Overstreet 					BUG_ON(!bch_keylist_empty(&keys));
1474a1f0358bSKent Overstreet 
1475a1f0358bSKent Overstreet 					rw_unlock(true, last->b);
1476a1f0358bSKent Overstreet 					last->b = n;
1477a1f0358bSKent Overstreet 
1478a1f0358bSKent Overstreet 					/* Invalidated our iterator */
1479a1f0358bSKent Overstreet 					ret = -EINTR;
1480a1f0358bSKent Overstreet 					break;
1481a1f0358bSKent Overstreet 				}
1482a1f0358bSKent Overstreet 			}
1483a1f0358bSKent Overstreet 
1484a1f0358bSKent Overstreet 			if (last->b->level) {
1485a1f0358bSKent Overstreet 				ret = btree_gc_recurse(last->b, op, writes, gc);
1486a1f0358bSKent Overstreet 				if (ret)
1487a1f0358bSKent Overstreet 					break;
1488a1f0358bSKent Overstreet 			}
1489a1f0358bSKent Overstreet 
1490a1f0358bSKent Overstreet 			bkey_copy_key(&b->c->gc_done, &last->b->key);
1491a1f0358bSKent Overstreet 
1492a1f0358bSKent Overstreet 			/*
1493a1f0358bSKent Overstreet 			 * Must flush leaf nodes before gc ends, since replace
1494a1f0358bSKent Overstreet 			 * operations aren't journalled
1495cafe5635SKent Overstreet 			 */
1496a1f0358bSKent Overstreet 			if (btree_node_dirty(last->b))
1497a1f0358bSKent Overstreet 				bch_btree_node_write(last->b, writes);
1498a1f0358bSKent Overstreet 			rw_unlock(true, last->b);
1499a1f0358bSKent Overstreet 		}
1500a1f0358bSKent Overstreet 
1501a1f0358bSKent Overstreet 		memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1502a1f0358bSKent Overstreet 		r->b = NULL;
1503a1f0358bSKent Overstreet 
1504cafe5635SKent Overstreet 		if (need_resched()) {
1505cafe5635SKent Overstreet 			ret = -EAGAIN;
1506cafe5635SKent Overstreet 			break;
1507cafe5635SKent Overstreet 		}
1508cafe5635SKent Overstreet 	}
1509cafe5635SKent Overstreet 
1510a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1511a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(r[i].b)) {
1512a1f0358bSKent Overstreet 			if (btree_node_dirty(r[i].b))
1513a1f0358bSKent Overstreet 				bch_btree_node_write(r[i].b, writes);
1514a1f0358bSKent Overstreet 			rw_unlock(true, r[i].b);
1515a1f0358bSKent Overstreet 		}
1516cafe5635SKent Overstreet 
1517a1f0358bSKent Overstreet 	bch_keylist_free(&keys);
1518cafe5635SKent Overstreet 
1519cafe5635SKent Overstreet 	return ret;
1520cafe5635SKent Overstreet }
1521cafe5635SKent Overstreet 
1522cafe5635SKent Overstreet static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1523cafe5635SKent Overstreet 			     struct closure *writes, struct gc_stat *gc)
1524cafe5635SKent Overstreet {
1525cafe5635SKent Overstreet 	struct btree *n = NULL;
1526a1f0358bSKent Overstreet 	int ret = 0;
1527a1f0358bSKent Overstreet 	bool should_rewrite;
1528cafe5635SKent Overstreet 
1529a1f0358bSKent Overstreet 	should_rewrite = btree_gc_mark_node(b, gc);
1530a1f0358bSKent Overstreet 	if (should_rewrite) {
1531bc9389eeSKent Overstreet 		n = btree_node_alloc_replacement(b, false);
1532cafe5635SKent Overstreet 
1533cafe5635SKent Overstreet 		if (!IS_ERR_OR_NULL(n)) {
1534a1f0358bSKent Overstreet 			bch_btree_node_write_sync(n);
1535a1f0358bSKent Overstreet 			bch_btree_set_root(n);
1536a1f0358bSKent Overstreet 			btree_node_free(b);
1537a1f0358bSKent Overstreet 			rw_unlock(true, n);
1538a1f0358bSKent Overstreet 
1539a1f0358bSKent Overstreet 			return -EINTR;
1540cafe5635SKent Overstreet 		}
1541a1f0358bSKent Overstreet 	}
1542a1f0358bSKent Overstreet 
1543a1f0358bSKent Overstreet 	if (b->level) {
1544a1f0358bSKent Overstreet 		ret = btree_gc_recurse(b, op, writes, gc);
1545a1f0358bSKent Overstreet 		if (ret)
1546a1f0358bSKent Overstreet 			return ret;
1547a1f0358bSKent Overstreet 	}
1548a1f0358bSKent Overstreet 
1549a1f0358bSKent Overstreet 	bkey_copy_key(&b->c->gc_done, &b->key);
1550cafe5635SKent Overstreet 
1551cafe5635SKent Overstreet 	return ret;
1552cafe5635SKent Overstreet }
1553cafe5635SKent Overstreet 
1554cafe5635SKent Overstreet static void btree_gc_start(struct cache_set *c)
1555cafe5635SKent Overstreet {
1556cafe5635SKent Overstreet 	struct cache *ca;
1557cafe5635SKent Overstreet 	struct bucket *b;
1558cafe5635SKent Overstreet 	unsigned i;
1559cafe5635SKent Overstreet 
1560cafe5635SKent Overstreet 	if (!c->gc_mark_valid)
1561cafe5635SKent Overstreet 		return;
1562cafe5635SKent Overstreet 
1563cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1564cafe5635SKent Overstreet 
1565cafe5635SKent Overstreet 	c->gc_mark_valid = 0;
1566cafe5635SKent Overstreet 	c->gc_done = ZERO_KEY;
1567cafe5635SKent Overstreet 
1568cafe5635SKent Overstreet 	for_each_cache(ca, c, i)
1569cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1570cafe5635SKent Overstreet 			b->gc_gen = b->gen;
157129ebf465SKent Overstreet 			if (!atomic_read(&b->pin)) {
1572cafe5635SKent Overstreet 				SET_GC_MARK(b, GC_MARK_RECLAIMABLE);
157329ebf465SKent Overstreet 				SET_GC_SECTORS_USED(b, 0);
157429ebf465SKent Overstreet 			}
1575cafe5635SKent Overstreet 		}
1576cafe5635SKent Overstreet 
1577cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1578cafe5635SKent Overstreet }
1579cafe5635SKent Overstreet 
1580cafe5635SKent Overstreet size_t bch_btree_gc_finish(struct cache_set *c)
1581cafe5635SKent Overstreet {
1582cafe5635SKent Overstreet 	size_t available = 0;
1583cafe5635SKent Overstreet 	struct bucket *b;
1584cafe5635SKent Overstreet 	struct cache *ca;
1585cafe5635SKent Overstreet 	unsigned i;
1586cafe5635SKent Overstreet 
1587cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1588cafe5635SKent Overstreet 
1589cafe5635SKent Overstreet 	set_gc_sectors(c);
1590cafe5635SKent Overstreet 	c->gc_mark_valid = 1;
1591cafe5635SKent Overstreet 	c->need_gc	= 0;
1592cafe5635SKent Overstreet 
1593cafe5635SKent Overstreet 	if (c->root)
1594cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(&c->root->key); i++)
1595cafe5635SKent Overstreet 			SET_GC_MARK(PTR_BUCKET(c, &c->root->key, i),
1596cafe5635SKent Overstreet 				    GC_MARK_METADATA);
1597cafe5635SKent Overstreet 
1598cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1599cafe5635SKent Overstreet 		SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1600cafe5635SKent Overstreet 			    GC_MARK_METADATA);
1601cafe5635SKent Overstreet 
1602bf0a628aSNicholas Swenson 	/* don't reclaim buckets to which writeback keys point */
1603bf0a628aSNicholas Swenson 	rcu_read_lock();
1604bf0a628aSNicholas Swenson 	for (i = 0; i < c->nr_uuids; i++) {
1605bf0a628aSNicholas Swenson 		struct bcache_device *d = c->devices[i];
1606bf0a628aSNicholas Swenson 		struct cached_dev *dc;
1607bf0a628aSNicholas Swenson 		struct keybuf_key *w, *n;
1608bf0a628aSNicholas Swenson 		unsigned j;
1609bf0a628aSNicholas Swenson 
1610bf0a628aSNicholas Swenson 		if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
1611bf0a628aSNicholas Swenson 			continue;
1612bf0a628aSNicholas Swenson 		dc = container_of(d, struct cached_dev, disk);
1613bf0a628aSNicholas Swenson 
1614bf0a628aSNicholas Swenson 		spin_lock(&dc->writeback_keys.lock);
1615bf0a628aSNicholas Swenson 		rbtree_postorder_for_each_entry_safe(w, n,
1616bf0a628aSNicholas Swenson 					&dc->writeback_keys.keys, node)
1617bf0a628aSNicholas Swenson 			for (j = 0; j < KEY_PTRS(&w->key); j++)
1618bf0a628aSNicholas Swenson 				SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
1619bf0a628aSNicholas Swenson 					    GC_MARK_DIRTY);
1620bf0a628aSNicholas Swenson 		spin_unlock(&dc->writeback_keys.lock);
1621bf0a628aSNicholas Swenson 	}
1622bf0a628aSNicholas Swenson 	rcu_read_unlock();
1623bf0a628aSNicholas Swenson 
1624cafe5635SKent Overstreet 	for_each_cache(ca, c, i) {
1625cafe5635SKent Overstreet 		uint64_t *i;
1626cafe5635SKent Overstreet 
1627cafe5635SKent Overstreet 		ca->invalidate_needs_gc = 0;
1628cafe5635SKent Overstreet 
1629cafe5635SKent Overstreet 		for (i = ca->sb.d; i < ca->sb.d + ca->sb.keys; i++)
1630cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1631cafe5635SKent Overstreet 
1632cafe5635SKent Overstreet 		for (i = ca->prio_buckets;
1633cafe5635SKent Overstreet 		     i < ca->prio_buckets + prio_buckets(ca) * 2; i++)
1634cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1635cafe5635SKent Overstreet 
1636cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1637cafe5635SKent Overstreet 			b->last_gc	= b->gc_gen;
1638cafe5635SKent Overstreet 			c->need_gc	= max(c->need_gc, bucket_gc_gen(b));
1639cafe5635SKent Overstreet 
1640cafe5635SKent Overstreet 			if (!atomic_read(&b->pin) &&
1641cafe5635SKent Overstreet 			    GC_MARK(b) == GC_MARK_RECLAIMABLE) {
1642cafe5635SKent Overstreet 				available++;
1643cafe5635SKent Overstreet 				if (!GC_SECTORS_USED(b))
1644cafe5635SKent Overstreet 					bch_bucket_add_unused(ca, b);
1645cafe5635SKent Overstreet 			}
1646cafe5635SKent Overstreet 		}
1647cafe5635SKent Overstreet 	}
1648cafe5635SKent Overstreet 
1649cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1650cafe5635SKent Overstreet 	return available;
1651cafe5635SKent Overstreet }
1652cafe5635SKent Overstreet 
165372a44517SKent Overstreet static void bch_btree_gc(struct cache_set *c)
1654cafe5635SKent Overstreet {
1655cafe5635SKent Overstreet 	int ret;
1656cafe5635SKent Overstreet 	unsigned long available;
1657cafe5635SKent Overstreet 	struct gc_stat stats;
1658cafe5635SKent Overstreet 	struct closure writes;
1659cafe5635SKent Overstreet 	struct btree_op op;
1660cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
166157943511SKent Overstreet 
1662c37511b8SKent Overstreet 	trace_bcache_gc_start(c);
1663cafe5635SKent Overstreet 
1664cafe5635SKent Overstreet 	memset(&stats, 0, sizeof(struct gc_stat));
1665cafe5635SKent Overstreet 	closure_init_stack(&writes);
1666b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1667cafe5635SKent Overstreet 
1668cafe5635SKent Overstreet 	btree_gc_start(c);
1669cafe5635SKent Overstreet 
1670a1f0358bSKent Overstreet 	do {
1671cafe5635SKent Overstreet 		ret = btree_root(gc_root, c, &op, &writes, &stats);
1672cafe5635SKent Overstreet 		closure_sync(&writes);
1673cafe5635SKent Overstreet 
1674a1f0358bSKent Overstreet 		if (ret && ret != -EAGAIN)
1675cafe5635SKent Overstreet 			pr_warn("gc failed!");
1676a1f0358bSKent Overstreet 	} while (ret);
1677cafe5635SKent Overstreet 
1678cafe5635SKent Overstreet 	available = bch_btree_gc_finish(c);
167957943511SKent Overstreet 	wake_up_allocators(c);
168057943511SKent Overstreet 
1681169ef1cfSKent Overstreet 	bch_time_stats_update(&c->btree_gc_time, start_time);
1682cafe5635SKent Overstreet 
1683cafe5635SKent Overstreet 	stats.key_bytes *= sizeof(uint64_t);
1684cafe5635SKent Overstreet 	stats.data	<<= 9;
1685cafe5635SKent Overstreet 	stats.in_use	= (c->nbuckets - available) * 100 / c->nbuckets;
1686cafe5635SKent Overstreet 	memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1687cafe5635SKent Overstreet 
1688c37511b8SKent Overstreet 	trace_bcache_gc_end(c);
1689cafe5635SKent Overstreet 
169072a44517SKent Overstreet 	bch_moving_gc(c);
1691cafe5635SKent Overstreet }
1692cafe5635SKent Overstreet 
169372a44517SKent Overstreet static int bch_gc_thread(void *arg)
1694cafe5635SKent Overstreet {
169572a44517SKent Overstreet 	struct cache_set *c = arg;
1696a1f0358bSKent Overstreet 	struct cache *ca;
1697a1f0358bSKent Overstreet 	unsigned i;
169872a44517SKent Overstreet 
169972a44517SKent Overstreet 	while (1) {
1700a1f0358bSKent Overstreet again:
170172a44517SKent Overstreet 		bch_btree_gc(c);
170272a44517SKent Overstreet 
170372a44517SKent Overstreet 		set_current_state(TASK_INTERRUPTIBLE);
170472a44517SKent Overstreet 		if (kthread_should_stop())
170572a44517SKent Overstreet 			break;
170672a44517SKent Overstreet 
1707a1f0358bSKent Overstreet 		mutex_lock(&c->bucket_lock);
1708a1f0358bSKent Overstreet 
1709a1f0358bSKent Overstreet 		for_each_cache(ca, c, i)
1710a1f0358bSKent Overstreet 			if (ca->invalidate_needs_gc) {
1711a1f0358bSKent Overstreet 				mutex_unlock(&c->bucket_lock);
1712a1f0358bSKent Overstreet 				set_current_state(TASK_RUNNING);
1713a1f0358bSKent Overstreet 				goto again;
1714a1f0358bSKent Overstreet 			}
1715a1f0358bSKent Overstreet 
1716a1f0358bSKent Overstreet 		mutex_unlock(&c->bucket_lock);
1717a1f0358bSKent Overstreet 
171872a44517SKent Overstreet 		try_to_freeze();
171972a44517SKent Overstreet 		schedule();
172072a44517SKent Overstreet 	}
172172a44517SKent Overstreet 
172272a44517SKent Overstreet 	return 0;
172372a44517SKent Overstreet }
172472a44517SKent Overstreet 
172572a44517SKent Overstreet int bch_gc_thread_start(struct cache_set *c)
172672a44517SKent Overstreet {
172772a44517SKent Overstreet 	c->gc_thread = kthread_create(bch_gc_thread, c, "bcache_gc");
172872a44517SKent Overstreet 	if (IS_ERR(c->gc_thread))
172972a44517SKent Overstreet 		return PTR_ERR(c->gc_thread);
173072a44517SKent Overstreet 
173172a44517SKent Overstreet 	set_task_state(c->gc_thread, TASK_INTERRUPTIBLE);
173272a44517SKent Overstreet 	return 0;
1733cafe5635SKent Overstreet }
1734cafe5635SKent Overstreet 
1735cafe5635SKent Overstreet /* Initial partial gc */
1736cafe5635SKent Overstreet 
1737cafe5635SKent Overstreet static int bch_btree_check_recurse(struct btree *b, struct btree_op *op,
1738cafe5635SKent Overstreet 				   unsigned long **seen)
1739cafe5635SKent Overstreet {
174050310164SKent Overstreet 	int ret = 0;
1741cafe5635SKent Overstreet 	unsigned i;
174250310164SKent Overstreet 	struct bkey *k, *p = NULL;
1743cafe5635SKent Overstreet 	struct bucket *g;
1744cafe5635SKent Overstreet 	struct btree_iter iter;
1745cafe5635SKent Overstreet 
1746cafe5635SKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1747cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(k); i++) {
1748cafe5635SKent Overstreet 			if (!ptr_available(b->c, k, i))
1749cafe5635SKent Overstreet 				continue;
1750cafe5635SKent Overstreet 
1751cafe5635SKent Overstreet 			g = PTR_BUCKET(b->c, k, i);
1752cafe5635SKent Overstreet 
1753cafe5635SKent Overstreet 			if (!__test_and_set_bit(PTR_BUCKET_NR(b->c, k, i),
1754cafe5635SKent Overstreet 						seen[PTR_DEV(k, i)]) ||
1755cafe5635SKent Overstreet 			    !ptr_stale(b->c, k, i)) {
1756cafe5635SKent Overstreet 				g->gen = PTR_GEN(k, i);
1757cafe5635SKent Overstreet 
1758cafe5635SKent Overstreet 				if (b->level)
1759cafe5635SKent Overstreet 					g->prio = BTREE_PRIO;
1760cafe5635SKent Overstreet 				else if (g->prio == BTREE_PRIO)
1761cafe5635SKent Overstreet 					g->prio = INITIAL_PRIO;
1762cafe5635SKent Overstreet 			}
1763cafe5635SKent Overstreet 		}
1764cafe5635SKent Overstreet 
1765cafe5635SKent Overstreet 		btree_mark_key(b, k);
1766cafe5635SKent Overstreet 	}
1767cafe5635SKent Overstreet 
1768cafe5635SKent Overstreet 	if (b->level) {
176950310164SKent Overstreet 		bch_btree_iter_init(b, &iter, NULL);
1770cafe5635SKent Overstreet 
177150310164SKent Overstreet 		do {
177250310164SKent Overstreet 			k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad);
177350310164SKent Overstreet 			if (k)
177450310164SKent Overstreet 				btree_node_prefetch(b->c, k, b->level - 1);
177550310164SKent Overstreet 
1776cafe5635SKent Overstreet 			if (p)
177750310164SKent Overstreet 				ret = btree(check_recurse, p, b, op, seen);
1778cafe5635SKent Overstreet 
177950310164SKent Overstreet 			p = k;
178050310164SKent Overstreet 		} while (p && !ret);
1781cafe5635SKent Overstreet 	}
1782cafe5635SKent Overstreet 
1783cafe5635SKent Overstreet 	return 0;
1784cafe5635SKent Overstreet }
1785cafe5635SKent Overstreet 
1786c18536a7SKent Overstreet int bch_btree_check(struct cache_set *c)
1787cafe5635SKent Overstreet {
1788cafe5635SKent Overstreet 	int ret = -ENOMEM;
1789cafe5635SKent Overstreet 	unsigned i;
1790cafe5635SKent Overstreet 	unsigned long *seen[MAX_CACHES_PER_SET];
1791c18536a7SKent Overstreet 	struct btree_op op;
1792cafe5635SKent Overstreet 
1793cafe5635SKent Overstreet 	memset(seen, 0, sizeof(seen));
1794b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1795cafe5635SKent Overstreet 
1796cafe5635SKent Overstreet 	for (i = 0; c->cache[i]; i++) {
1797cafe5635SKent Overstreet 		size_t n = DIV_ROUND_UP(c->cache[i]->sb.nbuckets, 8);
1798cafe5635SKent Overstreet 		seen[i] = kmalloc(n, GFP_KERNEL);
1799cafe5635SKent Overstreet 		if (!seen[i])
1800cafe5635SKent Overstreet 			goto err;
1801cafe5635SKent Overstreet 
1802cafe5635SKent Overstreet 		/* Disables the seen array until prio_read() uses it too */
1803cafe5635SKent Overstreet 		memset(seen[i], 0xFF, n);
1804cafe5635SKent Overstreet 	}
1805cafe5635SKent Overstreet 
1806c18536a7SKent Overstreet 	ret = btree_root(check_recurse, c, &op, seen);
1807cafe5635SKent Overstreet err:
1808cafe5635SKent Overstreet 	for (i = 0; i < MAX_CACHES_PER_SET; i++)
1809cafe5635SKent Overstreet 		kfree(seen[i]);
1810cafe5635SKent Overstreet 	return ret;
1811cafe5635SKent Overstreet }
1812cafe5635SKent Overstreet 
1813cafe5635SKent Overstreet /* Btree insertion */
1814cafe5635SKent Overstreet 
1815cafe5635SKent Overstreet static void shift_keys(struct btree *b, struct bkey *where, struct bkey *insert)
1816cafe5635SKent Overstreet {
1817cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
1818cafe5635SKent Overstreet 
1819cafe5635SKent Overstreet 	memmove((uint64_t *) where + bkey_u64s(insert),
1820cafe5635SKent Overstreet 		where,
1821cafe5635SKent Overstreet 		(void *) end(i) - (void *) where);
1822cafe5635SKent Overstreet 
1823cafe5635SKent Overstreet 	i->keys += bkey_u64s(insert);
1824cafe5635SKent Overstreet 	bkey_copy(where, insert);
1825cafe5635SKent Overstreet 	bch_bset_fix_lookup_table(b, where);
1826cafe5635SKent Overstreet }
1827cafe5635SKent Overstreet 
18281b207d80SKent Overstreet static bool fix_overlapping_extents(struct btree *b, struct bkey *insert,
1829cafe5635SKent Overstreet 				    struct btree_iter *iter,
18301b207d80SKent Overstreet 				    struct bkey *replace_key)
1831cafe5635SKent Overstreet {
1832279afbadSKent Overstreet 	void subtract_dirty(struct bkey *k, uint64_t offset, int sectors)
1833cafe5635SKent Overstreet 	{
1834279afbadSKent Overstreet 		if (KEY_DIRTY(k))
1835279afbadSKent Overstreet 			bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
1836279afbadSKent Overstreet 						     offset, -sectors);
1837cafe5635SKent Overstreet 	}
1838cafe5635SKent Overstreet 
1839279afbadSKent Overstreet 	uint64_t old_offset;
1840cafe5635SKent Overstreet 	unsigned old_size, sectors_found = 0;
1841cafe5635SKent Overstreet 
1842cafe5635SKent Overstreet 	while (1) {
1843cafe5635SKent Overstreet 		struct bkey *k = bch_btree_iter_next(iter);
1844cafe5635SKent Overstreet 		if (!k ||
1845cafe5635SKent Overstreet 		    bkey_cmp(&START_KEY(k), insert) >= 0)
1846cafe5635SKent Overstreet 			break;
1847cafe5635SKent Overstreet 
1848cafe5635SKent Overstreet 		if (bkey_cmp(k, &START_KEY(insert)) <= 0)
1849cafe5635SKent Overstreet 			continue;
1850cafe5635SKent Overstreet 
1851279afbadSKent Overstreet 		old_offset = KEY_START(k);
1852cafe5635SKent Overstreet 		old_size = KEY_SIZE(k);
1853cafe5635SKent Overstreet 
1854cafe5635SKent Overstreet 		/*
1855cafe5635SKent Overstreet 		 * We might overlap with 0 size extents; we can't skip these
1856cafe5635SKent Overstreet 		 * because if they're in the set we're inserting to we have to
1857cafe5635SKent Overstreet 		 * adjust them so they don't overlap with the key we're
18581b207d80SKent Overstreet 		 * inserting. But we don't want to check them for replace
1859cafe5635SKent Overstreet 		 * operations.
1860cafe5635SKent Overstreet 		 */
1861cafe5635SKent Overstreet 
18621b207d80SKent Overstreet 		if (replace_key && KEY_SIZE(k)) {
1863cafe5635SKent Overstreet 			/*
1864cafe5635SKent Overstreet 			 * k might have been split since we inserted/found the
1865cafe5635SKent Overstreet 			 * key we're replacing
1866cafe5635SKent Overstreet 			 */
1867cafe5635SKent Overstreet 			unsigned i;
1868cafe5635SKent Overstreet 			uint64_t offset = KEY_START(k) -
18691b207d80SKent Overstreet 				KEY_START(replace_key);
1870cafe5635SKent Overstreet 
1871cafe5635SKent Overstreet 			/* But it must be a subset of the replace key */
18721b207d80SKent Overstreet 			if (KEY_START(k) < KEY_START(replace_key) ||
18731b207d80SKent Overstreet 			    KEY_OFFSET(k) > KEY_OFFSET(replace_key))
1874cafe5635SKent Overstreet 				goto check_failed;
1875cafe5635SKent Overstreet 
1876cafe5635SKent Overstreet 			/* We didn't find a key that we were supposed to */
1877cafe5635SKent Overstreet 			if (KEY_START(k) > KEY_START(insert) + sectors_found)
1878cafe5635SKent Overstreet 				goto check_failed;
1879cafe5635SKent Overstreet 
1880d24a6e10SKent Overstreet 			if (KEY_PTRS(k) != KEY_PTRS(replace_key) ||
1881d24a6e10SKent Overstreet 			    KEY_DIRTY(k) != KEY_DIRTY(replace_key))
1882cafe5635SKent Overstreet 				goto check_failed;
1883cafe5635SKent Overstreet 
1884cafe5635SKent Overstreet 			/* skip past gen */
1885cafe5635SKent Overstreet 			offset <<= 8;
1886cafe5635SKent Overstreet 
18871b207d80SKent Overstreet 			BUG_ON(!KEY_PTRS(replace_key));
1888cafe5635SKent Overstreet 
18891b207d80SKent Overstreet 			for (i = 0; i < KEY_PTRS(replace_key); i++)
18901b207d80SKent Overstreet 				if (k->ptr[i] != replace_key->ptr[i] + offset)
1891cafe5635SKent Overstreet 					goto check_failed;
1892cafe5635SKent Overstreet 
1893cafe5635SKent Overstreet 			sectors_found = KEY_OFFSET(k) - KEY_START(insert);
1894cafe5635SKent Overstreet 		}
1895cafe5635SKent Overstreet 
1896cafe5635SKent Overstreet 		if (bkey_cmp(insert, k) < 0 &&
1897cafe5635SKent Overstreet 		    bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0) {
1898cafe5635SKent Overstreet 			/*
1899cafe5635SKent Overstreet 			 * We overlapped in the middle of an existing key: that
1900cafe5635SKent Overstreet 			 * means we have to split the old key. But we have to do
1901cafe5635SKent Overstreet 			 * slightly different things depending on whether the
1902cafe5635SKent Overstreet 			 * old key has been written out yet.
1903cafe5635SKent Overstreet 			 */
1904cafe5635SKent Overstreet 
1905cafe5635SKent Overstreet 			struct bkey *top;
1906cafe5635SKent Overstreet 
1907279afbadSKent Overstreet 			subtract_dirty(k, KEY_START(insert), KEY_SIZE(insert));
1908cafe5635SKent Overstreet 
1909cafe5635SKent Overstreet 			if (bkey_written(b, k)) {
1910cafe5635SKent Overstreet 				/*
1911cafe5635SKent Overstreet 				 * We insert a new key to cover the top of the
1912cafe5635SKent Overstreet 				 * old key, and the old key is modified in place
1913cafe5635SKent Overstreet 				 * to represent the bottom split.
1914cafe5635SKent Overstreet 				 *
1915cafe5635SKent Overstreet 				 * It's completely arbitrary whether the new key
1916cafe5635SKent Overstreet 				 * is the top or the bottom, but it has to match
1917cafe5635SKent Overstreet 				 * up with what btree_sort_fixup() does - it
1918cafe5635SKent Overstreet 				 * doesn't check for this kind of overlap, it
1919cafe5635SKent Overstreet 				 * depends on us inserting a new key for the top
1920cafe5635SKent Overstreet 				 * here.
1921cafe5635SKent Overstreet 				 */
1922cafe5635SKent Overstreet 				top = bch_bset_search(b, &b->sets[b->nsets],
1923cafe5635SKent Overstreet 						      insert);
1924cafe5635SKent Overstreet 				shift_keys(b, top, k);
1925cafe5635SKent Overstreet 			} else {
1926cafe5635SKent Overstreet 				BKEY_PADDED(key) temp;
1927cafe5635SKent Overstreet 				bkey_copy(&temp.key, k);
1928cafe5635SKent Overstreet 				shift_keys(b, k, &temp.key);
1929cafe5635SKent Overstreet 				top = bkey_next(k);
1930cafe5635SKent Overstreet 			}
1931cafe5635SKent Overstreet 
1932cafe5635SKent Overstreet 			bch_cut_front(insert, top);
1933cafe5635SKent Overstreet 			bch_cut_back(&START_KEY(insert), k);
1934cafe5635SKent Overstreet 			bch_bset_fix_invalidated_key(b, k);
1935cafe5635SKent Overstreet 			return false;
1936cafe5635SKent Overstreet 		}
1937cafe5635SKent Overstreet 
1938cafe5635SKent Overstreet 		if (bkey_cmp(insert, k) < 0) {
1939cafe5635SKent Overstreet 			bch_cut_front(insert, k);
1940cafe5635SKent Overstreet 		} else {
19411fa8455dSKent Overstreet 			if (bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0)
19421fa8455dSKent Overstreet 				old_offset = KEY_START(insert);
19431fa8455dSKent Overstreet 
1944cafe5635SKent Overstreet 			if (bkey_written(b, k) &&
1945cafe5635SKent Overstreet 			    bkey_cmp(&START_KEY(insert), &START_KEY(k)) <= 0) {
1946cafe5635SKent Overstreet 				/*
1947cafe5635SKent Overstreet 				 * Completely overwrote, so we don't have to
1948cafe5635SKent Overstreet 				 * invalidate the binary search tree
1949cafe5635SKent Overstreet 				 */
1950cafe5635SKent Overstreet 				bch_cut_front(k, k);
1951cafe5635SKent Overstreet 			} else {
1952cafe5635SKent Overstreet 				__bch_cut_back(&START_KEY(insert), k);
1953cafe5635SKent Overstreet 				bch_bset_fix_invalidated_key(b, k);
1954cafe5635SKent Overstreet 			}
1955cafe5635SKent Overstreet 		}
1956cafe5635SKent Overstreet 
1957279afbadSKent Overstreet 		subtract_dirty(k, old_offset, old_size - KEY_SIZE(k));
1958cafe5635SKent Overstreet 	}
1959cafe5635SKent Overstreet 
1960cafe5635SKent Overstreet check_failed:
19611b207d80SKent Overstreet 	if (replace_key) {
1962cafe5635SKent Overstreet 		if (!sectors_found) {
1963cafe5635SKent Overstreet 			return true;
1964cafe5635SKent Overstreet 		} else if (sectors_found < KEY_SIZE(insert)) {
1965cafe5635SKent Overstreet 			SET_KEY_OFFSET(insert, KEY_OFFSET(insert) -
1966cafe5635SKent Overstreet 				       (KEY_SIZE(insert) - sectors_found));
1967cafe5635SKent Overstreet 			SET_KEY_SIZE(insert, sectors_found);
1968cafe5635SKent Overstreet 		}
1969cafe5635SKent Overstreet 	}
1970cafe5635SKent Overstreet 
1971cafe5635SKent Overstreet 	return false;
1972cafe5635SKent Overstreet }
1973cafe5635SKent Overstreet 
1974cafe5635SKent Overstreet static bool btree_insert_key(struct btree *b, struct btree_op *op,
19751b207d80SKent Overstreet 			     struct bkey *k, struct bkey *replace_key)
1976cafe5635SKent Overstreet {
1977cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
1978cafe5635SKent Overstreet 	struct bkey *m, *prev;
197985b1492eSKent Overstreet 	unsigned status = BTREE_INSERT_STATUS_INSERT;
1980cafe5635SKent Overstreet 
1981cafe5635SKent Overstreet 	BUG_ON(bkey_cmp(k, &b->key) > 0);
1982cafe5635SKent Overstreet 	BUG_ON(b->level && !KEY_PTRS(k));
1983cafe5635SKent Overstreet 	BUG_ON(!b->level && !KEY_OFFSET(k));
1984cafe5635SKent Overstreet 
1985cafe5635SKent Overstreet 	if (!b->level) {
1986cafe5635SKent Overstreet 		struct btree_iter iter;
1987cafe5635SKent Overstreet 
1988cafe5635SKent Overstreet 		/*
1989cafe5635SKent Overstreet 		 * bset_search() returns the first key that is strictly greater
1990cafe5635SKent Overstreet 		 * than the search key - but for back merging, we want to find
19910eacac22SKent Overstreet 		 * the previous key.
1992cafe5635SKent Overstreet 		 */
1993cafe5635SKent Overstreet 		prev = NULL;
19940eacac22SKent Overstreet 		m = bch_btree_iter_init(b, &iter, PRECEDING_KEY(&START_KEY(k)));
1995cafe5635SKent Overstreet 
19961b207d80SKent Overstreet 		if (fix_overlapping_extents(b, k, &iter, replace_key)) {
19971b207d80SKent Overstreet 			op->insert_collision = true;
1998cafe5635SKent Overstreet 			return false;
19991b207d80SKent Overstreet 		}
2000cafe5635SKent Overstreet 
20011fa8455dSKent Overstreet 		if (KEY_DIRTY(k))
20021fa8455dSKent Overstreet 			bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
20031fa8455dSKent Overstreet 						     KEY_START(k), KEY_SIZE(k));
20041fa8455dSKent Overstreet 
2005cafe5635SKent Overstreet 		while (m != end(i) &&
2006cafe5635SKent Overstreet 		       bkey_cmp(k, &START_KEY(m)) > 0)
2007cafe5635SKent Overstreet 			prev = m, m = bkey_next(m);
2008cafe5635SKent Overstreet 
2009cafe5635SKent Overstreet 		if (key_merging_disabled(b->c))
2010cafe5635SKent Overstreet 			goto insert;
2011cafe5635SKent Overstreet 
2012cafe5635SKent Overstreet 		/* prev is in the tree, if we merge we're done */
201385b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_BACK_MERGE;
2014cafe5635SKent Overstreet 		if (prev &&
2015cafe5635SKent Overstreet 		    bch_bkey_try_merge(b, prev, k))
2016cafe5635SKent Overstreet 			goto merged;
2017cafe5635SKent Overstreet 
201885b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_OVERWROTE;
2019cafe5635SKent Overstreet 		if (m != end(i) &&
2020cafe5635SKent Overstreet 		    KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
2021cafe5635SKent Overstreet 			goto copy;
2022cafe5635SKent Overstreet 
202385b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_FRONT_MERGE;
2024cafe5635SKent Overstreet 		if (m != end(i) &&
2025cafe5635SKent Overstreet 		    bch_bkey_try_merge(b, k, m))
2026cafe5635SKent Overstreet 			goto copy;
20271b207d80SKent Overstreet 	} else {
20281b207d80SKent Overstreet 		BUG_ON(replace_key);
2029cafe5635SKent Overstreet 		m = bch_bset_search(b, &b->sets[b->nsets], k);
20301b207d80SKent Overstreet 	}
2031cafe5635SKent Overstreet 
2032cafe5635SKent Overstreet insert:	shift_keys(b, m, k);
2033cafe5635SKent Overstreet copy:	bkey_copy(m, k);
2034cafe5635SKent Overstreet merged:
20351b207d80SKent Overstreet 	bch_check_keys(b, "%u for %s", status,
20361b207d80SKent Overstreet 		       replace_key ? "replace" : "insert");
2037cafe5635SKent Overstreet 
2038cafe5635SKent Overstreet 	if (b->level && !KEY_OFFSET(k))
203957943511SKent Overstreet 		btree_current_write(b)->prio_blocked++;
2040cafe5635SKent Overstreet 
20411b207d80SKent Overstreet 	trace_bcache_btree_insert_key(b, k, replace_key != NULL, status);
2042cafe5635SKent Overstreet 
2043cafe5635SKent Overstreet 	return true;
2044cafe5635SKent Overstreet }
2045cafe5635SKent Overstreet 
204626c949f8SKent Overstreet static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
20471b207d80SKent Overstreet 				  struct keylist *insert_keys,
20481b207d80SKent Overstreet 				  struct bkey *replace_key)
2049cafe5635SKent Overstreet {
2050cafe5635SKent Overstreet 	bool ret = false;
2051280481d0SKent Overstreet 	int oldsize = bch_count_data(b);
2052cafe5635SKent Overstreet 
205326c949f8SKent Overstreet 	while (!bch_keylist_empty(insert_keys)) {
2054403b6cdeSKent Overstreet 		struct bset *i = write_block(b);
2055c2f95ae2SKent Overstreet 		struct bkey *k = insert_keys->keys;
205626c949f8SKent Overstreet 
2057403b6cdeSKent Overstreet 		if (b->written + __set_blocks(i, i->keys + bkey_u64s(k), b->c)
2058403b6cdeSKent Overstreet 		    > btree_blocks(b))
2059403b6cdeSKent Overstreet 			break;
2060403b6cdeSKent Overstreet 
2061403b6cdeSKent Overstreet 		if (bkey_cmp(k, &b->key) <= 0) {
20623a3b6a4eSKent Overstreet 			if (!b->level)
20633a3b6a4eSKent Overstreet 				bkey_put(b->c, k);
206426c949f8SKent Overstreet 
20651b207d80SKent Overstreet 			ret |= btree_insert_key(b, op, k, replace_key);
206626c949f8SKent Overstreet 			bch_keylist_pop_front(insert_keys);
206726c949f8SKent Overstreet 		} else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
206826c949f8SKent Overstreet 			BKEY_PADDED(key) temp;
2069c2f95ae2SKent Overstreet 			bkey_copy(&temp.key, insert_keys->keys);
207026c949f8SKent Overstreet 
207126c949f8SKent Overstreet 			bch_cut_back(&b->key, &temp.key);
2072c2f95ae2SKent Overstreet 			bch_cut_front(&b->key, insert_keys->keys);
207326c949f8SKent Overstreet 
20741b207d80SKent Overstreet 			ret |= btree_insert_key(b, op, &temp.key, replace_key);
207526c949f8SKent Overstreet 			break;
207626c949f8SKent Overstreet 		} else {
207726c949f8SKent Overstreet 			break;
207826c949f8SKent Overstreet 		}
2079cafe5635SKent Overstreet 	}
2080cafe5635SKent Overstreet 
2081403b6cdeSKent Overstreet 	BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
2082403b6cdeSKent Overstreet 
2083cafe5635SKent Overstreet 	BUG_ON(bch_count_data(b) < oldsize);
2084cafe5635SKent Overstreet 	return ret;
2085cafe5635SKent Overstreet }
2086cafe5635SKent Overstreet 
208726c949f8SKent Overstreet static int btree_split(struct btree *b, struct btree_op *op,
208826c949f8SKent Overstreet 		       struct keylist *insert_keys,
20891b207d80SKent Overstreet 		       struct bkey *replace_key)
2090cafe5635SKent Overstreet {
2091d6fd3b11SKent Overstreet 	bool split;
2092cafe5635SKent Overstreet 	struct btree *n1, *n2 = NULL, *n3 = NULL;
2093cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
2094b54d6934SKent Overstreet 	struct closure cl;
209517e21a9fSKent Overstreet 	struct keylist parent_keys;
2096b54d6934SKent Overstreet 
2097b54d6934SKent Overstreet 	closure_init_stack(&cl);
209817e21a9fSKent Overstreet 	bch_keylist_init(&parent_keys);
2099cafe5635SKent Overstreet 
2100*78365411SKent Overstreet 	if (!b->level &&
2101*78365411SKent Overstreet 	    btree_check_reserve(b, op))
2102*78365411SKent Overstreet 		return -EINTR;
2103*78365411SKent Overstreet 
2104bc9389eeSKent Overstreet 	n1 = btree_node_alloc_replacement(b, true);
2105cafe5635SKent Overstreet 	if (IS_ERR(n1))
2106cafe5635SKent Overstreet 		goto err;
2107cafe5635SKent Overstreet 
2108cafe5635SKent Overstreet 	split = set_blocks(n1->sets[0].data, n1->c) > (btree_blocks(b) * 4) / 5;
2109cafe5635SKent Overstreet 
2110cafe5635SKent Overstreet 	if (split) {
2111cafe5635SKent Overstreet 		unsigned keys = 0;
2112cafe5635SKent Overstreet 
2113c37511b8SKent Overstreet 		trace_bcache_btree_node_split(b, n1->sets[0].data->keys);
2114c37511b8SKent Overstreet 
2115bc9389eeSKent Overstreet 		n2 = bch_btree_node_alloc(b->c, b->level, true);
2116cafe5635SKent Overstreet 		if (IS_ERR(n2))
2117cafe5635SKent Overstreet 			goto err_free1;
2118cafe5635SKent Overstreet 
2119d6fd3b11SKent Overstreet 		if (!b->parent) {
2120bc9389eeSKent Overstreet 			n3 = bch_btree_node_alloc(b->c, b->level + 1, true);
2121cafe5635SKent Overstreet 			if (IS_ERR(n3))
2122cafe5635SKent Overstreet 				goto err_free2;
2123cafe5635SKent Overstreet 		}
2124cafe5635SKent Overstreet 
21251b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2126cafe5635SKent Overstreet 
2127d6fd3b11SKent Overstreet 		/*
2128d6fd3b11SKent Overstreet 		 * Has to be a linear search because we don't have an auxiliary
2129cafe5635SKent Overstreet 		 * search tree yet
2130cafe5635SKent Overstreet 		 */
2131cafe5635SKent Overstreet 
2132cafe5635SKent Overstreet 		while (keys < (n1->sets[0].data->keys * 3) / 5)
2133cafe5635SKent Overstreet 			keys += bkey_u64s(node(n1->sets[0].data, keys));
2134cafe5635SKent Overstreet 
2135cafe5635SKent Overstreet 		bkey_copy_key(&n1->key, node(n1->sets[0].data, keys));
2136cafe5635SKent Overstreet 		keys += bkey_u64s(node(n1->sets[0].data, keys));
2137cafe5635SKent Overstreet 
2138cafe5635SKent Overstreet 		n2->sets[0].data->keys = n1->sets[0].data->keys - keys;
2139cafe5635SKent Overstreet 		n1->sets[0].data->keys = keys;
2140cafe5635SKent Overstreet 
2141cafe5635SKent Overstreet 		memcpy(n2->sets[0].data->start,
2142cafe5635SKent Overstreet 		       end(n1->sets[0].data),
2143cafe5635SKent Overstreet 		       n2->sets[0].data->keys * sizeof(uint64_t));
2144cafe5635SKent Overstreet 
2145cafe5635SKent Overstreet 		bkey_copy_key(&n2->key, &b->key);
2146cafe5635SKent Overstreet 
214717e21a9fSKent Overstreet 		bch_keylist_add(&parent_keys, &n2->key);
2148b54d6934SKent Overstreet 		bch_btree_node_write(n2, &cl);
2149cafe5635SKent Overstreet 		rw_unlock(true, n2);
2150c37511b8SKent Overstreet 	} else {
2151c37511b8SKent Overstreet 		trace_bcache_btree_node_compact(b, n1->sets[0].data->keys);
2152c37511b8SKent Overstreet 
21531b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2154c37511b8SKent Overstreet 	}
2155cafe5635SKent Overstreet 
215617e21a9fSKent Overstreet 	bch_keylist_add(&parent_keys, &n1->key);
2157b54d6934SKent Overstreet 	bch_btree_node_write(n1, &cl);
2158cafe5635SKent Overstreet 
2159cafe5635SKent Overstreet 	if (n3) {
2160d6fd3b11SKent Overstreet 		/* Depth increases, make a new root */
2161cafe5635SKent Overstreet 		bkey_copy_key(&n3->key, &MAX_KEY);
216217e21a9fSKent Overstreet 		bch_btree_insert_keys(n3, op, &parent_keys, NULL);
2163b54d6934SKent Overstreet 		bch_btree_node_write(n3, &cl);
2164cafe5635SKent Overstreet 
2165b54d6934SKent Overstreet 		closure_sync(&cl);
2166cafe5635SKent Overstreet 		bch_btree_set_root(n3);
2167cafe5635SKent Overstreet 		rw_unlock(true, n3);
216817e21a9fSKent Overstreet 
216917e21a9fSKent Overstreet 		btree_node_free(b);
2170d6fd3b11SKent Overstreet 	} else if (!b->parent) {
2171d6fd3b11SKent Overstreet 		/* Root filled up but didn't need to be split */
2172b54d6934SKent Overstreet 		closure_sync(&cl);
2173cafe5635SKent Overstreet 		bch_btree_set_root(n1);
217417e21a9fSKent Overstreet 
217517e21a9fSKent Overstreet 		btree_node_free(b);
2176cafe5635SKent Overstreet 	} else {
217717e21a9fSKent Overstreet 		/* Split a non root node */
2178b54d6934SKent Overstreet 		closure_sync(&cl);
217917e21a9fSKent Overstreet 		make_btree_freeing_key(b, parent_keys.top);
218017e21a9fSKent Overstreet 		bch_keylist_push(&parent_keys);
218117e21a9fSKent Overstreet 
218217e21a9fSKent Overstreet 		btree_node_free(b);
218317e21a9fSKent Overstreet 
218417e21a9fSKent Overstreet 		bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
218517e21a9fSKent Overstreet 		BUG_ON(!bch_keylist_empty(&parent_keys));
2186cafe5635SKent Overstreet 	}
2187cafe5635SKent Overstreet 
2188cafe5635SKent Overstreet 	rw_unlock(true, n1);
2189cafe5635SKent Overstreet 
2190169ef1cfSKent Overstreet 	bch_time_stats_update(&b->c->btree_split_time, start_time);
2191cafe5635SKent Overstreet 
2192cafe5635SKent Overstreet 	return 0;
2193cafe5635SKent Overstreet err_free2:
2194e8e1d468SKent Overstreet 	btree_node_free(n2);
2195cafe5635SKent Overstreet 	rw_unlock(true, n2);
2196cafe5635SKent Overstreet err_free1:
2197e8e1d468SKent Overstreet 	btree_node_free(n1);
2198cafe5635SKent Overstreet 	rw_unlock(true, n1);
2199cafe5635SKent Overstreet err:
2200cafe5635SKent Overstreet 	if (n3 == ERR_PTR(-EAGAIN) ||
2201cafe5635SKent Overstreet 	    n2 == ERR_PTR(-EAGAIN) ||
2202cafe5635SKent Overstreet 	    n1 == ERR_PTR(-EAGAIN))
2203cafe5635SKent Overstreet 		return -EAGAIN;
2204cafe5635SKent Overstreet 
2205cafe5635SKent Overstreet 	pr_warn("couldn't split");
2206cafe5635SKent Overstreet 	return -ENOMEM;
2207cafe5635SKent Overstreet }
2208cafe5635SKent Overstreet 
220926c949f8SKent Overstreet static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
2210c18536a7SKent Overstreet 				 struct keylist *insert_keys,
22111b207d80SKent Overstreet 				 atomic_t *journal_ref,
22121b207d80SKent Overstreet 				 struct bkey *replace_key)
221326c949f8SKent Overstreet {
22141b207d80SKent Overstreet 	BUG_ON(b->level && replace_key);
22151b207d80SKent Overstreet 
221626c949f8SKent Overstreet 	if (should_split(b)) {
221726c949f8SKent Overstreet 		if (current->bio_list) {
221826c949f8SKent Overstreet 			op->lock = b->c->root->level + 1;
221917e21a9fSKent Overstreet 			return -EAGAIN;
222026c949f8SKent Overstreet 		} else if (op->lock <= b->c->root->level) {
222126c949f8SKent Overstreet 			op->lock = b->c->root->level + 1;
222217e21a9fSKent Overstreet 			return -EINTR;
222326c949f8SKent Overstreet 		} else {
222417e21a9fSKent Overstreet 			/* Invalidated all iterators */
222517e21a9fSKent Overstreet 			return btree_split(b, op, insert_keys, replace_key) ?:
222617e21a9fSKent Overstreet 				-EINTR;
222726c949f8SKent Overstreet 		}
222826c949f8SKent Overstreet 	} else {
222926c949f8SKent Overstreet 		BUG_ON(write_block(b) != b->sets[b->nsets].data);
223026c949f8SKent Overstreet 
223117e21a9fSKent Overstreet 		if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
2232f269af5aSKent Overstreet 			if (!b->level)
2233c18536a7SKent Overstreet 				bch_btree_leaf_dirty(b, journal_ref);
2234f269af5aSKent Overstreet 			else
2235f269af5aSKent Overstreet 				bch_btree_node_write_sync(b);
223626c949f8SKent Overstreet 		}
223726c949f8SKent Overstreet 
223817e21a9fSKent Overstreet 		return 0;
223917e21a9fSKent Overstreet 	}
224026c949f8SKent Overstreet }
224126c949f8SKent Overstreet 
2242e7c590ebSKent Overstreet int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2243e7c590ebSKent Overstreet 			       struct bkey *check_key)
2244e7c590ebSKent Overstreet {
2245e7c590ebSKent Overstreet 	int ret = -EINTR;
2246e7c590ebSKent Overstreet 	uint64_t btree_ptr = b->key.ptr[0];
2247e7c590ebSKent Overstreet 	unsigned long seq = b->seq;
2248e7c590ebSKent Overstreet 	struct keylist insert;
2249e7c590ebSKent Overstreet 	bool upgrade = op->lock == -1;
2250e7c590ebSKent Overstreet 
2251e7c590ebSKent Overstreet 	bch_keylist_init(&insert);
2252e7c590ebSKent Overstreet 
2253e7c590ebSKent Overstreet 	if (upgrade) {
2254e7c590ebSKent Overstreet 		rw_unlock(false, b);
2255e7c590ebSKent Overstreet 		rw_lock(true, b, b->level);
2256e7c590ebSKent Overstreet 
2257e7c590ebSKent Overstreet 		if (b->key.ptr[0] != btree_ptr ||
2258e7c590ebSKent Overstreet 		    b->seq != seq + 1)
2259e7c590ebSKent Overstreet 			goto out;
2260e7c590ebSKent Overstreet 	}
2261e7c590ebSKent Overstreet 
2262e7c590ebSKent Overstreet 	SET_KEY_PTRS(check_key, 1);
2263e7c590ebSKent Overstreet 	get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2264e7c590ebSKent Overstreet 
2265e7c590ebSKent Overstreet 	SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2266e7c590ebSKent Overstreet 
2267e7c590ebSKent Overstreet 	bch_keylist_add(&insert, check_key);
2268e7c590ebSKent Overstreet 
22691b207d80SKent Overstreet 	ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2270e7c590ebSKent Overstreet 
2271e7c590ebSKent Overstreet 	BUG_ON(!ret && !bch_keylist_empty(&insert));
2272e7c590ebSKent Overstreet out:
2273e7c590ebSKent Overstreet 	if (upgrade)
2274e7c590ebSKent Overstreet 		downgrade_write(&b->lock);
2275e7c590ebSKent Overstreet 	return ret;
2276e7c590ebSKent Overstreet }
2277e7c590ebSKent Overstreet 
2278cc7b8819SKent Overstreet struct btree_insert_op {
2279cc7b8819SKent Overstreet 	struct btree_op	op;
2280cc7b8819SKent Overstreet 	struct keylist	*keys;
2281cc7b8819SKent Overstreet 	atomic_t	*journal_ref;
2282cc7b8819SKent Overstreet 	struct bkey	*replace_key;
2283cc7b8819SKent Overstreet };
2284cc7b8819SKent Overstreet 
228508239ca2SWei Yongjun static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2286cafe5635SKent Overstreet {
2287cc7b8819SKent Overstreet 	struct btree_insert_op *op = container_of(b_op,
2288cc7b8819SKent Overstreet 					struct btree_insert_op, op);
2289403b6cdeSKent Overstreet 
2290cc7b8819SKent Overstreet 	int ret = bch_btree_insert_node(b, &op->op, op->keys,
2291cc7b8819SKent Overstreet 					op->journal_ref, op->replace_key);
2292cc7b8819SKent Overstreet 	if (ret && !bch_keylist_empty(op->keys))
2293cc7b8819SKent Overstreet 		return ret;
2294cc7b8819SKent Overstreet 	else
2295cc7b8819SKent Overstreet 		return MAP_DONE;
2296cafe5635SKent Overstreet }
2297cafe5635SKent Overstreet 
2298cc7b8819SKent Overstreet int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2299cc7b8819SKent Overstreet 		     atomic_t *journal_ref, struct bkey *replace_key)
2300cafe5635SKent Overstreet {
2301cc7b8819SKent Overstreet 	struct btree_insert_op op;
2302cafe5635SKent Overstreet 	int ret = 0;
2303cafe5635SKent Overstreet 
2304cc7b8819SKent Overstreet 	BUG_ON(current->bio_list);
23054f3d4014SKent Overstreet 	BUG_ON(bch_keylist_empty(keys));
2306cafe5635SKent Overstreet 
2307cc7b8819SKent Overstreet 	bch_btree_op_init(&op.op, 0);
2308cc7b8819SKent Overstreet 	op.keys		= keys;
2309cc7b8819SKent Overstreet 	op.journal_ref	= journal_ref;
2310cc7b8819SKent Overstreet 	op.replace_key	= replace_key;
2311cafe5635SKent Overstreet 
2312cc7b8819SKent Overstreet 	while (!ret && !bch_keylist_empty(keys)) {
2313cc7b8819SKent Overstreet 		op.op.lock = 0;
2314cc7b8819SKent Overstreet 		ret = bch_btree_map_leaf_nodes(&op.op, c,
2315cc7b8819SKent Overstreet 					       &START_KEY(keys->keys),
2316cc7b8819SKent Overstreet 					       btree_insert_fn);
2317cc7b8819SKent Overstreet 	}
2318cc7b8819SKent Overstreet 
2319cc7b8819SKent Overstreet 	if (ret) {
2320cafe5635SKent Overstreet 		struct bkey *k;
2321cafe5635SKent Overstreet 
23221b207d80SKent Overstreet 		pr_err("error %i", ret);
2323cafe5635SKent Overstreet 
23244f3d4014SKent Overstreet 		while ((k = bch_keylist_pop(keys)))
23253a3b6a4eSKent Overstreet 			bkey_put(c, k);
2326cc7b8819SKent Overstreet 	} else if (op.op.insert_collision)
2327cc7b8819SKent Overstreet 		ret = -ESRCH;
23286054c6d4SKent Overstreet 
2329cafe5635SKent Overstreet 	return ret;
2330cafe5635SKent Overstreet }
2331cafe5635SKent Overstreet 
2332cafe5635SKent Overstreet void bch_btree_set_root(struct btree *b)
2333cafe5635SKent Overstreet {
2334cafe5635SKent Overstreet 	unsigned i;
2335e49c7c37SKent Overstreet 	struct closure cl;
2336e49c7c37SKent Overstreet 
2337e49c7c37SKent Overstreet 	closure_init_stack(&cl);
2338cafe5635SKent Overstreet 
2339c37511b8SKent Overstreet 	trace_bcache_btree_set_root(b);
2340c37511b8SKent Overstreet 
2341cafe5635SKent Overstreet 	BUG_ON(!b->written);
2342cafe5635SKent Overstreet 
2343cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++)
2344cafe5635SKent Overstreet 		BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2345cafe5635SKent Overstreet 
2346cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
2347cafe5635SKent Overstreet 	list_del_init(&b->list);
2348cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
2349cafe5635SKent Overstreet 
2350cafe5635SKent Overstreet 	b->c->root = b;
2351cafe5635SKent Overstreet 
2352e49c7c37SKent Overstreet 	bch_journal_meta(b->c, &cl);
2353e49c7c37SKent Overstreet 	closure_sync(&cl);
2354cafe5635SKent Overstreet }
2355cafe5635SKent Overstreet 
235648dad8baSKent Overstreet /* Map across nodes or keys */
235748dad8baSKent Overstreet 
235848dad8baSKent Overstreet static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
235948dad8baSKent Overstreet 				       struct bkey *from,
236048dad8baSKent Overstreet 				       btree_map_nodes_fn *fn, int flags)
236148dad8baSKent Overstreet {
236248dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
236348dad8baSKent Overstreet 
236448dad8baSKent Overstreet 	if (b->level) {
236548dad8baSKent Overstreet 		struct bkey *k;
236648dad8baSKent Overstreet 		struct btree_iter iter;
236748dad8baSKent Overstreet 
236848dad8baSKent Overstreet 		bch_btree_iter_init(b, &iter, from);
236948dad8baSKent Overstreet 
237048dad8baSKent Overstreet 		while ((k = bch_btree_iter_next_filter(&iter, b,
237148dad8baSKent Overstreet 						       bch_ptr_bad))) {
237248dad8baSKent Overstreet 			ret = btree(map_nodes_recurse, k, b,
237348dad8baSKent Overstreet 				    op, from, fn, flags);
237448dad8baSKent Overstreet 			from = NULL;
237548dad8baSKent Overstreet 
237648dad8baSKent Overstreet 			if (ret != MAP_CONTINUE)
237748dad8baSKent Overstreet 				return ret;
237848dad8baSKent Overstreet 		}
237948dad8baSKent Overstreet 	}
238048dad8baSKent Overstreet 
238148dad8baSKent Overstreet 	if (!b->level || flags == MAP_ALL_NODES)
238248dad8baSKent Overstreet 		ret = fn(op, b);
238348dad8baSKent Overstreet 
238448dad8baSKent Overstreet 	return ret;
238548dad8baSKent Overstreet }
238648dad8baSKent Overstreet 
238748dad8baSKent Overstreet int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
238848dad8baSKent Overstreet 			  struct bkey *from, btree_map_nodes_fn *fn, int flags)
238948dad8baSKent Overstreet {
2390b54d6934SKent Overstreet 	return btree_root(map_nodes_recurse, c, op, from, fn, flags);
239148dad8baSKent Overstreet }
239248dad8baSKent Overstreet 
239348dad8baSKent Overstreet static int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
239448dad8baSKent Overstreet 				      struct bkey *from, btree_map_keys_fn *fn,
239548dad8baSKent Overstreet 				      int flags)
239648dad8baSKent Overstreet {
239748dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
239848dad8baSKent Overstreet 	struct bkey *k;
239948dad8baSKent Overstreet 	struct btree_iter iter;
240048dad8baSKent Overstreet 
240148dad8baSKent Overstreet 	bch_btree_iter_init(b, &iter, from);
240248dad8baSKent Overstreet 
240348dad8baSKent Overstreet 	while ((k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad))) {
240448dad8baSKent Overstreet 		ret = !b->level
240548dad8baSKent Overstreet 			? fn(op, b, k)
240648dad8baSKent Overstreet 			: btree(map_keys_recurse, k, b, op, from, fn, flags);
240748dad8baSKent Overstreet 		from = NULL;
240848dad8baSKent Overstreet 
240948dad8baSKent Overstreet 		if (ret != MAP_CONTINUE)
241048dad8baSKent Overstreet 			return ret;
241148dad8baSKent Overstreet 	}
241248dad8baSKent Overstreet 
241348dad8baSKent Overstreet 	if (!b->level && (flags & MAP_END_KEY))
241448dad8baSKent Overstreet 		ret = fn(op, b, &KEY(KEY_INODE(&b->key),
241548dad8baSKent Overstreet 				     KEY_OFFSET(&b->key), 0));
241648dad8baSKent Overstreet 
241748dad8baSKent Overstreet 	return ret;
241848dad8baSKent Overstreet }
241948dad8baSKent Overstreet 
242048dad8baSKent Overstreet int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
242148dad8baSKent Overstreet 		       struct bkey *from, btree_map_keys_fn *fn, int flags)
242248dad8baSKent Overstreet {
2423b54d6934SKent Overstreet 	return btree_root(map_keys_recurse, c, op, from, fn, flags);
242448dad8baSKent Overstreet }
242548dad8baSKent Overstreet 
2426cafe5635SKent Overstreet /* Keybuf code */
2427cafe5635SKent Overstreet 
2428cafe5635SKent Overstreet static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2429cafe5635SKent Overstreet {
2430cafe5635SKent Overstreet 	/* Overlapping keys compare equal */
2431cafe5635SKent Overstreet 	if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2432cafe5635SKent Overstreet 		return -1;
2433cafe5635SKent Overstreet 	if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2434cafe5635SKent Overstreet 		return 1;
2435cafe5635SKent Overstreet 	return 0;
2436cafe5635SKent Overstreet }
2437cafe5635SKent Overstreet 
2438cafe5635SKent Overstreet static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2439cafe5635SKent Overstreet 					    struct keybuf_key *r)
2440cafe5635SKent Overstreet {
2441cafe5635SKent Overstreet 	return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2442cafe5635SKent Overstreet }
2443cafe5635SKent Overstreet 
244448dad8baSKent Overstreet struct refill {
244548dad8baSKent Overstreet 	struct btree_op	op;
244648a915a8SKent Overstreet 	unsigned	nr_found;
244748dad8baSKent Overstreet 	struct keybuf	*buf;
244848dad8baSKent Overstreet 	struct bkey	*end;
244948dad8baSKent Overstreet 	keybuf_pred_fn	*pred;
245048dad8baSKent Overstreet };
245148dad8baSKent Overstreet 
245248dad8baSKent Overstreet static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
245348dad8baSKent Overstreet 			    struct bkey *k)
2454cafe5635SKent Overstreet {
245548dad8baSKent Overstreet 	struct refill *refill = container_of(op, struct refill, op);
245648dad8baSKent Overstreet 	struct keybuf *buf = refill->buf;
245748dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
2458cafe5635SKent Overstreet 
245948dad8baSKent Overstreet 	if (bkey_cmp(k, refill->end) >= 0) {
246048dad8baSKent Overstreet 		ret = MAP_DONE;
246148dad8baSKent Overstreet 		goto out;
2462cafe5635SKent Overstreet 	}
2463cafe5635SKent Overstreet 
246448dad8baSKent Overstreet 	if (!KEY_SIZE(k)) /* end key */
246548dad8baSKent Overstreet 		goto out;
2466cafe5635SKent Overstreet 
246748dad8baSKent Overstreet 	if (refill->pred(buf, k)) {
2468cafe5635SKent Overstreet 		struct keybuf_key *w;
2469cafe5635SKent Overstreet 
2470cafe5635SKent Overstreet 		spin_lock(&buf->lock);
2471cafe5635SKent Overstreet 
2472cafe5635SKent Overstreet 		w = array_alloc(&buf->freelist);
247348dad8baSKent Overstreet 		if (!w) {
247448dad8baSKent Overstreet 			spin_unlock(&buf->lock);
247548dad8baSKent Overstreet 			return MAP_DONE;
247648dad8baSKent Overstreet 		}
2477cafe5635SKent Overstreet 
2478cafe5635SKent Overstreet 		w->private = NULL;
2479cafe5635SKent Overstreet 		bkey_copy(&w->key, k);
2480cafe5635SKent Overstreet 
2481cafe5635SKent Overstreet 		if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2482cafe5635SKent Overstreet 			array_free(&buf->freelist, w);
248348a915a8SKent Overstreet 		else
248448a915a8SKent Overstreet 			refill->nr_found++;
2485cafe5635SKent Overstreet 
248648dad8baSKent Overstreet 		if (array_freelist_empty(&buf->freelist))
248748dad8baSKent Overstreet 			ret = MAP_DONE;
248848dad8baSKent Overstreet 
2489cafe5635SKent Overstreet 		spin_unlock(&buf->lock);
2490cafe5635SKent Overstreet 	}
249148dad8baSKent Overstreet out:
249248dad8baSKent Overstreet 	buf->last_scanned = *k;
249348dad8baSKent Overstreet 	return ret;
2494cafe5635SKent Overstreet }
2495cafe5635SKent Overstreet 
2496cafe5635SKent Overstreet void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
249772c27061SKent Overstreet 		       struct bkey *end, keybuf_pred_fn *pred)
2498cafe5635SKent Overstreet {
2499cafe5635SKent Overstreet 	struct bkey start = buf->last_scanned;
250048dad8baSKent Overstreet 	struct refill refill;
2501cafe5635SKent Overstreet 
2502cafe5635SKent Overstreet 	cond_resched();
2503cafe5635SKent Overstreet 
2504b54d6934SKent Overstreet 	bch_btree_op_init(&refill.op, -1);
250548a915a8SKent Overstreet 	refill.nr_found	= 0;
250648dad8baSKent Overstreet 	refill.buf	= buf;
250748dad8baSKent Overstreet 	refill.end	= end;
250848dad8baSKent Overstreet 	refill.pred	= pred;
250948dad8baSKent Overstreet 
251048dad8baSKent Overstreet 	bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
251148dad8baSKent Overstreet 			   refill_keybuf_fn, MAP_END_KEY);
2512cafe5635SKent Overstreet 
251348a915a8SKent Overstreet 	trace_bcache_keyscan(refill.nr_found,
2514cafe5635SKent Overstreet 			     KEY_INODE(&start), KEY_OFFSET(&start),
251548a915a8SKent Overstreet 			     KEY_INODE(&buf->last_scanned),
251648a915a8SKent Overstreet 			     KEY_OFFSET(&buf->last_scanned));
2517cafe5635SKent Overstreet 
2518cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2519cafe5635SKent Overstreet 
2520cafe5635SKent Overstreet 	if (!RB_EMPTY_ROOT(&buf->keys)) {
2521cafe5635SKent Overstreet 		struct keybuf_key *w;
2522cafe5635SKent Overstreet 		w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2523cafe5635SKent Overstreet 		buf->start	= START_KEY(&w->key);
2524cafe5635SKent Overstreet 
2525cafe5635SKent Overstreet 		w = RB_LAST(&buf->keys, struct keybuf_key, node);
2526cafe5635SKent Overstreet 		buf->end	= w->key;
2527cafe5635SKent Overstreet 	} else {
2528cafe5635SKent Overstreet 		buf->start	= MAX_KEY;
2529cafe5635SKent Overstreet 		buf->end	= MAX_KEY;
2530cafe5635SKent Overstreet 	}
2531cafe5635SKent Overstreet 
2532cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2533cafe5635SKent Overstreet }
2534cafe5635SKent Overstreet 
2535cafe5635SKent Overstreet static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2536cafe5635SKent Overstreet {
2537cafe5635SKent Overstreet 	rb_erase(&w->node, &buf->keys);
2538cafe5635SKent Overstreet 	array_free(&buf->freelist, w);
2539cafe5635SKent Overstreet }
2540cafe5635SKent Overstreet 
2541cafe5635SKent Overstreet void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2542cafe5635SKent Overstreet {
2543cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2544cafe5635SKent Overstreet 	__bch_keybuf_del(buf, w);
2545cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2546cafe5635SKent Overstreet }
2547cafe5635SKent Overstreet 
2548cafe5635SKent Overstreet bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2549cafe5635SKent Overstreet 				  struct bkey *end)
2550cafe5635SKent Overstreet {
2551cafe5635SKent Overstreet 	bool ret = false;
2552cafe5635SKent Overstreet 	struct keybuf_key *p, *w, s;
2553cafe5635SKent Overstreet 	s.key = *start;
2554cafe5635SKent Overstreet 
2555cafe5635SKent Overstreet 	if (bkey_cmp(end, &buf->start) <= 0 ||
2556cafe5635SKent Overstreet 	    bkey_cmp(start, &buf->end) >= 0)
2557cafe5635SKent Overstreet 		return false;
2558cafe5635SKent Overstreet 
2559cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2560cafe5635SKent Overstreet 	w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2561cafe5635SKent Overstreet 
2562cafe5635SKent Overstreet 	while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2563cafe5635SKent Overstreet 		p = w;
2564cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2565cafe5635SKent Overstreet 
2566cafe5635SKent Overstreet 		if (p->private)
2567cafe5635SKent Overstreet 			ret = true;
2568cafe5635SKent Overstreet 		else
2569cafe5635SKent Overstreet 			__bch_keybuf_del(buf, p);
2570cafe5635SKent Overstreet 	}
2571cafe5635SKent Overstreet 
2572cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2573cafe5635SKent Overstreet 	return ret;
2574cafe5635SKent Overstreet }
2575cafe5635SKent Overstreet 
2576cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2577cafe5635SKent Overstreet {
2578cafe5635SKent Overstreet 	struct keybuf_key *w;
2579cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2580cafe5635SKent Overstreet 
2581cafe5635SKent Overstreet 	w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2582cafe5635SKent Overstreet 
2583cafe5635SKent Overstreet 	while (w && w->private)
2584cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2585cafe5635SKent Overstreet 
2586cafe5635SKent Overstreet 	if (w)
2587cafe5635SKent Overstreet 		w->private = ERR_PTR(-EINTR);
2588cafe5635SKent Overstreet 
2589cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2590cafe5635SKent Overstreet 	return w;
2591cafe5635SKent Overstreet }
2592cafe5635SKent Overstreet 
2593cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2594cafe5635SKent Overstreet 					  struct keybuf *buf,
259572c27061SKent Overstreet 					  struct bkey *end,
259672c27061SKent Overstreet 					  keybuf_pred_fn *pred)
2597cafe5635SKent Overstreet {
2598cafe5635SKent Overstreet 	struct keybuf_key *ret;
2599cafe5635SKent Overstreet 
2600cafe5635SKent Overstreet 	while (1) {
2601cafe5635SKent Overstreet 		ret = bch_keybuf_next(buf);
2602cafe5635SKent Overstreet 		if (ret)
2603cafe5635SKent Overstreet 			break;
2604cafe5635SKent Overstreet 
2605cafe5635SKent Overstreet 		if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2606cafe5635SKent Overstreet 			pr_debug("scan finished");
2607cafe5635SKent Overstreet 			break;
2608cafe5635SKent Overstreet 		}
2609cafe5635SKent Overstreet 
261072c27061SKent Overstreet 		bch_refill_keybuf(c, buf, end, pred);
2611cafe5635SKent Overstreet 	}
2612cafe5635SKent Overstreet 
2613cafe5635SKent Overstreet 	return ret;
2614cafe5635SKent Overstreet }
2615cafe5635SKent Overstreet 
261672c27061SKent Overstreet void bch_keybuf_init(struct keybuf *buf)
2617cafe5635SKent Overstreet {
2618cafe5635SKent Overstreet 	buf->last_scanned	= MAX_KEY;
2619cafe5635SKent Overstreet 	buf->keys		= RB_ROOT;
2620cafe5635SKent Overstreet 
2621cafe5635SKent Overstreet 	spin_lock_init(&buf->lock);
2622cafe5635SKent Overstreet 	array_allocator_init(&buf->freelist);
2623cafe5635SKent Overstreet }
2624cafe5635SKent Overstreet 
2625cafe5635SKent Overstreet void bch_btree_exit(void)
2626cafe5635SKent Overstreet {
2627cafe5635SKent Overstreet 	if (btree_io_wq)
2628cafe5635SKent Overstreet 		destroy_workqueue(btree_io_wq);
2629cafe5635SKent Overstreet }
2630cafe5635SKent Overstreet 
2631cafe5635SKent Overstreet int __init bch_btree_init(void)
2632cafe5635SKent Overstreet {
263372a44517SKent Overstreet 	btree_io_wq = create_singlethread_workqueue("bch_btree_io");
263472a44517SKent Overstreet 	if (!btree_io_wq)
2635cafe5635SKent Overstreet 		return -ENOMEM;
2636cafe5635SKent Overstreet 
2637cafe5635SKent Overstreet 	return 0;
2638cafe5635SKent Overstreet }
2639