xref: /linux/drivers/md/bcache/btree.c (revision 59158fde429fb5d18064e2734b3dd5e6048affbd)
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"
2665d45231SKent Overstreet #include "extents.h"
27279afbadSKent Overstreet #include "writeback.h"
28cafe5635SKent Overstreet 
29cafe5635SKent Overstreet #include <linux/slab.h>
30cafe5635SKent Overstreet #include <linux/bitops.h>
3172a44517SKent Overstreet #include <linux/freezer.h>
32cafe5635SKent Overstreet #include <linux/hash.h>
3372a44517SKent Overstreet #include <linux/kthread.h>
34cd953ed0SGeert Uytterhoeven #include <linux/prefetch.h>
35cafe5635SKent Overstreet #include <linux/random.h>
36cafe5635SKent Overstreet #include <linux/rcupdate.h>
37cafe5635SKent Overstreet #include <trace/events/bcache.h>
38cafe5635SKent Overstreet 
39cafe5635SKent Overstreet /*
40cafe5635SKent Overstreet  * Todo:
41cafe5635SKent Overstreet  * register_bcache: Return errors out to userspace correctly
42cafe5635SKent Overstreet  *
43cafe5635SKent Overstreet  * Writeback: don't undirty key until after a cache flush
44cafe5635SKent Overstreet  *
45cafe5635SKent Overstreet  * Create an iterator for key pointers
46cafe5635SKent Overstreet  *
47cafe5635SKent Overstreet  * On btree write error, mark bucket such that it won't be freed from the cache
48cafe5635SKent Overstreet  *
49cafe5635SKent Overstreet  * Journalling:
50cafe5635SKent Overstreet  *   Check for bad keys in replay
51cafe5635SKent Overstreet  *   Propagate barriers
52cafe5635SKent Overstreet  *   Refcount journal entries in journal_replay
53cafe5635SKent Overstreet  *
54cafe5635SKent Overstreet  * Garbage collection:
55cafe5635SKent Overstreet  *   Finish incremental gc
56cafe5635SKent Overstreet  *   Gc should free old UUIDs, data for invalid UUIDs
57cafe5635SKent Overstreet  *
58cafe5635SKent Overstreet  * Provide a way to list backing device UUIDs we have data cached for, and
59cafe5635SKent Overstreet  * probably how long it's been since we've seen them, and a way to invalidate
60cafe5635SKent Overstreet  * dirty data for devices that will never be attached again
61cafe5635SKent Overstreet  *
62cafe5635SKent Overstreet  * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
63cafe5635SKent Overstreet  * that based on that and how much dirty data we have we can keep writeback
64cafe5635SKent Overstreet  * from being starved
65cafe5635SKent Overstreet  *
66cafe5635SKent Overstreet  * Add a tracepoint or somesuch to watch for writeback starvation
67cafe5635SKent Overstreet  *
68cafe5635SKent Overstreet  * When btree depth > 1 and splitting an interior node, we have to make sure
69cafe5635SKent Overstreet  * alloc_bucket() cannot fail. This should be true but is not completely
70cafe5635SKent Overstreet  * obvious.
71cafe5635SKent Overstreet  *
72cafe5635SKent Overstreet  * Make sure all allocations get charged to the root cgroup
73cafe5635SKent Overstreet  *
74cafe5635SKent Overstreet  * Plugging?
75cafe5635SKent Overstreet  *
76cafe5635SKent Overstreet  * If data write is less than hard sector size of ssd, round up offset in open
77cafe5635SKent Overstreet  * bucket to the next whole sector
78cafe5635SKent Overstreet  *
79cafe5635SKent Overstreet  * Also lookup by cgroup in get_open_bucket()
80cafe5635SKent Overstreet  *
81cafe5635SKent Overstreet  * Superblock needs to be fleshed out for multiple cache devices
82cafe5635SKent Overstreet  *
83cafe5635SKent Overstreet  * Add a sysfs tunable for the number of writeback IOs in flight
84cafe5635SKent Overstreet  *
85cafe5635SKent Overstreet  * Add a sysfs tunable for the number of open data buckets
86cafe5635SKent Overstreet  *
87cafe5635SKent Overstreet  * IO tracking: Can we track when one process is doing io on behalf of another?
88cafe5635SKent Overstreet  * IO tracking: Don't use just an average, weigh more recent stuff higher
89cafe5635SKent Overstreet  *
90cafe5635SKent Overstreet  * Test module load/unload
91cafe5635SKent Overstreet  */
92cafe5635SKent Overstreet 
93df8e8970SKent Overstreet enum {
94df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_INSERT,
95df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_BACK_MERGE,
96df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_OVERWROTE,
97df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_FRONT_MERGE,
98df8e8970SKent Overstreet };
99df8e8970SKent Overstreet 
100cafe5635SKent Overstreet #define MAX_NEED_GC		64
101cafe5635SKent Overstreet #define MAX_SAVE_PRIO		72
102cafe5635SKent Overstreet 
103cafe5635SKent Overstreet #define PTR_DIRTY_BIT		(((uint64_t) 1 << 36))
104cafe5635SKent Overstreet 
105cafe5635SKent Overstreet #define PTR_HASH(c, k)							\
106cafe5635SKent Overstreet 	(((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
107cafe5635SKent Overstreet 
108cafe5635SKent Overstreet static struct workqueue_struct *btree_io_wq;
109cafe5635SKent Overstreet 
110df8e8970SKent Overstreet #define insert_lock(s, b)	((b)->level <= (s)->lock)
111df8e8970SKent Overstreet 
112df8e8970SKent Overstreet /*
113df8e8970SKent Overstreet  * These macros are for recursing down the btree - they handle the details of
114df8e8970SKent Overstreet  * locking and looking up nodes in the cache for you. They're best treated as
115df8e8970SKent Overstreet  * mere syntax when reading code that uses them.
116df8e8970SKent Overstreet  *
117df8e8970SKent Overstreet  * op->lock determines whether we take a read or a write lock at a given depth.
118df8e8970SKent Overstreet  * If you've got a read lock and find that you need a write lock (i.e. you're
119df8e8970SKent Overstreet  * going to have to split), set op->lock and return -EINTR; btree_root() will
120df8e8970SKent Overstreet  * call you again and you'll have the correct lock.
121df8e8970SKent Overstreet  */
122df8e8970SKent Overstreet 
123df8e8970SKent Overstreet /**
124df8e8970SKent Overstreet  * btree - recurse down the btree on a specified key
125df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
126df8e8970SKent Overstreet  * @key:	key to recurse on
127df8e8970SKent Overstreet  * @b:		parent btree node
128df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
129df8e8970SKent Overstreet  */
130df8e8970SKent Overstreet #define btree(fn, key, b, op, ...)					\
131df8e8970SKent Overstreet ({									\
132df8e8970SKent Overstreet 	int _r, l = (b)->level - 1;					\
133df8e8970SKent Overstreet 	bool _w = l <= (op)->lock;					\
134df8e8970SKent Overstreet 	struct btree *_child = bch_btree_node_get((b)->c, key, l, _w);	\
135df8e8970SKent Overstreet 	if (!IS_ERR(_child)) {						\
136df8e8970SKent Overstreet 		_child->parent = (b);					\
137df8e8970SKent Overstreet 		_r = bch_btree_ ## fn(_child, op, ##__VA_ARGS__);	\
138df8e8970SKent Overstreet 		rw_unlock(_w, _child);					\
139df8e8970SKent Overstreet 	} else								\
140df8e8970SKent Overstreet 		_r = PTR_ERR(_child);					\
141df8e8970SKent Overstreet 	_r;								\
142df8e8970SKent Overstreet })
143df8e8970SKent Overstreet 
144df8e8970SKent Overstreet /**
145df8e8970SKent Overstreet  * btree_root - call a function on the root of the btree
146df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
147df8e8970SKent Overstreet  * @c:		cache set
148df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
149df8e8970SKent Overstreet  */
150df8e8970SKent Overstreet #define btree_root(fn, c, op, ...)					\
151df8e8970SKent Overstreet ({									\
152df8e8970SKent Overstreet 	int _r = -EINTR;						\
153df8e8970SKent Overstreet 	do {								\
154df8e8970SKent Overstreet 		struct btree *_b = (c)->root;				\
155df8e8970SKent Overstreet 		bool _w = insert_lock(op, _b);				\
156df8e8970SKent Overstreet 		rw_lock(_w, _b, _b->level);				\
157df8e8970SKent Overstreet 		if (_b == (c)->root &&					\
158df8e8970SKent Overstreet 		    _w == insert_lock(op, _b)) {			\
159df8e8970SKent Overstreet 			_b->parent = NULL;				\
160df8e8970SKent Overstreet 			_r = bch_btree_ ## fn(_b, op, ##__VA_ARGS__);	\
161df8e8970SKent Overstreet 		}							\
162df8e8970SKent Overstreet 		rw_unlock(_w, _b);					\
16378365411SKent Overstreet 		if (_r == -EINTR)					\
16478365411SKent Overstreet 			schedule();					\
165df8e8970SKent Overstreet 		bch_cannibalize_unlock(c);				\
166df8e8970SKent Overstreet 		if (_r == -ENOSPC) {					\
167df8e8970SKent Overstreet 			wait_event((c)->try_wait,			\
168df8e8970SKent Overstreet 				   !(c)->try_harder);			\
169df8e8970SKent Overstreet 			_r = -EINTR;					\
170df8e8970SKent Overstreet 		}							\
171df8e8970SKent Overstreet 	} while (_r == -EINTR);						\
172df8e8970SKent Overstreet 									\
17378365411SKent Overstreet 	finish_wait(&(c)->bucket_wait, &(op)->wait);			\
174df8e8970SKent Overstreet 	_r;								\
175df8e8970SKent Overstreet })
176df8e8970SKent Overstreet 
177a85e968eSKent Overstreet static inline struct bset *write_block(struct btree *b)
178a85e968eSKent Overstreet {
179a85e968eSKent Overstreet 	return ((void *) btree_bset_first(b)) + b->written * block_bytes(b->c);
180a85e968eSKent Overstreet }
181a85e968eSKent Overstreet 
182cafe5635SKent Overstreet /* Btree key manipulation */
183cafe5635SKent Overstreet 
1843a3b6a4eSKent Overstreet void bkey_put(struct cache_set *c, struct bkey *k)
185e7c590ebSKent Overstreet {
186e7c590ebSKent Overstreet 	unsigned i;
187e7c590ebSKent Overstreet 
188e7c590ebSKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
189e7c590ebSKent Overstreet 		if (ptr_available(c, k, i))
190e7c590ebSKent Overstreet 			atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
191e7c590ebSKent Overstreet }
192e7c590ebSKent Overstreet 
193cafe5635SKent Overstreet /* Btree IO */
194cafe5635SKent Overstreet 
195cafe5635SKent Overstreet static uint64_t btree_csum_set(struct btree *b, struct bset *i)
196cafe5635SKent Overstreet {
197cafe5635SKent Overstreet 	uint64_t crc = b->key.ptr[0];
198fafff81cSKent Overstreet 	void *data = (void *) i + 8, *end = bset_bkey_last(i);
199cafe5635SKent Overstreet 
200169ef1cfSKent Overstreet 	crc = bch_crc64_update(crc, data, end - data);
201c19ed23aSKent Overstreet 	return crc ^ 0xffffffffffffffffULL;
202cafe5635SKent Overstreet }
203cafe5635SKent Overstreet 
20478b77bf8SKent Overstreet void bch_btree_node_read_done(struct btree *b)
205cafe5635SKent Overstreet {
206cafe5635SKent Overstreet 	const char *err = "bad btree header";
207ee811287SKent Overstreet 	struct bset *i = btree_bset_first(b);
20857943511SKent Overstreet 	struct btree_iter *iter;
209cafe5635SKent Overstreet 
21057943511SKent Overstreet 	iter = mempool_alloc(b->c->fill_iter, GFP_NOWAIT);
21157943511SKent Overstreet 	iter->size = b->c->sb.bucket_size / b->c->sb.block_size;
212cafe5635SKent Overstreet 	iter->used = 0;
213cafe5635SKent Overstreet 
214280481d0SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
215280481d0SKent Overstreet 	iter->b = b;
216280481d0SKent Overstreet #endif
217280481d0SKent Overstreet 
21857943511SKent Overstreet 	if (!i->seq)
219cafe5635SKent Overstreet 		goto err;
220cafe5635SKent Overstreet 
221cafe5635SKent Overstreet 	for (;
222a85e968eSKent Overstreet 	     b->written < btree_blocks(b) && i->seq == b->keys.set[0].data->seq;
223cafe5635SKent Overstreet 	     i = write_block(b)) {
224cafe5635SKent Overstreet 		err = "unsupported bset version";
225cafe5635SKent Overstreet 		if (i->version > BCACHE_BSET_VERSION)
226cafe5635SKent Overstreet 			goto err;
227cafe5635SKent Overstreet 
228cafe5635SKent Overstreet 		err = "bad btree header";
229ee811287SKent Overstreet 		if (b->written + set_blocks(i, block_bytes(b->c)) >
230ee811287SKent Overstreet 		    btree_blocks(b))
231cafe5635SKent Overstreet 			goto err;
232cafe5635SKent Overstreet 
233cafe5635SKent Overstreet 		err = "bad magic";
23481ab4190SKent Overstreet 		if (i->magic != bset_magic(&b->c->sb))
235cafe5635SKent Overstreet 			goto err;
236cafe5635SKent Overstreet 
237cafe5635SKent Overstreet 		err = "bad checksum";
238cafe5635SKent Overstreet 		switch (i->version) {
239cafe5635SKent Overstreet 		case 0:
240cafe5635SKent Overstreet 			if (i->csum != csum_set(i))
241cafe5635SKent Overstreet 				goto err;
242cafe5635SKent Overstreet 			break;
243cafe5635SKent Overstreet 		case BCACHE_BSET_VERSION:
244cafe5635SKent Overstreet 			if (i->csum != btree_csum_set(b, i))
245cafe5635SKent Overstreet 				goto err;
246cafe5635SKent Overstreet 			break;
247cafe5635SKent Overstreet 		}
248cafe5635SKent Overstreet 
249cafe5635SKent Overstreet 		err = "empty set";
250a85e968eSKent Overstreet 		if (i != b->keys.set[0].data && !i->keys)
251cafe5635SKent Overstreet 			goto err;
252cafe5635SKent Overstreet 
253fafff81cSKent Overstreet 		bch_btree_iter_push(iter, i->start, bset_bkey_last(i));
254cafe5635SKent Overstreet 
255ee811287SKent Overstreet 		b->written += set_blocks(i, block_bytes(b->c));
256cafe5635SKent Overstreet 	}
257cafe5635SKent Overstreet 
258cafe5635SKent Overstreet 	err = "corrupted btree";
259cafe5635SKent Overstreet 	for (i = write_block(b);
260a85e968eSKent Overstreet 	     bset_sector_offset(&b->keys, i) < KEY_SIZE(&b->key);
261cafe5635SKent Overstreet 	     i = ((void *) i) + block_bytes(b->c))
262a85e968eSKent Overstreet 		if (i->seq == b->keys.set[0].data->seq)
263cafe5635SKent Overstreet 			goto err;
264cafe5635SKent Overstreet 
265a85e968eSKent Overstreet 	bch_btree_sort_and_fix_extents(&b->keys, iter, &b->c->sort);
266cafe5635SKent Overstreet 
267a85e968eSKent Overstreet 	i = b->keys.set[0].data;
268cafe5635SKent Overstreet 	err = "short btree key";
269a85e968eSKent Overstreet 	if (b->keys.set[0].size &&
270a85e968eSKent Overstreet 	    bkey_cmp(&b->key, &b->keys.set[0].end) < 0)
271cafe5635SKent Overstreet 		goto err;
272cafe5635SKent Overstreet 
273cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
274a85e968eSKent Overstreet 		bch_bset_init_next(&b->keys, write_block(b),
275a85e968eSKent Overstreet 				   bset_magic(&b->c->sb));
276cafe5635SKent Overstreet out:
27757943511SKent Overstreet 	mempool_free(iter, b->c->fill_iter);
27857943511SKent Overstreet 	return;
279cafe5635SKent Overstreet err:
280cafe5635SKent Overstreet 	set_btree_node_io_error(b);
28188b9f8c4SKent Overstreet 	bch_cache_set_error(b->c, "%s at bucket %zu, block %u, %u keys",
282cafe5635SKent Overstreet 			    err, PTR_BUCKET_NR(b->c, &b->key, 0),
28388b9f8c4SKent Overstreet 			    bset_block_offset(b, i), i->keys);
284cafe5635SKent Overstreet 	goto out;
285cafe5635SKent Overstreet }
286cafe5635SKent Overstreet 
28757943511SKent Overstreet static void btree_node_read_endio(struct bio *bio, int error)
288cafe5635SKent Overstreet {
28957943511SKent Overstreet 	struct closure *cl = bio->bi_private;
29057943511SKent Overstreet 	closure_put(cl);
29157943511SKent Overstreet }
292cafe5635SKent Overstreet 
29378b77bf8SKent Overstreet static void bch_btree_node_read(struct btree *b)
29457943511SKent Overstreet {
29557943511SKent Overstreet 	uint64_t start_time = local_clock();
29657943511SKent Overstreet 	struct closure cl;
29757943511SKent Overstreet 	struct bio *bio;
298cafe5635SKent Overstreet 
299c37511b8SKent Overstreet 	trace_bcache_btree_read(b);
300c37511b8SKent Overstreet 
30157943511SKent Overstreet 	closure_init_stack(&cl);
302cafe5635SKent Overstreet 
30357943511SKent Overstreet 	bio = bch_bbio_alloc(b->c);
30457943511SKent Overstreet 	bio->bi_rw	= REQ_META|READ_SYNC;
3054f024f37SKent Overstreet 	bio->bi_iter.bi_size = KEY_SIZE(&b->key) << 9;
30657943511SKent Overstreet 	bio->bi_end_io	= btree_node_read_endio;
30757943511SKent Overstreet 	bio->bi_private	= &cl;
30857943511SKent Overstreet 
309a85e968eSKent Overstreet 	bch_bio_map(bio, b->keys.set[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;
396ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
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;
408ee811287SKent Overstreet 	b->bio->bi_iter.bi_size	= roundup(set_bytes(i), 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);
427ee811287SKent Overstreet 	SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) +
428a85e968eSKent Overstreet 		       bset_sector_offset(&b->keys, i));
429cafe5635SKent Overstreet 
4308e51e414SKent Overstreet 	if (!bio_alloc_pages(b->bio, GFP_NOIO)) {
431cafe5635SKent Overstreet 		int j;
432cafe5635SKent Overstreet 		struct bio_vec *bv;
433cafe5635SKent Overstreet 		void *base = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
434cafe5635SKent Overstreet 
4357988613bSKent Overstreet 		bio_for_each_segment_all(bv, b->bio, j)
436cafe5635SKent Overstreet 			memcpy(page_address(bv->bv_page),
437cafe5635SKent Overstreet 			       base + j * PAGE_SIZE, PAGE_SIZE);
438cafe5635SKent Overstreet 
439cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
440cafe5635SKent Overstreet 
44157943511SKent Overstreet 		continue_at(cl, btree_node_write_done, NULL);
442cafe5635SKent Overstreet 	} else {
443cafe5635SKent Overstreet 		b->bio->bi_vcnt = 0;
444169ef1cfSKent Overstreet 		bch_bio_map(b->bio, i);
445cafe5635SKent Overstreet 
446cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
447cafe5635SKent Overstreet 
448cafe5635SKent Overstreet 		closure_sync(cl);
449cb7a583eSKent Overstreet 		continue_at_nobarrier(cl, __btree_node_write_done, NULL);
450cafe5635SKent Overstreet 	}
451cafe5635SKent Overstreet }
452cafe5635SKent Overstreet 
45357943511SKent Overstreet void bch_btree_node_write(struct btree *b, struct closure *parent)
454cafe5635SKent Overstreet {
455ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
456cafe5635SKent Overstreet 
457c37511b8SKent Overstreet 	trace_bcache_btree_write(b);
458c37511b8SKent Overstreet 
459cafe5635SKent Overstreet 	BUG_ON(current->bio_list);
46057943511SKent Overstreet 	BUG_ON(b->written >= btree_blocks(b));
46157943511SKent Overstreet 	BUG_ON(b->written && !i->keys);
462ee811287SKent Overstreet 	BUG_ON(btree_bset_first(b)->seq != i->seq);
463280481d0SKent Overstreet 	bch_check_keys(b, "writing");
464cafe5635SKent Overstreet 
465cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
466cafe5635SKent Overstreet 
46757943511SKent Overstreet 	/* If caller isn't waiting for write, parent refcount is cache set */
468cb7a583eSKent Overstreet 	down(&b->io_mutex);
469cb7a583eSKent Overstreet 	closure_init(&b->io, parent ?: &b->c->cl);
47057943511SKent Overstreet 
471cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty,	 &b->flags);
472cafe5635SKent Overstreet 	change_bit(BTREE_NODE_write_idx, &b->flags);
473cafe5635SKent Overstreet 
47457943511SKent Overstreet 	do_btree_node_write(b);
475cafe5635SKent Overstreet 
476ee811287SKent Overstreet 	atomic_long_add(set_blocks(i, block_bytes(b->c)) * b->c->sb.block_size,
477cafe5635SKent Overstreet 			&PTR_CACHE(b->c, &b->key, 0)->btree_sectors_written);
478cafe5635SKent Overstreet 
479a85e968eSKent Overstreet 	b->written += set_blocks(i, block_bytes(b->c));
480a85e968eSKent Overstreet 
48167539e85SKent Overstreet 	/* If not a leaf node, always sort */
482a85e968eSKent Overstreet 	if (b->level && b->keys.nsets)
48367539e85SKent Overstreet 		bch_btree_sort(b, &b->c->sort);
48467539e85SKent Overstreet 	else
48567539e85SKent Overstreet 		bch_btree_sort_lazy(b, &b->c->sort);
486cafe5635SKent Overstreet 
48778b77bf8SKent Overstreet 	/*
48878b77bf8SKent Overstreet 	 * do verify if there was more than one set initially (i.e. we did a
48978b77bf8SKent Overstreet 	 * sort) and we sorted down to a single set:
49078b77bf8SKent Overstreet 	 */
491a85e968eSKent Overstreet 	if (i != b->keys.set->data && !b->keys.nsets)
49278b77bf8SKent Overstreet 		bch_btree_verify(b);
49378b77bf8SKent Overstreet 
494cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
495a85e968eSKent Overstreet 		bch_bset_init_next(&b->keys, write_block(b),
496a85e968eSKent Overstreet 				   bset_magic(&b->c->sb));
497cafe5635SKent Overstreet }
498cafe5635SKent Overstreet 
499f269af5aSKent Overstreet static void bch_btree_node_write_sync(struct btree *b)
500f269af5aSKent Overstreet {
501f269af5aSKent Overstreet 	struct closure cl;
502f269af5aSKent Overstreet 
503f269af5aSKent Overstreet 	closure_init_stack(&cl);
504f269af5aSKent Overstreet 	bch_btree_node_write(b, &cl);
505f269af5aSKent Overstreet 	closure_sync(&cl);
506f269af5aSKent Overstreet }
507f269af5aSKent Overstreet 
50857943511SKent Overstreet static void btree_node_write_work(struct work_struct *w)
509cafe5635SKent Overstreet {
510cafe5635SKent Overstreet 	struct btree *b = container_of(to_delayed_work(w), struct btree, work);
511cafe5635SKent Overstreet 
51257943511SKent Overstreet 	rw_lock(true, b, b->level);
513cafe5635SKent Overstreet 
514cafe5635SKent Overstreet 	if (btree_node_dirty(b))
51557943511SKent Overstreet 		bch_btree_node_write(b, NULL);
51657943511SKent Overstreet 	rw_unlock(true, b);
517cafe5635SKent Overstreet }
518cafe5635SKent Overstreet 
519c18536a7SKent Overstreet static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
520cafe5635SKent Overstreet {
521ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
522cafe5635SKent Overstreet 	struct btree_write *w = btree_current_write(b);
523cafe5635SKent Overstreet 
52457943511SKent Overstreet 	BUG_ON(!b->written);
52557943511SKent Overstreet 	BUG_ON(!i->keys);
526cafe5635SKent Overstreet 
52757943511SKent Overstreet 	if (!btree_node_dirty(b))
52857943511SKent Overstreet 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
52957943511SKent Overstreet 
530cafe5635SKent Overstreet 	set_btree_node_dirty(b);
531cafe5635SKent Overstreet 
532c18536a7SKent Overstreet 	if (journal_ref) {
533cafe5635SKent Overstreet 		if (w->journal &&
534c18536a7SKent Overstreet 		    journal_pin_cmp(b->c, w->journal, journal_ref)) {
535cafe5635SKent Overstreet 			atomic_dec_bug(w->journal);
536cafe5635SKent Overstreet 			w->journal = NULL;
537cafe5635SKent Overstreet 		}
538cafe5635SKent Overstreet 
539cafe5635SKent Overstreet 		if (!w->journal) {
540c18536a7SKent Overstreet 			w->journal = journal_ref;
541cafe5635SKent Overstreet 			atomic_inc(w->journal);
542cafe5635SKent Overstreet 		}
543cafe5635SKent Overstreet 	}
544cafe5635SKent Overstreet 
545cafe5635SKent Overstreet 	/* Force write if set is too big */
54657943511SKent Overstreet 	if (set_bytes(i) > PAGE_SIZE - 48 &&
54757943511SKent Overstreet 	    !current->bio_list)
54857943511SKent Overstreet 		bch_btree_node_write(b, NULL);
549cafe5635SKent Overstreet }
550cafe5635SKent Overstreet 
551cafe5635SKent Overstreet /*
552cafe5635SKent Overstreet  * Btree in memory cache - allocation/freeing
553cafe5635SKent Overstreet  * mca -> memory cache
554cafe5635SKent Overstreet  */
555cafe5635SKent Overstreet 
556cafe5635SKent Overstreet #define mca_reserve(c)	(((c->root && c->root->level)		\
557cafe5635SKent Overstreet 			  ? c->root->level : 1) * 8 + 16)
558cafe5635SKent Overstreet #define mca_can_free(c)						\
559cafe5635SKent Overstreet 	max_t(int, 0, c->bucket_cache_used - mca_reserve(c))
560cafe5635SKent Overstreet 
561cafe5635SKent Overstreet static void mca_data_free(struct btree *b)
562cafe5635SKent Overstreet {
563cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
564cafe5635SKent Overstreet 
565a85e968eSKent Overstreet 	bch_btree_keys_free(&b->keys);
566cafe5635SKent Overstreet 
567cafe5635SKent Overstreet 	b->c->bucket_cache_used--;
568ee811287SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freed);
569cafe5635SKent Overstreet }
570cafe5635SKent Overstreet 
571cafe5635SKent Overstreet static void mca_bucket_free(struct btree *b)
572cafe5635SKent Overstreet {
573cafe5635SKent Overstreet 	BUG_ON(btree_node_dirty(b));
574cafe5635SKent Overstreet 
575cafe5635SKent Overstreet 	b->key.ptr[0] = 0;
576cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
577cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freeable);
578cafe5635SKent Overstreet }
579cafe5635SKent Overstreet 
580cafe5635SKent Overstreet static unsigned btree_order(struct bkey *k)
581cafe5635SKent Overstreet {
582cafe5635SKent Overstreet 	return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
583cafe5635SKent Overstreet }
584cafe5635SKent Overstreet 
585cafe5635SKent Overstreet static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
586cafe5635SKent Overstreet {
587a85e968eSKent Overstreet 	if (!bch_btree_keys_alloc(&b->keys,
588ee811287SKent Overstreet 				  max_t(unsigned,
589cafe5635SKent Overstreet 					ilog2(b->c->btree_pages),
590ee811287SKent Overstreet 					btree_order(k)),
591ee811287SKent Overstreet 				  gfp)) {
592cafe5635SKent Overstreet 		b->c->bucket_cache_used++;
593ee811287SKent Overstreet 		list_move(&b->list, &b->c->btree_cache);
594ee811287SKent Overstreet 	} else {
595ee811287SKent Overstreet 		list_move(&b->list, &b->c->btree_cache_freed);
596ee811287SKent Overstreet 	}
597cafe5635SKent Overstreet }
598cafe5635SKent Overstreet 
599cafe5635SKent Overstreet static struct btree *mca_bucket_alloc(struct cache_set *c,
600cafe5635SKent Overstreet 				      struct bkey *k, gfp_t gfp)
601cafe5635SKent Overstreet {
602cafe5635SKent Overstreet 	struct btree *b = kzalloc(sizeof(struct btree), gfp);
603cafe5635SKent Overstreet 	if (!b)
604cafe5635SKent Overstreet 		return NULL;
605cafe5635SKent Overstreet 
606cafe5635SKent Overstreet 	init_rwsem(&b->lock);
607cafe5635SKent Overstreet 	lockdep_set_novalidate_class(&b->lock);
608cafe5635SKent Overstreet 	INIT_LIST_HEAD(&b->list);
60957943511SKent Overstreet 	INIT_DELAYED_WORK(&b->work, btree_node_write_work);
610cafe5635SKent Overstreet 	b->c = c;
611cb7a583eSKent Overstreet 	sema_init(&b->io_mutex, 1);
612cafe5635SKent Overstreet 
613cafe5635SKent Overstreet 	mca_data_alloc(b, k, gfp);
614cafe5635SKent Overstreet 	return b;
615cafe5635SKent Overstreet }
616cafe5635SKent Overstreet 
617e8e1d468SKent Overstreet static int mca_reap(struct btree *b, unsigned min_order, bool flush)
618cafe5635SKent Overstreet {
619e8e1d468SKent Overstreet 	struct closure cl;
620e8e1d468SKent Overstreet 
621e8e1d468SKent Overstreet 	closure_init_stack(&cl);
622cafe5635SKent Overstreet 	lockdep_assert_held(&b->c->bucket_lock);
623cafe5635SKent Overstreet 
624cafe5635SKent Overstreet 	if (!down_write_trylock(&b->lock))
625cafe5635SKent Overstreet 		return -ENOMEM;
626cafe5635SKent Overstreet 
627a85e968eSKent Overstreet 	BUG_ON(btree_node_dirty(b) && !b->keys.set[0].data);
628e8e1d468SKent Overstreet 
629a85e968eSKent Overstreet 	if (b->keys.page_order < min_order)
630cb7a583eSKent Overstreet 		goto out_unlock;
631cb7a583eSKent Overstreet 
632cb7a583eSKent Overstreet 	if (!flush) {
633cb7a583eSKent Overstreet 		if (btree_node_dirty(b))
634cb7a583eSKent Overstreet 			goto out_unlock;
635cb7a583eSKent Overstreet 
636cb7a583eSKent Overstreet 		if (down_trylock(&b->io_mutex))
637cb7a583eSKent Overstreet 			goto out_unlock;
638cb7a583eSKent Overstreet 		up(&b->io_mutex);
639cafe5635SKent Overstreet 	}
640cafe5635SKent Overstreet 
641f269af5aSKent Overstreet 	if (btree_node_dirty(b))
642f269af5aSKent Overstreet 		bch_btree_node_write_sync(b);
643cafe5635SKent Overstreet 
644e8e1d468SKent Overstreet 	/* wait for any in flight btree write */
645cb7a583eSKent Overstreet 	down(&b->io_mutex);
646cb7a583eSKent Overstreet 	up(&b->io_mutex);
647e8e1d468SKent Overstreet 
648cafe5635SKent Overstreet 	return 0;
649cb7a583eSKent Overstreet out_unlock:
650cb7a583eSKent Overstreet 	rw_unlock(true, b);
651cb7a583eSKent Overstreet 	return -ENOMEM;
652cafe5635SKent Overstreet }
653cafe5635SKent Overstreet 
6547dc19d5aSDave Chinner static unsigned long bch_mca_scan(struct shrinker *shrink,
6557dc19d5aSDave Chinner 				  struct shrink_control *sc)
656cafe5635SKent Overstreet {
657cafe5635SKent Overstreet 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
658cafe5635SKent Overstreet 	struct btree *b, *t;
659cafe5635SKent Overstreet 	unsigned long i, nr = sc->nr_to_scan;
6607dc19d5aSDave Chinner 	unsigned long freed = 0;
661cafe5635SKent Overstreet 
662cafe5635SKent Overstreet 	if (c->shrinker_disabled)
6637dc19d5aSDave Chinner 		return SHRINK_STOP;
664cafe5635SKent Overstreet 
665cafe5635SKent Overstreet 	if (c->try_harder)
6667dc19d5aSDave Chinner 		return SHRINK_STOP;
667cafe5635SKent Overstreet 
668cafe5635SKent Overstreet 	/* Return -1 if we can't do anything right now */
669a698e08cSKent Overstreet 	if (sc->gfp_mask & __GFP_IO)
670cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
671cafe5635SKent Overstreet 	else if (!mutex_trylock(&c->bucket_lock))
672cafe5635SKent Overstreet 		return -1;
673cafe5635SKent Overstreet 
67436c9ea98SKent Overstreet 	/*
67536c9ea98SKent Overstreet 	 * It's _really_ critical that we don't free too many btree nodes - we
67636c9ea98SKent Overstreet 	 * have to always leave ourselves a reserve. The reserve is how we
67736c9ea98SKent Overstreet 	 * guarantee that allocating memory for a new btree node can always
67836c9ea98SKent Overstreet 	 * succeed, so that inserting keys into the btree can always succeed and
67936c9ea98SKent Overstreet 	 * IO can always make forward progress:
68036c9ea98SKent Overstreet 	 */
681cafe5635SKent Overstreet 	nr /= c->btree_pages;
682cafe5635SKent Overstreet 	nr = min_t(unsigned long, nr, mca_can_free(c));
683cafe5635SKent Overstreet 
684cafe5635SKent Overstreet 	i = 0;
685cafe5635SKent Overstreet 	list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
6867dc19d5aSDave Chinner 		if (freed >= nr)
687cafe5635SKent Overstreet 			break;
688cafe5635SKent Overstreet 
689cafe5635SKent Overstreet 		if (++i > 3 &&
690e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
691cafe5635SKent Overstreet 			mca_data_free(b);
692cafe5635SKent Overstreet 			rw_unlock(true, b);
6937dc19d5aSDave Chinner 			freed++;
694cafe5635SKent Overstreet 		}
695cafe5635SKent Overstreet 	}
696cafe5635SKent Overstreet 
697b0f32a56SKent Overstreet 	for (i = 0; (nr--) && i < c->bucket_cache_used; i++) {
698cafe5635SKent Overstreet 		if (list_empty(&c->btree_cache))
699cafe5635SKent Overstreet 			goto out;
700cafe5635SKent Overstreet 
701cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
702cafe5635SKent Overstreet 		list_rotate_left(&c->btree_cache);
703cafe5635SKent Overstreet 
704cafe5635SKent Overstreet 		if (!b->accessed &&
705e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
706cafe5635SKent Overstreet 			mca_bucket_free(b);
707cafe5635SKent Overstreet 			mca_data_free(b);
708cafe5635SKent Overstreet 			rw_unlock(true, b);
7097dc19d5aSDave Chinner 			freed++;
710cafe5635SKent Overstreet 		} else
711cafe5635SKent Overstreet 			b->accessed = 0;
712cafe5635SKent Overstreet 	}
713cafe5635SKent Overstreet out:
714cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
7157dc19d5aSDave Chinner 	return freed;
7167dc19d5aSDave Chinner }
7177dc19d5aSDave Chinner 
7187dc19d5aSDave Chinner static unsigned long bch_mca_count(struct shrinker *shrink,
7197dc19d5aSDave Chinner 				   struct shrink_control *sc)
7207dc19d5aSDave Chinner {
7217dc19d5aSDave Chinner 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
7227dc19d5aSDave Chinner 
7237dc19d5aSDave Chinner 	if (c->shrinker_disabled)
7247dc19d5aSDave Chinner 		return 0;
7257dc19d5aSDave Chinner 
7267dc19d5aSDave Chinner 	if (c->try_harder)
7277dc19d5aSDave Chinner 		return 0;
7287dc19d5aSDave Chinner 
7297dc19d5aSDave Chinner 	return mca_can_free(c) * c->btree_pages;
730cafe5635SKent Overstreet }
731cafe5635SKent Overstreet 
732cafe5635SKent Overstreet void bch_btree_cache_free(struct cache_set *c)
733cafe5635SKent Overstreet {
734cafe5635SKent Overstreet 	struct btree *b;
735cafe5635SKent Overstreet 	struct closure cl;
736cafe5635SKent Overstreet 	closure_init_stack(&cl);
737cafe5635SKent Overstreet 
738cafe5635SKent Overstreet 	if (c->shrink.list.next)
739cafe5635SKent Overstreet 		unregister_shrinker(&c->shrink);
740cafe5635SKent Overstreet 
741cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
742cafe5635SKent Overstreet 
743cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
744cafe5635SKent Overstreet 	if (c->verify_data)
745cafe5635SKent Overstreet 		list_move(&c->verify_data->list, &c->btree_cache);
74678b77bf8SKent Overstreet 
74778b77bf8SKent Overstreet 	free_pages((unsigned long) c->verify_ondisk, ilog2(bucket_pages(c)));
748cafe5635SKent Overstreet #endif
749cafe5635SKent Overstreet 
750cafe5635SKent Overstreet 	list_splice(&c->btree_cache_freeable,
751cafe5635SKent Overstreet 		    &c->btree_cache);
752cafe5635SKent Overstreet 
753cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache)) {
754cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
755cafe5635SKent Overstreet 
756cafe5635SKent Overstreet 		if (btree_node_dirty(b))
757cafe5635SKent Overstreet 			btree_complete_write(b, btree_current_write(b));
758cafe5635SKent Overstreet 		clear_bit(BTREE_NODE_dirty, &b->flags);
759cafe5635SKent Overstreet 
760cafe5635SKent Overstreet 		mca_data_free(b);
761cafe5635SKent Overstreet 	}
762cafe5635SKent Overstreet 
763cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache_freed)) {
764cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache_freed,
765cafe5635SKent Overstreet 				     struct btree, list);
766cafe5635SKent Overstreet 		list_del(&b->list);
767cafe5635SKent Overstreet 		cancel_delayed_work_sync(&b->work);
768cafe5635SKent Overstreet 		kfree(b);
769cafe5635SKent Overstreet 	}
770cafe5635SKent Overstreet 
771cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
772cafe5635SKent Overstreet }
773cafe5635SKent Overstreet 
774cafe5635SKent Overstreet int bch_btree_cache_alloc(struct cache_set *c)
775cafe5635SKent Overstreet {
776cafe5635SKent Overstreet 	unsigned i;
777cafe5635SKent Overstreet 
778cafe5635SKent Overstreet 	for (i = 0; i < mca_reserve(c); i++)
77972a44517SKent Overstreet 		if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
78072a44517SKent Overstreet 			return -ENOMEM;
781cafe5635SKent Overstreet 
782cafe5635SKent Overstreet 	list_splice_init(&c->btree_cache,
783cafe5635SKent Overstreet 			 &c->btree_cache_freeable);
784cafe5635SKent Overstreet 
785cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
786cafe5635SKent Overstreet 	mutex_init(&c->verify_lock);
787cafe5635SKent Overstreet 
78878b77bf8SKent Overstreet 	c->verify_ondisk = (void *)
78978b77bf8SKent Overstreet 		__get_free_pages(GFP_KERNEL, ilog2(bucket_pages(c)));
79078b77bf8SKent Overstreet 
791cafe5635SKent Overstreet 	c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
792cafe5635SKent Overstreet 
793cafe5635SKent Overstreet 	if (c->verify_data &&
794a85e968eSKent Overstreet 	    c->verify_data->keys.set->data)
795cafe5635SKent Overstreet 		list_del_init(&c->verify_data->list);
796cafe5635SKent Overstreet 	else
797cafe5635SKent Overstreet 		c->verify_data = NULL;
798cafe5635SKent Overstreet #endif
799cafe5635SKent Overstreet 
8007dc19d5aSDave Chinner 	c->shrink.count_objects = bch_mca_count;
8017dc19d5aSDave Chinner 	c->shrink.scan_objects = bch_mca_scan;
802cafe5635SKent Overstreet 	c->shrink.seeks = 4;
803cafe5635SKent Overstreet 	c->shrink.batch = c->btree_pages * 2;
804cafe5635SKent Overstreet 	register_shrinker(&c->shrink);
805cafe5635SKent Overstreet 
806cafe5635SKent Overstreet 	return 0;
807cafe5635SKent Overstreet }
808cafe5635SKent Overstreet 
809cafe5635SKent Overstreet /* Btree in memory cache - hash table */
810cafe5635SKent Overstreet 
811cafe5635SKent Overstreet static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
812cafe5635SKent Overstreet {
813cafe5635SKent Overstreet 	return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
814cafe5635SKent Overstreet }
815cafe5635SKent Overstreet 
816cafe5635SKent Overstreet static struct btree *mca_find(struct cache_set *c, struct bkey *k)
817cafe5635SKent Overstreet {
818cafe5635SKent Overstreet 	struct btree *b;
819cafe5635SKent Overstreet 
820cafe5635SKent Overstreet 	rcu_read_lock();
821cafe5635SKent Overstreet 	hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
822cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
823cafe5635SKent Overstreet 			goto out;
824cafe5635SKent Overstreet 	b = NULL;
825cafe5635SKent Overstreet out:
826cafe5635SKent Overstreet 	rcu_read_unlock();
827cafe5635SKent Overstreet 	return b;
828cafe5635SKent Overstreet }
829cafe5635SKent Overstreet 
830e8e1d468SKent Overstreet static struct btree *mca_cannibalize(struct cache_set *c, struct bkey *k)
831cafe5635SKent Overstreet {
832e8e1d468SKent Overstreet 	struct btree *b;
833cafe5635SKent Overstreet 
834c37511b8SKent Overstreet 	trace_bcache_btree_cache_cannibalize(c);
835c37511b8SKent Overstreet 
836e8e1d468SKent Overstreet 	if (!c->try_harder) {
837e8e1d468SKent Overstreet 		c->try_harder = current;
838cafe5635SKent Overstreet 		c->try_harder_start = local_clock();
839e8e1d468SKent Overstreet 	} else if (c->try_harder != current)
840e8e1d468SKent Overstreet 		return ERR_PTR(-ENOSPC);
841cafe5635SKent Overstreet 
842e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
843e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
844e8e1d468SKent Overstreet 			return b;
845cafe5635SKent Overstreet 
846e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
847e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), true))
848e8e1d468SKent Overstreet 			return b;
849e8e1d468SKent Overstreet 
850e8e1d468SKent Overstreet 	return ERR_PTR(-ENOMEM);
851cafe5635SKent Overstreet }
852cafe5635SKent Overstreet 
853cafe5635SKent Overstreet /*
854cafe5635SKent Overstreet  * We can only have one thread cannibalizing other cached btree nodes at a time,
855cafe5635SKent Overstreet  * or we'll deadlock. We use an open coded mutex to ensure that, which a
856cafe5635SKent Overstreet  * cannibalize_bucket() will take. This means every time we unlock the root of
857cafe5635SKent Overstreet  * the btree, we need to release this lock if we have it held.
858cafe5635SKent Overstreet  */
859df8e8970SKent Overstreet static void bch_cannibalize_unlock(struct cache_set *c)
860cafe5635SKent Overstreet {
861e8e1d468SKent Overstreet 	if (c->try_harder == current) {
862169ef1cfSKent Overstreet 		bch_time_stats_update(&c->try_harder_time, c->try_harder_start);
863cafe5635SKent Overstreet 		c->try_harder = NULL;
864e8e1d468SKent Overstreet 		wake_up(&c->try_wait);
865cafe5635SKent Overstreet 	}
866cafe5635SKent Overstreet }
867cafe5635SKent Overstreet 
868e8e1d468SKent Overstreet static struct btree *mca_alloc(struct cache_set *c, struct bkey *k, int level)
869cafe5635SKent Overstreet {
870cafe5635SKent Overstreet 	struct btree *b;
871cafe5635SKent Overstreet 
872e8e1d468SKent Overstreet 	BUG_ON(current->bio_list);
873e8e1d468SKent Overstreet 
874cafe5635SKent Overstreet 	lockdep_assert_held(&c->bucket_lock);
875cafe5635SKent Overstreet 
876cafe5635SKent Overstreet 	if (mca_find(c, k))
877cafe5635SKent Overstreet 		return NULL;
878cafe5635SKent Overstreet 
879cafe5635SKent Overstreet 	/* btree_free() doesn't free memory; it sticks the node on the end of
880cafe5635SKent Overstreet 	 * the list. Check if there's any freed nodes there:
881cafe5635SKent Overstreet 	 */
882cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freeable, list)
883e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
884cafe5635SKent Overstreet 			goto out;
885cafe5635SKent Overstreet 
886cafe5635SKent Overstreet 	/* We never free struct btree itself, just the memory that holds the on
887cafe5635SKent Overstreet 	 * disk node. Check the freed list before allocating a new one:
888cafe5635SKent Overstreet 	 */
889cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freed, list)
890e8e1d468SKent Overstreet 		if (!mca_reap(b, 0, false)) {
891cafe5635SKent Overstreet 			mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
892a85e968eSKent Overstreet 			if (!b->keys.set[0].data)
893cafe5635SKent Overstreet 				goto err;
894cafe5635SKent Overstreet 			else
895cafe5635SKent Overstreet 				goto out;
896cafe5635SKent Overstreet 		}
897cafe5635SKent Overstreet 
898cafe5635SKent Overstreet 	b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
899cafe5635SKent Overstreet 	if (!b)
900cafe5635SKent Overstreet 		goto err;
901cafe5635SKent Overstreet 
902cafe5635SKent Overstreet 	BUG_ON(!down_write_trylock(&b->lock));
903a85e968eSKent Overstreet 	if (!b->keys.set->data)
904cafe5635SKent Overstreet 		goto err;
905cafe5635SKent Overstreet out:
906cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
907cafe5635SKent Overstreet 
908cafe5635SKent Overstreet 	bkey_copy(&b->key, k);
909cafe5635SKent Overstreet 	list_move(&b->list, &c->btree_cache);
910cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
911cafe5635SKent Overstreet 	hlist_add_head_rcu(&b->hash, mca_hash(c, k));
912cafe5635SKent Overstreet 
913cafe5635SKent Overstreet 	lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
914d6fd3b11SKent Overstreet 	b->parent	= (void *) ~0UL;
915a85e968eSKent Overstreet 	b->flags	= 0;
916a85e968eSKent Overstreet 	b->written	= 0;
917a85e968eSKent Overstreet 	b->level	= level;
918cafe5635SKent Overstreet 
91965d45231SKent Overstreet 	if (!b->level)
920a85e968eSKent Overstreet 		bch_btree_keys_init(&b->keys, &bch_extent_keys_ops,
921a85e968eSKent Overstreet 				    &b->c->expensive_debug_checks);
92265d45231SKent Overstreet 	else
923a85e968eSKent Overstreet 		bch_btree_keys_init(&b->keys, &bch_btree_keys_ops,
924a85e968eSKent Overstreet 				    &b->c->expensive_debug_checks);
925cafe5635SKent Overstreet 
926cafe5635SKent Overstreet 	return b;
927cafe5635SKent Overstreet err:
928cafe5635SKent Overstreet 	if (b)
929cafe5635SKent Overstreet 		rw_unlock(true, b);
930cafe5635SKent Overstreet 
931e8e1d468SKent Overstreet 	b = mca_cannibalize(c, k);
932cafe5635SKent Overstreet 	if (!IS_ERR(b))
933cafe5635SKent Overstreet 		goto out;
934cafe5635SKent Overstreet 
935cafe5635SKent Overstreet 	return b;
936cafe5635SKent Overstreet }
937cafe5635SKent Overstreet 
938cafe5635SKent Overstreet /**
939cafe5635SKent Overstreet  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
940cafe5635SKent Overstreet  * in from disk if necessary.
941cafe5635SKent Overstreet  *
942b54d6934SKent Overstreet  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
943cafe5635SKent Overstreet  *
944cafe5635SKent Overstreet  * The btree node will have either a read or a write lock held, depending on
945cafe5635SKent Overstreet  * level and op->lock.
946cafe5635SKent Overstreet  */
947cafe5635SKent Overstreet struct btree *bch_btree_node_get(struct cache_set *c, struct bkey *k,
948e8e1d468SKent Overstreet 				 int level, bool write)
949cafe5635SKent Overstreet {
950cafe5635SKent Overstreet 	int i = 0;
951cafe5635SKent Overstreet 	struct btree *b;
952cafe5635SKent Overstreet 
953cafe5635SKent Overstreet 	BUG_ON(level < 0);
954cafe5635SKent Overstreet retry:
955cafe5635SKent Overstreet 	b = mca_find(c, k);
956cafe5635SKent Overstreet 
957cafe5635SKent Overstreet 	if (!b) {
95857943511SKent Overstreet 		if (current->bio_list)
95957943511SKent Overstreet 			return ERR_PTR(-EAGAIN);
96057943511SKent Overstreet 
961cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
962e8e1d468SKent Overstreet 		b = mca_alloc(c, k, level);
963cafe5635SKent Overstreet 		mutex_unlock(&c->bucket_lock);
964cafe5635SKent Overstreet 
965cafe5635SKent Overstreet 		if (!b)
966cafe5635SKent Overstreet 			goto retry;
967cafe5635SKent Overstreet 		if (IS_ERR(b))
968cafe5635SKent Overstreet 			return b;
969cafe5635SKent Overstreet 
97057943511SKent Overstreet 		bch_btree_node_read(b);
971cafe5635SKent Overstreet 
972cafe5635SKent Overstreet 		if (!write)
973cafe5635SKent Overstreet 			downgrade_write(&b->lock);
974cafe5635SKent Overstreet 	} else {
975cafe5635SKent Overstreet 		rw_lock(write, b, level);
976cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
977cafe5635SKent Overstreet 			rw_unlock(write, b);
978cafe5635SKent Overstreet 			goto retry;
979cafe5635SKent Overstreet 		}
980cafe5635SKent Overstreet 		BUG_ON(b->level != level);
981cafe5635SKent Overstreet 	}
982cafe5635SKent Overstreet 
983cafe5635SKent Overstreet 	b->accessed = 1;
984cafe5635SKent Overstreet 
985a85e968eSKent Overstreet 	for (; i <= b->keys.nsets && b->keys.set[i].size; i++) {
986a85e968eSKent Overstreet 		prefetch(b->keys.set[i].tree);
987a85e968eSKent Overstreet 		prefetch(b->keys.set[i].data);
988cafe5635SKent Overstreet 	}
989cafe5635SKent Overstreet 
990a85e968eSKent Overstreet 	for (; i <= b->keys.nsets; i++)
991a85e968eSKent Overstreet 		prefetch(b->keys.set[i].data);
992cafe5635SKent Overstreet 
99357943511SKent Overstreet 	if (btree_node_io_error(b)) {
994cafe5635SKent Overstreet 		rw_unlock(write, b);
99557943511SKent Overstreet 		return ERR_PTR(-EIO);
99657943511SKent Overstreet 	}
99757943511SKent Overstreet 
998cafe5635SKent Overstreet 	BUG_ON(!b->written);
999cafe5635SKent Overstreet 
1000cafe5635SKent Overstreet 	return b;
1001cafe5635SKent Overstreet }
1002cafe5635SKent Overstreet 
1003cafe5635SKent Overstreet static void btree_node_prefetch(struct cache_set *c, struct bkey *k, int level)
1004cafe5635SKent Overstreet {
1005cafe5635SKent Overstreet 	struct btree *b;
1006cafe5635SKent Overstreet 
1007cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1008e8e1d468SKent Overstreet 	b = mca_alloc(c, k, level);
1009cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1010cafe5635SKent Overstreet 
1011cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(b)) {
101257943511SKent Overstreet 		bch_btree_node_read(b);
1013cafe5635SKent Overstreet 		rw_unlock(true, b);
1014cafe5635SKent Overstreet 	}
1015cafe5635SKent Overstreet }
1016cafe5635SKent Overstreet 
1017cafe5635SKent Overstreet /* Btree alloc */
1018cafe5635SKent Overstreet 
1019e8e1d468SKent Overstreet static void btree_node_free(struct btree *b)
1020cafe5635SKent Overstreet {
1021cafe5635SKent Overstreet 	unsigned i;
1022cafe5635SKent Overstreet 
1023c37511b8SKent Overstreet 	trace_bcache_btree_node_free(b);
1024c37511b8SKent Overstreet 
1025cafe5635SKent Overstreet 	BUG_ON(b == b->c->root);
1026cafe5635SKent Overstreet 
1027cafe5635SKent Overstreet 	if (btree_node_dirty(b))
1028cafe5635SKent Overstreet 		btree_complete_write(b, btree_current_write(b));
1029cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty, &b->flags);
1030cafe5635SKent Overstreet 
1031cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
1032cafe5635SKent Overstreet 
1033cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
1034cafe5635SKent Overstreet 
1035cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++) {
1036cafe5635SKent Overstreet 		BUG_ON(atomic_read(&PTR_BUCKET(b->c, &b->key, i)->pin));
1037cafe5635SKent Overstreet 
1038cafe5635SKent Overstreet 		bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
1039cafe5635SKent Overstreet 			    PTR_BUCKET(b->c, &b->key, i));
1040cafe5635SKent Overstreet 	}
1041cafe5635SKent Overstreet 
1042cafe5635SKent Overstreet 	bch_bucket_free(b->c, &b->key);
1043cafe5635SKent Overstreet 	mca_bucket_free(b);
1044cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
1045cafe5635SKent Overstreet }
1046cafe5635SKent Overstreet 
1047bc9389eeSKent Overstreet struct btree *bch_btree_node_alloc(struct cache_set *c, int level, bool wait)
1048cafe5635SKent Overstreet {
1049cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
1050cafe5635SKent Overstreet 	struct btree *b = ERR_PTR(-EAGAIN);
1051cafe5635SKent Overstreet 
1052cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1053cafe5635SKent Overstreet retry:
105478365411SKent Overstreet 	if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, wait))
1055cafe5635SKent Overstreet 		goto err;
1056cafe5635SKent Overstreet 
10573a3b6a4eSKent Overstreet 	bkey_put(c, &k.key);
1058cafe5635SKent Overstreet 	SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1059cafe5635SKent Overstreet 
1060e8e1d468SKent Overstreet 	b = mca_alloc(c, &k.key, level);
1061cafe5635SKent Overstreet 	if (IS_ERR(b))
1062cafe5635SKent Overstreet 		goto err_free;
1063cafe5635SKent Overstreet 
1064cafe5635SKent Overstreet 	if (!b) {
1065b1a67b0fSKent Overstreet 		cache_bug(c,
1066b1a67b0fSKent Overstreet 			"Tried to allocate bucket that was in btree cache");
1067cafe5635SKent Overstreet 		goto retry;
1068cafe5635SKent Overstreet 	}
1069cafe5635SKent Overstreet 
1070cafe5635SKent Overstreet 	b->accessed = 1;
1071a85e968eSKent Overstreet 	bch_bset_init_next(&b->keys, b->keys.set->data, bset_magic(&b->c->sb));
1072cafe5635SKent Overstreet 
1073cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1074c37511b8SKent Overstreet 
1075c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc(b);
1076cafe5635SKent Overstreet 	return b;
1077cafe5635SKent Overstreet err_free:
1078cafe5635SKent Overstreet 	bch_bucket_free(c, &k.key);
1079cafe5635SKent Overstreet err:
1080cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1081c37511b8SKent Overstreet 
1082c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc_fail(b);
1083cafe5635SKent Overstreet 	return b;
1084cafe5635SKent Overstreet }
1085cafe5635SKent Overstreet 
1086bc9389eeSKent Overstreet static struct btree *btree_node_alloc_replacement(struct btree *b, bool wait)
1087cafe5635SKent Overstreet {
1088bc9389eeSKent Overstreet 	struct btree *n = bch_btree_node_alloc(b->c, b->level, wait);
108967539e85SKent Overstreet 	if (!IS_ERR_OR_NULL(n)) {
109067539e85SKent Overstreet 		bch_btree_sort_into(b, n, &b->c->sort);
109167539e85SKent Overstreet 		bkey_copy_key(&n->key, &b->key);
109267539e85SKent Overstreet 	}
1093cafe5635SKent Overstreet 
1094cafe5635SKent Overstreet 	return n;
1095cafe5635SKent Overstreet }
1096cafe5635SKent Overstreet 
10978835c123SKent Overstreet static void make_btree_freeing_key(struct btree *b, struct bkey *k)
10988835c123SKent Overstreet {
10998835c123SKent Overstreet 	unsigned i;
11008835c123SKent Overstreet 
11018835c123SKent Overstreet 	bkey_copy(k, &b->key);
11028835c123SKent Overstreet 	bkey_copy_key(k, &ZERO_KEY);
11038835c123SKent Overstreet 
11048835c123SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
11058835c123SKent Overstreet 		uint8_t g = PTR_BUCKET(b->c, k, i)->gen + 1;
11068835c123SKent Overstreet 
11078835c123SKent Overstreet 		SET_PTR_GEN(k, i, g);
11088835c123SKent Overstreet 	}
11098835c123SKent Overstreet 
11108835c123SKent Overstreet 	atomic_inc(&b->c->prio_blocked);
11118835c123SKent Overstreet }
11128835c123SKent Overstreet 
111378365411SKent Overstreet static int btree_check_reserve(struct btree *b, struct btree_op *op)
111478365411SKent Overstreet {
111578365411SKent Overstreet 	struct cache_set *c = b->c;
111678365411SKent Overstreet 	struct cache *ca;
111778365411SKent Overstreet 	unsigned i, reserve = c->root->level * 2 + 1;
111878365411SKent Overstreet 	int ret = 0;
111978365411SKent Overstreet 
112078365411SKent Overstreet 	mutex_lock(&c->bucket_lock);
112178365411SKent Overstreet 
112278365411SKent Overstreet 	for_each_cache(ca, c, i)
112378365411SKent Overstreet 		if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
112478365411SKent Overstreet 			if (op)
112578365411SKent Overstreet 				prepare_to_wait(&c->bucket_wait, &op->wait,
112678365411SKent Overstreet 						TASK_UNINTERRUPTIBLE);
112778365411SKent Overstreet 			ret = -EINTR;
112878365411SKent Overstreet 			break;
112978365411SKent Overstreet 		}
113078365411SKent Overstreet 
113178365411SKent Overstreet 	mutex_unlock(&c->bucket_lock);
113278365411SKent Overstreet 	return ret;
113378365411SKent Overstreet }
113478365411SKent Overstreet 
1135cafe5635SKent Overstreet /* Garbage collection */
1136cafe5635SKent Overstreet 
1137cafe5635SKent Overstreet uint8_t __bch_btree_mark_key(struct cache_set *c, int level, struct bkey *k)
1138cafe5635SKent Overstreet {
1139cafe5635SKent Overstreet 	uint8_t stale = 0;
1140cafe5635SKent Overstreet 	unsigned i;
1141cafe5635SKent Overstreet 	struct bucket *g;
1142cafe5635SKent Overstreet 
1143cafe5635SKent Overstreet 	/*
1144cafe5635SKent Overstreet 	 * ptr_invalid() can't return true for the keys that mark btree nodes as
1145cafe5635SKent Overstreet 	 * freed, but since ptr_bad() returns true we'll never actually use them
1146cafe5635SKent Overstreet 	 * for anything and thus we don't want mark their pointers here
1147cafe5635SKent Overstreet 	 */
1148cafe5635SKent Overstreet 	if (!bkey_cmp(k, &ZERO_KEY))
1149cafe5635SKent Overstreet 		return stale;
1150cafe5635SKent Overstreet 
1151cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
1152cafe5635SKent Overstreet 		if (!ptr_available(c, k, i))
1153cafe5635SKent Overstreet 			continue;
1154cafe5635SKent Overstreet 
1155cafe5635SKent Overstreet 		g = PTR_BUCKET(c, k, i);
1156cafe5635SKent Overstreet 
1157cafe5635SKent Overstreet 		if (gen_after(g->gc_gen, PTR_GEN(k, i)))
1158cafe5635SKent Overstreet 			g->gc_gen = PTR_GEN(k, i);
1159cafe5635SKent Overstreet 
1160cafe5635SKent Overstreet 		if (ptr_stale(c, k, i)) {
1161cafe5635SKent Overstreet 			stale = max(stale, ptr_stale(c, k, i));
1162cafe5635SKent Overstreet 			continue;
1163cafe5635SKent Overstreet 		}
1164cafe5635SKent Overstreet 
1165cafe5635SKent Overstreet 		cache_bug_on(GC_MARK(g) &&
1166cafe5635SKent Overstreet 			     (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1167cafe5635SKent Overstreet 			     c, "inconsistent ptrs: mark = %llu, level = %i",
1168cafe5635SKent Overstreet 			     GC_MARK(g), level);
1169cafe5635SKent Overstreet 
1170cafe5635SKent Overstreet 		if (level)
1171cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_METADATA);
1172cafe5635SKent Overstreet 		else if (KEY_DIRTY(k))
1173cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_DIRTY);
1174cafe5635SKent Overstreet 
1175cafe5635SKent Overstreet 		/* guard against overflow */
1176cafe5635SKent Overstreet 		SET_GC_SECTORS_USED(g, min_t(unsigned,
1177cafe5635SKent Overstreet 					     GC_SECTORS_USED(g) + KEY_SIZE(k),
1178cafe5635SKent Overstreet 					     (1 << 14) - 1));
1179cafe5635SKent Overstreet 
1180cafe5635SKent Overstreet 		BUG_ON(!GC_SECTORS_USED(g));
1181cafe5635SKent Overstreet 	}
1182cafe5635SKent Overstreet 
1183cafe5635SKent Overstreet 	return stale;
1184cafe5635SKent Overstreet }
1185cafe5635SKent Overstreet 
1186cafe5635SKent Overstreet #define btree_mark_key(b, k)	__bch_btree_mark_key(b->c, b->level, k)
1187cafe5635SKent Overstreet 
1188a1f0358bSKent Overstreet static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1189cafe5635SKent Overstreet {
1190cafe5635SKent Overstreet 	uint8_t stale = 0;
1191a1f0358bSKent Overstreet 	unsigned keys = 0, good_keys = 0;
1192cafe5635SKent Overstreet 	struct bkey *k;
1193cafe5635SKent Overstreet 	struct btree_iter iter;
1194cafe5635SKent Overstreet 	struct bset_tree *t;
1195cafe5635SKent Overstreet 
1196cafe5635SKent Overstreet 	gc->nodes++;
1197cafe5635SKent Overstreet 
1198cafe5635SKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1199cafe5635SKent Overstreet 		stale = max(stale, btree_mark_key(b, k));
1200a1f0358bSKent Overstreet 		keys++;
1201cafe5635SKent Overstreet 
1202a85e968eSKent Overstreet 		if (bch_ptr_bad(&b->keys, k))
1203cafe5635SKent Overstreet 			continue;
1204cafe5635SKent Overstreet 
1205cafe5635SKent Overstreet 		gc->key_bytes += bkey_u64s(k);
1206cafe5635SKent Overstreet 		gc->nkeys++;
1207a1f0358bSKent Overstreet 		good_keys++;
1208cafe5635SKent Overstreet 
1209cafe5635SKent Overstreet 		gc->data += KEY_SIZE(k);
1210cafe5635SKent Overstreet 	}
1211cafe5635SKent Overstreet 
1212a85e968eSKent Overstreet 	for (t = b->keys.set; t <= &b->keys.set[b->keys.nsets]; t++)
1213cafe5635SKent Overstreet 		btree_bug_on(t->size &&
1214a85e968eSKent Overstreet 			     bset_written(&b->keys, t) &&
1215cafe5635SKent Overstreet 			     bkey_cmp(&b->key, &t->end) < 0,
1216cafe5635SKent Overstreet 			     b, "found short btree key in gc");
1217cafe5635SKent Overstreet 
1218a1f0358bSKent Overstreet 	if (b->c->gc_always_rewrite)
1219a1f0358bSKent Overstreet 		return true;
1220a1f0358bSKent Overstreet 
1221a1f0358bSKent Overstreet 	if (stale > 10)
1222a1f0358bSKent Overstreet 		return true;
1223a1f0358bSKent Overstreet 
1224a1f0358bSKent Overstreet 	if ((keys - good_keys) * 2 > keys)
1225a1f0358bSKent Overstreet 		return true;
1226a1f0358bSKent Overstreet 
1227a1f0358bSKent Overstreet 	return false;
1228cafe5635SKent Overstreet }
1229cafe5635SKent Overstreet 
1230a1f0358bSKent Overstreet #define GC_MERGE_NODES	4U
1231cafe5635SKent Overstreet 
1232cafe5635SKent Overstreet struct gc_merge_info {
1233cafe5635SKent Overstreet 	struct btree	*b;
1234cafe5635SKent Overstreet 	unsigned	keys;
1235cafe5635SKent Overstreet };
1236cafe5635SKent Overstreet 
1237a1f0358bSKent Overstreet static int bch_btree_insert_node(struct btree *, struct btree_op *,
1238a1f0358bSKent Overstreet 				 struct keylist *, atomic_t *, struct bkey *);
1239a1f0358bSKent Overstreet 
1240a1f0358bSKent Overstreet static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
1241a1f0358bSKent Overstreet 			     struct keylist *keylist, struct gc_stat *gc,
1242e8e1d468SKent Overstreet 			     struct gc_merge_info *r)
1243cafe5635SKent Overstreet {
1244a1f0358bSKent Overstreet 	unsigned i, nodes = 0, keys = 0, blocks;
1245a1f0358bSKent Overstreet 	struct btree *new_nodes[GC_MERGE_NODES];
1246b54d6934SKent Overstreet 	struct closure cl;
1247a1f0358bSKent Overstreet 	struct bkey *k;
1248b54d6934SKent Overstreet 
1249a1f0358bSKent Overstreet 	memset(new_nodes, 0, sizeof(new_nodes));
1250b54d6934SKent Overstreet 	closure_init_stack(&cl);
1251cafe5635SKent Overstreet 
1252a1f0358bSKent Overstreet 	while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1253cafe5635SKent Overstreet 		keys += r[nodes++].keys;
1254cafe5635SKent Overstreet 
1255cafe5635SKent Overstreet 	blocks = btree_default_blocks(b->c) * 2 / 3;
1256cafe5635SKent Overstreet 
1257cafe5635SKent Overstreet 	if (nodes < 2 ||
1258a85e968eSKent Overstreet 	    __set_blocks(b->keys.set[0].data, keys,
1259ee811287SKent Overstreet 			 block_bytes(b->c)) > blocks * (nodes - 1))
1260a1f0358bSKent Overstreet 		return 0;
1261cafe5635SKent Overstreet 
1262a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1263bc9389eeSKent Overstreet 		new_nodes[i] = btree_node_alloc_replacement(r[i].b, false);
1264a1f0358bSKent Overstreet 		if (IS_ERR_OR_NULL(new_nodes[i]))
1265a1f0358bSKent Overstreet 			goto out_nocoalesce;
1266cafe5635SKent Overstreet 	}
1267cafe5635SKent Overstreet 
1268cafe5635SKent Overstreet 	for (i = nodes - 1; i > 0; --i) {
1269ee811287SKent Overstreet 		struct bset *n1 = btree_bset_first(new_nodes[i]);
1270ee811287SKent Overstreet 		struct bset *n2 = btree_bset_first(new_nodes[i - 1]);
1271cafe5635SKent Overstreet 		struct bkey *k, *last = NULL;
1272cafe5635SKent Overstreet 
1273cafe5635SKent Overstreet 		keys = 0;
1274cafe5635SKent Overstreet 
1275a1f0358bSKent Overstreet 		if (i > 1) {
1276cafe5635SKent Overstreet 			for (k = n2->start;
1277fafff81cSKent Overstreet 			     k < bset_bkey_last(n2);
1278cafe5635SKent Overstreet 			     k = bkey_next(k)) {
1279cafe5635SKent Overstreet 				if (__set_blocks(n1, n1->keys + keys +
1280ee811287SKent Overstreet 						 bkey_u64s(k),
1281ee811287SKent Overstreet 						 block_bytes(b->c)) > blocks)
1282cafe5635SKent Overstreet 					break;
1283cafe5635SKent Overstreet 
1284cafe5635SKent Overstreet 				last = k;
1285cafe5635SKent Overstreet 				keys += bkey_u64s(k);
1286cafe5635SKent Overstreet 			}
1287a1f0358bSKent Overstreet 		} else {
1288a1f0358bSKent Overstreet 			/*
1289a1f0358bSKent Overstreet 			 * Last node we're not getting rid of - we're getting
1290a1f0358bSKent Overstreet 			 * rid of the node at r[0]. Have to try and fit all of
1291a1f0358bSKent Overstreet 			 * the remaining keys into this node; we can't ensure
1292a1f0358bSKent Overstreet 			 * they will always fit due to rounding and variable
1293a1f0358bSKent Overstreet 			 * length keys (shouldn't be possible in practice,
1294a1f0358bSKent Overstreet 			 * though)
1295a1f0358bSKent Overstreet 			 */
1296a1f0358bSKent Overstreet 			if (__set_blocks(n1, n1->keys + n2->keys,
1297ee811287SKent Overstreet 					 block_bytes(b->c)) >
1298ee811287SKent Overstreet 			    btree_blocks(new_nodes[i]))
1299a1f0358bSKent Overstreet 				goto out_nocoalesce;
1300a1f0358bSKent Overstreet 
1301a1f0358bSKent Overstreet 			keys = n2->keys;
1302a1f0358bSKent Overstreet 			/* Take the key of the node we're getting rid of */
1303a1f0358bSKent Overstreet 			last = &r->b->key;
1304a1f0358bSKent Overstreet 		}
1305cafe5635SKent Overstreet 
1306ee811287SKent Overstreet 		BUG_ON(__set_blocks(n1, n1->keys + keys, block_bytes(b->c)) >
1307ee811287SKent Overstreet 		       btree_blocks(new_nodes[i]));
1308cafe5635SKent Overstreet 
1309a1f0358bSKent Overstreet 		if (last)
1310a1f0358bSKent Overstreet 			bkey_copy_key(&new_nodes[i]->key, last);
1311cafe5635SKent Overstreet 
1312fafff81cSKent Overstreet 		memcpy(bset_bkey_last(n1),
1313cafe5635SKent Overstreet 		       n2->start,
1314fafff81cSKent Overstreet 		       (void *) bset_bkey_idx(n2, keys) - (void *) n2->start);
1315cafe5635SKent Overstreet 
1316cafe5635SKent Overstreet 		n1->keys += keys;
1317a1f0358bSKent Overstreet 		r[i].keys = n1->keys;
1318cafe5635SKent Overstreet 
1319cafe5635SKent Overstreet 		memmove(n2->start,
1320fafff81cSKent Overstreet 			bset_bkey_idx(n2, keys),
1321fafff81cSKent Overstreet 			(void *) bset_bkey_last(n2) -
1322fafff81cSKent Overstreet 			(void *) bset_bkey_idx(n2, keys));
1323cafe5635SKent Overstreet 
1324cafe5635SKent Overstreet 		n2->keys -= keys;
1325cafe5635SKent Overstreet 
1326085d2a3dSKent Overstreet 		if (__bch_keylist_realloc(keylist,
1327085d2a3dSKent Overstreet 					  bkey_u64s(&new_nodes[i]->key)))
1328a1f0358bSKent Overstreet 			goto out_nocoalesce;
1329a1f0358bSKent Overstreet 
1330a1f0358bSKent Overstreet 		bch_btree_node_write(new_nodes[i], &cl);
1331a1f0358bSKent Overstreet 		bch_keylist_add(keylist, &new_nodes[i]->key);
1332cafe5635SKent Overstreet 	}
1333cafe5635SKent Overstreet 
1334a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1335085d2a3dSKent Overstreet 		if (__bch_keylist_realloc(keylist, bkey_u64s(&r[i].b->key)))
1336a1f0358bSKent Overstreet 			goto out_nocoalesce;
1337a1f0358bSKent Overstreet 
1338a1f0358bSKent Overstreet 		make_btree_freeing_key(r[i].b, keylist->top);
1339a1f0358bSKent Overstreet 		bch_keylist_push(keylist);
1340a1f0358bSKent Overstreet 	}
1341a1f0358bSKent Overstreet 
1342a1f0358bSKent Overstreet 	/* We emptied out this node */
1343ee811287SKent Overstreet 	BUG_ON(btree_bset_first(new_nodes[0])->keys);
1344a1f0358bSKent Overstreet 	btree_node_free(new_nodes[0]);
1345a1f0358bSKent Overstreet 	rw_unlock(true, new_nodes[0]);
1346a1f0358bSKent Overstreet 
1347a1f0358bSKent Overstreet 	closure_sync(&cl);
1348a1f0358bSKent Overstreet 
1349a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1350a1f0358bSKent Overstreet 		btree_node_free(r[i].b);
1351a1f0358bSKent Overstreet 		rw_unlock(true, r[i].b);
1352a1f0358bSKent Overstreet 
1353a1f0358bSKent Overstreet 		r[i].b = new_nodes[i];
1354a1f0358bSKent Overstreet 	}
1355a1f0358bSKent Overstreet 
1356a1f0358bSKent Overstreet 	bch_btree_insert_node(b, op, keylist, NULL, NULL);
1357a1f0358bSKent Overstreet 	BUG_ON(!bch_keylist_empty(keylist));
1358a1f0358bSKent Overstreet 
1359a1f0358bSKent Overstreet 	memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1360a1f0358bSKent Overstreet 	r[nodes - 1].b = ERR_PTR(-EINTR);
1361cafe5635SKent Overstreet 
1362c37511b8SKent Overstreet 	trace_bcache_btree_gc_coalesce(nodes);
1363cafe5635SKent Overstreet 	gc->nodes--;
1364cafe5635SKent Overstreet 
1365a1f0358bSKent Overstreet 	/* Invalidated our iterator */
1366a1f0358bSKent Overstreet 	return -EINTR;
1367a1f0358bSKent Overstreet 
1368a1f0358bSKent Overstreet out_nocoalesce:
1369a1f0358bSKent Overstreet 	closure_sync(&cl);
1370a1f0358bSKent Overstreet 
1371a1f0358bSKent Overstreet 	while ((k = bch_keylist_pop(keylist)))
1372a1f0358bSKent Overstreet 		if (!bkey_cmp(k, &ZERO_KEY))
1373a1f0358bSKent Overstreet 			atomic_dec(&b->c->prio_blocked);
1374a1f0358bSKent Overstreet 
1375a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++)
1376a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(new_nodes[i])) {
1377a1f0358bSKent Overstreet 			btree_node_free(new_nodes[i]);
1378a1f0358bSKent Overstreet 			rw_unlock(true, new_nodes[i]);
1379a1f0358bSKent Overstreet 		}
1380a1f0358bSKent Overstreet 	return 0;
1381a1f0358bSKent Overstreet }
1382a1f0358bSKent Overstreet 
1383a1f0358bSKent Overstreet static unsigned btree_gc_count_keys(struct btree *b)
1384a1f0358bSKent Overstreet {
1385a1f0358bSKent Overstreet 	struct bkey *k;
1386a1f0358bSKent Overstreet 	struct btree_iter iter;
1387a1f0358bSKent Overstreet 	unsigned ret = 0;
1388a1f0358bSKent Overstreet 
1389a1f0358bSKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_bad)
1390a1f0358bSKent Overstreet 		ret += bkey_u64s(k);
1391a1f0358bSKent Overstreet 
1392a1f0358bSKent Overstreet 	return ret;
1393cafe5635SKent Overstreet }
1394cafe5635SKent Overstreet 
1395cafe5635SKent Overstreet static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1396cafe5635SKent Overstreet 			    struct closure *writes, struct gc_stat *gc)
1397cafe5635SKent Overstreet {
1398cafe5635SKent Overstreet 	unsigned i;
1399a1f0358bSKent Overstreet 	int ret = 0;
1400a1f0358bSKent Overstreet 	bool should_rewrite;
1401a1f0358bSKent Overstreet 	struct btree *n;
1402a1f0358bSKent Overstreet 	struct bkey *k;
1403a1f0358bSKent Overstreet 	struct keylist keys;
1404a1f0358bSKent Overstreet 	struct btree_iter iter;
1405cafe5635SKent Overstreet 	struct gc_merge_info r[GC_MERGE_NODES];
1406a1f0358bSKent Overstreet 	struct gc_merge_info *last = r + GC_MERGE_NODES - 1;
1407cafe5635SKent Overstreet 
1408a1f0358bSKent Overstreet 	bch_keylist_init(&keys);
1409a1f0358bSKent Overstreet 	bch_btree_iter_init(b, &iter, &b->c->gc_done);
1410cafe5635SKent Overstreet 
1411a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1412a1f0358bSKent Overstreet 		r[i].b = ERR_PTR(-EINTR);
1413cafe5635SKent Overstreet 
1414a1f0358bSKent Overstreet 	while (1) {
1415a85e968eSKent Overstreet 		k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad);
1416a1f0358bSKent Overstreet 		if (k) {
1417a1f0358bSKent Overstreet 			r->b = bch_btree_node_get(b->c, k, b->level - 1, true);
1418cafe5635SKent Overstreet 			if (IS_ERR(r->b)) {
1419cafe5635SKent Overstreet 				ret = PTR_ERR(r->b);
1420cafe5635SKent Overstreet 				break;
1421cafe5635SKent Overstreet 			}
1422cafe5635SKent Overstreet 
1423a1f0358bSKent Overstreet 			r->keys = btree_gc_count_keys(r->b);
1424cafe5635SKent Overstreet 
1425a1f0358bSKent Overstreet 			ret = btree_gc_coalesce(b, op, &keys, gc, r);
1426a1f0358bSKent Overstreet 			if (ret)
1427cafe5635SKent Overstreet 				break;
1428cafe5635SKent Overstreet 		}
1429cafe5635SKent Overstreet 
1430a1f0358bSKent Overstreet 		if (!last->b)
1431a1f0358bSKent Overstreet 			break;
1432cafe5635SKent Overstreet 
1433a1f0358bSKent Overstreet 		if (!IS_ERR(last->b)) {
1434a1f0358bSKent Overstreet 			should_rewrite = btree_gc_mark_node(last->b, gc);
143578365411SKent Overstreet 			if (should_rewrite &&
143678365411SKent Overstreet 			    !btree_check_reserve(b, NULL)) {
1437bc9389eeSKent Overstreet 				n = btree_node_alloc_replacement(last->b,
1438bc9389eeSKent Overstreet 								 false);
1439cafe5635SKent Overstreet 
1440a1f0358bSKent Overstreet 				if (!IS_ERR_OR_NULL(n)) {
1441a1f0358bSKent Overstreet 					bch_btree_node_write_sync(n);
1442a1f0358bSKent Overstreet 					bch_keylist_add(&keys, &n->key);
1443cafe5635SKent Overstreet 
1444a1f0358bSKent Overstreet 					make_btree_freeing_key(last->b,
1445a1f0358bSKent Overstreet 							       keys.top);
1446a1f0358bSKent Overstreet 					bch_keylist_push(&keys);
1447cafe5635SKent Overstreet 
1448a1f0358bSKent Overstreet 					btree_node_free(last->b);
1449a1f0358bSKent Overstreet 
1450a1f0358bSKent Overstreet 					bch_btree_insert_node(b, op, &keys,
1451a1f0358bSKent Overstreet 							      NULL, NULL);
1452a1f0358bSKent Overstreet 					BUG_ON(!bch_keylist_empty(&keys));
1453a1f0358bSKent Overstreet 
1454a1f0358bSKent Overstreet 					rw_unlock(true, last->b);
1455a1f0358bSKent Overstreet 					last->b = n;
1456a1f0358bSKent Overstreet 
1457a1f0358bSKent Overstreet 					/* Invalidated our iterator */
1458a1f0358bSKent Overstreet 					ret = -EINTR;
1459a1f0358bSKent Overstreet 					break;
1460a1f0358bSKent Overstreet 				}
1461a1f0358bSKent Overstreet 			}
1462a1f0358bSKent Overstreet 
1463a1f0358bSKent Overstreet 			if (last->b->level) {
1464a1f0358bSKent Overstreet 				ret = btree_gc_recurse(last->b, op, writes, gc);
1465a1f0358bSKent Overstreet 				if (ret)
1466a1f0358bSKent Overstreet 					break;
1467a1f0358bSKent Overstreet 			}
1468a1f0358bSKent Overstreet 
1469a1f0358bSKent Overstreet 			bkey_copy_key(&b->c->gc_done, &last->b->key);
1470a1f0358bSKent Overstreet 
1471a1f0358bSKent Overstreet 			/*
1472a1f0358bSKent Overstreet 			 * Must flush leaf nodes before gc ends, since replace
1473a1f0358bSKent Overstreet 			 * operations aren't journalled
1474cafe5635SKent Overstreet 			 */
1475a1f0358bSKent Overstreet 			if (btree_node_dirty(last->b))
1476a1f0358bSKent Overstreet 				bch_btree_node_write(last->b, writes);
1477a1f0358bSKent Overstreet 			rw_unlock(true, last->b);
1478a1f0358bSKent Overstreet 		}
1479a1f0358bSKent Overstreet 
1480a1f0358bSKent Overstreet 		memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1481a1f0358bSKent Overstreet 		r->b = NULL;
1482a1f0358bSKent Overstreet 
1483cafe5635SKent Overstreet 		if (need_resched()) {
1484cafe5635SKent Overstreet 			ret = -EAGAIN;
1485cafe5635SKent Overstreet 			break;
1486cafe5635SKent Overstreet 		}
1487cafe5635SKent Overstreet 	}
1488cafe5635SKent Overstreet 
1489a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1490a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(r[i].b)) {
1491a1f0358bSKent Overstreet 			if (btree_node_dirty(r[i].b))
1492a1f0358bSKent Overstreet 				bch_btree_node_write(r[i].b, writes);
1493a1f0358bSKent Overstreet 			rw_unlock(true, r[i].b);
1494a1f0358bSKent Overstreet 		}
1495cafe5635SKent Overstreet 
1496a1f0358bSKent Overstreet 	bch_keylist_free(&keys);
1497cafe5635SKent Overstreet 
1498cafe5635SKent Overstreet 	return ret;
1499cafe5635SKent Overstreet }
1500cafe5635SKent Overstreet 
1501cafe5635SKent Overstreet static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1502cafe5635SKent Overstreet 			     struct closure *writes, struct gc_stat *gc)
1503cafe5635SKent Overstreet {
1504cafe5635SKent Overstreet 	struct btree *n = NULL;
1505a1f0358bSKent Overstreet 	int ret = 0;
1506a1f0358bSKent Overstreet 	bool should_rewrite;
1507cafe5635SKent Overstreet 
1508a1f0358bSKent Overstreet 	should_rewrite = btree_gc_mark_node(b, gc);
1509a1f0358bSKent Overstreet 	if (should_rewrite) {
1510bc9389eeSKent Overstreet 		n = btree_node_alloc_replacement(b, false);
1511cafe5635SKent Overstreet 
1512cafe5635SKent Overstreet 		if (!IS_ERR_OR_NULL(n)) {
1513a1f0358bSKent Overstreet 			bch_btree_node_write_sync(n);
1514a1f0358bSKent Overstreet 			bch_btree_set_root(n);
1515a1f0358bSKent Overstreet 			btree_node_free(b);
1516a1f0358bSKent Overstreet 			rw_unlock(true, n);
1517a1f0358bSKent Overstreet 
1518a1f0358bSKent Overstreet 			return -EINTR;
1519cafe5635SKent Overstreet 		}
1520a1f0358bSKent Overstreet 	}
1521a1f0358bSKent Overstreet 
1522a1f0358bSKent Overstreet 	if (b->level) {
1523a1f0358bSKent Overstreet 		ret = btree_gc_recurse(b, op, writes, gc);
1524a1f0358bSKent Overstreet 		if (ret)
1525a1f0358bSKent Overstreet 			return ret;
1526a1f0358bSKent Overstreet 	}
1527a1f0358bSKent Overstreet 
1528a1f0358bSKent Overstreet 	bkey_copy_key(&b->c->gc_done, &b->key);
1529cafe5635SKent Overstreet 
1530cafe5635SKent Overstreet 	return ret;
1531cafe5635SKent Overstreet }
1532cafe5635SKent Overstreet 
1533cafe5635SKent Overstreet static void btree_gc_start(struct cache_set *c)
1534cafe5635SKent Overstreet {
1535cafe5635SKent Overstreet 	struct cache *ca;
1536cafe5635SKent Overstreet 	struct bucket *b;
1537cafe5635SKent Overstreet 	unsigned i;
1538cafe5635SKent Overstreet 
1539cafe5635SKent Overstreet 	if (!c->gc_mark_valid)
1540cafe5635SKent Overstreet 		return;
1541cafe5635SKent Overstreet 
1542cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1543cafe5635SKent Overstreet 
1544cafe5635SKent Overstreet 	c->gc_mark_valid = 0;
1545cafe5635SKent Overstreet 	c->gc_done = ZERO_KEY;
1546cafe5635SKent Overstreet 
1547cafe5635SKent Overstreet 	for_each_cache(ca, c, i)
1548cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1549cafe5635SKent Overstreet 			b->gc_gen = b->gen;
155029ebf465SKent Overstreet 			if (!atomic_read(&b->pin)) {
1551cafe5635SKent Overstreet 				SET_GC_MARK(b, GC_MARK_RECLAIMABLE);
155229ebf465SKent Overstreet 				SET_GC_SECTORS_USED(b, 0);
155329ebf465SKent Overstreet 			}
1554cafe5635SKent Overstreet 		}
1555cafe5635SKent Overstreet 
1556cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1557cafe5635SKent Overstreet }
1558cafe5635SKent Overstreet 
1559cafe5635SKent Overstreet size_t bch_btree_gc_finish(struct cache_set *c)
1560cafe5635SKent Overstreet {
1561cafe5635SKent Overstreet 	size_t available = 0;
1562cafe5635SKent Overstreet 	struct bucket *b;
1563cafe5635SKent Overstreet 	struct cache *ca;
1564cafe5635SKent Overstreet 	unsigned i;
1565cafe5635SKent Overstreet 
1566cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1567cafe5635SKent Overstreet 
1568cafe5635SKent Overstreet 	set_gc_sectors(c);
1569cafe5635SKent Overstreet 	c->gc_mark_valid = 1;
1570cafe5635SKent Overstreet 	c->need_gc	= 0;
1571cafe5635SKent Overstreet 
1572cafe5635SKent Overstreet 	if (c->root)
1573cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(&c->root->key); i++)
1574cafe5635SKent Overstreet 			SET_GC_MARK(PTR_BUCKET(c, &c->root->key, i),
1575cafe5635SKent Overstreet 				    GC_MARK_METADATA);
1576cafe5635SKent Overstreet 
1577cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1578cafe5635SKent Overstreet 		SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1579cafe5635SKent Overstreet 			    GC_MARK_METADATA);
1580cafe5635SKent Overstreet 
1581bf0a628aSNicholas Swenson 	/* don't reclaim buckets to which writeback keys point */
1582bf0a628aSNicholas Swenson 	rcu_read_lock();
1583bf0a628aSNicholas Swenson 	for (i = 0; i < c->nr_uuids; i++) {
1584bf0a628aSNicholas Swenson 		struct bcache_device *d = c->devices[i];
1585bf0a628aSNicholas Swenson 		struct cached_dev *dc;
1586bf0a628aSNicholas Swenson 		struct keybuf_key *w, *n;
1587bf0a628aSNicholas Swenson 		unsigned j;
1588bf0a628aSNicholas Swenson 
1589bf0a628aSNicholas Swenson 		if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
1590bf0a628aSNicholas Swenson 			continue;
1591bf0a628aSNicholas Swenson 		dc = container_of(d, struct cached_dev, disk);
1592bf0a628aSNicholas Swenson 
1593bf0a628aSNicholas Swenson 		spin_lock(&dc->writeback_keys.lock);
1594bf0a628aSNicholas Swenson 		rbtree_postorder_for_each_entry_safe(w, n,
1595bf0a628aSNicholas Swenson 					&dc->writeback_keys.keys, node)
1596bf0a628aSNicholas Swenson 			for (j = 0; j < KEY_PTRS(&w->key); j++)
1597bf0a628aSNicholas Swenson 				SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
1598bf0a628aSNicholas Swenson 					    GC_MARK_DIRTY);
1599bf0a628aSNicholas Swenson 		spin_unlock(&dc->writeback_keys.lock);
1600bf0a628aSNicholas Swenson 	}
1601bf0a628aSNicholas Swenson 	rcu_read_unlock();
1602bf0a628aSNicholas Swenson 
1603cafe5635SKent Overstreet 	for_each_cache(ca, c, i) {
1604cafe5635SKent Overstreet 		uint64_t *i;
1605cafe5635SKent Overstreet 
1606cafe5635SKent Overstreet 		ca->invalidate_needs_gc = 0;
1607cafe5635SKent Overstreet 
1608cafe5635SKent Overstreet 		for (i = ca->sb.d; i < ca->sb.d + ca->sb.keys; i++)
1609cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1610cafe5635SKent Overstreet 
1611cafe5635SKent Overstreet 		for (i = ca->prio_buckets;
1612cafe5635SKent Overstreet 		     i < ca->prio_buckets + prio_buckets(ca) * 2; i++)
1613cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1614cafe5635SKent Overstreet 
1615cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1616cafe5635SKent Overstreet 			b->last_gc	= b->gc_gen;
1617cafe5635SKent Overstreet 			c->need_gc	= max(c->need_gc, bucket_gc_gen(b));
1618cafe5635SKent Overstreet 
1619cafe5635SKent Overstreet 			if (!atomic_read(&b->pin) &&
1620cafe5635SKent Overstreet 			    GC_MARK(b) == GC_MARK_RECLAIMABLE) {
1621cafe5635SKent Overstreet 				available++;
1622cafe5635SKent Overstreet 				if (!GC_SECTORS_USED(b))
1623cafe5635SKent Overstreet 					bch_bucket_add_unused(ca, b);
1624cafe5635SKent Overstreet 			}
1625cafe5635SKent Overstreet 		}
1626cafe5635SKent Overstreet 	}
1627cafe5635SKent Overstreet 
1628cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1629cafe5635SKent Overstreet 	return available;
1630cafe5635SKent Overstreet }
1631cafe5635SKent Overstreet 
163272a44517SKent Overstreet static void bch_btree_gc(struct cache_set *c)
1633cafe5635SKent Overstreet {
1634cafe5635SKent Overstreet 	int ret;
1635cafe5635SKent Overstreet 	unsigned long available;
1636cafe5635SKent Overstreet 	struct gc_stat stats;
1637cafe5635SKent Overstreet 	struct closure writes;
1638cafe5635SKent Overstreet 	struct btree_op op;
1639cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
164057943511SKent Overstreet 
1641c37511b8SKent Overstreet 	trace_bcache_gc_start(c);
1642cafe5635SKent Overstreet 
1643cafe5635SKent Overstreet 	memset(&stats, 0, sizeof(struct gc_stat));
1644cafe5635SKent Overstreet 	closure_init_stack(&writes);
1645b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1646cafe5635SKent Overstreet 
1647cafe5635SKent Overstreet 	btree_gc_start(c);
1648cafe5635SKent Overstreet 
1649a1f0358bSKent Overstreet 	do {
1650cafe5635SKent Overstreet 		ret = btree_root(gc_root, c, &op, &writes, &stats);
1651cafe5635SKent Overstreet 		closure_sync(&writes);
1652cafe5635SKent Overstreet 
1653a1f0358bSKent Overstreet 		if (ret && ret != -EAGAIN)
1654cafe5635SKent Overstreet 			pr_warn("gc failed!");
1655a1f0358bSKent Overstreet 	} while (ret);
1656cafe5635SKent Overstreet 
1657cafe5635SKent Overstreet 	available = bch_btree_gc_finish(c);
165857943511SKent Overstreet 	wake_up_allocators(c);
165957943511SKent Overstreet 
1660169ef1cfSKent Overstreet 	bch_time_stats_update(&c->btree_gc_time, start_time);
1661cafe5635SKent Overstreet 
1662cafe5635SKent Overstreet 	stats.key_bytes *= sizeof(uint64_t);
1663cafe5635SKent Overstreet 	stats.data	<<= 9;
1664cafe5635SKent Overstreet 	stats.in_use	= (c->nbuckets - available) * 100 / c->nbuckets;
1665cafe5635SKent Overstreet 	memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1666cafe5635SKent Overstreet 
1667c37511b8SKent Overstreet 	trace_bcache_gc_end(c);
1668cafe5635SKent Overstreet 
166972a44517SKent Overstreet 	bch_moving_gc(c);
1670cafe5635SKent Overstreet }
1671cafe5635SKent Overstreet 
167272a44517SKent Overstreet static int bch_gc_thread(void *arg)
1673cafe5635SKent Overstreet {
167472a44517SKent Overstreet 	struct cache_set *c = arg;
1675a1f0358bSKent Overstreet 	struct cache *ca;
1676a1f0358bSKent Overstreet 	unsigned i;
167772a44517SKent Overstreet 
167872a44517SKent Overstreet 	while (1) {
1679a1f0358bSKent Overstreet again:
168072a44517SKent Overstreet 		bch_btree_gc(c);
168172a44517SKent Overstreet 
168272a44517SKent Overstreet 		set_current_state(TASK_INTERRUPTIBLE);
168372a44517SKent Overstreet 		if (kthread_should_stop())
168472a44517SKent Overstreet 			break;
168572a44517SKent Overstreet 
1686a1f0358bSKent Overstreet 		mutex_lock(&c->bucket_lock);
1687a1f0358bSKent Overstreet 
1688a1f0358bSKent Overstreet 		for_each_cache(ca, c, i)
1689a1f0358bSKent Overstreet 			if (ca->invalidate_needs_gc) {
1690a1f0358bSKent Overstreet 				mutex_unlock(&c->bucket_lock);
1691a1f0358bSKent Overstreet 				set_current_state(TASK_RUNNING);
1692a1f0358bSKent Overstreet 				goto again;
1693a1f0358bSKent Overstreet 			}
1694a1f0358bSKent Overstreet 
1695a1f0358bSKent Overstreet 		mutex_unlock(&c->bucket_lock);
1696a1f0358bSKent Overstreet 
169772a44517SKent Overstreet 		try_to_freeze();
169872a44517SKent Overstreet 		schedule();
169972a44517SKent Overstreet 	}
170072a44517SKent Overstreet 
170172a44517SKent Overstreet 	return 0;
170272a44517SKent Overstreet }
170372a44517SKent Overstreet 
170472a44517SKent Overstreet int bch_gc_thread_start(struct cache_set *c)
170572a44517SKent Overstreet {
170672a44517SKent Overstreet 	c->gc_thread = kthread_create(bch_gc_thread, c, "bcache_gc");
170772a44517SKent Overstreet 	if (IS_ERR(c->gc_thread))
170872a44517SKent Overstreet 		return PTR_ERR(c->gc_thread);
170972a44517SKent Overstreet 
171072a44517SKent Overstreet 	set_task_state(c->gc_thread, TASK_INTERRUPTIBLE);
171172a44517SKent Overstreet 	return 0;
1712cafe5635SKent Overstreet }
1713cafe5635SKent Overstreet 
1714cafe5635SKent Overstreet /* Initial partial gc */
1715cafe5635SKent Overstreet 
1716cafe5635SKent Overstreet static int bch_btree_check_recurse(struct btree *b, struct btree_op *op,
1717cafe5635SKent Overstreet 				   unsigned long **seen)
1718cafe5635SKent Overstreet {
171950310164SKent Overstreet 	int ret = 0;
1720cafe5635SKent Overstreet 	unsigned i;
172150310164SKent Overstreet 	struct bkey *k, *p = NULL;
1722cafe5635SKent Overstreet 	struct bucket *g;
1723cafe5635SKent Overstreet 	struct btree_iter iter;
1724cafe5635SKent Overstreet 
1725cafe5635SKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1726cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(k); i++) {
1727cafe5635SKent Overstreet 			if (!ptr_available(b->c, k, i))
1728cafe5635SKent Overstreet 				continue;
1729cafe5635SKent Overstreet 
1730cafe5635SKent Overstreet 			g = PTR_BUCKET(b->c, k, i);
1731cafe5635SKent Overstreet 
1732cafe5635SKent Overstreet 			if (!__test_and_set_bit(PTR_BUCKET_NR(b->c, k, i),
1733cafe5635SKent Overstreet 						seen[PTR_DEV(k, i)]) ||
1734cafe5635SKent Overstreet 			    !ptr_stale(b->c, k, i)) {
1735cafe5635SKent Overstreet 				g->gen = PTR_GEN(k, i);
1736cafe5635SKent Overstreet 
1737cafe5635SKent Overstreet 				if (b->level)
1738cafe5635SKent Overstreet 					g->prio = BTREE_PRIO;
1739cafe5635SKent Overstreet 				else if (g->prio == BTREE_PRIO)
1740cafe5635SKent Overstreet 					g->prio = INITIAL_PRIO;
1741cafe5635SKent Overstreet 			}
1742cafe5635SKent Overstreet 		}
1743cafe5635SKent Overstreet 
1744cafe5635SKent Overstreet 		btree_mark_key(b, k);
1745cafe5635SKent Overstreet 	}
1746cafe5635SKent Overstreet 
1747cafe5635SKent Overstreet 	if (b->level) {
174850310164SKent Overstreet 		bch_btree_iter_init(b, &iter, NULL);
1749cafe5635SKent Overstreet 
175050310164SKent Overstreet 		do {
1751a85e968eSKent Overstreet 			k = bch_btree_iter_next_filter(&iter, &b->keys,
1752a85e968eSKent Overstreet 						       bch_ptr_bad);
175350310164SKent Overstreet 			if (k)
175450310164SKent Overstreet 				btree_node_prefetch(b->c, k, b->level - 1);
175550310164SKent Overstreet 
1756cafe5635SKent Overstreet 			if (p)
175750310164SKent Overstreet 				ret = btree(check_recurse, p, b, op, seen);
1758cafe5635SKent Overstreet 
175950310164SKent Overstreet 			p = k;
176050310164SKent Overstreet 		} while (p && !ret);
1761cafe5635SKent Overstreet 	}
1762cafe5635SKent Overstreet 
1763cafe5635SKent Overstreet 	return 0;
1764cafe5635SKent Overstreet }
1765cafe5635SKent Overstreet 
1766c18536a7SKent Overstreet int bch_btree_check(struct cache_set *c)
1767cafe5635SKent Overstreet {
1768cafe5635SKent Overstreet 	int ret = -ENOMEM;
1769cafe5635SKent Overstreet 	unsigned i;
1770cafe5635SKent Overstreet 	unsigned long *seen[MAX_CACHES_PER_SET];
1771c18536a7SKent Overstreet 	struct btree_op op;
1772cafe5635SKent Overstreet 
1773cafe5635SKent Overstreet 	memset(seen, 0, sizeof(seen));
1774b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1775cafe5635SKent Overstreet 
1776cafe5635SKent Overstreet 	for (i = 0; c->cache[i]; i++) {
1777cafe5635SKent Overstreet 		size_t n = DIV_ROUND_UP(c->cache[i]->sb.nbuckets, 8);
1778cafe5635SKent Overstreet 		seen[i] = kmalloc(n, GFP_KERNEL);
1779cafe5635SKent Overstreet 		if (!seen[i])
1780cafe5635SKent Overstreet 			goto err;
1781cafe5635SKent Overstreet 
1782cafe5635SKent Overstreet 		/* Disables the seen array until prio_read() uses it too */
1783cafe5635SKent Overstreet 		memset(seen[i], 0xFF, n);
1784cafe5635SKent Overstreet 	}
1785cafe5635SKent Overstreet 
1786c18536a7SKent Overstreet 	ret = btree_root(check_recurse, c, &op, seen);
1787cafe5635SKent Overstreet err:
1788cafe5635SKent Overstreet 	for (i = 0; i < MAX_CACHES_PER_SET; i++)
1789cafe5635SKent Overstreet 		kfree(seen[i]);
1790cafe5635SKent Overstreet 	return ret;
1791cafe5635SKent Overstreet }
1792cafe5635SKent Overstreet 
1793cafe5635SKent Overstreet /* Btree insertion */
1794cafe5635SKent Overstreet 
17951b207d80SKent Overstreet static bool fix_overlapping_extents(struct btree *b, struct bkey *insert,
1796cafe5635SKent Overstreet 				    struct btree_iter *iter,
17971b207d80SKent Overstreet 				    struct bkey *replace_key)
1798cafe5635SKent Overstreet {
1799279afbadSKent Overstreet 	void subtract_dirty(struct bkey *k, uint64_t offset, int sectors)
1800cafe5635SKent Overstreet 	{
1801279afbadSKent Overstreet 		if (KEY_DIRTY(k))
1802279afbadSKent Overstreet 			bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
1803279afbadSKent Overstreet 						     offset, -sectors);
1804cafe5635SKent Overstreet 	}
1805cafe5635SKent Overstreet 
1806279afbadSKent Overstreet 	uint64_t old_offset;
1807cafe5635SKent Overstreet 	unsigned old_size, sectors_found = 0;
1808cafe5635SKent Overstreet 
1809cafe5635SKent Overstreet 	while (1) {
1810cafe5635SKent Overstreet 		struct bkey *k = bch_btree_iter_next(iter);
1811911c9610SKent Overstreet 		if (!k)
1812cafe5635SKent Overstreet 			break;
1813cafe5635SKent Overstreet 
1814911c9610SKent Overstreet 		if (bkey_cmp(&START_KEY(k), insert) >= 0) {
1815911c9610SKent Overstreet 			if (KEY_SIZE(k))
1816911c9610SKent Overstreet 				break;
1817911c9610SKent Overstreet 			else
1818911c9610SKent Overstreet 				continue;
1819911c9610SKent Overstreet 		}
1820911c9610SKent Overstreet 
1821cafe5635SKent Overstreet 		if (bkey_cmp(k, &START_KEY(insert)) <= 0)
1822cafe5635SKent Overstreet 			continue;
1823cafe5635SKent Overstreet 
1824279afbadSKent Overstreet 		old_offset = KEY_START(k);
1825cafe5635SKent Overstreet 		old_size = KEY_SIZE(k);
1826cafe5635SKent Overstreet 
1827cafe5635SKent Overstreet 		/*
1828cafe5635SKent Overstreet 		 * We might overlap with 0 size extents; we can't skip these
1829cafe5635SKent Overstreet 		 * because if they're in the set we're inserting to we have to
1830cafe5635SKent Overstreet 		 * adjust them so they don't overlap with the key we're
18311b207d80SKent Overstreet 		 * inserting. But we don't want to check them for replace
1832cafe5635SKent Overstreet 		 * operations.
1833cafe5635SKent Overstreet 		 */
1834cafe5635SKent Overstreet 
18351b207d80SKent Overstreet 		if (replace_key && KEY_SIZE(k)) {
1836cafe5635SKent Overstreet 			/*
1837cafe5635SKent Overstreet 			 * k might have been split since we inserted/found the
1838cafe5635SKent Overstreet 			 * key we're replacing
1839cafe5635SKent Overstreet 			 */
1840cafe5635SKent Overstreet 			unsigned i;
1841cafe5635SKent Overstreet 			uint64_t offset = KEY_START(k) -
18421b207d80SKent Overstreet 				KEY_START(replace_key);
1843cafe5635SKent Overstreet 
1844cafe5635SKent Overstreet 			/* But it must be a subset of the replace key */
18451b207d80SKent Overstreet 			if (KEY_START(k) < KEY_START(replace_key) ||
18461b207d80SKent Overstreet 			    KEY_OFFSET(k) > KEY_OFFSET(replace_key))
1847cafe5635SKent Overstreet 				goto check_failed;
1848cafe5635SKent Overstreet 
1849cafe5635SKent Overstreet 			/* We didn't find a key that we were supposed to */
1850cafe5635SKent Overstreet 			if (KEY_START(k) > KEY_START(insert) + sectors_found)
1851cafe5635SKent Overstreet 				goto check_failed;
1852cafe5635SKent Overstreet 
1853d24a6e10SKent Overstreet 			if (KEY_PTRS(k) != KEY_PTRS(replace_key) ||
1854d24a6e10SKent Overstreet 			    KEY_DIRTY(k) != KEY_DIRTY(replace_key))
1855cafe5635SKent Overstreet 				goto check_failed;
1856cafe5635SKent Overstreet 
1857cafe5635SKent Overstreet 			/* skip past gen */
1858cafe5635SKent Overstreet 			offset <<= 8;
1859cafe5635SKent Overstreet 
18601b207d80SKent Overstreet 			BUG_ON(!KEY_PTRS(replace_key));
1861cafe5635SKent Overstreet 
18621b207d80SKent Overstreet 			for (i = 0; i < KEY_PTRS(replace_key); i++)
18631b207d80SKent Overstreet 				if (k->ptr[i] != replace_key->ptr[i] + offset)
1864cafe5635SKent Overstreet 					goto check_failed;
1865cafe5635SKent Overstreet 
1866cafe5635SKent Overstreet 			sectors_found = KEY_OFFSET(k) - KEY_START(insert);
1867cafe5635SKent Overstreet 		}
1868cafe5635SKent Overstreet 
1869cafe5635SKent Overstreet 		if (bkey_cmp(insert, k) < 0 &&
1870cafe5635SKent Overstreet 		    bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0) {
1871cafe5635SKent Overstreet 			/*
1872cafe5635SKent Overstreet 			 * We overlapped in the middle of an existing key: that
1873cafe5635SKent Overstreet 			 * means we have to split the old key. But we have to do
1874cafe5635SKent Overstreet 			 * slightly different things depending on whether the
1875cafe5635SKent Overstreet 			 * old key has been written out yet.
1876cafe5635SKent Overstreet 			 */
1877cafe5635SKent Overstreet 
1878cafe5635SKent Overstreet 			struct bkey *top;
1879cafe5635SKent Overstreet 
1880279afbadSKent Overstreet 			subtract_dirty(k, KEY_START(insert), KEY_SIZE(insert));
1881cafe5635SKent Overstreet 
1882a85e968eSKent Overstreet 			if (bkey_written(&b->keys, k)) {
1883cafe5635SKent Overstreet 				/*
1884cafe5635SKent Overstreet 				 * We insert a new key to cover the top of the
1885cafe5635SKent Overstreet 				 * old key, and the old key is modified in place
1886cafe5635SKent Overstreet 				 * to represent the bottom split.
1887cafe5635SKent Overstreet 				 *
1888cafe5635SKent Overstreet 				 * It's completely arbitrary whether the new key
1889cafe5635SKent Overstreet 				 * is the top or the bottom, but it has to match
1890cafe5635SKent Overstreet 				 * up with what btree_sort_fixup() does - it
1891cafe5635SKent Overstreet 				 * doesn't check for this kind of overlap, it
1892cafe5635SKent Overstreet 				 * depends on us inserting a new key for the top
1893cafe5635SKent Overstreet 				 * here.
1894cafe5635SKent Overstreet 				 */
1895a85e968eSKent Overstreet 				top = bch_bset_search(b,
1896a85e968eSKent Overstreet 						      bset_tree_last(&b->keys),
1897cafe5635SKent Overstreet 						      insert);
1898a85e968eSKent Overstreet 				bch_bset_insert(&b->keys, top, k);
1899cafe5635SKent Overstreet 			} else {
1900cafe5635SKent Overstreet 				BKEY_PADDED(key) temp;
1901cafe5635SKent Overstreet 				bkey_copy(&temp.key, k);
1902a85e968eSKent Overstreet 				bch_bset_insert(&b->keys, k, &temp.key);
1903cafe5635SKent Overstreet 				top = bkey_next(k);
1904cafe5635SKent Overstreet 			}
1905cafe5635SKent Overstreet 
1906cafe5635SKent Overstreet 			bch_cut_front(insert, top);
1907cafe5635SKent Overstreet 			bch_cut_back(&START_KEY(insert), k);
1908a85e968eSKent Overstreet 			bch_bset_fix_invalidated_key(&b->keys, k);
1909cafe5635SKent Overstreet 			return false;
1910cafe5635SKent Overstreet 		}
1911cafe5635SKent Overstreet 
1912cafe5635SKent Overstreet 		if (bkey_cmp(insert, k) < 0) {
1913cafe5635SKent Overstreet 			bch_cut_front(insert, k);
1914cafe5635SKent Overstreet 		} else {
19151fa8455dSKent Overstreet 			if (bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0)
19161fa8455dSKent Overstreet 				old_offset = KEY_START(insert);
19171fa8455dSKent Overstreet 
1918a85e968eSKent Overstreet 			if (bkey_written(&b->keys, k) &&
1919cafe5635SKent Overstreet 			    bkey_cmp(&START_KEY(insert), &START_KEY(k)) <= 0) {
1920cafe5635SKent Overstreet 				/*
1921cafe5635SKent Overstreet 				 * Completely overwrote, so we don't have to
1922cafe5635SKent Overstreet 				 * invalidate the binary search tree
1923cafe5635SKent Overstreet 				 */
1924cafe5635SKent Overstreet 				bch_cut_front(k, k);
1925cafe5635SKent Overstreet 			} else {
1926cafe5635SKent Overstreet 				__bch_cut_back(&START_KEY(insert), k);
1927a85e968eSKent Overstreet 				bch_bset_fix_invalidated_key(&b->keys, k);
1928cafe5635SKent Overstreet 			}
1929cafe5635SKent Overstreet 		}
1930cafe5635SKent Overstreet 
1931279afbadSKent Overstreet 		subtract_dirty(k, old_offset, old_size - KEY_SIZE(k));
1932cafe5635SKent Overstreet 	}
1933cafe5635SKent Overstreet 
1934cafe5635SKent Overstreet check_failed:
19351b207d80SKent Overstreet 	if (replace_key) {
1936cafe5635SKent Overstreet 		if (!sectors_found) {
1937cafe5635SKent Overstreet 			return true;
1938cafe5635SKent Overstreet 		} else if (sectors_found < KEY_SIZE(insert)) {
1939cafe5635SKent Overstreet 			SET_KEY_OFFSET(insert, KEY_OFFSET(insert) -
1940cafe5635SKent Overstreet 				       (KEY_SIZE(insert) - sectors_found));
1941cafe5635SKent Overstreet 			SET_KEY_SIZE(insert, sectors_found);
1942cafe5635SKent Overstreet 		}
1943cafe5635SKent Overstreet 	}
1944cafe5635SKent Overstreet 
1945cafe5635SKent Overstreet 	return false;
1946cafe5635SKent Overstreet }
1947cafe5635SKent Overstreet 
1948cafe5635SKent Overstreet static bool btree_insert_key(struct btree *b, struct btree_op *op,
19491b207d80SKent Overstreet 			     struct bkey *k, struct bkey *replace_key)
1950cafe5635SKent Overstreet {
1951ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
1952cafe5635SKent Overstreet 	struct bkey *m, *prev;
195385b1492eSKent Overstreet 	unsigned status = BTREE_INSERT_STATUS_INSERT;
1954cafe5635SKent Overstreet 
1955cafe5635SKent Overstreet 	BUG_ON(bkey_cmp(k, &b->key) > 0);
1956cafe5635SKent Overstreet 	BUG_ON(b->level && !KEY_PTRS(k));
1957cafe5635SKent Overstreet 	BUG_ON(!b->level && !KEY_OFFSET(k));
1958cafe5635SKent Overstreet 
1959cafe5635SKent Overstreet 	if (!b->level) {
1960cafe5635SKent Overstreet 		struct btree_iter iter;
1961cafe5635SKent Overstreet 
1962cafe5635SKent Overstreet 		/*
1963cafe5635SKent Overstreet 		 * bset_search() returns the first key that is strictly greater
1964cafe5635SKent Overstreet 		 * than the search key - but for back merging, we want to find
19650eacac22SKent Overstreet 		 * the previous key.
1966cafe5635SKent Overstreet 		 */
1967cafe5635SKent Overstreet 		prev = NULL;
1968a85e968eSKent Overstreet 		m = bch_btree_iter_init(b, &iter,
1969a85e968eSKent Overstreet 					PRECEDING_KEY(&START_KEY(k)));
1970cafe5635SKent Overstreet 
19711b207d80SKent Overstreet 		if (fix_overlapping_extents(b, k, &iter, replace_key)) {
19721b207d80SKent Overstreet 			op->insert_collision = true;
1973cafe5635SKent Overstreet 			return false;
19741b207d80SKent Overstreet 		}
1975cafe5635SKent Overstreet 
19761fa8455dSKent Overstreet 		if (KEY_DIRTY(k))
19771fa8455dSKent Overstreet 			bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
19781fa8455dSKent Overstreet 						     KEY_START(k), KEY_SIZE(k));
19791fa8455dSKent Overstreet 
1980fafff81cSKent Overstreet 		while (m != bset_bkey_last(i) &&
1981cafe5635SKent Overstreet 		       bkey_cmp(k, &START_KEY(m)) > 0)
1982cafe5635SKent Overstreet 			prev = m, m = bkey_next(m);
1983cafe5635SKent Overstreet 
1984cafe5635SKent Overstreet 		if (key_merging_disabled(b->c))
1985cafe5635SKent Overstreet 			goto insert;
1986cafe5635SKent Overstreet 
1987cafe5635SKent Overstreet 		/* prev is in the tree, if we merge we're done */
198885b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_BACK_MERGE;
1989cafe5635SKent Overstreet 		if (prev &&
1990a85e968eSKent Overstreet 		    bch_bkey_try_merge(&b->keys, prev, k))
1991cafe5635SKent Overstreet 			goto merged;
1992cafe5635SKent Overstreet 
199385b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_OVERWROTE;
1994fafff81cSKent Overstreet 		if (m != bset_bkey_last(i) &&
1995cafe5635SKent Overstreet 		    KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
1996cafe5635SKent Overstreet 			goto copy;
1997cafe5635SKent Overstreet 
199885b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_FRONT_MERGE;
1999fafff81cSKent Overstreet 		if (m != bset_bkey_last(i) &&
2000a85e968eSKent Overstreet 		    bch_bkey_try_merge(&b->keys, k, m))
2001cafe5635SKent Overstreet 			goto copy;
20021b207d80SKent Overstreet 	} else {
20031b207d80SKent Overstreet 		BUG_ON(replace_key);
2004a85e968eSKent Overstreet 		m = bch_bset_search(b, bset_tree_last(&b->keys), k);
20051b207d80SKent Overstreet 	}
2006cafe5635SKent Overstreet 
2007a85e968eSKent Overstreet insert:	bch_bset_insert(&b->keys, m, k);
2008cafe5635SKent Overstreet copy:	bkey_copy(m, k);
2009cafe5635SKent Overstreet merged:
20101b207d80SKent Overstreet 	bch_check_keys(b, "%u for %s", status,
20111b207d80SKent Overstreet 		       replace_key ? "replace" : "insert");
2012cafe5635SKent Overstreet 
2013cafe5635SKent Overstreet 	if (b->level && !KEY_OFFSET(k))
201457943511SKent Overstreet 		btree_current_write(b)->prio_blocked++;
2015cafe5635SKent Overstreet 
20161b207d80SKent Overstreet 	trace_bcache_btree_insert_key(b, k, replace_key != NULL, status);
2017cafe5635SKent Overstreet 
2018cafe5635SKent Overstreet 	return true;
2019cafe5635SKent Overstreet }
2020cafe5635SKent Overstreet 
2021*59158fdeSKent Overstreet static size_t insert_u64s_remaining(struct btree *b)
2022*59158fdeSKent Overstreet {
2023*59158fdeSKent Overstreet 	ssize_t ret = bch_btree_keys_u64s_remaining(&b->keys);
2024*59158fdeSKent Overstreet 
2025*59158fdeSKent Overstreet 	/*
2026*59158fdeSKent Overstreet 	 * Might land in the middle of an existing extent and have to split it
2027*59158fdeSKent Overstreet 	 */
2028*59158fdeSKent Overstreet 	if (b->keys.ops->is_extents)
2029*59158fdeSKent Overstreet 		ret -= KEY_MAX_U64S;
2030*59158fdeSKent Overstreet 
2031*59158fdeSKent Overstreet 	return max(ret, 0L);
2032*59158fdeSKent Overstreet }
2033*59158fdeSKent Overstreet 
203426c949f8SKent Overstreet static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
20351b207d80SKent Overstreet 				  struct keylist *insert_keys,
20361b207d80SKent Overstreet 				  struct bkey *replace_key)
2037cafe5635SKent Overstreet {
2038cafe5635SKent Overstreet 	bool ret = false;
2039280481d0SKent Overstreet 	int oldsize = bch_count_data(b);
2040cafe5635SKent Overstreet 
204126c949f8SKent Overstreet 	while (!bch_keylist_empty(insert_keys)) {
2042c2f95ae2SKent Overstreet 		struct bkey *k = insert_keys->keys;
204326c949f8SKent Overstreet 
2044*59158fdeSKent Overstreet 		if (bkey_u64s(k) > insert_u64s_remaining(b))
2045403b6cdeSKent Overstreet 			break;
2046403b6cdeSKent Overstreet 
2047403b6cdeSKent Overstreet 		if (bkey_cmp(k, &b->key) <= 0) {
20483a3b6a4eSKent Overstreet 			if (!b->level)
20493a3b6a4eSKent Overstreet 				bkey_put(b->c, k);
205026c949f8SKent Overstreet 
20511b207d80SKent Overstreet 			ret |= btree_insert_key(b, op, k, replace_key);
205226c949f8SKent Overstreet 			bch_keylist_pop_front(insert_keys);
205326c949f8SKent Overstreet 		} else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
205426c949f8SKent Overstreet 			BKEY_PADDED(key) temp;
2055c2f95ae2SKent Overstreet 			bkey_copy(&temp.key, insert_keys->keys);
205626c949f8SKent Overstreet 
205726c949f8SKent Overstreet 			bch_cut_back(&b->key, &temp.key);
2058c2f95ae2SKent Overstreet 			bch_cut_front(&b->key, insert_keys->keys);
205926c949f8SKent Overstreet 
20601b207d80SKent Overstreet 			ret |= btree_insert_key(b, op, &temp.key, replace_key);
206126c949f8SKent Overstreet 			break;
206226c949f8SKent Overstreet 		} else {
206326c949f8SKent Overstreet 			break;
206426c949f8SKent Overstreet 		}
2065cafe5635SKent Overstreet 	}
2066cafe5635SKent Overstreet 
2067403b6cdeSKent Overstreet 	BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
2068403b6cdeSKent Overstreet 
2069cafe5635SKent Overstreet 	BUG_ON(bch_count_data(b) < oldsize);
2070cafe5635SKent Overstreet 	return ret;
2071cafe5635SKent Overstreet }
2072cafe5635SKent Overstreet 
207326c949f8SKent Overstreet static int btree_split(struct btree *b, struct btree_op *op,
207426c949f8SKent Overstreet 		       struct keylist *insert_keys,
20751b207d80SKent Overstreet 		       struct bkey *replace_key)
2076cafe5635SKent Overstreet {
2077d6fd3b11SKent Overstreet 	bool split;
2078cafe5635SKent Overstreet 	struct btree *n1, *n2 = NULL, *n3 = NULL;
2079cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
2080b54d6934SKent Overstreet 	struct closure cl;
208117e21a9fSKent Overstreet 	struct keylist parent_keys;
2082b54d6934SKent Overstreet 
2083b54d6934SKent Overstreet 	closure_init_stack(&cl);
208417e21a9fSKent Overstreet 	bch_keylist_init(&parent_keys);
2085cafe5635SKent Overstreet 
208678365411SKent Overstreet 	if (!b->level &&
208778365411SKent Overstreet 	    btree_check_reserve(b, op))
208878365411SKent Overstreet 		return -EINTR;
208978365411SKent Overstreet 
2090bc9389eeSKent Overstreet 	n1 = btree_node_alloc_replacement(b, true);
2091cafe5635SKent Overstreet 	if (IS_ERR(n1))
2092cafe5635SKent Overstreet 		goto err;
2093cafe5635SKent Overstreet 
2094ee811287SKent Overstreet 	split = set_blocks(btree_bset_first(n1),
2095ee811287SKent Overstreet 			   block_bytes(n1->c)) > (btree_blocks(b) * 4) / 5;
2096cafe5635SKent Overstreet 
2097cafe5635SKent Overstreet 	if (split) {
2098cafe5635SKent Overstreet 		unsigned keys = 0;
2099cafe5635SKent Overstreet 
2100ee811287SKent Overstreet 		trace_bcache_btree_node_split(b, btree_bset_first(n1)->keys);
2101c37511b8SKent Overstreet 
2102bc9389eeSKent Overstreet 		n2 = bch_btree_node_alloc(b->c, b->level, true);
2103cafe5635SKent Overstreet 		if (IS_ERR(n2))
2104cafe5635SKent Overstreet 			goto err_free1;
2105cafe5635SKent Overstreet 
2106d6fd3b11SKent Overstreet 		if (!b->parent) {
2107bc9389eeSKent Overstreet 			n3 = bch_btree_node_alloc(b->c, b->level + 1, true);
2108cafe5635SKent Overstreet 			if (IS_ERR(n3))
2109cafe5635SKent Overstreet 				goto err_free2;
2110cafe5635SKent Overstreet 		}
2111cafe5635SKent Overstreet 
21121b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2113cafe5635SKent Overstreet 
2114d6fd3b11SKent Overstreet 		/*
2115d6fd3b11SKent Overstreet 		 * Has to be a linear search because we don't have an auxiliary
2116cafe5635SKent Overstreet 		 * search tree yet
2117cafe5635SKent Overstreet 		 */
2118cafe5635SKent Overstreet 
2119ee811287SKent Overstreet 		while (keys < (btree_bset_first(n1)->keys * 3) / 5)
2120ee811287SKent Overstreet 			keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1),
2121fafff81cSKent Overstreet 							keys));
2122cafe5635SKent Overstreet 
2123fafff81cSKent Overstreet 		bkey_copy_key(&n1->key,
2124ee811287SKent Overstreet 			      bset_bkey_idx(btree_bset_first(n1), keys));
2125ee811287SKent Overstreet 		keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1), keys));
2126cafe5635SKent Overstreet 
2127ee811287SKent Overstreet 		btree_bset_first(n2)->keys = btree_bset_first(n1)->keys - keys;
2128ee811287SKent Overstreet 		btree_bset_first(n1)->keys = keys;
2129cafe5635SKent Overstreet 
2130ee811287SKent Overstreet 		memcpy(btree_bset_first(n2)->start,
2131ee811287SKent Overstreet 		       bset_bkey_last(btree_bset_first(n1)),
2132ee811287SKent Overstreet 		       btree_bset_first(n2)->keys * sizeof(uint64_t));
2133cafe5635SKent Overstreet 
2134cafe5635SKent Overstreet 		bkey_copy_key(&n2->key, &b->key);
2135cafe5635SKent Overstreet 
213617e21a9fSKent Overstreet 		bch_keylist_add(&parent_keys, &n2->key);
2137b54d6934SKent Overstreet 		bch_btree_node_write(n2, &cl);
2138cafe5635SKent Overstreet 		rw_unlock(true, n2);
2139c37511b8SKent Overstreet 	} else {
2140ee811287SKent Overstreet 		trace_bcache_btree_node_compact(b, btree_bset_first(n1)->keys);
2141c37511b8SKent Overstreet 
21421b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2143c37511b8SKent Overstreet 	}
2144cafe5635SKent Overstreet 
214517e21a9fSKent Overstreet 	bch_keylist_add(&parent_keys, &n1->key);
2146b54d6934SKent Overstreet 	bch_btree_node_write(n1, &cl);
2147cafe5635SKent Overstreet 
2148cafe5635SKent Overstreet 	if (n3) {
2149d6fd3b11SKent Overstreet 		/* Depth increases, make a new root */
2150cafe5635SKent Overstreet 		bkey_copy_key(&n3->key, &MAX_KEY);
215117e21a9fSKent Overstreet 		bch_btree_insert_keys(n3, op, &parent_keys, NULL);
2152b54d6934SKent Overstreet 		bch_btree_node_write(n3, &cl);
2153cafe5635SKent Overstreet 
2154b54d6934SKent Overstreet 		closure_sync(&cl);
2155cafe5635SKent Overstreet 		bch_btree_set_root(n3);
2156cafe5635SKent Overstreet 		rw_unlock(true, n3);
215717e21a9fSKent Overstreet 
215817e21a9fSKent Overstreet 		btree_node_free(b);
2159d6fd3b11SKent Overstreet 	} else if (!b->parent) {
2160d6fd3b11SKent Overstreet 		/* Root filled up but didn't need to be split */
2161b54d6934SKent Overstreet 		closure_sync(&cl);
2162cafe5635SKent Overstreet 		bch_btree_set_root(n1);
216317e21a9fSKent Overstreet 
216417e21a9fSKent Overstreet 		btree_node_free(b);
2165cafe5635SKent Overstreet 	} else {
216617e21a9fSKent Overstreet 		/* Split a non root node */
2167b54d6934SKent Overstreet 		closure_sync(&cl);
216817e21a9fSKent Overstreet 		make_btree_freeing_key(b, parent_keys.top);
216917e21a9fSKent Overstreet 		bch_keylist_push(&parent_keys);
217017e21a9fSKent Overstreet 
217117e21a9fSKent Overstreet 		btree_node_free(b);
217217e21a9fSKent Overstreet 
217317e21a9fSKent Overstreet 		bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
217417e21a9fSKent Overstreet 		BUG_ON(!bch_keylist_empty(&parent_keys));
2175cafe5635SKent Overstreet 	}
2176cafe5635SKent Overstreet 
2177cafe5635SKent Overstreet 	rw_unlock(true, n1);
2178cafe5635SKent Overstreet 
2179169ef1cfSKent Overstreet 	bch_time_stats_update(&b->c->btree_split_time, start_time);
2180cafe5635SKent Overstreet 
2181cafe5635SKent Overstreet 	return 0;
2182cafe5635SKent Overstreet err_free2:
21835f5837d2SKent Overstreet 	bkey_put(b->c, &n2->key);
2184e8e1d468SKent Overstreet 	btree_node_free(n2);
2185cafe5635SKent Overstreet 	rw_unlock(true, n2);
2186cafe5635SKent Overstreet err_free1:
21875f5837d2SKent Overstreet 	bkey_put(b->c, &n1->key);
2188e8e1d468SKent Overstreet 	btree_node_free(n1);
2189cafe5635SKent Overstreet 	rw_unlock(true, n1);
2190cafe5635SKent Overstreet err:
21915f5837d2SKent Overstreet 	WARN(1, "bcache: btree split failed");
21925f5837d2SKent Overstreet 
2193cafe5635SKent Overstreet 	if (n3 == ERR_PTR(-EAGAIN) ||
2194cafe5635SKent Overstreet 	    n2 == ERR_PTR(-EAGAIN) ||
2195cafe5635SKent Overstreet 	    n1 == ERR_PTR(-EAGAIN))
2196cafe5635SKent Overstreet 		return -EAGAIN;
2197cafe5635SKent Overstreet 
2198cafe5635SKent Overstreet 	return -ENOMEM;
2199cafe5635SKent Overstreet }
2200cafe5635SKent Overstreet 
220126c949f8SKent Overstreet static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
2202c18536a7SKent Overstreet 				 struct keylist *insert_keys,
22031b207d80SKent Overstreet 				 atomic_t *journal_ref,
22041b207d80SKent Overstreet 				 struct bkey *replace_key)
220526c949f8SKent Overstreet {
22061b207d80SKent Overstreet 	BUG_ON(b->level && replace_key);
22071b207d80SKent Overstreet 
2208*59158fdeSKent Overstreet 	if (bch_keylist_nkeys(insert_keys) > insert_u64s_remaining(b)) {
220926c949f8SKent Overstreet 		if (current->bio_list) {
221026c949f8SKent Overstreet 			op->lock = b->c->root->level + 1;
221117e21a9fSKent Overstreet 			return -EAGAIN;
221226c949f8SKent Overstreet 		} else if (op->lock <= b->c->root->level) {
221326c949f8SKent Overstreet 			op->lock = b->c->root->level + 1;
221417e21a9fSKent Overstreet 			return -EINTR;
221526c949f8SKent Overstreet 		} else {
221617e21a9fSKent Overstreet 			/* Invalidated all iterators */
221717e21a9fSKent Overstreet 			return btree_split(b, op, insert_keys, replace_key) ?:
221817e21a9fSKent Overstreet 				-EINTR;
221926c949f8SKent Overstreet 		}
222026c949f8SKent Overstreet 	} else {
2221ee811287SKent Overstreet 		BUG_ON(write_block(b) != btree_bset_last(b));
222226c949f8SKent Overstreet 
222317e21a9fSKent Overstreet 		if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
2224f269af5aSKent Overstreet 			if (!b->level)
2225c18536a7SKent Overstreet 				bch_btree_leaf_dirty(b, journal_ref);
2226f269af5aSKent Overstreet 			else
2227f269af5aSKent Overstreet 				bch_btree_node_write_sync(b);
222826c949f8SKent Overstreet 		}
222926c949f8SKent Overstreet 
223017e21a9fSKent Overstreet 		return 0;
223117e21a9fSKent Overstreet 	}
223226c949f8SKent Overstreet }
223326c949f8SKent Overstreet 
2234e7c590ebSKent Overstreet int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2235e7c590ebSKent Overstreet 			       struct bkey *check_key)
2236e7c590ebSKent Overstreet {
2237e7c590ebSKent Overstreet 	int ret = -EINTR;
2238e7c590ebSKent Overstreet 	uint64_t btree_ptr = b->key.ptr[0];
2239e7c590ebSKent Overstreet 	unsigned long seq = b->seq;
2240e7c590ebSKent Overstreet 	struct keylist insert;
2241e7c590ebSKent Overstreet 	bool upgrade = op->lock == -1;
2242e7c590ebSKent Overstreet 
2243e7c590ebSKent Overstreet 	bch_keylist_init(&insert);
2244e7c590ebSKent Overstreet 
2245e7c590ebSKent Overstreet 	if (upgrade) {
2246e7c590ebSKent Overstreet 		rw_unlock(false, b);
2247e7c590ebSKent Overstreet 		rw_lock(true, b, b->level);
2248e7c590ebSKent Overstreet 
2249e7c590ebSKent Overstreet 		if (b->key.ptr[0] != btree_ptr ||
2250e7c590ebSKent Overstreet 		    b->seq != seq + 1)
2251e7c590ebSKent Overstreet 			goto out;
2252e7c590ebSKent Overstreet 	}
2253e7c590ebSKent Overstreet 
2254e7c590ebSKent Overstreet 	SET_KEY_PTRS(check_key, 1);
2255e7c590ebSKent Overstreet 	get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2256e7c590ebSKent Overstreet 
2257e7c590ebSKent Overstreet 	SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2258e7c590ebSKent Overstreet 
2259e7c590ebSKent Overstreet 	bch_keylist_add(&insert, check_key);
2260e7c590ebSKent Overstreet 
22611b207d80SKent Overstreet 	ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2262e7c590ebSKent Overstreet 
2263e7c590ebSKent Overstreet 	BUG_ON(!ret && !bch_keylist_empty(&insert));
2264e7c590ebSKent Overstreet out:
2265e7c590ebSKent Overstreet 	if (upgrade)
2266e7c590ebSKent Overstreet 		downgrade_write(&b->lock);
2267e7c590ebSKent Overstreet 	return ret;
2268e7c590ebSKent Overstreet }
2269e7c590ebSKent Overstreet 
2270cc7b8819SKent Overstreet struct btree_insert_op {
2271cc7b8819SKent Overstreet 	struct btree_op	op;
2272cc7b8819SKent Overstreet 	struct keylist	*keys;
2273cc7b8819SKent Overstreet 	atomic_t	*journal_ref;
2274cc7b8819SKent Overstreet 	struct bkey	*replace_key;
2275cc7b8819SKent Overstreet };
2276cc7b8819SKent Overstreet 
227708239ca2SWei Yongjun static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2278cafe5635SKent Overstreet {
2279cc7b8819SKent Overstreet 	struct btree_insert_op *op = container_of(b_op,
2280cc7b8819SKent Overstreet 					struct btree_insert_op, op);
2281403b6cdeSKent Overstreet 
2282cc7b8819SKent Overstreet 	int ret = bch_btree_insert_node(b, &op->op, op->keys,
2283cc7b8819SKent Overstreet 					op->journal_ref, op->replace_key);
2284cc7b8819SKent Overstreet 	if (ret && !bch_keylist_empty(op->keys))
2285cc7b8819SKent Overstreet 		return ret;
2286cc7b8819SKent Overstreet 	else
2287cc7b8819SKent Overstreet 		return MAP_DONE;
2288cafe5635SKent Overstreet }
2289cafe5635SKent Overstreet 
2290cc7b8819SKent Overstreet int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2291cc7b8819SKent Overstreet 		     atomic_t *journal_ref, struct bkey *replace_key)
2292cafe5635SKent Overstreet {
2293cc7b8819SKent Overstreet 	struct btree_insert_op op;
2294cafe5635SKent Overstreet 	int ret = 0;
2295cafe5635SKent Overstreet 
2296cc7b8819SKent Overstreet 	BUG_ON(current->bio_list);
22974f3d4014SKent Overstreet 	BUG_ON(bch_keylist_empty(keys));
2298cafe5635SKent Overstreet 
2299cc7b8819SKent Overstreet 	bch_btree_op_init(&op.op, 0);
2300cc7b8819SKent Overstreet 	op.keys		= keys;
2301cc7b8819SKent Overstreet 	op.journal_ref	= journal_ref;
2302cc7b8819SKent Overstreet 	op.replace_key	= replace_key;
2303cafe5635SKent Overstreet 
2304cc7b8819SKent Overstreet 	while (!ret && !bch_keylist_empty(keys)) {
2305cc7b8819SKent Overstreet 		op.op.lock = 0;
2306cc7b8819SKent Overstreet 		ret = bch_btree_map_leaf_nodes(&op.op, c,
2307cc7b8819SKent Overstreet 					       &START_KEY(keys->keys),
2308cc7b8819SKent Overstreet 					       btree_insert_fn);
2309cc7b8819SKent Overstreet 	}
2310cc7b8819SKent Overstreet 
2311cc7b8819SKent Overstreet 	if (ret) {
2312cafe5635SKent Overstreet 		struct bkey *k;
2313cafe5635SKent Overstreet 
23141b207d80SKent Overstreet 		pr_err("error %i", ret);
2315cafe5635SKent Overstreet 
23164f3d4014SKent Overstreet 		while ((k = bch_keylist_pop(keys)))
23173a3b6a4eSKent Overstreet 			bkey_put(c, k);
2318cc7b8819SKent Overstreet 	} else if (op.op.insert_collision)
2319cc7b8819SKent Overstreet 		ret = -ESRCH;
23206054c6d4SKent Overstreet 
2321cafe5635SKent Overstreet 	return ret;
2322cafe5635SKent Overstreet }
2323cafe5635SKent Overstreet 
2324cafe5635SKent Overstreet void bch_btree_set_root(struct btree *b)
2325cafe5635SKent Overstreet {
2326cafe5635SKent Overstreet 	unsigned i;
2327e49c7c37SKent Overstreet 	struct closure cl;
2328e49c7c37SKent Overstreet 
2329e49c7c37SKent Overstreet 	closure_init_stack(&cl);
2330cafe5635SKent Overstreet 
2331c37511b8SKent Overstreet 	trace_bcache_btree_set_root(b);
2332c37511b8SKent Overstreet 
2333cafe5635SKent Overstreet 	BUG_ON(!b->written);
2334cafe5635SKent Overstreet 
2335cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++)
2336cafe5635SKent Overstreet 		BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2337cafe5635SKent Overstreet 
2338cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
2339cafe5635SKent Overstreet 	list_del_init(&b->list);
2340cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
2341cafe5635SKent Overstreet 
2342cafe5635SKent Overstreet 	b->c->root = b;
2343cafe5635SKent Overstreet 
2344e49c7c37SKent Overstreet 	bch_journal_meta(b->c, &cl);
2345e49c7c37SKent Overstreet 	closure_sync(&cl);
2346cafe5635SKent Overstreet }
2347cafe5635SKent Overstreet 
234848dad8baSKent Overstreet /* Map across nodes or keys */
234948dad8baSKent Overstreet 
235048dad8baSKent Overstreet static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
235148dad8baSKent Overstreet 				       struct bkey *from,
235248dad8baSKent Overstreet 				       btree_map_nodes_fn *fn, int flags)
235348dad8baSKent Overstreet {
235448dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
235548dad8baSKent Overstreet 
235648dad8baSKent Overstreet 	if (b->level) {
235748dad8baSKent Overstreet 		struct bkey *k;
235848dad8baSKent Overstreet 		struct btree_iter iter;
235948dad8baSKent Overstreet 
236048dad8baSKent Overstreet 		bch_btree_iter_init(b, &iter, from);
236148dad8baSKent Overstreet 
2362a85e968eSKent Overstreet 		while ((k = bch_btree_iter_next_filter(&iter, &b->keys,
236348dad8baSKent Overstreet 						       bch_ptr_bad))) {
236448dad8baSKent Overstreet 			ret = btree(map_nodes_recurse, k, b,
236548dad8baSKent Overstreet 				    op, from, fn, flags);
236648dad8baSKent Overstreet 			from = NULL;
236748dad8baSKent Overstreet 
236848dad8baSKent Overstreet 			if (ret != MAP_CONTINUE)
236948dad8baSKent Overstreet 				return ret;
237048dad8baSKent Overstreet 		}
237148dad8baSKent Overstreet 	}
237248dad8baSKent Overstreet 
237348dad8baSKent Overstreet 	if (!b->level || flags == MAP_ALL_NODES)
237448dad8baSKent Overstreet 		ret = fn(op, b);
237548dad8baSKent Overstreet 
237648dad8baSKent Overstreet 	return ret;
237748dad8baSKent Overstreet }
237848dad8baSKent Overstreet 
237948dad8baSKent Overstreet int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
238048dad8baSKent Overstreet 			  struct bkey *from, btree_map_nodes_fn *fn, int flags)
238148dad8baSKent Overstreet {
2382b54d6934SKent Overstreet 	return btree_root(map_nodes_recurse, c, op, from, fn, flags);
238348dad8baSKent Overstreet }
238448dad8baSKent Overstreet 
238548dad8baSKent Overstreet static int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
238648dad8baSKent Overstreet 				      struct bkey *from, btree_map_keys_fn *fn,
238748dad8baSKent Overstreet 				      int flags)
238848dad8baSKent Overstreet {
238948dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
239048dad8baSKent Overstreet 	struct bkey *k;
239148dad8baSKent Overstreet 	struct btree_iter iter;
239248dad8baSKent Overstreet 
239348dad8baSKent Overstreet 	bch_btree_iter_init(b, &iter, from);
239448dad8baSKent Overstreet 
2395a85e968eSKent Overstreet 	while ((k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad))) {
239648dad8baSKent Overstreet 		ret = !b->level
239748dad8baSKent Overstreet 			? fn(op, b, k)
239848dad8baSKent Overstreet 			: btree(map_keys_recurse, k, b, op, from, fn, flags);
239948dad8baSKent Overstreet 		from = NULL;
240048dad8baSKent Overstreet 
240148dad8baSKent Overstreet 		if (ret != MAP_CONTINUE)
240248dad8baSKent Overstreet 			return ret;
240348dad8baSKent Overstreet 	}
240448dad8baSKent Overstreet 
240548dad8baSKent Overstreet 	if (!b->level && (flags & MAP_END_KEY))
240648dad8baSKent Overstreet 		ret = fn(op, b, &KEY(KEY_INODE(&b->key),
240748dad8baSKent Overstreet 				     KEY_OFFSET(&b->key), 0));
240848dad8baSKent Overstreet 
240948dad8baSKent Overstreet 	return ret;
241048dad8baSKent Overstreet }
241148dad8baSKent Overstreet 
241248dad8baSKent Overstreet int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
241348dad8baSKent Overstreet 		       struct bkey *from, btree_map_keys_fn *fn, int flags)
241448dad8baSKent Overstreet {
2415b54d6934SKent Overstreet 	return btree_root(map_keys_recurse, c, op, from, fn, flags);
241648dad8baSKent Overstreet }
241748dad8baSKent Overstreet 
2418cafe5635SKent Overstreet /* Keybuf code */
2419cafe5635SKent Overstreet 
2420cafe5635SKent Overstreet static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2421cafe5635SKent Overstreet {
2422cafe5635SKent Overstreet 	/* Overlapping keys compare equal */
2423cafe5635SKent Overstreet 	if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2424cafe5635SKent Overstreet 		return -1;
2425cafe5635SKent Overstreet 	if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2426cafe5635SKent Overstreet 		return 1;
2427cafe5635SKent Overstreet 	return 0;
2428cafe5635SKent Overstreet }
2429cafe5635SKent Overstreet 
2430cafe5635SKent Overstreet static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2431cafe5635SKent Overstreet 					    struct keybuf_key *r)
2432cafe5635SKent Overstreet {
2433cafe5635SKent Overstreet 	return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2434cafe5635SKent Overstreet }
2435cafe5635SKent Overstreet 
243648dad8baSKent Overstreet struct refill {
243748dad8baSKent Overstreet 	struct btree_op	op;
243848a915a8SKent Overstreet 	unsigned	nr_found;
243948dad8baSKent Overstreet 	struct keybuf	*buf;
244048dad8baSKent Overstreet 	struct bkey	*end;
244148dad8baSKent Overstreet 	keybuf_pred_fn	*pred;
244248dad8baSKent Overstreet };
244348dad8baSKent Overstreet 
244448dad8baSKent Overstreet static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
244548dad8baSKent Overstreet 			    struct bkey *k)
2446cafe5635SKent Overstreet {
244748dad8baSKent Overstreet 	struct refill *refill = container_of(op, struct refill, op);
244848dad8baSKent Overstreet 	struct keybuf *buf = refill->buf;
244948dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
2450cafe5635SKent Overstreet 
245148dad8baSKent Overstreet 	if (bkey_cmp(k, refill->end) >= 0) {
245248dad8baSKent Overstreet 		ret = MAP_DONE;
245348dad8baSKent Overstreet 		goto out;
2454cafe5635SKent Overstreet 	}
2455cafe5635SKent Overstreet 
245648dad8baSKent Overstreet 	if (!KEY_SIZE(k)) /* end key */
245748dad8baSKent Overstreet 		goto out;
2458cafe5635SKent Overstreet 
245948dad8baSKent Overstreet 	if (refill->pred(buf, k)) {
2460cafe5635SKent Overstreet 		struct keybuf_key *w;
2461cafe5635SKent Overstreet 
2462cafe5635SKent Overstreet 		spin_lock(&buf->lock);
2463cafe5635SKent Overstreet 
2464cafe5635SKent Overstreet 		w = array_alloc(&buf->freelist);
246548dad8baSKent Overstreet 		if (!w) {
246648dad8baSKent Overstreet 			spin_unlock(&buf->lock);
246748dad8baSKent Overstreet 			return MAP_DONE;
246848dad8baSKent Overstreet 		}
2469cafe5635SKent Overstreet 
2470cafe5635SKent Overstreet 		w->private = NULL;
2471cafe5635SKent Overstreet 		bkey_copy(&w->key, k);
2472cafe5635SKent Overstreet 
2473cafe5635SKent Overstreet 		if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2474cafe5635SKent Overstreet 			array_free(&buf->freelist, w);
247548a915a8SKent Overstreet 		else
247648a915a8SKent Overstreet 			refill->nr_found++;
2477cafe5635SKent Overstreet 
247848dad8baSKent Overstreet 		if (array_freelist_empty(&buf->freelist))
247948dad8baSKent Overstreet 			ret = MAP_DONE;
248048dad8baSKent Overstreet 
2481cafe5635SKent Overstreet 		spin_unlock(&buf->lock);
2482cafe5635SKent Overstreet 	}
248348dad8baSKent Overstreet out:
248448dad8baSKent Overstreet 	buf->last_scanned = *k;
248548dad8baSKent Overstreet 	return ret;
2486cafe5635SKent Overstreet }
2487cafe5635SKent Overstreet 
2488cafe5635SKent Overstreet void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
248972c27061SKent Overstreet 		       struct bkey *end, keybuf_pred_fn *pred)
2490cafe5635SKent Overstreet {
2491cafe5635SKent Overstreet 	struct bkey start = buf->last_scanned;
249248dad8baSKent Overstreet 	struct refill refill;
2493cafe5635SKent Overstreet 
2494cafe5635SKent Overstreet 	cond_resched();
2495cafe5635SKent Overstreet 
2496b54d6934SKent Overstreet 	bch_btree_op_init(&refill.op, -1);
249748a915a8SKent Overstreet 	refill.nr_found	= 0;
249848dad8baSKent Overstreet 	refill.buf	= buf;
249948dad8baSKent Overstreet 	refill.end	= end;
250048dad8baSKent Overstreet 	refill.pred	= pred;
250148dad8baSKent Overstreet 
250248dad8baSKent Overstreet 	bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
250348dad8baSKent Overstreet 			   refill_keybuf_fn, MAP_END_KEY);
2504cafe5635SKent Overstreet 
250548a915a8SKent Overstreet 	trace_bcache_keyscan(refill.nr_found,
2506cafe5635SKent Overstreet 			     KEY_INODE(&start), KEY_OFFSET(&start),
250748a915a8SKent Overstreet 			     KEY_INODE(&buf->last_scanned),
250848a915a8SKent Overstreet 			     KEY_OFFSET(&buf->last_scanned));
2509cafe5635SKent Overstreet 
2510cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2511cafe5635SKent Overstreet 
2512cafe5635SKent Overstreet 	if (!RB_EMPTY_ROOT(&buf->keys)) {
2513cafe5635SKent Overstreet 		struct keybuf_key *w;
2514cafe5635SKent Overstreet 		w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2515cafe5635SKent Overstreet 		buf->start	= START_KEY(&w->key);
2516cafe5635SKent Overstreet 
2517cafe5635SKent Overstreet 		w = RB_LAST(&buf->keys, struct keybuf_key, node);
2518cafe5635SKent Overstreet 		buf->end	= w->key;
2519cafe5635SKent Overstreet 	} else {
2520cafe5635SKent Overstreet 		buf->start	= MAX_KEY;
2521cafe5635SKent Overstreet 		buf->end	= MAX_KEY;
2522cafe5635SKent Overstreet 	}
2523cafe5635SKent Overstreet 
2524cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2525cafe5635SKent Overstreet }
2526cafe5635SKent Overstreet 
2527cafe5635SKent Overstreet static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2528cafe5635SKent Overstreet {
2529cafe5635SKent Overstreet 	rb_erase(&w->node, &buf->keys);
2530cafe5635SKent Overstreet 	array_free(&buf->freelist, w);
2531cafe5635SKent Overstreet }
2532cafe5635SKent Overstreet 
2533cafe5635SKent Overstreet void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2534cafe5635SKent Overstreet {
2535cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2536cafe5635SKent Overstreet 	__bch_keybuf_del(buf, w);
2537cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2538cafe5635SKent Overstreet }
2539cafe5635SKent Overstreet 
2540cafe5635SKent Overstreet bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2541cafe5635SKent Overstreet 				  struct bkey *end)
2542cafe5635SKent Overstreet {
2543cafe5635SKent Overstreet 	bool ret = false;
2544cafe5635SKent Overstreet 	struct keybuf_key *p, *w, s;
2545cafe5635SKent Overstreet 	s.key = *start;
2546cafe5635SKent Overstreet 
2547cafe5635SKent Overstreet 	if (bkey_cmp(end, &buf->start) <= 0 ||
2548cafe5635SKent Overstreet 	    bkey_cmp(start, &buf->end) >= 0)
2549cafe5635SKent Overstreet 		return false;
2550cafe5635SKent Overstreet 
2551cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2552cafe5635SKent Overstreet 	w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2553cafe5635SKent Overstreet 
2554cafe5635SKent Overstreet 	while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2555cafe5635SKent Overstreet 		p = w;
2556cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2557cafe5635SKent Overstreet 
2558cafe5635SKent Overstreet 		if (p->private)
2559cafe5635SKent Overstreet 			ret = true;
2560cafe5635SKent Overstreet 		else
2561cafe5635SKent Overstreet 			__bch_keybuf_del(buf, p);
2562cafe5635SKent Overstreet 	}
2563cafe5635SKent Overstreet 
2564cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2565cafe5635SKent Overstreet 	return ret;
2566cafe5635SKent Overstreet }
2567cafe5635SKent Overstreet 
2568cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2569cafe5635SKent Overstreet {
2570cafe5635SKent Overstreet 	struct keybuf_key *w;
2571cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2572cafe5635SKent Overstreet 
2573cafe5635SKent Overstreet 	w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2574cafe5635SKent Overstreet 
2575cafe5635SKent Overstreet 	while (w && w->private)
2576cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2577cafe5635SKent Overstreet 
2578cafe5635SKent Overstreet 	if (w)
2579cafe5635SKent Overstreet 		w->private = ERR_PTR(-EINTR);
2580cafe5635SKent Overstreet 
2581cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2582cafe5635SKent Overstreet 	return w;
2583cafe5635SKent Overstreet }
2584cafe5635SKent Overstreet 
2585cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2586cafe5635SKent Overstreet 					  struct keybuf *buf,
258772c27061SKent Overstreet 					  struct bkey *end,
258872c27061SKent Overstreet 					  keybuf_pred_fn *pred)
2589cafe5635SKent Overstreet {
2590cafe5635SKent Overstreet 	struct keybuf_key *ret;
2591cafe5635SKent Overstreet 
2592cafe5635SKent Overstreet 	while (1) {
2593cafe5635SKent Overstreet 		ret = bch_keybuf_next(buf);
2594cafe5635SKent Overstreet 		if (ret)
2595cafe5635SKent Overstreet 			break;
2596cafe5635SKent Overstreet 
2597cafe5635SKent Overstreet 		if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2598cafe5635SKent Overstreet 			pr_debug("scan finished");
2599cafe5635SKent Overstreet 			break;
2600cafe5635SKent Overstreet 		}
2601cafe5635SKent Overstreet 
260272c27061SKent Overstreet 		bch_refill_keybuf(c, buf, end, pred);
2603cafe5635SKent Overstreet 	}
2604cafe5635SKent Overstreet 
2605cafe5635SKent Overstreet 	return ret;
2606cafe5635SKent Overstreet }
2607cafe5635SKent Overstreet 
260872c27061SKent Overstreet void bch_keybuf_init(struct keybuf *buf)
2609cafe5635SKent Overstreet {
2610cafe5635SKent Overstreet 	buf->last_scanned	= MAX_KEY;
2611cafe5635SKent Overstreet 	buf->keys		= RB_ROOT;
2612cafe5635SKent Overstreet 
2613cafe5635SKent Overstreet 	spin_lock_init(&buf->lock);
2614cafe5635SKent Overstreet 	array_allocator_init(&buf->freelist);
2615cafe5635SKent Overstreet }
2616cafe5635SKent Overstreet 
2617cafe5635SKent Overstreet void bch_btree_exit(void)
2618cafe5635SKent Overstreet {
2619cafe5635SKent Overstreet 	if (btree_io_wq)
2620cafe5635SKent Overstreet 		destroy_workqueue(btree_io_wq);
2621cafe5635SKent Overstreet }
2622cafe5635SKent Overstreet 
2623cafe5635SKent Overstreet int __init bch_btree_init(void)
2624cafe5635SKent Overstreet {
262572a44517SKent Overstreet 	btree_io_wq = create_singlethread_workqueue("bch_btree_io");
262672a44517SKent Overstreet 	if (!btree_io_wq)
2627cafe5635SKent Overstreet 		return -ENOMEM;
2628cafe5635SKent Overstreet 
2629cafe5635SKent Overstreet 	return 0;
2630cafe5635SKent Overstreet }
2631