xref: /linux/drivers/md/bcache/btree.c (revision 3572324af0f4ef877545e5a17bd3e788551f166a)
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"
27cafe5635SKent Overstreet 
28cafe5635SKent Overstreet #include <linux/slab.h>
29cafe5635SKent Overstreet #include <linux/bitops.h>
3072a44517SKent Overstreet #include <linux/freezer.h>
31cafe5635SKent Overstreet #include <linux/hash.h>
3272a44517SKent Overstreet #include <linux/kthread.h>
33cd953ed0SGeert Uytterhoeven #include <linux/prefetch.h>
34cafe5635SKent Overstreet #include <linux/random.h>
35cafe5635SKent Overstreet #include <linux/rcupdate.h>
36cafe5635SKent Overstreet #include <trace/events/bcache.h>
37cafe5635SKent Overstreet 
38cafe5635SKent Overstreet /*
39cafe5635SKent Overstreet  * Todo:
40cafe5635SKent Overstreet  * register_bcache: Return errors out to userspace correctly
41cafe5635SKent Overstreet  *
42cafe5635SKent Overstreet  * Writeback: don't undirty key until after a cache flush
43cafe5635SKent Overstreet  *
44cafe5635SKent Overstreet  * Create an iterator for key pointers
45cafe5635SKent Overstreet  *
46cafe5635SKent Overstreet  * On btree write error, mark bucket such that it won't be freed from the cache
47cafe5635SKent Overstreet  *
48cafe5635SKent Overstreet  * Journalling:
49cafe5635SKent Overstreet  *   Check for bad keys in replay
50cafe5635SKent Overstreet  *   Propagate barriers
51cafe5635SKent Overstreet  *   Refcount journal entries in journal_replay
52cafe5635SKent Overstreet  *
53cafe5635SKent Overstreet  * Garbage collection:
54cafe5635SKent Overstreet  *   Finish incremental gc
55cafe5635SKent Overstreet  *   Gc should free old UUIDs, data for invalid UUIDs
56cafe5635SKent Overstreet  *
57cafe5635SKent Overstreet  * Provide a way to list backing device UUIDs we have data cached for, and
58cafe5635SKent Overstreet  * probably how long it's been since we've seen them, and a way to invalidate
59cafe5635SKent Overstreet  * dirty data for devices that will never be attached again
60cafe5635SKent Overstreet  *
61cafe5635SKent Overstreet  * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
62cafe5635SKent Overstreet  * that based on that and how much dirty data we have we can keep writeback
63cafe5635SKent Overstreet  * from being starved
64cafe5635SKent Overstreet  *
65cafe5635SKent Overstreet  * Add a tracepoint or somesuch to watch for writeback starvation
66cafe5635SKent Overstreet  *
67cafe5635SKent Overstreet  * When btree depth > 1 and splitting an interior node, we have to make sure
68cafe5635SKent Overstreet  * alloc_bucket() cannot fail. This should be true but is not completely
69cafe5635SKent Overstreet  * obvious.
70cafe5635SKent Overstreet  *
71cafe5635SKent Overstreet  * Make sure all allocations get charged to the root cgroup
72cafe5635SKent Overstreet  *
73cafe5635SKent Overstreet  * Plugging?
74cafe5635SKent Overstreet  *
75cafe5635SKent Overstreet  * If data write is less than hard sector size of ssd, round up offset in open
76cafe5635SKent Overstreet  * bucket to the next whole sector
77cafe5635SKent Overstreet  *
78cafe5635SKent Overstreet  * Also lookup by cgroup in get_open_bucket()
79cafe5635SKent Overstreet  *
80cafe5635SKent Overstreet  * Superblock needs to be fleshed out for multiple cache devices
81cafe5635SKent Overstreet  *
82cafe5635SKent Overstreet  * Add a sysfs tunable for the number of writeback IOs in flight
83cafe5635SKent Overstreet  *
84cafe5635SKent Overstreet  * Add a sysfs tunable for the number of open data buckets
85cafe5635SKent Overstreet  *
86cafe5635SKent Overstreet  * IO tracking: Can we track when one process is doing io on behalf of another?
87cafe5635SKent Overstreet  * IO tracking: Don't use just an average, weigh more recent stuff higher
88cafe5635SKent Overstreet  *
89cafe5635SKent Overstreet  * Test module load/unload
90cafe5635SKent Overstreet  */
91cafe5635SKent Overstreet 
92cafe5635SKent Overstreet #define MAX_NEED_GC		64
93cafe5635SKent Overstreet #define MAX_SAVE_PRIO		72
94cafe5635SKent Overstreet 
95cafe5635SKent Overstreet #define PTR_DIRTY_BIT		(((uint64_t) 1 << 36))
96cafe5635SKent Overstreet 
97cafe5635SKent Overstreet #define PTR_HASH(c, k)							\
98cafe5635SKent Overstreet 	(((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
99cafe5635SKent Overstreet 
100cafe5635SKent Overstreet static struct workqueue_struct *btree_io_wq;
101cafe5635SKent Overstreet 
102df8e8970SKent Overstreet #define insert_lock(s, b)	((b)->level <= (s)->lock)
103df8e8970SKent Overstreet 
104df8e8970SKent Overstreet /*
105df8e8970SKent Overstreet  * These macros are for recursing down the btree - they handle the details of
106df8e8970SKent Overstreet  * locking and looking up nodes in the cache for you. They're best treated as
107df8e8970SKent Overstreet  * mere syntax when reading code that uses them.
108df8e8970SKent Overstreet  *
109df8e8970SKent Overstreet  * op->lock determines whether we take a read or a write lock at a given depth.
110df8e8970SKent Overstreet  * If you've got a read lock and find that you need a write lock (i.e. you're
111df8e8970SKent Overstreet  * going to have to split), set op->lock and return -EINTR; btree_root() will
112df8e8970SKent Overstreet  * call you again and you'll have the correct lock.
113df8e8970SKent Overstreet  */
114df8e8970SKent Overstreet 
115df8e8970SKent Overstreet /**
116df8e8970SKent Overstreet  * btree - recurse down the btree on a specified key
117df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
118df8e8970SKent Overstreet  * @key:	key to recurse on
119df8e8970SKent Overstreet  * @b:		parent btree node
120df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
121df8e8970SKent Overstreet  */
122df8e8970SKent Overstreet #define btree(fn, key, b, op, ...)					\
123df8e8970SKent Overstreet ({									\
124df8e8970SKent Overstreet 	int _r, l = (b)->level - 1;					\
125df8e8970SKent Overstreet 	bool _w = l <= (op)->lock;					\
126df8e8970SKent Overstreet 	struct btree *_child = bch_btree_node_get((b)->c, key, l, _w);	\
127df8e8970SKent Overstreet 	if (!IS_ERR(_child)) {						\
128df8e8970SKent Overstreet 		_child->parent = (b);					\
129df8e8970SKent Overstreet 		_r = bch_btree_ ## fn(_child, op, ##__VA_ARGS__);	\
130df8e8970SKent Overstreet 		rw_unlock(_w, _child);					\
131df8e8970SKent Overstreet 	} else								\
132df8e8970SKent Overstreet 		_r = PTR_ERR(_child);					\
133df8e8970SKent Overstreet 	_r;								\
134df8e8970SKent Overstreet })
135df8e8970SKent Overstreet 
136df8e8970SKent Overstreet /**
137df8e8970SKent Overstreet  * btree_root - call a function on the root of the btree
138df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
139df8e8970SKent Overstreet  * @c:		cache set
140df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
141df8e8970SKent Overstreet  */
142df8e8970SKent Overstreet #define btree_root(fn, c, op, ...)					\
143df8e8970SKent Overstreet ({									\
144df8e8970SKent Overstreet 	int _r = -EINTR;						\
145df8e8970SKent Overstreet 	do {								\
146df8e8970SKent Overstreet 		struct btree *_b = (c)->root;				\
147df8e8970SKent Overstreet 		bool _w = insert_lock(op, _b);				\
148df8e8970SKent Overstreet 		rw_lock(_w, _b, _b->level);				\
149df8e8970SKent Overstreet 		if (_b == (c)->root &&					\
150df8e8970SKent Overstreet 		    _w == insert_lock(op, _b)) {			\
151df8e8970SKent Overstreet 			_b->parent = NULL;				\
152df8e8970SKent Overstreet 			_r = bch_btree_ ## fn(_b, op, ##__VA_ARGS__);	\
153df8e8970SKent Overstreet 		}							\
154df8e8970SKent Overstreet 		rw_unlock(_w, _b);					\
15578365411SKent Overstreet 		if (_r == -EINTR)					\
15678365411SKent Overstreet 			schedule();					\
157df8e8970SKent Overstreet 		bch_cannibalize_unlock(c);				\
158df8e8970SKent Overstreet 		if (_r == -ENOSPC) {					\
159df8e8970SKent Overstreet 			wait_event((c)->try_wait,			\
160df8e8970SKent Overstreet 				   !(c)->try_harder);			\
161df8e8970SKent Overstreet 			_r = -EINTR;					\
162df8e8970SKent Overstreet 		}							\
163df8e8970SKent Overstreet 	} while (_r == -EINTR);						\
164df8e8970SKent Overstreet 									\
16578365411SKent Overstreet 	finish_wait(&(c)->bucket_wait, &(op)->wait);			\
166df8e8970SKent Overstreet 	_r;								\
167df8e8970SKent Overstreet })
168df8e8970SKent Overstreet 
169a85e968eSKent Overstreet static inline struct bset *write_block(struct btree *b)
170a85e968eSKent Overstreet {
171a85e968eSKent Overstreet 	return ((void *) btree_bset_first(b)) + b->written * block_bytes(b->c);
172a85e968eSKent Overstreet }
173a85e968eSKent Overstreet 
174cafe5635SKent Overstreet /* Btree key manipulation */
175cafe5635SKent Overstreet 
1763a3b6a4eSKent Overstreet void bkey_put(struct cache_set *c, struct bkey *k)
177e7c590ebSKent Overstreet {
178e7c590ebSKent Overstreet 	unsigned i;
179e7c590ebSKent Overstreet 
180e7c590ebSKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
181e7c590ebSKent Overstreet 		if (ptr_available(c, k, i))
182e7c590ebSKent Overstreet 			atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
183e7c590ebSKent Overstreet }
184e7c590ebSKent Overstreet 
185cafe5635SKent Overstreet /* Btree IO */
186cafe5635SKent Overstreet 
187cafe5635SKent Overstreet static uint64_t btree_csum_set(struct btree *b, struct bset *i)
188cafe5635SKent Overstreet {
189cafe5635SKent Overstreet 	uint64_t crc = b->key.ptr[0];
190fafff81cSKent Overstreet 	void *data = (void *) i + 8, *end = bset_bkey_last(i);
191cafe5635SKent Overstreet 
192169ef1cfSKent Overstreet 	crc = bch_crc64_update(crc, data, end - data);
193c19ed23aSKent Overstreet 	return crc ^ 0xffffffffffffffffULL;
194cafe5635SKent Overstreet }
195cafe5635SKent Overstreet 
19678b77bf8SKent Overstreet void bch_btree_node_read_done(struct btree *b)
197cafe5635SKent Overstreet {
198cafe5635SKent Overstreet 	const char *err = "bad btree header";
199ee811287SKent Overstreet 	struct bset *i = btree_bset_first(b);
20057943511SKent Overstreet 	struct btree_iter *iter;
201cafe5635SKent Overstreet 
20257943511SKent Overstreet 	iter = mempool_alloc(b->c->fill_iter, GFP_NOWAIT);
20357943511SKent Overstreet 	iter->size = b->c->sb.bucket_size / b->c->sb.block_size;
204cafe5635SKent Overstreet 	iter->used = 0;
205cafe5635SKent Overstreet 
206280481d0SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
207c052dd9aSKent Overstreet 	iter->b = &b->keys;
208280481d0SKent Overstreet #endif
209280481d0SKent Overstreet 
21057943511SKent Overstreet 	if (!i->seq)
211cafe5635SKent Overstreet 		goto err;
212cafe5635SKent Overstreet 
213cafe5635SKent Overstreet 	for (;
214a85e968eSKent Overstreet 	     b->written < btree_blocks(b) && i->seq == b->keys.set[0].data->seq;
215cafe5635SKent Overstreet 	     i = write_block(b)) {
216cafe5635SKent Overstreet 		err = "unsupported bset version";
217cafe5635SKent Overstreet 		if (i->version > BCACHE_BSET_VERSION)
218cafe5635SKent Overstreet 			goto err;
219cafe5635SKent Overstreet 
220cafe5635SKent Overstreet 		err = "bad btree header";
221ee811287SKent Overstreet 		if (b->written + set_blocks(i, block_bytes(b->c)) >
222ee811287SKent Overstreet 		    btree_blocks(b))
223cafe5635SKent Overstreet 			goto err;
224cafe5635SKent Overstreet 
225cafe5635SKent Overstreet 		err = "bad magic";
22681ab4190SKent Overstreet 		if (i->magic != bset_magic(&b->c->sb))
227cafe5635SKent Overstreet 			goto err;
228cafe5635SKent Overstreet 
229cafe5635SKent Overstreet 		err = "bad checksum";
230cafe5635SKent Overstreet 		switch (i->version) {
231cafe5635SKent Overstreet 		case 0:
232cafe5635SKent Overstreet 			if (i->csum != csum_set(i))
233cafe5635SKent Overstreet 				goto err;
234cafe5635SKent Overstreet 			break;
235cafe5635SKent Overstreet 		case BCACHE_BSET_VERSION:
236cafe5635SKent Overstreet 			if (i->csum != btree_csum_set(b, i))
237cafe5635SKent Overstreet 				goto err;
238cafe5635SKent Overstreet 			break;
239cafe5635SKent Overstreet 		}
240cafe5635SKent Overstreet 
241cafe5635SKent Overstreet 		err = "empty set";
242a85e968eSKent Overstreet 		if (i != b->keys.set[0].data && !i->keys)
243cafe5635SKent Overstreet 			goto err;
244cafe5635SKent Overstreet 
245fafff81cSKent Overstreet 		bch_btree_iter_push(iter, i->start, bset_bkey_last(i));
246cafe5635SKent Overstreet 
247ee811287SKent Overstreet 		b->written += set_blocks(i, block_bytes(b->c));
248cafe5635SKent Overstreet 	}
249cafe5635SKent Overstreet 
250cafe5635SKent Overstreet 	err = "corrupted btree";
251cafe5635SKent Overstreet 	for (i = write_block(b);
252a85e968eSKent Overstreet 	     bset_sector_offset(&b->keys, i) < KEY_SIZE(&b->key);
253cafe5635SKent Overstreet 	     i = ((void *) i) + block_bytes(b->c))
254a85e968eSKent Overstreet 		if (i->seq == b->keys.set[0].data->seq)
255cafe5635SKent Overstreet 			goto err;
256cafe5635SKent Overstreet 
257a85e968eSKent Overstreet 	bch_btree_sort_and_fix_extents(&b->keys, iter, &b->c->sort);
258cafe5635SKent Overstreet 
259a85e968eSKent Overstreet 	i = b->keys.set[0].data;
260cafe5635SKent Overstreet 	err = "short btree key";
261a85e968eSKent Overstreet 	if (b->keys.set[0].size &&
262a85e968eSKent Overstreet 	    bkey_cmp(&b->key, &b->keys.set[0].end) < 0)
263cafe5635SKent Overstreet 		goto err;
264cafe5635SKent Overstreet 
265cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
266a85e968eSKent Overstreet 		bch_bset_init_next(&b->keys, write_block(b),
267a85e968eSKent Overstreet 				   bset_magic(&b->c->sb));
268cafe5635SKent Overstreet out:
26957943511SKent Overstreet 	mempool_free(iter, b->c->fill_iter);
27057943511SKent Overstreet 	return;
271cafe5635SKent Overstreet err:
272cafe5635SKent Overstreet 	set_btree_node_io_error(b);
27388b9f8c4SKent Overstreet 	bch_cache_set_error(b->c, "%s at bucket %zu, block %u, %u keys",
274cafe5635SKent Overstreet 			    err, PTR_BUCKET_NR(b->c, &b->key, 0),
27588b9f8c4SKent Overstreet 			    bset_block_offset(b, i), i->keys);
276cafe5635SKent Overstreet 	goto out;
277cafe5635SKent Overstreet }
278cafe5635SKent Overstreet 
27957943511SKent Overstreet static void btree_node_read_endio(struct bio *bio, int error)
280cafe5635SKent Overstreet {
28157943511SKent Overstreet 	struct closure *cl = bio->bi_private;
28257943511SKent Overstreet 	closure_put(cl);
28357943511SKent Overstreet }
284cafe5635SKent Overstreet 
28578b77bf8SKent Overstreet static void bch_btree_node_read(struct btree *b)
28657943511SKent Overstreet {
28757943511SKent Overstreet 	uint64_t start_time = local_clock();
28857943511SKent Overstreet 	struct closure cl;
28957943511SKent Overstreet 	struct bio *bio;
290cafe5635SKent Overstreet 
291c37511b8SKent Overstreet 	trace_bcache_btree_read(b);
292c37511b8SKent Overstreet 
29357943511SKent Overstreet 	closure_init_stack(&cl);
294cafe5635SKent Overstreet 
29557943511SKent Overstreet 	bio = bch_bbio_alloc(b->c);
29657943511SKent Overstreet 	bio->bi_rw	= REQ_META|READ_SYNC;
2974f024f37SKent Overstreet 	bio->bi_iter.bi_size = KEY_SIZE(&b->key) << 9;
29857943511SKent Overstreet 	bio->bi_end_io	= btree_node_read_endio;
29957943511SKent Overstreet 	bio->bi_private	= &cl;
30057943511SKent Overstreet 
301a85e968eSKent Overstreet 	bch_bio_map(bio, b->keys.set[0].data);
30257943511SKent Overstreet 
30357943511SKent Overstreet 	bch_submit_bbio(bio, b->c, &b->key, 0);
30457943511SKent Overstreet 	closure_sync(&cl);
30557943511SKent Overstreet 
30657943511SKent Overstreet 	if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
30757943511SKent Overstreet 		set_btree_node_io_error(b);
30857943511SKent Overstreet 
30957943511SKent Overstreet 	bch_bbio_free(bio, b->c);
31057943511SKent Overstreet 
31157943511SKent Overstreet 	if (btree_node_io_error(b))
31257943511SKent Overstreet 		goto err;
31357943511SKent Overstreet 
31457943511SKent Overstreet 	bch_btree_node_read_done(b);
31557943511SKent Overstreet 	bch_time_stats_update(&b->c->btree_read_time, start_time);
31657943511SKent Overstreet 
31757943511SKent Overstreet 	return;
31857943511SKent Overstreet err:
31961cbd250SGeert Uytterhoeven 	bch_cache_set_error(b->c, "io error reading bucket %zu",
32057943511SKent Overstreet 			    PTR_BUCKET_NR(b->c, &b->key, 0));
321cafe5635SKent Overstreet }
322cafe5635SKent Overstreet 
323cafe5635SKent Overstreet static void btree_complete_write(struct btree *b, struct btree_write *w)
324cafe5635SKent Overstreet {
325cafe5635SKent Overstreet 	if (w->prio_blocked &&
326cafe5635SKent Overstreet 	    !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
327119ba0f8SKent Overstreet 		wake_up_allocators(b->c);
328cafe5635SKent Overstreet 
329cafe5635SKent Overstreet 	if (w->journal) {
330cafe5635SKent Overstreet 		atomic_dec_bug(w->journal);
331cafe5635SKent Overstreet 		__closure_wake_up(&b->c->journal.wait);
332cafe5635SKent Overstreet 	}
333cafe5635SKent Overstreet 
334cafe5635SKent Overstreet 	w->prio_blocked	= 0;
335cafe5635SKent Overstreet 	w->journal	= NULL;
336cafe5635SKent Overstreet }
337cafe5635SKent Overstreet 
338cb7a583eSKent Overstreet static void btree_node_write_unlock(struct closure *cl)
339cb7a583eSKent Overstreet {
340cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
341cb7a583eSKent Overstreet 
342cb7a583eSKent Overstreet 	up(&b->io_mutex);
343cb7a583eSKent Overstreet }
344cb7a583eSKent Overstreet 
34557943511SKent Overstreet static void __btree_node_write_done(struct closure *cl)
346cafe5635SKent Overstreet {
347cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
348cafe5635SKent Overstreet 	struct btree_write *w = btree_prev_write(b);
349cafe5635SKent Overstreet 
350cafe5635SKent Overstreet 	bch_bbio_free(b->bio, b->c);
351cafe5635SKent Overstreet 	b->bio = NULL;
352cafe5635SKent Overstreet 	btree_complete_write(b, w);
353cafe5635SKent Overstreet 
354cafe5635SKent Overstreet 	if (btree_node_dirty(b))
355cafe5635SKent Overstreet 		queue_delayed_work(btree_io_wq, &b->work,
356cafe5635SKent Overstreet 				   msecs_to_jiffies(30000));
357cafe5635SKent Overstreet 
358cb7a583eSKent Overstreet 	closure_return_with_destructor(cl, btree_node_write_unlock);
359cafe5635SKent Overstreet }
360cafe5635SKent Overstreet 
36157943511SKent Overstreet static void btree_node_write_done(struct closure *cl)
362cafe5635SKent Overstreet {
363cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
364cafe5635SKent Overstreet 	struct bio_vec *bv;
365cafe5635SKent Overstreet 	int n;
366cafe5635SKent Overstreet 
3677988613bSKent Overstreet 	bio_for_each_segment_all(bv, b->bio, n)
368cafe5635SKent Overstreet 		__free_page(bv->bv_page);
369cafe5635SKent Overstreet 
37057943511SKent Overstreet 	__btree_node_write_done(cl);
371cafe5635SKent Overstreet }
372cafe5635SKent Overstreet 
37357943511SKent Overstreet static void btree_node_write_endio(struct bio *bio, int error)
37457943511SKent Overstreet {
37557943511SKent Overstreet 	struct closure *cl = bio->bi_private;
376cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
37757943511SKent Overstreet 
37857943511SKent Overstreet 	if (error)
37957943511SKent Overstreet 		set_btree_node_io_error(b);
38057943511SKent Overstreet 
38157943511SKent Overstreet 	bch_bbio_count_io_errors(b->c, bio, error, "writing btree");
38257943511SKent Overstreet 	closure_put(cl);
38357943511SKent Overstreet }
38457943511SKent Overstreet 
38557943511SKent Overstreet static void do_btree_node_write(struct btree *b)
386cafe5635SKent Overstreet {
387cb7a583eSKent Overstreet 	struct closure *cl = &b->io;
388ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
389cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
390cafe5635SKent Overstreet 
391cafe5635SKent Overstreet 	i->version	= BCACHE_BSET_VERSION;
392cafe5635SKent Overstreet 	i->csum		= btree_csum_set(b, i);
393cafe5635SKent Overstreet 
39457943511SKent Overstreet 	BUG_ON(b->bio);
39557943511SKent Overstreet 	b->bio = bch_bbio_alloc(b->c);
39657943511SKent Overstreet 
39757943511SKent Overstreet 	b->bio->bi_end_io	= btree_node_write_endio;
398faadf0c9SKent Overstreet 	b->bio->bi_private	= cl;
399e49c7c37SKent Overstreet 	b->bio->bi_rw		= REQ_META|WRITE_SYNC|REQ_FUA;
400ee811287SKent Overstreet 	b->bio->bi_iter.bi_size	= roundup(set_bytes(i), block_bytes(b->c));
401169ef1cfSKent Overstreet 	bch_bio_map(b->bio, i);
402cafe5635SKent Overstreet 
403e49c7c37SKent Overstreet 	/*
404e49c7c37SKent Overstreet 	 * If we're appending to a leaf node, we don't technically need FUA -
405e49c7c37SKent Overstreet 	 * this write just needs to be persisted before the next journal write,
406e49c7c37SKent Overstreet 	 * which will be marked FLUSH|FUA.
407e49c7c37SKent Overstreet 	 *
408e49c7c37SKent Overstreet 	 * Similarly if we're writing a new btree root - the pointer is going to
409e49c7c37SKent Overstreet 	 * be in the next journal entry.
410e49c7c37SKent Overstreet 	 *
411e49c7c37SKent Overstreet 	 * But if we're writing a new btree node (that isn't a root) or
412e49c7c37SKent Overstreet 	 * appending to a non leaf btree node, we need either FUA or a flush
413e49c7c37SKent Overstreet 	 * when we write the parent with the new pointer. FUA is cheaper than a
414e49c7c37SKent Overstreet 	 * flush, and writes appending to leaf nodes aren't blocking anything so
415e49c7c37SKent Overstreet 	 * just make all btree node writes FUA to keep things sane.
416e49c7c37SKent Overstreet 	 */
417e49c7c37SKent Overstreet 
418cafe5635SKent Overstreet 	bkey_copy(&k.key, &b->key);
419ee811287SKent Overstreet 	SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) +
420a85e968eSKent Overstreet 		       bset_sector_offset(&b->keys, i));
421cafe5635SKent Overstreet 
4228e51e414SKent Overstreet 	if (!bio_alloc_pages(b->bio, GFP_NOIO)) {
423cafe5635SKent Overstreet 		int j;
424cafe5635SKent Overstreet 		struct bio_vec *bv;
425cafe5635SKent Overstreet 		void *base = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
426cafe5635SKent Overstreet 
4277988613bSKent Overstreet 		bio_for_each_segment_all(bv, b->bio, j)
428cafe5635SKent Overstreet 			memcpy(page_address(bv->bv_page),
429cafe5635SKent Overstreet 			       base + j * PAGE_SIZE, PAGE_SIZE);
430cafe5635SKent Overstreet 
431cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
432cafe5635SKent Overstreet 
43357943511SKent Overstreet 		continue_at(cl, btree_node_write_done, NULL);
434cafe5635SKent Overstreet 	} else {
435cafe5635SKent Overstreet 		b->bio->bi_vcnt = 0;
436169ef1cfSKent Overstreet 		bch_bio_map(b->bio, i);
437cafe5635SKent Overstreet 
438cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
439cafe5635SKent Overstreet 
440cafe5635SKent Overstreet 		closure_sync(cl);
441cb7a583eSKent Overstreet 		continue_at_nobarrier(cl, __btree_node_write_done, NULL);
442cafe5635SKent Overstreet 	}
443cafe5635SKent Overstreet }
444cafe5635SKent Overstreet 
44557943511SKent Overstreet void bch_btree_node_write(struct btree *b, struct closure *parent)
446cafe5635SKent Overstreet {
447ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
448cafe5635SKent Overstreet 
449c37511b8SKent Overstreet 	trace_bcache_btree_write(b);
450c37511b8SKent Overstreet 
451cafe5635SKent Overstreet 	BUG_ON(current->bio_list);
45257943511SKent Overstreet 	BUG_ON(b->written >= btree_blocks(b));
45357943511SKent Overstreet 	BUG_ON(b->written && !i->keys);
454ee811287SKent Overstreet 	BUG_ON(btree_bset_first(b)->seq != i->seq);
455dc9d98d6SKent Overstreet 	bch_check_keys(&b->keys, "writing");
456cafe5635SKent Overstreet 
457cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
458cafe5635SKent Overstreet 
45957943511SKent Overstreet 	/* If caller isn't waiting for write, parent refcount is cache set */
460cb7a583eSKent Overstreet 	down(&b->io_mutex);
461cb7a583eSKent Overstreet 	closure_init(&b->io, parent ?: &b->c->cl);
46257943511SKent Overstreet 
463cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty,	 &b->flags);
464cafe5635SKent Overstreet 	change_bit(BTREE_NODE_write_idx, &b->flags);
465cafe5635SKent Overstreet 
46657943511SKent Overstreet 	do_btree_node_write(b);
467cafe5635SKent Overstreet 
468ee811287SKent Overstreet 	atomic_long_add(set_blocks(i, block_bytes(b->c)) * b->c->sb.block_size,
469cafe5635SKent Overstreet 			&PTR_CACHE(b->c, &b->key, 0)->btree_sectors_written);
470cafe5635SKent Overstreet 
471a85e968eSKent Overstreet 	b->written += set_blocks(i, block_bytes(b->c));
472a85e968eSKent Overstreet 
47367539e85SKent Overstreet 	/* If not a leaf node, always sort */
474a85e968eSKent Overstreet 	if (b->level && b->keys.nsets)
47589ebb4a2SKent Overstreet 		bch_btree_sort(&b->keys, &b->c->sort);
47667539e85SKent Overstreet 	else
47789ebb4a2SKent Overstreet 		bch_btree_sort_lazy(&b->keys, &b->c->sort);
478cafe5635SKent Overstreet 
47978b77bf8SKent Overstreet 	/*
48078b77bf8SKent Overstreet 	 * do verify if there was more than one set initially (i.e. we did a
48178b77bf8SKent Overstreet 	 * sort) and we sorted down to a single set:
48278b77bf8SKent Overstreet 	 */
483a85e968eSKent Overstreet 	if (i != b->keys.set->data && !b->keys.nsets)
48478b77bf8SKent Overstreet 		bch_btree_verify(b);
48578b77bf8SKent Overstreet 
486cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
487a85e968eSKent Overstreet 		bch_bset_init_next(&b->keys, write_block(b),
488a85e968eSKent Overstreet 				   bset_magic(&b->c->sb));
489cafe5635SKent Overstreet }
490cafe5635SKent Overstreet 
491f269af5aSKent Overstreet static void bch_btree_node_write_sync(struct btree *b)
492f269af5aSKent Overstreet {
493f269af5aSKent Overstreet 	struct closure cl;
494f269af5aSKent Overstreet 
495f269af5aSKent Overstreet 	closure_init_stack(&cl);
496f269af5aSKent Overstreet 	bch_btree_node_write(b, &cl);
497f269af5aSKent Overstreet 	closure_sync(&cl);
498f269af5aSKent Overstreet }
499f269af5aSKent Overstreet 
50057943511SKent Overstreet static void btree_node_write_work(struct work_struct *w)
501cafe5635SKent Overstreet {
502cafe5635SKent Overstreet 	struct btree *b = container_of(to_delayed_work(w), struct btree, work);
503cafe5635SKent Overstreet 
50457943511SKent Overstreet 	rw_lock(true, b, b->level);
505cafe5635SKent Overstreet 
506cafe5635SKent Overstreet 	if (btree_node_dirty(b))
50757943511SKent Overstreet 		bch_btree_node_write(b, NULL);
50857943511SKent Overstreet 	rw_unlock(true, b);
509cafe5635SKent Overstreet }
510cafe5635SKent Overstreet 
511c18536a7SKent Overstreet static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
512cafe5635SKent Overstreet {
513ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
514cafe5635SKent Overstreet 	struct btree_write *w = btree_current_write(b);
515cafe5635SKent Overstreet 
51657943511SKent Overstreet 	BUG_ON(!b->written);
51757943511SKent Overstreet 	BUG_ON(!i->keys);
518cafe5635SKent Overstreet 
51957943511SKent Overstreet 	if (!btree_node_dirty(b))
52057943511SKent Overstreet 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
52157943511SKent Overstreet 
522cafe5635SKent Overstreet 	set_btree_node_dirty(b);
523cafe5635SKent Overstreet 
524c18536a7SKent Overstreet 	if (journal_ref) {
525cafe5635SKent Overstreet 		if (w->journal &&
526c18536a7SKent Overstreet 		    journal_pin_cmp(b->c, w->journal, journal_ref)) {
527cafe5635SKent Overstreet 			atomic_dec_bug(w->journal);
528cafe5635SKent Overstreet 			w->journal = NULL;
529cafe5635SKent Overstreet 		}
530cafe5635SKent Overstreet 
531cafe5635SKent Overstreet 		if (!w->journal) {
532c18536a7SKent Overstreet 			w->journal = journal_ref;
533cafe5635SKent Overstreet 			atomic_inc(w->journal);
534cafe5635SKent Overstreet 		}
535cafe5635SKent Overstreet 	}
536cafe5635SKent Overstreet 
537cafe5635SKent Overstreet 	/* Force write if set is too big */
53857943511SKent Overstreet 	if (set_bytes(i) > PAGE_SIZE - 48 &&
53957943511SKent Overstreet 	    !current->bio_list)
54057943511SKent Overstreet 		bch_btree_node_write(b, NULL);
541cafe5635SKent Overstreet }
542cafe5635SKent Overstreet 
543cafe5635SKent Overstreet /*
544cafe5635SKent Overstreet  * Btree in memory cache - allocation/freeing
545cafe5635SKent Overstreet  * mca -> memory cache
546cafe5635SKent Overstreet  */
547cafe5635SKent Overstreet 
548cafe5635SKent Overstreet #define mca_reserve(c)	(((c->root && c->root->level)		\
549cafe5635SKent Overstreet 			  ? c->root->level : 1) * 8 + 16)
550cafe5635SKent Overstreet #define mca_can_free(c)						\
551cafe5635SKent Overstreet 	max_t(int, 0, c->bucket_cache_used - mca_reserve(c))
552cafe5635SKent Overstreet 
553cafe5635SKent Overstreet static void mca_data_free(struct btree *b)
554cafe5635SKent Overstreet {
555cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
556cafe5635SKent Overstreet 
557a85e968eSKent Overstreet 	bch_btree_keys_free(&b->keys);
558cafe5635SKent Overstreet 
559cafe5635SKent Overstreet 	b->c->bucket_cache_used--;
560ee811287SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freed);
561cafe5635SKent Overstreet }
562cafe5635SKent Overstreet 
563cafe5635SKent Overstreet static void mca_bucket_free(struct btree *b)
564cafe5635SKent Overstreet {
565cafe5635SKent Overstreet 	BUG_ON(btree_node_dirty(b));
566cafe5635SKent Overstreet 
567cafe5635SKent Overstreet 	b->key.ptr[0] = 0;
568cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
569cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freeable);
570cafe5635SKent Overstreet }
571cafe5635SKent Overstreet 
572cafe5635SKent Overstreet static unsigned btree_order(struct bkey *k)
573cafe5635SKent Overstreet {
574cafe5635SKent Overstreet 	return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
575cafe5635SKent Overstreet }
576cafe5635SKent Overstreet 
577cafe5635SKent Overstreet static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
578cafe5635SKent Overstreet {
579a85e968eSKent Overstreet 	if (!bch_btree_keys_alloc(&b->keys,
580ee811287SKent Overstreet 				  max_t(unsigned,
581cafe5635SKent Overstreet 					ilog2(b->c->btree_pages),
582ee811287SKent Overstreet 					btree_order(k)),
583ee811287SKent Overstreet 				  gfp)) {
584cafe5635SKent Overstreet 		b->c->bucket_cache_used++;
585ee811287SKent Overstreet 		list_move(&b->list, &b->c->btree_cache);
586ee811287SKent Overstreet 	} else {
587ee811287SKent Overstreet 		list_move(&b->list, &b->c->btree_cache_freed);
588ee811287SKent Overstreet 	}
589cafe5635SKent Overstreet }
590cafe5635SKent Overstreet 
591cafe5635SKent Overstreet static struct btree *mca_bucket_alloc(struct cache_set *c,
592cafe5635SKent Overstreet 				      struct bkey *k, gfp_t gfp)
593cafe5635SKent Overstreet {
594cafe5635SKent Overstreet 	struct btree *b = kzalloc(sizeof(struct btree), gfp);
595cafe5635SKent Overstreet 	if (!b)
596cafe5635SKent Overstreet 		return NULL;
597cafe5635SKent Overstreet 
598cafe5635SKent Overstreet 	init_rwsem(&b->lock);
599cafe5635SKent Overstreet 	lockdep_set_novalidate_class(&b->lock);
600cafe5635SKent Overstreet 	INIT_LIST_HEAD(&b->list);
60157943511SKent Overstreet 	INIT_DELAYED_WORK(&b->work, btree_node_write_work);
602cafe5635SKent Overstreet 	b->c = c;
603cb7a583eSKent Overstreet 	sema_init(&b->io_mutex, 1);
604cafe5635SKent Overstreet 
605cafe5635SKent Overstreet 	mca_data_alloc(b, k, gfp);
606cafe5635SKent Overstreet 	return b;
607cafe5635SKent Overstreet }
608cafe5635SKent Overstreet 
609e8e1d468SKent Overstreet static int mca_reap(struct btree *b, unsigned min_order, bool flush)
610cafe5635SKent Overstreet {
611e8e1d468SKent Overstreet 	struct closure cl;
612e8e1d468SKent Overstreet 
613e8e1d468SKent Overstreet 	closure_init_stack(&cl);
614cafe5635SKent Overstreet 	lockdep_assert_held(&b->c->bucket_lock);
615cafe5635SKent Overstreet 
616cafe5635SKent Overstreet 	if (!down_write_trylock(&b->lock))
617cafe5635SKent Overstreet 		return -ENOMEM;
618cafe5635SKent Overstreet 
619a85e968eSKent Overstreet 	BUG_ON(btree_node_dirty(b) && !b->keys.set[0].data);
620e8e1d468SKent Overstreet 
621a85e968eSKent Overstreet 	if (b->keys.page_order < min_order)
622cb7a583eSKent Overstreet 		goto out_unlock;
623cb7a583eSKent Overstreet 
624cb7a583eSKent Overstreet 	if (!flush) {
625cb7a583eSKent Overstreet 		if (btree_node_dirty(b))
626cb7a583eSKent Overstreet 			goto out_unlock;
627cb7a583eSKent Overstreet 
628cb7a583eSKent Overstreet 		if (down_trylock(&b->io_mutex))
629cb7a583eSKent Overstreet 			goto out_unlock;
630cb7a583eSKent Overstreet 		up(&b->io_mutex);
631cafe5635SKent Overstreet 	}
632cafe5635SKent Overstreet 
633f269af5aSKent Overstreet 	if (btree_node_dirty(b))
634f269af5aSKent Overstreet 		bch_btree_node_write_sync(b);
635cafe5635SKent Overstreet 
636e8e1d468SKent Overstreet 	/* wait for any in flight btree write */
637cb7a583eSKent Overstreet 	down(&b->io_mutex);
638cb7a583eSKent Overstreet 	up(&b->io_mutex);
639e8e1d468SKent Overstreet 
640cafe5635SKent Overstreet 	return 0;
641cb7a583eSKent Overstreet out_unlock:
642cb7a583eSKent Overstreet 	rw_unlock(true, b);
643cb7a583eSKent Overstreet 	return -ENOMEM;
644cafe5635SKent Overstreet }
645cafe5635SKent Overstreet 
6467dc19d5aSDave Chinner static unsigned long bch_mca_scan(struct shrinker *shrink,
6477dc19d5aSDave Chinner 				  struct shrink_control *sc)
648cafe5635SKent Overstreet {
649cafe5635SKent Overstreet 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
650cafe5635SKent Overstreet 	struct btree *b, *t;
651cafe5635SKent Overstreet 	unsigned long i, nr = sc->nr_to_scan;
6527dc19d5aSDave Chinner 	unsigned long freed = 0;
653cafe5635SKent Overstreet 
654cafe5635SKent Overstreet 	if (c->shrinker_disabled)
6557dc19d5aSDave Chinner 		return SHRINK_STOP;
656cafe5635SKent Overstreet 
657cafe5635SKent Overstreet 	if (c->try_harder)
6587dc19d5aSDave Chinner 		return SHRINK_STOP;
659cafe5635SKent Overstreet 
660cafe5635SKent Overstreet 	/* Return -1 if we can't do anything right now */
661a698e08cSKent Overstreet 	if (sc->gfp_mask & __GFP_IO)
662cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
663cafe5635SKent Overstreet 	else if (!mutex_trylock(&c->bucket_lock))
664cafe5635SKent Overstreet 		return -1;
665cafe5635SKent Overstreet 
66636c9ea98SKent Overstreet 	/*
66736c9ea98SKent Overstreet 	 * It's _really_ critical that we don't free too many btree nodes - we
66836c9ea98SKent Overstreet 	 * have to always leave ourselves a reserve. The reserve is how we
66936c9ea98SKent Overstreet 	 * guarantee that allocating memory for a new btree node can always
67036c9ea98SKent Overstreet 	 * succeed, so that inserting keys into the btree can always succeed and
67136c9ea98SKent Overstreet 	 * IO can always make forward progress:
67236c9ea98SKent Overstreet 	 */
673cafe5635SKent Overstreet 	nr /= c->btree_pages;
674cafe5635SKent Overstreet 	nr = min_t(unsigned long, nr, mca_can_free(c));
675cafe5635SKent Overstreet 
676cafe5635SKent Overstreet 	i = 0;
677cafe5635SKent Overstreet 	list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
6787dc19d5aSDave Chinner 		if (freed >= nr)
679cafe5635SKent Overstreet 			break;
680cafe5635SKent Overstreet 
681cafe5635SKent Overstreet 		if (++i > 3 &&
682e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
683cafe5635SKent Overstreet 			mca_data_free(b);
684cafe5635SKent Overstreet 			rw_unlock(true, b);
6857dc19d5aSDave Chinner 			freed++;
686cafe5635SKent Overstreet 		}
687cafe5635SKent Overstreet 	}
688cafe5635SKent Overstreet 
689b0f32a56SKent Overstreet 	for (i = 0; (nr--) && i < c->bucket_cache_used; i++) {
690cafe5635SKent Overstreet 		if (list_empty(&c->btree_cache))
691cafe5635SKent Overstreet 			goto out;
692cafe5635SKent Overstreet 
693cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
694cafe5635SKent Overstreet 		list_rotate_left(&c->btree_cache);
695cafe5635SKent Overstreet 
696cafe5635SKent Overstreet 		if (!b->accessed &&
697e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
698cafe5635SKent Overstreet 			mca_bucket_free(b);
699cafe5635SKent Overstreet 			mca_data_free(b);
700cafe5635SKent Overstreet 			rw_unlock(true, b);
7017dc19d5aSDave Chinner 			freed++;
702cafe5635SKent Overstreet 		} else
703cafe5635SKent Overstreet 			b->accessed = 0;
704cafe5635SKent Overstreet 	}
705cafe5635SKent Overstreet out:
706cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
7077dc19d5aSDave Chinner 	return freed;
7087dc19d5aSDave Chinner }
7097dc19d5aSDave Chinner 
7107dc19d5aSDave Chinner static unsigned long bch_mca_count(struct shrinker *shrink,
7117dc19d5aSDave Chinner 				   struct shrink_control *sc)
7127dc19d5aSDave Chinner {
7137dc19d5aSDave Chinner 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
7147dc19d5aSDave Chinner 
7157dc19d5aSDave Chinner 	if (c->shrinker_disabled)
7167dc19d5aSDave Chinner 		return 0;
7177dc19d5aSDave Chinner 
7187dc19d5aSDave Chinner 	if (c->try_harder)
7197dc19d5aSDave Chinner 		return 0;
7207dc19d5aSDave Chinner 
7217dc19d5aSDave Chinner 	return mca_can_free(c) * c->btree_pages;
722cafe5635SKent Overstreet }
723cafe5635SKent Overstreet 
724cafe5635SKent Overstreet void bch_btree_cache_free(struct cache_set *c)
725cafe5635SKent Overstreet {
726cafe5635SKent Overstreet 	struct btree *b;
727cafe5635SKent Overstreet 	struct closure cl;
728cafe5635SKent Overstreet 	closure_init_stack(&cl);
729cafe5635SKent Overstreet 
730cafe5635SKent Overstreet 	if (c->shrink.list.next)
731cafe5635SKent Overstreet 		unregister_shrinker(&c->shrink);
732cafe5635SKent Overstreet 
733cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
734cafe5635SKent Overstreet 
735cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
736cafe5635SKent Overstreet 	if (c->verify_data)
737cafe5635SKent Overstreet 		list_move(&c->verify_data->list, &c->btree_cache);
73878b77bf8SKent Overstreet 
73978b77bf8SKent Overstreet 	free_pages((unsigned long) c->verify_ondisk, ilog2(bucket_pages(c)));
740cafe5635SKent Overstreet #endif
741cafe5635SKent Overstreet 
742cafe5635SKent Overstreet 	list_splice(&c->btree_cache_freeable,
743cafe5635SKent Overstreet 		    &c->btree_cache);
744cafe5635SKent Overstreet 
745cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache)) {
746cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
747cafe5635SKent Overstreet 
748cafe5635SKent Overstreet 		if (btree_node_dirty(b))
749cafe5635SKent Overstreet 			btree_complete_write(b, btree_current_write(b));
750cafe5635SKent Overstreet 		clear_bit(BTREE_NODE_dirty, &b->flags);
751cafe5635SKent Overstreet 
752cafe5635SKent Overstreet 		mca_data_free(b);
753cafe5635SKent Overstreet 	}
754cafe5635SKent Overstreet 
755cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache_freed)) {
756cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache_freed,
757cafe5635SKent Overstreet 				     struct btree, list);
758cafe5635SKent Overstreet 		list_del(&b->list);
759cafe5635SKent Overstreet 		cancel_delayed_work_sync(&b->work);
760cafe5635SKent Overstreet 		kfree(b);
761cafe5635SKent Overstreet 	}
762cafe5635SKent Overstreet 
763cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
764cafe5635SKent Overstreet }
765cafe5635SKent Overstreet 
766cafe5635SKent Overstreet int bch_btree_cache_alloc(struct cache_set *c)
767cafe5635SKent Overstreet {
768cafe5635SKent Overstreet 	unsigned i;
769cafe5635SKent Overstreet 
770cafe5635SKent Overstreet 	for (i = 0; i < mca_reserve(c); i++)
77172a44517SKent Overstreet 		if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
77272a44517SKent Overstreet 			return -ENOMEM;
773cafe5635SKent Overstreet 
774cafe5635SKent Overstreet 	list_splice_init(&c->btree_cache,
775cafe5635SKent Overstreet 			 &c->btree_cache_freeable);
776cafe5635SKent Overstreet 
777cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
778cafe5635SKent Overstreet 	mutex_init(&c->verify_lock);
779cafe5635SKent Overstreet 
78078b77bf8SKent Overstreet 	c->verify_ondisk = (void *)
78178b77bf8SKent Overstreet 		__get_free_pages(GFP_KERNEL, ilog2(bucket_pages(c)));
78278b77bf8SKent Overstreet 
783cafe5635SKent Overstreet 	c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
784cafe5635SKent Overstreet 
785cafe5635SKent Overstreet 	if (c->verify_data &&
786a85e968eSKent Overstreet 	    c->verify_data->keys.set->data)
787cafe5635SKent Overstreet 		list_del_init(&c->verify_data->list);
788cafe5635SKent Overstreet 	else
789cafe5635SKent Overstreet 		c->verify_data = NULL;
790cafe5635SKent Overstreet #endif
791cafe5635SKent Overstreet 
7927dc19d5aSDave Chinner 	c->shrink.count_objects = bch_mca_count;
7937dc19d5aSDave Chinner 	c->shrink.scan_objects = bch_mca_scan;
794cafe5635SKent Overstreet 	c->shrink.seeks = 4;
795cafe5635SKent Overstreet 	c->shrink.batch = c->btree_pages * 2;
796cafe5635SKent Overstreet 	register_shrinker(&c->shrink);
797cafe5635SKent Overstreet 
798cafe5635SKent Overstreet 	return 0;
799cafe5635SKent Overstreet }
800cafe5635SKent Overstreet 
801cafe5635SKent Overstreet /* Btree in memory cache - hash table */
802cafe5635SKent Overstreet 
803cafe5635SKent Overstreet static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
804cafe5635SKent Overstreet {
805cafe5635SKent Overstreet 	return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
806cafe5635SKent Overstreet }
807cafe5635SKent Overstreet 
808cafe5635SKent Overstreet static struct btree *mca_find(struct cache_set *c, struct bkey *k)
809cafe5635SKent Overstreet {
810cafe5635SKent Overstreet 	struct btree *b;
811cafe5635SKent Overstreet 
812cafe5635SKent Overstreet 	rcu_read_lock();
813cafe5635SKent Overstreet 	hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
814cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
815cafe5635SKent Overstreet 			goto out;
816cafe5635SKent Overstreet 	b = NULL;
817cafe5635SKent Overstreet out:
818cafe5635SKent Overstreet 	rcu_read_unlock();
819cafe5635SKent Overstreet 	return b;
820cafe5635SKent Overstreet }
821cafe5635SKent Overstreet 
822e8e1d468SKent Overstreet static struct btree *mca_cannibalize(struct cache_set *c, struct bkey *k)
823cafe5635SKent Overstreet {
824e8e1d468SKent Overstreet 	struct btree *b;
825cafe5635SKent Overstreet 
826c37511b8SKent Overstreet 	trace_bcache_btree_cache_cannibalize(c);
827c37511b8SKent Overstreet 
828e8e1d468SKent Overstreet 	if (!c->try_harder) {
829e8e1d468SKent Overstreet 		c->try_harder = current;
830cafe5635SKent Overstreet 		c->try_harder_start = local_clock();
831e8e1d468SKent Overstreet 	} else if (c->try_harder != current)
832e8e1d468SKent Overstreet 		return ERR_PTR(-ENOSPC);
833cafe5635SKent Overstreet 
834e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
835e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
836e8e1d468SKent Overstreet 			return b;
837cafe5635SKent Overstreet 
838e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
839e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), true))
840e8e1d468SKent Overstreet 			return b;
841e8e1d468SKent Overstreet 
842e8e1d468SKent Overstreet 	return ERR_PTR(-ENOMEM);
843cafe5635SKent Overstreet }
844cafe5635SKent Overstreet 
845cafe5635SKent Overstreet /*
846cafe5635SKent Overstreet  * We can only have one thread cannibalizing other cached btree nodes at a time,
847cafe5635SKent Overstreet  * or we'll deadlock. We use an open coded mutex to ensure that, which a
848cafe5635SKent Overstreet  * cannibalize_bucket() will take. This means every time we unlock the root of
849cafe5635SKent Overstreet  * the btree, we need to release this lock if we have it held.
850cafe5635SKent Overstreet  */
851df8e8970SKent Overstreet static void bch_cannibalize_unlock(struct cache_set *c)
852cafe5635SKent Overstreet {
853e8e1d468SKent Overstreet 	if (c->try_harder == current) {
854169ef1cfSKent Overstreet 		bch_time_stats_update(&c->try_harder_time, c->try_harder_start);
855cafe5635SKent Overstreet 		c->try_harder = NULL;
856e8e1d468SKent Overstreet 		wake_up(&c->try_wait);
857cafe5635SKent Overstreet 	}
858cafe5635SKent Overstreet }
859cafe5635SKent Overstreet 
860e8e1d468SKent Overstreet static struct btree *mca_alloc(struct cache_set *c, struct bkey *k, int level)
861cafe5635SKent Overstreet {
862cafe5635SKent Overstreet 	struct btree *b;
863cafe5635SKent Overstreet 
864e8e1d468SKent Overstreet 	BUG_ON(current->bio_list);
865e8e1d468SKent Overstreet 
866cafe5635SKent Overstreet 	lockdep_assert_held(&c->bucket_lock);
867cafe5635SKent Overstreet 
868cafe5635SKent Overstreet 	if (mca_find(c, k))
869cafe5635SKent Overstreet 		return NULL;
870cafe5635SKent Overstreet 
871cafe5635SKent Overstreet 	/* btree_free() doesn't free memory; it sticks the node on the end of
872cafe5635SKent Overstreet 	 * the list. Check if there's any freed nodes there:
873cafe5635SKent Overstreet 	 */
874cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freeable, list)
875e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
876cafe5635SKent Overstreet 			goto out;
877cafe5635SKent Overstreet 
878cafe5635SKent Overstreet 	/* We never free struct btree itself, just the memory that holds the on
879cafe5635SKent Overstreet 	 * disk node. Check the freed list before allocating a new one:
880cafe5635SKent Overstreet 	 */
881cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freed, list)
882e8e1d468SKent Overstreet 		if (!mca_reap(b, 0, false)) {
883cafe5635SKent Overstreet 			mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
884a85e968eSKent Overstreet 			if (!b->keys.set[0].data)
885cafe5635SKent Overstreet 				goto err;
886cafe5635SKent Overstreet 			else
887cafe5635SKent Overstreet 				goto out;
888cafe5635SKent Overstreet 		}
889cafe5635SKent Overstreet 
890cafe5635SKent Overstreet 	b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
891cafe5635SKent Overstreet 	if (!b)
892cafe5635SKent Overstreet 		goto err;
893cafe5635SKent Overstreet 
894cafe5635SKent Overstreet 	BUG_ON(!down_write_trylock(&b->lock));
895a85e968eSKent Overstreet 	if (!b->keys.set->data)
896cafe5635SKent Overstreet 		goto err;
897cafe5635SKent Overstreet out:
898cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
899cafe5635SKent Overstreet 
900cafe5635SKent Overstreet 	bkey_copy(&b->key, k);
901cafe5635SKent Overstreet 	list_move(&b->list, &c->btree_cache);
902cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
903cafe5635SKent Overstreet 	hlist_add_head_rcu(&b->hash, mca_hash(c, k));
904cafe5635SKent Overstreet 
905cafe5635SKent Overstreet 	lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
906d6fd3b11SKent Overstreet 	b->parent	= (void *) ~0UL;
907a85e968eSKent Overstreet 	b->flags	= 0;
908a85e968eSKent Overstreet 	b->written	= 0;
909a85e968eSKent Overstreet 	b->level	= level;
910cafe5635SKent Overstreet 
91165d45231SKent Overstreet 	if (!b->level)
912a85e968eSKent Overstreet 		bch_btree_keys_init(&b->keys, &bch_extent_keys_ops,
913a85e968eSKent Overstreet 				    &b->c->expensive_debug_checks);
91465d45231SKent Overstreet 	else
915a85e968eSKent Overstreet 		bch_btree_keys_init(&b->keys, &bch_btree_keys_ops,
916a85e968eSKent Overstreet 				    &b->c->expensive_debug_checks);
917cafe5635SKent Overstreet 
918cafe5635SKent Overstreet 	return b;
919cafe5635SKent Overstreet err:
920cafe5635SKent Overstreet 	if (b)
921cafe5635SKent Overstreet 		rw_unlock(true, b);
922cafe5635SKent Overstreet 
923e8e1d468SKent Overstreet 	b = mca_cannibalize(c, k);
924cafe5635SKent Overstreet 	if (!IS_ERR(b))
925cafe5635SKent Overstreet 		goto out;
926cafe5635SKent Overstreet 
927cafe5635SKent Overstreet 	return b;
928cafe5635SKent Overstreet }
929cafe5635SKent Overstreet 
930cafe5635SKent Overstreet /**
931cafe5635SKent Overstreet  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
932cafe5635SKent Overstreet  * in from disk if necessary.
933cafe5635SKent Overstreet  *
934b54d6934SKent Overstreet  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
935cafe5635SKent Overstreet  *
936cafe5635SKent Overstreet  * The btree node will have either a read or a write lock held, depending on
937cafe5635SKent Overstreet  * level and op->lock.
938cafe5635SKent Overstreet  */
939cafe5635SKent Overstreet struct btree *bch_btree_node_get(struct cache_set *c, struct bkey *k,
940e8e1d468SKent Overstreet 				 int level, bool write)
941cafe5635SKent Overstreet {
942cafe5635SKent Overstreet 	int i = 0;
943cafe5635SKent Overstreet 	struct btree *b;
944cafe5635SKent Overstreet 
945cafe5635SKent Overstreet 	BUG_ON(level < 0);
946cafe5635SKent Overstreet retry:
947cafe5635SKent Overstreet 	b = mca_find(c, k);
948cafe5635SKent Overstreet 
949cafe5635SKent Overstreet 	if (!b) {
95057943511SKent Overstreet 		if (current->bio_list)
95157943511SKent Overstreet 			return ERR_PTR(-EAGAIN);
95257943511SKent Overstreet 
953cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
954e8e1d468SKent Overstreet 		b = mca_alloc(c, k, level);
955cafe5635SKent Overstreet 		mutex_unlock(&c->bucket_lock);
956cafe5635SKent Overstreet 
957cafe5635SKent Overstreet 		if (!b)
958cafe5635SKent Overstreet 			goto retry;
959cafe5635SKent Overstreet 		if (IS_ERR(b))
960cafe5635SKent Overstreet 			return b;
961cafe5635SKent Overstreet 
96257943511SKent Overstreet 		bch_btree_node_read(b);
963cafe5635SKent Overstreet 
964cafe5635SKent Overstreet 		if (!write)
965cafe5635SKent Overstreet 			downgrade_write(&b->lock);
966cafe5635SKent Overstreet 	} else {
967cafe5635SKent Overstreet 		rw_lock(write, b, level);
968cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
969cafe5635SKent Overstreet 			rw_unlock(write, b);
970cafe5635SKent Overstreet 			goto retry;
971cafe5635SKent Overstreet 		}
972cafe5635SKent Overstreet 		BUG_ON(b->level != level);
973cafe5635SKent Overstreet 	}
974cafe5635SKent Overstreet 
975cafe5635SKent Overstreet 	b->accessed = 1;
976cafe5635SKent Overstreet 
977a85e968eSKent Overstreet 	for (; i <= b->keys.nsets && b->keys.set[i].size; i++) {
978a85e968eSKent Overstreet 		prefetch(b->keys.set[i].tree);
979a85e968eSKent Overstreet 		prefetch(b->keys.set[i].data);
980cafe5635SKent Overstreet 	}
981cafe5635SKent Overstreet 
982a85e968eSKent Overstreet 	for (; i <= b->keys.nsets; i++)
983a85e968eSKent Overstreet 		prefetch(b->keys.set[i].data);
984cafe5635SKent Overstreet 
98557943511SKent Overstreet 	if (btree_node_io_error(b)) {
986cafe5635SKent Overstreet 		rw_unlock(write, b);
98757943511SKent Overstreet 		return ERR_PTR(-EIO);
98857943511SKent Overstreet 	}
98957943511SKent Overstreet 
990cafe5635SKent Overstreet 	BUG_ON(!b->written);
991cafe5635SKent Overstreet 
992cafe5635SKent Overstreet 	return b;
993cafe5635SKent Overstreet }
994cafe5635SKent Overstreet 
995cafe5635SKent Overstreet static void btree_node_prefetch(struct cache_set *c, struct bkey *k, int level)
996cafe5635SKent Overstreet {
997cafe5635SKent Overstreet 	struct btree *b;
998cafe5635SKent Overstreet 
999cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1000e8e1d468SKent Overstreet 	b = mca_alloc(c, k, level);
1001cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1002cafe5635SKent Overstreet 
1003cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(b)) {
100457943511SKent Overstreet 		bch_btree_node_read(b);
1005cafe5635SKent Overstreet 		rw_unlock(true, b);
1006cafe5635SKent Overstreet 	}
1007cafe5635SKent Overstreet }
1008cafe5635SKent Overstreet 
1009cafe5635SKent Overstreet /* Btree alloc */
1010cafe5635SKent Overstreet 
1011e8e1d468SKent Overstreet static void btree_node_free(struct btree *b)
1012cafe5635SKent Overstreet {
1013cafe5635SKent Overstreet 	unsigned i;
1014cafe5635SKent Overstreet 
1015c37511b8SKent Overstreet 	trace_bcache_btree_node_free(b);
1016c37511b8SKent Overstreet 
1017cafe5635SKent Overstreet 	BUG_ON(b == b->c->root);
1018cafe5635SKent Overstreet 
1019cafe5635SKent Overstreet 	if (btree_node_dirty(b))
1020cafe5635SKent Overstreet 		btree_complete_write(b, btree_current_write(b));
1021cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty, &b->flags);
1022cafe5635SKent Overstreet 
1023cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
1024cafe5635SKent Overstreet 
1025cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
1026cafe5635SKent Overstreet 
1027cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++) {
1028cafe5635SKent Overstreet 		BUG_ON(atomic_read(&PTR_BUCKET(b->c, &b->key, i)->pin));
1029cafe5635SKent Overstreet 
1030cafe5635SKent Overstreet 		bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
1031cafe5635SKent Overstreet 			    PTR_BUCKET(b->c, &b->key, i));
1032cafe5635SKent Overstreet 	}
1033cafe5635SKent Overstreet 
1034cafe5635SKent Overstreet 	bch_bucket_free(b->c, &b->key);
1035cafe5635SKent Overstreet 	mca_bucket_free(b);
1036cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
1037cafe5635SKent Overstreet }
1038cafe5635SKent Overstreet 
1039bc9389eeSKent Overstreet struct btree *bch_btree_node_alloc(struct cache_set *c, int level, bool wait)
1040cafe5635SKent Overstreet {
1041cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
1042cafe5635SKent Overstreet 	struct btree *b = ERR_PTR(-EAGAIN);
1043cafe5635SKent Overstreet 
1044cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1045cafe5635SKent Overstreet retry:
104678365411SKent Overstreet 	if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, wait))
1047cafe5635SKent Overstreet 		goto err;
1048cafe5635SKent Overstreet 
10493a3b6a4eSKent Overstreet 	bkey_put(c, &k.key);
1050cafe5635SKent Overstreet 	SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1051cafe5635SKent Overstreet 
1052e8e1d468SKent Overstreet 	b = mca_alloc(c, &k.key, level);
1053cafe5635SKent Overstreet 	if (IS_ERR(b))
1054cafe5635SKent Overstreet 		goto err_free;
1055cafe5635SKent Overstreet 
1056cafe5635SKent Overstreet 	if (!b) {
1057b1a67b0fSKent Overstreet 		cache_bug(c,
1058b1a67b0fSKent Overstreet 			"Tried to allocate bucket that was in btree cache");
1059cafe5635SKent Overstreet 		goto retry;
1060cafe5635SKent Overstreet 	}
1061cafe5635SKent Overstreet 
1062cafe5635SKent Overstreet 	b->accessed = 1;
1063a85e968eSKent Overstreet 	bch_bset_init_next(&b->keys, b->keys.set->data, bset_magic(&b->c->sb));
1064cafe5635SKent Overstreet 
1065cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1066c37511b8SKent Overstreet 
1067c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc(b);
1068cafe5635SKent Overstreet 	return b;
1069cafe5635SKent Overstreet err_free:
1070cafe5635SKent Overstreet 	bch_bucket_free(c, &k.key);
1071cafe5635SKent Overstreet err:
1072cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1073c37511b8SKent Overstreet 
1074c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc_fail(b);
1075cafe5635SKent Overstreet 	return b;
1076cafe5635SKent Overstreet }
1077cafe5635SKent Overstreet 
1078bc9389eeSKent Overstreet static struct btree *btree_node_alloc_replacement(struct btree *b, bool wait)
1079cafe5635SKent Overstreet {
1080bc9389eeSKent Overstreet 	struct btree *n = bch_btree_node_alloc(b->c, b->level, wait);
108167539e85SKent Overstreet 	if (!IS_ERR_OR_NULL(n)) {
108289ebb4a2SKent Overstreet 		bch_btree_sort_into(&b->keys, &n->keys, &b->c->sort);
108367539e85SKent Overstreet 		bkey_copy_key(&n->key, &b->key);
108467539e85SKent Overstreet 	}
1085cafe5635SKent Overstreet 
1086cafe5635SKent Overstreet 	return n;
1087cafe5635SKent Overstreet }
1088cafe5635SKent Overstreet 
10898835c123SKent Overstreet static void make_btree_freeing_key(struct btree *b, struct bkey *k)
10908835c123SKent Overstreet {
10918835c123SKent Overstreet 	unsigned i;
10928835c123SKent Overstreet 
10938835c123SKent Overstreet 	bkey_copy(k, &b->key);
10948835c123SKent Overstreet 	bkey_copy_key(k, &ZERO_KEY);
10958835c123SKent Overstreet 
10968835c123SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
10978835c123SKent Overstreet 		uint8_t g = PTR_BUCKET(b->c, k, i)->gen + 1;
10988835c123SKent Overstreet 
10998835c123SKent Overstreet 		SET_PTR_GEN(k, i, g);
11008835c123SKent Overstreet 	}
11018835c123SKent Overstreet 
11028835c123SKent Overstreet 	atomic_inc(&b->c->prio_blocked);
11038835c123SKent Overstreet }
11048835c123SKent Overstreet 
110578365411SKent Overstreet static int btree_check_reserve(struct btree *b, struct btree_op *op)
110678365411SKent Overstreet {
110778365411SKent Overstreet 	struct cache_set *c = b->c;
110878365411SKent Overstreet 	struct cache *ca;
110978365411SKent Overstreet 	unsigned i, reserve = c->root->level * 2 + 1;
111078365411SKent Overstreet 	int ret = 0;
111178365411SKent Overstreet 
111278365411SKent Overstreet 	mutex_lock(&c->bucket_lock);
111378365411SKent Overstreet 
111478365411SKent Overstreet 	for_each_cache(ca, c, i)
111578365411SKent Overstreet 		if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
111678365411SKent Overstreet 			if (op)
111778365411SKent Overstreet 				prepare_to_wait(&c->bucket_wait, &op->wait,
111878365411SKent Overstreet 						TASK_UNINTERRUPTIBLE);
111978365411SKent Overstreet 			ret = -EINTR;
112078365411SKent Overstreet 			break;
112178365411SKent Overstreet 		}
112278365411SKent Overstreet 
112378365411SKent Overstreet 	mutex_unlock(&c->bucket_lock);
112478365411SKent Overstreet 	return ret;
112578365411SKent Overstreet }
112678365411SKent Overstreet 
1127cafe5635SKent Overstreet /* Garbage collection */
1128cafe5635SKent Overstreet 
1129cafe5635SKent Overstreet uint8_t __bch_btree_mark_key(struct cache_set *c, int level, struct bkey *k)
1130cafe5635SKent Overstreet {
1131cafe5635SKent Overstreet 	uint8_t stale = 0;
1132cafe5635SKent Overstreet 	unsigned i;
1133cafe5635SKent Overstreet 	struct bucket *g;
1134cafe5635SKent Overstreet 
1135cafe5635SKent Overstreet 	/*
1136cafe5635SKent Overstreet 	 * ptr_invalid() can't return true for the keys that mark btree nodes as
1137cafe5635SKent Overstreet 	 * freed, but since ptr_bad() returns true we'll never actually use them
1138cafe5635SKent Overstreet 	 * for anything and thus we don't want mark their pointers here
1139cafe5635SKent Overstreet 	 */
1140cafe5635SKent Overstreet 	if (!bkey_cmp(k, &ZERO_KEY))
1141cafe5635SKent Overstreet 		return stale;
1142cafe5635SKent Overstreet 
1143cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
1144cafe5635SKent Overstreet 		if (!ptr_available(c, k, i))
1145cafe5635SKent Overstreet 			continue;
1146cafe5635SKent Overstreet 
1147cafe5635SKent Overstreet 		g = PTR_BUCKET(c, k, i);
1148cafe5635SKent Overstreet 
1149cafe5635SKent Overstreet 		if (gen_after(g->gc_gen, PTR_GEN(k, i)))
1150cafe5635SKent Overstreet 			g->gc_gen = PTR_GEN(k, i);
1151cafe5635SKent Overstreet 
1152cafe5635SKent Overstreet 		if (ptr_stale(c, k, i)) {
1153cafe5635SKent Overstreet 			stale = max(stale, ptr_stale(c, k, i));
1154cafe5635SKent Overstreet 			continue;
1155cafe5635SKent Overstreet 		}
1156cafe5635SKent Overstreet 
1157cafe5635SKent Overstreet 		cache_bug_on(GC_MARK(g) &&
1158cafe5635SKent Overstreet 			     (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1159cafe5635SKent Overstreet 			     c, "inconsistent ptrs: mark = %llu, level = %i",
1160cafe5635SKent Overstreet 			     GC_MARK(g), level);
1161cafe5635SKent Overstreet 
1162cafe5635SKent Overstreet 		if (level)
1163cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_METADATA);
1164cafe5635SKent Overstreet 		else if (KEY_DIRTY(k))
1165cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_DIRTY);
1166cafe5635SKent Overstreet 
1167cafe5635SKent Overstreet 		/* guard against overflow */
1168cafe5635SKent Overstreet 		SET_GC_SECTORS_USED(g, min_t(unsigned,
1169cafe5635SKent Overstreet 					     GC_SECTORS_USED(g) + KEY_SIZE(k),
117094717447SDarrick J. Wong 					     MAX_GC_SECTORS_USED));
1171cafe5635SKent Overstreet 
1172cafe5635SKent Overstreet 		BUG_ON(!GC_SECTORS_USED(g));
1173cafe5635SKent Overstreet 	}
1174cafe5635SKent Overstreet 
1175cafe5635SKent Overstreet 	return stale;
1176cafe5635SKent Overstreet }
1177cafe5635SKent Overstreet 
1178cafe5635SKent Overstreet #define btree_mark_key(b, k)	__bch_btree_mark_key(b->c, b->level, k)
1179cafe5635SKent Overstreet 
1180a1f0358bSKent Overstreet static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1181cafe5635SKent Overstreet {
1182cafe5635SKent Overstreet 	uint8_t stale = 0;
1183a1f0358bSKent Overstreet 	unsigned keys = 0, good_keys = 0;
1184cafe5635SKent Overstreet 	struct bkey *k;
1185cafe5635SKent Overstreet 	struct btree_iter iter;
1186cafe5635SKent Overstreet 	struct bset_tree *t;
1187cafe5635SKent Overstreet 
1188cafe5635SKent Overstreet 	gc->nodes++;
1189cafe5635SKent Overstreet 
1190c052dd9aSKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid) {
1191cafe5635SKent Overstreet 		stale = max(stale, btree_mark_key(b, k));
1192a1f0358bSKent Overstreet 		keys++;
1193cafe5635SKent Overstreet 
1194a85e968eSKent Overstreet 		if (bch_ptr_bad(&b->keys, k))
1195cafe5635SKent Overstreet 			continue;
1196cafe5635SKent Overstreet 
1197cafe5635SKent Overstreet 		gc->key_bytes += bkey_u64s(k);
1198cafe5635SKent Overstreet 		gc->nkeys++;
1199a1f0358bSKent Overstreet 		good_keys++;
1200cafe5635SKent Overstreet 
1201cafe5635SKent Overstreet 		gc->data += KEY_SIZE(k);
1202cafe5635SKent Overstreet 	}
1203cafe5635SKent Overstreet 
1204a85e968eSKent Overstreet 	for (t = b->keys.set; t <= &b->keys.set[b->keys.nsets]; t++)
1205cafe5635SKent Overstreet 		btree_bug_on(t->size &&
1206a85e968eSKent Overstreet 			     bset_written(&b->keys, t) &&
1207cafe5635SKent Overstreet 			     bkey_cmp(&b->key, &t->end) < 0,
1208cafe5635SKent Overstreet 			     b, "found short btree key in gc");
1209cafe5635SKent Overstreet 
1210a1f0358bSKent Overstreet 	if (b->c->gc_always_rewrite)
1211a1f0358bSKent Overstreet 		return true;
1212a1f0358bSKent Overstreet 
1213a1f0358bSKent Overstreet 	if (stale > 10)
1214a1f0358bSKent Overstreet 		return true;
1215a1f0358bSKent Overstreet 
1216a1f0358bSKent Overstreet 	if ((keys - good_keys) * 2 > keys)
1217a1f0358bSKent Overstreet 		return true;
1218a1f0358bSKent Overstreet 
1219a1f0358bSKent Overstreet 	return false;
1220cafe5635SKent Overstreet }
1221cafe5635SKent Overstreet 
1222a1f0358bSKent Overstreet #define GC_MERGE_NODES	4U
1223cafe5635SKent Overstreet 
1224cafe5635SKent Overstreet struct gc_merge_info {
1225cafe5635SKent Overstreet 	struct btree	*b;
1226cafe5635SKent Overstreet 	unsigned	keys;
1227cafe5635SKent Overstreet };
1228cafe5635SKent Overstreet 
1229a1f0358bSKent Overstreet static int bch_btree_insert_node(struct btree *, struct btree_op *,
1230a1f0358bSKent Overstreet 				 struct keylist *, atomic_t *, struct bkey *);
1231a1f0358bSKent Overstreet 
1232a1f0358bSKent Overstreet static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
1233a1f0358bSKent Overstreet 			     struct keylist *keylist, struct gc_stat *gc,
1234e8e1d468SKent Overstreet 			     struct gc_merge_info *r)
1235cafe5635SKent Overstreet {
1236a1f0358bSKent Overstreet 	unsigned i, nodes = 0, keys = 0, blocks;
1237a1f0358bSKent Overstreet 	struct btree *new_nodes[GC_MERGE_NODES];
1238b54d6934SKent Overstreet 	struct closure cl;
1239a1f0358bSKent Overstreet 	struct bkey *k;
1240b54d6934SKent Overstreet 
1241a1f0358bSKent Overstreet 	memset(new_nodes, 0, sizeof(new_nodes));
1242b54d6934SKent Overstreet 	closure_init_stack(&cl);
1243cafe5635SKent Overstreet 
1244a1f0358bSKent Overstreet 	while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1245cafe5635SKent Overstreet 		keys += r[nodes++].keys;
1246cafe5635SKent Overstreet 
1247cafe5635SKent Overstreet 	blocks = btree_default_blocks(b->c) * 2 / 3;
1248cafe5635SKent Overstreet 
1249cafe5635SKent Overstreet 	if (nodes < 2 ||
1250a85e968eSKent Overstreet 	    __set_blocks(b->keys.set[0].data, keys,
1251ee811287SKent Overstreet 			 block_bytes(b->c)) > blocks * (nodes - 1))
1252a1f0358bSKent Overstreet 		return 0;
1253cafe5635SKent Overstreet 
1254a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1255bc9389eeSKent Overstreet 		new_nodes[i] = btree_node_alloc_replacement(r[i].b, false);
1256a1f0358bSKent Overstreet 		if (IS_ERR_OR_NULL(new_nodes[i]))
1257a1f0358bSKent Overstreet 			goto out_nocoalesce;
1258cafe5635SKent Overstreet 	}
1259cafe5635SKent Overstreet 
1260cafe5635SKent Overstreet 	for (i = nodes - 1; i > 0; --i) {
1261ee811287SKent Overstreet 		struct bset *n1 = btree_bset_first(new_nodes[i]);
1262ee811287SKent Overstreet 		struct bset *n2 = btree_bset_first(new_nodes[i - 1]);
1263cafe5635SKent Overstreet 		struct bkey *k, *last = NULL;
1264cafe5635SKent Overstreet 
1265cafe5635SKent Overstreet 		keys = 0;
1266cafe5635SKent Overstreet 
1267a1f0358bSKent Overstreet 		if (i > 1) {
1268cafe5635SKent Overstreet 			for (k = n2->start;
1269fafff81cSKent Overstreet 			     k < bset_bkey_last(n2);
1270cafe5635SKent Overstreet 			     k = bkey_next(k)) {
1271cafe5635SKent Overstreet 				if (__set_blocks(n1, n1->keys + keys +
1272ee811287SKent Overstreet 						 bkey_u64s(k),
1273ee811287SKent Overstreet 						 block_bytes(b->c)) > blocks)
1274cafe5635SKent Overstreet 					break;
1275cafe5635SKent Overstreet 
1276cafe5635SKent Overstreet 				last = k;
1277cafe5635SKent Overstreet 				keys += bkey_u64s(k);
1278cafe5635SKent Overstreet 			}
1279a1f0358bSKent Overstreet 		} else {
1280a1f0358bSKent Overstreet 			/*
1281a1f0358bSKent Overstreet 			 * Last node we're not getting rid of - we're getting
1282a1f0358bSKent Overstreet 			 * rid of the node at r[0]. Have to try and fit all of
1283a1f0358bSKent Overstreet 			 * the remaining keys into this node; we can't ensure
1284a1f0358bSKent Overstreet 			 * they will always fit due to rounding and variable
1285a1f0358bSKent Overstreet 			 * length keys (shouldn't be possible in practice,
1286a1f0358bSKent Overstreet 			 * though)
1287a1f0358bSKent Overstreet 			 */
1288a1f0358bSKent Overstreet 			if (__set_blocks(n1, n1->keys + n2->keys,
1289ee811287SKent Overstreet 					 block_bytes(b->c)) >
1290ee811287SKent Overstreet 			    btree_blocks(new_nodes[i]))
1291a1f0358bSKent Overstreet 				goto out_nocoalesce;
1292a1f0358bSKent Overstreet 
1293a1f0358bSKent Overstreet 			keys = n2->keys;
1294a1f0358bSKent Overstreet 			/* Take the key of the node we're getting rid of */
1295a1f0358bSKent Overstreet 			last = &r->b->key;
1296a1f0358bSKent Overstreet 		}
1297cafe5635SKent Overstreet 
1298ee811287SKent Overstreet 		BUG_ON(__set_blocks(n1, n1->keys + keys, block_bytes(b->c)) >
1299ee811287SKent Overstreet 		       btree_blocks(new_nodes[i]));
1300cafe5635SKent Overstreet 
1301a1f0358bSKent Overstreet 		if (last)
1302a1f0358bSKent Overstreet 			bkey_copy_key(&new_nodes[i]->key, last);
1303cafe5635SKent Overstreet 
1304fafff81cSKent Overstreet 		memcpy(bset_bkey_last(n1),
1305cafe5635SKent Overstreet 		       n2->start,
1306fafff81cSKent Overstreet 		       (void *) bset_bkey_idx(n2, keys) - (void *) n2->start);
1307cafe5635SKent Overstreet 
1308cafe5635SKent Overstreet 		n1->keys += keys;
1309a1f0358bSKent Overstreet 		r[i].keys = n1->keys;
1310cafe5635SKent Overstreet 
1311cafe5635SKent Overstreet 		memmove(n2->start,
1312fafff81cSKent Overstreet 			bset_bkey_idx(n2, keys),
1313fafff81cSKent Overstreet 			(void *) bset_bkey_last(n2) -
1314fafff81cSKent Overstreet 			(void *) bset_bkey_idx(n2, keys));
1315cafe5635SKent Overstreet 
1316cafe5635SKent Overstreet 		n2->keys -= keys;
1317cafe5635SKent Overstreet 
1318085d2a3dSKent Overstreet 		if (__bch_keylist_realloc(keylist,
1319085d2a3dSKent Overstreet 					  bkey_u64s(&new_nodes[i]->key)))
1320a1f0358bSKent Overstreet 			goto out_nocoalesce;
1321a1f0358bSKent Overstreet 
1322a1f0358bSKent Overstreet 		bch_btree_node_write(new_nodes[i], &cl);
1323a1f0358bSKent Overstreet 		bch_keylist_add(keylist, &new_nodes[i]->key);
1324cafe5635SKent Overstreet 	}
1325cafe5635SKent Overstreet 
1326a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1327085d2a3dSKent Overstreet 		if (__bch_keylist_realloc(keylist, bkey_u64s(&r[i].b->key)))
1328a1f0358bSKent Overstreet 			goto out_nocoalesce;
1329a1f0358bSKent Overstreet 
1330a1f0358bSKent Overstreet 		make_btree_freeing_key(r[i].b, keylist->top);
1331a1f0358bSKent Overstreet 		bch_keylist_push(keylist);
1332a1f0358bSKent Overstreet 	}
1333a1f0358bSKent Overstreet 
1334a1f0358bSKent Overstreet 	/* We emptied out this node */
1335ee811287SKent Overstreet 	BUG_ON(btree_bset_first(new_nodes[0])->keys);
1336a1f0358bSKent Overstreet 	btree_node_free(new_nodes[0]);
1337a1f0358bSKent Overstreet 	rw_unlock(true, new_nodes[0]);
1338a1f0358bSKent Overstreet 
1339a1f0358bSKent Overstreet 	closure_sync(&cl);
1340a1f0358bSKent Overstreet 
1341a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1342a1f0358bSKent Overstreet 		btree_node_free(r[i].b);
1343a1f0358bSKent Overstreet 		rw_unlock(true, r[i].b);
1344a1f0358bSKent Overstreet 
1345a1f0358bSKent Overstreet 		r[i].b = new_nodes[i];
1346a1f0358bSKent Overstreet 	}
1347a1f0358bSKent Overstreet 
1348a1f0358bSKent Overstreet 	bch_btree_insert_node(b, op, keylist, NULL, NULL);
1349a1f0358bSKent Overstreet 	BUG_ON(!bch_keylist_empty(keylist));
1350a1f0358bSKent Overstreet 
1351a1f0358bSKent Overstreet 	memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1352a1f0358bSKent Overstreet 	r[nodes - 1].b = ERR_PTR(-EINTR);
1353cafe5635SKent Overstreet 
1354c37511b8SKent Overstreet 	trace_bcache_btree_gc_coalesce(nodes);
1355cafe5635SKent Overstreet 	gc->nodes--;
1356cafe5635SKent Overstreet 
1357a1f0358bSKent Overstreet 	/* Invalidated our iterator */
1358a1f0358bSKent Overstreet 	return -EINTR;
1359a1f0358bSKent Overstreet 
1360a1f0358bSKent Overstreet out_nocoalesce:
1361a1f0358bSKent Overstreet 	closure_sync(&cl);
1362a1f0358bSKent Overstreet 
1363a1f0358bSKent Overstreet 	while ((k = bch_keylist_pop(keylist)))
1364a1f0358bSKent Overstreet 		if (!bkey_cmp(k, &ZERO_KEY))
1365a1f0358bSKent Overstreet 			atomic_dec(&b->c->prio_blocked);
1366a1f0358bSKent Overstreet 
1367a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++)
1368a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(new_nodes[i])) {
1369a1f0358bSKent Overstreet 			btree_node_free(new_nodes[i]);
1370a1f0358bSKent Overstreet 			rw_unlock(true, new_nodes[i]);
1371a1f0358bSKent Overstreet 		}
1372a1f0358bSKent Overstreet 	return 0;
1373a1f0358bSKent Overstreet }
1374a1f0358bSKent Overstreet 
1375a1f0358bSKent Overstreet static unsigned btree_gc_count_keys(struct btree *b)
1376a1f0358bSKent Overstreet {
1377a1f0358bSKent Overstreet 	struct bkey *k;
1378a1f0358bSKent Overstreet 	struct btree_iter iter;
1379a1f0358bSKent Overstreet 	unsigned ret = 0;
1380a1f0358bSKent Overstreet 
1381c052dd9aSKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_bad)
1382a1f0358bSKent Overstreet 		ret += bkey_u64s(k);
1383a1f0358bSKent Overstreet 
1384a1f0358bSKent Overstreet 	return ret;
1385cafe5635SKent Overstreet }
1386cafe5635SKent Overstreet 
1387cafe5635SKent Overstreet static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1388cafe5635SKent Overstreet 			    struct closure *writes, struct gc_stat *gc)
1389cafe5635SKent Overstreet {
1390cafe5635SKent Overstreet 	unsigned i;
1391a1f0358bSKent Overstreet 	int ret = 0;
1392a1f0358bSKent Overstreet 	bool should_rewrite;
1393a1f0358bSKent Overstreet 	struct btree *n;
1394a1f0358bSKent Overstreet 	struct bkey *k;
1395a1f0358bSKent Overstreet 	struct keylist keys;
1396a1f0358bSKent Overstreet 	struct btree_iter iter;
1397cafe5635SKent Overstreet 	struct gc_merge_info r[GC_MERGE_NODES];
1398a1f0358bSKent Overstreet 	struct gc_merge_info *last = r + GC_MERGE_NODES - 1;
1399cafe5635SKent Overstreet 
1400a1f0358bSKent Overstreet 	bch_keylist_init(&keys);
1401c052dd9aSKent Overstreet 	bch_btree_iter_init(&b->keys, &iter, &b->c->gc_done);
1402cafe5635SKent Overstreet 
1403a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1404a1f0358bSKent Overstreet 		r[i].b = ERR_PTR(-EINTR);
1405cafe5635SKent Overstreet 
1406a1f0358bSKent Overstreet 	while (1) {
1407a85e968eSKent Overstreet 		k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad);
1408a1f0358bSKent Overstreet 		if (k) {
1409a1f0358bSKent Overstreet 			r->b = bch_btree_node_get(b->c, k, b->level - 1, true);
1410cafe5635SKent Overstreet 			if (IS_ERR(r->b)) {
1411cafe5635SKent Overstreet 				ret = PTR_ERR(r->b);
1412cafe5635SKent Overstreet 				break;
1413cafe5635SKent Overstreet 			}
1414cafe5635SKent Overstreet 
1415a1f0358bSKent Overstreet 			r->keys = btree_gc_count_keys(r->b);
1416cafe5635SKent Overstreet 
1417a1f0358bSKent Overstreet 			ret = btree_gc_coalesce(b, op, &keys, gc, r);
1418a1f0358bSKent Overstreet 			if (ret)
1419cafe5635SKent Overstreet 				break;
1420cafe5635SKent Overstreet 		}
1421cafe5635SKent Overstreet 
1422a1f0358bSKent Overstreet 		if (!last->b)
1423a1f0358bSKent Overstreet 			break;
1424cafe5635SKent Overstreet 
1425a1f0358bSKent Overstreet 		if (!IS_ERR(last->b)) {
1426a1f0358bSKent Overstreet 			should_rewrite = btree_gc_mark_node(last->b, gc);
142778365411SKent Overstreet 			if (should_rewrite &&
142878365411SKent Overstreet 			    !btree_check_reserve(b, NULL)) {
1429bc9389eeSKent Overstreet 				n = btree_node_alloc_replacement(last->b,
1430bc9389eeSKent Overstreet 								 false);
1431cafe5635SKent Overstreet 
1432a1f0358bSKent Overstreet 				if (!IS_ERR_OR_NULL(n)) {
1433a1f0358bSKent Overstreet 					bch_btree_node_write_sync(n);
1434a1f0358bSKent Overstreet 					bch_keylist_add(&keys, &n->key);
1435cafe5635SKent Overstreet 
1436a1f0358bSKent Overstreet 					make_btree_freeing_key(last->b,
1437a1f0358bSKent Overstreet 							       keys.top);
1438a1f0358bSKent Overstreet 					bch_keylist_push(&keys);
1439cafe5635SKent Overstreet 
1440a1f0358bSKent Overstreet 					btree_node_free(last->b);
1441a1f0358bSKent Overstreet 
1442a1f0358bSKent Overstreet 					bch_btree_insert_node(b, op, &keys,
1443a1f0358bSKent Overstreet 							      NULL, NULL);
1444a1f0358bSKent Overstreet 					BUG_ON(!bch_keylist_empty(&keys));
1445a1f0358bSKent Overstreet 
1446a1f0358bSKent Overstreet 					rw_unlock(true, last->b);
1447a1f0358bSKent Overstreet 					last->b = n;
1448a1f0358bSKent Overstreet 
1449a1f0358bSKent Overstreet 					/* Invalidated our iterator */
1450a1f0358bSKent Overstreet 					ret = -EINTR;
1451a1f0358bSKent Overstreet 					break;
1452a1f0358bSKent Overstreet 				}
1453a1f0358bSKent Overstreet 			}
1454a1f0358bSKent Overstreet 
1455a1f0358bSKent Overstreet 			if (last->b->level) {
1456a1f0358bSKent Overstreet 				ret = btree_gc_recurse(last->b, op, writes, gc);
1457a1f0358bSKent Overstreet 				if (ret)
1458a1f0358bSKent Overstreet 					break;
1459a1f0358bSKent Overstreet 			}
1460a1f0358bSKent Overstreet 
1461a1f0358bSKent Overstreet 			bkey_copy_key(&b->c->gc_done, &last->b->key);
1462a1f0358bSKent Overstreet 
1463a1f0358bSKent Overstreet 			/*
1464a1f0358bSKent Overstreet 			 * Must flush leaf nodes before gc ends, since replace
1465a1f0358bSKent Overstreet 			 * operations aren't journalled
1466cafe5635SKent Overstreet 			 */
1467a1f0358bSKent Overstreet 			if (btree_node_dirty(last->b))
1468a1f0358bSKent Overstreet 				bch_btree_node_write(last->b, writes);
1469a1f0358bSKent Overstreet 			rw_unlock(true, last->b);
1470a1f0358bSKent Overstreet 		}
1471a1f0358bSKent Overstreet 
1472a1f0358bSKent Overstreet 		memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1473a1f0358bSKent Overstreet 		r->b = NULL;
1474a1f0358bSKent Overstreet 
1475cafe5635SKent Overstreet 		if (need_resched()) {
1476cafe5635SKent Overstreet 			ret = -EAGAIN;
1477cafe5635SKent Overstreet 			break;
1478cafe5635SKent Overstreet 		}
1479cafe5635SKent Overstreet 	}
1480cafe5635SKent Overstreet 
1481a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1482a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(r[i].b)) {
1483a1f0358bSKent Overstreet 			if (btree_node_dirty(r[i].b))
1484a1f0358bSKent Overstreet 				bch_btree_node_write(r[i].b, writes);
1485a1f0358bSKent Overstreet 			rw_unlock(true, r[i].b);
1486a1f0358bSKent Overstreet 		}
1487cafe5635SKent Overstreet 
1488a1f0358bSKent Overstreet 	bch_keylist_free(&keys);
1489cafe5635SKent Overstreet 
1490cafe5635SKent Overstreet 	return ret;
1491cafe5635SKent Overstreet }
1492cafe5635SKent Overstreet 
1493cafe5635SKent Overstreet static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1494cafe5635SKent Overstreet 			     struct closure *writes, struct gc_stat *gc)
1495cafe5635SKent Overstreet {
1496cafe5635SKent Overstreet 	struct btree *n = NULL;
1497a1f0358bSKent Overstreet 	int ret = 0;
1498a1f0358bSKent Overstreet 	bool should_rewrite;
1499cafe5635SKent Overstreet 
1500a1f0358bSKent Overstreet 	should_rewrite = btree_gc_mark_node(b, gc);
1501a1f0358bSKent Overstreet 	if (should_rewrite) {
1502bc9389eeSKent Overstreet 		n = btree_node_alloc_replacement(b, false);
1503cafe5635SKent Overstreet 
1504cafe5635SKent Overstreet 		if (!IS_ERR_OR_NULL(n)) {
1505a1f0358bSKent Overstreet 			bch_btree_node_write_sync(n);
1506a1f0358bSKent Overstreet 			bch_btree_set_root(n);
1507a1f0358bSKent Overstreet 			btree_node_free(b);
1508a1f0358bSKent Overstreet 			rw_unlock(true, n);
1509a1f0358bSKent Overstreet 
1510a1f0358bSKent Overstreet 			return -EINTR;
1511cafe5635SKent Overstreet 		}
1512a1f0358bSKent Overstreet 	}
1513a1f0358bSKent Overstreet 
1514a1f0358bSKent Overstreet 	if (b->level) {
1515a1f0358bSKent Overstreet 		ret = btree_gc_recurse(b, op, writes, gc);
1516a1f0358bSKent Overstreet 		if (ret)
1517a1f0358bSKent Overstreet 			return ret;
1518a1f0358bSKent Overstreet 	}
1519a1f0358bSKent Overstreet 
1520a1f0358bSKent Overstreet 	bkey_copy_key(&b->c->gc_done, &b->key);
1521cafe5635SKent Overstreet 
1522cafe5635SKent Overstreet 	return ret;
1523cafe5635SKent Overstreet }
1524cafe5635SKent Overstreet 
1525cafe5635SKent Overstreet static void btree_gc_start(struct cache_set *c)
1526cafe5635SKent Overstreet {
1527cafe5635SKent Overstreet 	struct cache *ca;
1528cafe5635SKent Overstreet 	struct bucket *b;
1529cafe5635SKent Overstreet 	unsigned i;
1530cafe5635SKent Overstreet 
1531cafe5635SKent Overstreet 	if (!c->gc_mark_valid)
1532cafe5635SKent Overstreet 		return;
1533cafe5635SKent Overstreet 
1534cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1535cafe5635SKent Overstreet 
1536cafe5635SKent Overstreet 	c->gc_mark_valid = 0;
1537cafe5635SKent Overstreet 	c->gc_done = ZERO_KEY;
1538cafe5635SKent Overstreet 
1539cafe5635SKent Overstreet 	for_each_cache(ca, c, i)
1540cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1541cafe5635SKent Overstreet 			b->gc_gen = b->gen;
154229ebf465SKent Overstreet 			if (!atomic_read(&b->pin)) {
1543cafe5635SKent Overstreet 				SET_GC_MARK(b, GC_MARK_RECLAIMABLE);
154429ebf465SKent Overstreet 				SET_GC_SECTORS_USED(b, 0);
154529ebf465SKent Overstreet 			}
1546cafe5635SKent Overstreet 		}
1547cafe5635SKent Overstreet 
1548cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1549cafe5635SKent Overstreet }
1550cafe5635SKent Overstreet 
1551cafe5635SKent Overstreet size_t bch_btree_gc_finish(struct cache_set *c)
1552cafe5635SKent Overstreet {
1553cafe5635SKent Overstreet 	size_t available = 0;
1554cafe5635SKent Overstreet 	struct bucket *b;
1555cafe5635SKent Overstreet 	struct cache *ca;
1556cafe5635SKent Overstreet 	unsigned i;
1557cafe5635SKent Overstreet 
1558cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1559cafe5635SKent Overstreet 
1560cafe5635SKent Overstreet 	set_gc_sectors(c);
1561cafe5635SKent Overstreet 	c->gc_mark_valid = 1;
1562cafe5635SKent Overstreet 	c->need_gc	= 0;
1563cafe5635SKent Overstreet 
1564cafe5635SKent Overstreet 	if (c->root)
1565cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(&c->root->key); i++)
1566cafe5635SKent Overstreet 			SET_GC_MARK(PTR_BUCKET(c, &c->root->key, i),
1567cafe5635SKent Overstreet 				    GC_MARK_METADATA);
1568cafe5635SKent Overstreet 
1569cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1570cafe5635SKent Overstreet 		SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1571cafe5635SKent Overstreet 			    GC_MARK_METADATA);
1572cafe5635SKent Overstreet 
1573bf0a628aSNicholas Swenson 	/* don't reclaim buckets to which writeback keys point */
1574bf0a628aSNicholas Swenson 	rcu_read_lock();
1575bf0a628aSNicholas Swenson 	for (i = 0; i < c->nr_uuids; i++) {
1576bf0a628aSNicholas Swenson 		struct bcache_device *d = c->devices[i];
1577bf0a628aSNicholas Swenson 		struct cached_dev *dc;
1578bf0a628aSNicholas Swenson 		struct keybuf_key *w, *n;
1579bf0a628aSNicholas Swenson 		unsigned j;
1580bf0a628aSNicholas Swenson 
1581bf0a628aSNicholas Swenson 		if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
1582bf0a628aSNicholas Swenson 			continue;
1583bf0a628aSNicholas Swenson 		dc = container_of(d, struct cached_dev, disk);
1584bf0a628aSNicholas Swenson 
1585bf0a628aSNicholas Swenson 		spin_lock(&dc->writeback_keys.lock);
1586bf0a628aSNicholas Swenson 		rbtree_postorder_for_each_entry_safe(w, n,
1587bf0a628aSNicholas Swenson 					&dc->writeback_keys.keys, node)
1588bf0a628aSNicholas Swenson 			for (j = 0; j < KEY_PTRS(&w->key); j++)
1589bf0a628aSNicholas Swenson 				SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
1590bf0a628aSNicholas Swenson 					    GC_MARK_DIRTY);
1591bf0a628aSNicholas Swenson 		spin_unlock(&dc->writeback_keys.lock);
1592bf0a628aSNicholas Swenson 	}
1593bf0a628aSNicholas Swenson 	rcu_read_unlock();
1594bf0a628aSNicholas Swenson 
1595cafe5635SKent Overstreet 	for_each_cache(ca, c, i) {
1596cafe5635SKent Overstreet 		uint64_t *i;
1597cafe5635SKent Overstreet 
1598cafe5635SKent Overstreet 		ca->invalidate_needs_gc = 0;
1599cafe5635SKent Overstreet 
1600cafe5635SKent Overstreet 		for (i = ca->sb.d; i < ca->sb.d + ca->sb.keys; i++)
1601cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1602cafe5635SKent Overstreet 
1603cafe5635SKent Overstreet 		for (i = ca->prio_buckets;
1604cafe5635SKent Overstreet 		     i < ca->prio_buckets + prio_buckets(ca) * 2; i++)
1605cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1606cafe5635SKent Overstreet 
1607cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1608cafe5635SKent Overstreet 			b->last_gc	= b->gc_gen;
1609cafe5635SKent Overstreet 			c->need_gc	= max(c->need_gc, bucket_gc_gen(b));
1610cafe5635SKent Overstreet 
1611cafe5635SKent Overstreet 			if (!atomic_read(&b->pin) &&
1612cafe5635SKent Overstreet 			    GC_MARK(b) == GC_MARK_RECLAIMABLE) {
1613cafe5635SKent Overstreet 				available++;
1614cafe5635SKent Overstreet 				if (!GC_SECTORS_USED(b))
1615cafe5635SKent Overstreet 					bch_bucket_add_unused(ca, b);
1616cafe5635SKent Overstreet 			}
1617cafe5635SKent Overstreet 		}
1618cafe5635SKent Overstreet 	}
1619cafe5635SKent Overstreet 
1620cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1621cafe5635SKent Overstreet 	return available;
1622cafe5635SKent Overstreet }
1623cafe5635SKent Overstreet 
162472a44517SKent Overstreet static void bch_btree_gc(struct cache_set *c)
1625cafe5635SKent Overstreet {
1626cafe5635SKent Overstreet 	int ret;
1627cafe5635SKent Overstreet 	unsigned long available;
1628cafe5635SKent Overstreet 	struct gc_stat stats;
1629cafe5635SKent Overstreet 	struct closure writes;
1630cafe5635SKent Overstreet 	struct btree_op op;
1631cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
163257943511SKent Overstreet 
1633c37511b8SKent Overstreet 	trace_bcache_gc_start(c);
1634cafe5635SKent Overstreet 
1635cafe5635SKent Overstreet 	memset(&stats, 0, sizeof(struct gc_stat));
1636cafe5635SKent Overstreet 	closure_init_stack(&writes);
1637b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1638cafe5635SKent Overstreet 
1639cafe5635SKent Overstreet 	btree_gc_start(c);
1640cafe5635SKent Overstreet 
1641a1f0358bSKent Overstreet 	do {
1642cafe5635SKent Overstreet 		ret = btree_root(gc_root, c, &op, &writes, &stats);
1643cafe5635SKent Overstreet 		closure_sync(&writes);
1644cafe5635SKent Overstreet 
1645a1f0358bSKent Overstreet 		if (ret && ret != -EAGAIN)
1646cafe5635SKent Overstreet 			pr_warn("gc failed!");
1647a1f0358bSKent Overstreet 	} while (ret);
1648cafe5635SKent Overstreet 
1649cafe5635SKent Overstreet 	available = bch_btree_gc_finish(c);
165057943511SKent Overstreet 	wake_up_allocators(c);
165157943511SKent Overstreet 
1652169ef1cfSKent Overstreet 	bch_time_stats_update(&c->btree_gc_time, start_time);
1653cafe5635SKent Overstreet 
1654cafe5635SKent Overstreet 	stats.key_bytes *= sizeof(uint64_t);
1655cafe5635SKent Overstreet 	stats.data	<<= 9;
1656cafe5635SKent Overstreet 	stats.in_use	= (c->nbuckets - available) * 100 / c->nbuckets;
1657cafe5635SKent Overstreet 	memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1658cafe5635SKent Overstreet 
1659c37511b8SKent Overstreet 	trace_bcache_gc_end(c);
1660cafe5635SKent Overstreet 
166172a44517SKent Overstreet 	bch_moving_gc(c);
1662cafe5635SKent Overstreet }
1663cafe5635SKent Overstreet 
166472a44517SKent Overstreet static int bch_gc_thread(void *arg)
1665cafe5635SKent Overstreet {
166672a44517SKent Overstreet 	struct cache_set *c = arg;
1667a1f0358bSKent Overstreet 	struct cache *ca;
1668a1f0358bSKent Overstreet 	unsigned i;
166972a44517SKent Overstreet 
167072a44517SKent Overstreet 	while (1) {
1671a1f0358bSKent Overstreet again:
167272a44517SKent Overstreet 		bch_btree_gc(c);
167372a44517SKent Overstreet 
167472a44517SKent Overstreet 		set_current_state(TASK_INTERRUPTIBLE);
167572a44517SKent Overstreet 		if (kthread_should_stop())
167672a44517SKent Overstreet 			break;
167772a44517SKent Overstreet 
1678a1f0358bSKent Overstreet 		mutex_lock(&c->bucket_lock);
1679a1f0358bSKent Overstreet 
1680a1f0358bSKent Overstreet 		for_each_cache(ca, c, i)
1681a1f0358bSKent Overstreet 			if (ca->invalidate_needs_gc) {
1682a1f0358bSKent Overstreet 				mutex_unlock(&c->bucket_lock);
1683a1f0358bSKent Overstreet 				set_current_state(TASK_RUNNING);
1684a1f0358bSKent Overstreet 				goto again;
1685a1f0358bSKent Overstreet 			}
1686a1f0358bSKent Overstreet 
1687a1f0358bSKent Overstreet 		mutex_unlock(&c->bucket_lock);
1688a1f0358bSKent Overstreet 
168972a44517SKent Overstreet 		try_to_freeze();
169072a44517SKent Overstreet 		schedule();
169172a44517SKent Overstreet 	}
169272a44517SKent Overstreet 
169372a44517SKent Overstreet 	return 0;
169472a44517SKent Overstreet }
169572a44517SKent Overstreet 
169672a44517SKent Overstreet int bch_gc_thread_start(struct cache_set *c)
169772a44517SKent Overstreet {
169872a44517SKent Overstreet 	c->gc_thread = kthread_create(bch_gc_thread, c, "bcache_gc");
169972a44517SKent Overstreet 	if (IS_ERR(c->gc_thread))
170072a44517SKent Overstreet 		return PTR_ERR(c->gc_thread);
170172a44517SKent Overstreet 
170272a44517SKent Overstreet 	set_task_state(c->gc_thread, TASK_INTERRUPTIBLE);
170372a44517SKent Overstreet 	return 0;
1704cafe5635SKent Overstreet }
1705cafe5635SKent Overstreet 
1706cafe5635SKent Overstreet /* Initial partial gc */
1707cafe5635SKent Overstreet 
1708cafe5635SKent Overstreet static int bch_btree_check_recurse(struct btree *b, struct btree_op *op,
1709cafe5635SKent Overstreet 				   unsigned long **seen)
1710cafe5635SKent Overstreet {
171150310164SKent Overstreet 	int ret = 0;
1712cafe5635SKent Overstreet 	unsigned i;
171350310164SKent Overstreet 	struct bkey *k, *p = NULL;
1714cafe5635SKent Overstreet 	struct bucket *g;
1715cafe5635SKent Overstreet 	struct btree_iter iter;
1716cafe5635SKent Overstreet 
1717c052dd9aSKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid) {
1718cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(k); i++) {
1719cafe5635SKent Overstreet 			if (!ptr_available(b->c, k, i))
1720cafe5635SKent Overstreet 				continue;
1721cafe5635SKent Overstreet 
1722cafe5635SKent Overstreet 			g = PTR_BUCKET(b->c, k, i);
1723cafe5635SKent Overstreet 
1724cafe5635SKent Overstreet 			if (!__test_and_set_bit(PTR_BUCKET_NR(b->c, k, i),
1725cafe5635SKent Overstreet 						seen[PTR_DEV(k, i)]) ||
1726cafe5635SKent Overstreet 			    !ptr_stale(b->c, k, i)) {
1727cafe5635SKent Overstreet 				g->gen = PTR_GEN(k, i);
1728cafe5635SKent Overstreet 
1729cafe5635SKent Overstreet 				if (b->level)
1730cafe5635SKent Overstreet 					g->prio = BTREE_PRIO;
1731cafe5635SKent Overstreet 				else if (g->prio == BTREE_PRIO)
1732cafe5635SKent Overstreet 					g->prio = INITIAL_PRIO;
1733cafe5635SKent Overstreet 			}
1734cafe5635SKent Overstreet 		}
1735cafe5635SKent Overstreet 
1736cafe5635SKent Overstreet 		btree_mark_key(b, k);
1737cafe5635SKent Overstreet 	}
1738cafe5635SKent Overstreet 
1739cafe5635SKent Overstreet 	if (b->level) {
1740c052dd9aSKent Overstreet 		bch_btree_iter_init(&b->keys, &iter, NULL);
1741cafe5635SKent Overstreet 
174250310164SKent Overstreet 		do {
1743a85e968eSKent Overstreet 			k = bch_btree_iter_next_filter(&iter, &b->keys,
1744a85e968eSKent Overstreet 						       bch_ptr_bad);
174550310164SKent Overstreet 			if (k)
174650310164SKent Overstreet 				btree_node_prefetch(b->c, k, b->level - 1);
174750310164SKent Overstreet 
1748cafe5635SKent Overstreet 			if (p)
174950310164SKent Overstreet 				ret = btree(check_recurse, p, b, op, seen);
1750cafe5635SKent Overstreet 
175150310164SKent Overstreet 			p = k;
175250310164SKent Overstreet 		} while (p && !ret);
1753cafe5635SKent Overstreet 	}
1754cafe5635SKent Overstreet 
1755cafe5635SKent Overstreet 	return 0;
1756cafe5635SKent Overstreet }
1757cafe5635SKent Overstreet 
1758c18536a7SKent Overstreet int bch_btree_check(struct cache_set *c)
1759cafe5635SKent Overstreet {
1760cafe5635SKent Overstreet 	int ret = -ENOMEM;
1761cafe5635SKent Overstreet 	unsigned i;
1762cafe5635SKent Overstreet 	unsigned long *seen[MAX_CACHES_PER_SET];
1763c18536a7SKent Overstreet 	struct btree_op op;
1764cafe5635SKent Overstreet 
1765cafe5635SKent Overstreet 	memset(seen, 0, sizeof(seen));
1766b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1767cafe5635SKent Overstreet 
1768cafe5635SKent Overstreet 	for (i = 0; c->cache[i]; i++) {
1769cafe5635SKent Overstreet 		size_t n = DIV_ROUND_UP(c->cache[i]->sb.nbuckets, 8);
1770cafe5635SKent Overstreet 		seen[i] = kmalloc(n, GFP_KERNEL);
1771cafe5635SKent Overstreet 		if (!seen[i])
1772cafe5635SKent Overstreet 			goto err;
1773cafe5635SKent Overstreet 
1774cafe5635SKent Overstreet 		/* Disables the seen array until prio_read() uses it too */
1775cafe5635SKent Overstreet 		memset(seen[i], 0xFF, n);
1776cafe5635SKent Overstreet 	}
1777cafe5635SKent Overstreet 
1778c18536a7SKent Overstreet 	ret = btree_root(check_recurse, c, &op, seen);
1779cafe5635SKent Overstreet err:
1780cafe5635SKent Overstreet 	for (i = 0; i < MAX_CACHES_PER_SET; i++)
1781cafe5635SKent Overstreet 		kfree(seen[i]);
1782cafe5635SKent Overstreet 	return ret;
1783cafe5635SKent Overstreet }
1784cafe5635SKent Overstreet 
1785cafe5635SKent Overstreet /* Btree insertion */
1786cafe5635SKent Overstreet 
1787829a60b9SKent Overstreet static bool btree_insert_key(struct btree *b, struct bkey *k,
17881b207d80SKent Overstreet 			     struct bkey *replace_key)
1789cafe5635SKent Overstreet {
1790829a60b9SKent Overstreet 	unsigned status;
1791cafe5635SKent Overstreet 
1792cafe5635SKent Overstreet 	BUG_ON(bkey_cmp(k, &b->key) > 0);
1793cafe5635SKent Overstreet 
1794829a60b9SKent Overstreet 	status = bch_btree_insert_key(&b->keys, k, replace_key);
1795829a60b9SKent Overstreet 	if (status != BTREE_INSERT_STATUS_NO_INSERT) {
1796dc9d98d6SKent Overstreet 		bch_check_keys(&b->keys, "%u for %s", status,
17971b207d80SKent Overstreet 			       replace_key ? "replace" : "insert");
1798cafe5635SKent Overstreet 
1799829a60b9SKent Overstreet 		trace_bcache_btree_insert_key(b, k, replace_key != NULL,
1800829a60b9SKent Overstreet 					      status);
1801cafe5635SKent Overstreet 		return true;
1802829a60b9SKent Overstreet 	} else
1803829a60b9SKent Overstreet 		return false;
1804cafe5635SKent Overstreet }
1805cafe5635SKent Overstreet 
180659158fdeSKent Overstreet static size_t insert_u64s_remaining(struct btree *b)
180759158fdeSKent Overstreet {
1808*3572324aSKent Overstreet 	long ret = bch_btree_keys_u64s_remaining(&b->keys);
180959158fdeSKent Overstreet 
181059158fdeSKent Overstreet 	/*
181159158fdeSKent Overstreet 	 * Might land in the middle of an existing extent and have to split it
181259158fdeSKent Overstreet 	 */
181359158fdeSKent Overstreet 	if (b->keys.ops->is_extents)
181459158fdeSKent Overstreet 		ret -= KEY_MAX_U64S;
181559158fdeSKent Overstreet 
181659158fdeSKent Overstreet 	return max(ret, 0L);
181759158fdeSKent Overstreet }
181859158fdeSKent Overstreet 
181926c949f8SKent Overstreet static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
18201b207d80SKent Overstreet 				  struct keylist *insert_keys,
18211b207d80SKent Overstreet 				  struct bkey *replace_key)
1822cafe5635SKent Overstreet {
1823cafe5635SKent Overstreet 	bool ret = false;
1824dc9d98d6SKent Overstreet 	int oldsize = bch_count_data(&b->keys);
1825cafe5635SKent Overstreet 
182626c949f8SKent Overstreet 	while (!bch_keylist_empty(insert_keys)) {
1827c2f95ae2SKent Overstreet 		struct bkey *k = insert_keys->keys;
182826c949f8SKent Overstreet 
182959158fdeSKent Overstreet 		if (bkey_u64s(k) > insert_u64s_remaining(b))
1830403b6cdeSKent Overstreet 			break;
1831403b6cdeSKent Overstreet 
1832403b6cdeSKent Overstreet 		if (bkey_cmp(k, &b->key) <= 0) {
18333a3b6a4eSKent Overstreet 			if (!b->level)
18343a3b6a4eSKent Overstreet 				bkey_put(b->c, k);
183526c949f8SKent Overstreet 
1836829a60b9SKent Overstreet 			ret |= btree_insert_key(b, k, replace_key);
183726c949f8SKent Overstreet 			bch_keylist_pop_front(insert_keys);
183826c949f8SKent Overstreet 		} else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
183926c949f8SKent Overstreet 			BKEY_PADDED(key) temp;
1840c2f95ae2SKent Overstreet 			bkey_copy(&temp.key, insert_keys->keys);
184126c949f8SKent Overstreet 
184226c949f8SKent Overstreet 			bch_cut_back(&b->key, &temp.key);
1843c2f95ae2SKent Overstreet 			bch_cut_front(&b->key, insert_keys->keys);
184426c949f8SKent Overstreet 
1845829a60b9SKent Overstreet 			ret |= btree_insert_key(b, &temp.key, replace_key);
184626c949f8SKent Overstreet 			break;
184726c949f8SKent Overstreet 		} else {
184826c949f8SKent Overstreet 			break;
184926c949f8SKent Overstreet 		}
1850cafe5635SKent Overstreet 	}
1851cafe5635SKent Overstreet 
1852829a60b9SKent Overstreet 	if (!ret)
1853829a60b9SKent Overstreet 		op->insert_collision = true;
1854829a60b9SKent Overstreet 
1855403b6cdeSKent Overstreet 	BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
1856403b6cdeSKent Overstreet 
1857dc9d98d6SKent Overstreet 	BUG_ON(bch_count_data(&b->keys) < oldsize);
1858cafe5635SKent Overstreet 	return ret;
1859cafe5635SKent Overstreet }
1860cafe5635SKent Overstreet 
186126c949f8SKent Overstreet static int btree_split(struct btree *b, struct btree_op *op,
186226c949f8SKent Overstreet 		       struct keylist *insert_keys,
18631b207d80SKent Overstreet 		       struct bkey *replace_key)
1864cafe5635SKent Overstreet {
1865d6fd3b11SKent Overstreet 	bool split;
1866cafe5635SKent Overstreet 	struct btree *n1, *n2 = NULL, *n3 = NULL;
1867cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
1868b54d6934SKent Overstreet 	struct closure cl;
186917e21a9fSKent Overstreet 	struct keylist parent_keys;
1870b54d6934SKent Overstreet 
1871b54d6934SKent Overstreet 	closure_init_stack(&cl);
187217e21a9fSKent Overstreet 	bch_keylist_init(&parent_keys);
1873cafe5635SKent Overstreet 
187478365411SKent Overstreet 	if (!b->level &&
187578365411SKent Overstreet 	    btree_check_reserve(b, op))
187678365411SKent Overstreet 		return -EINTR;
187778365411SKent Overstreet 
1878bc9389eeSKent Overstreet 	n1 = btree_node_alloc_replacement(b, true);
1879cafe5635SKent Overstreet 	if (IS_ERR(n1))
1880cafe5635SKent Overstreet 		goto err;
1881cafe5635SKent Overstreet 
1882ee811287SKent Overstreet 	split = set_blocks(btree_bset_first(n1),
1883ee811287SKent Overstreet 			   block_bytes(n1->c)) > (btree_blocks(b) * 4) / 5;
1884cafe5635SKent Overstreet 
1885cafe5635SKent Overstreet 	if (split) {
1886cafe5635SKent Overstreet 		unsigned keys = 0;
1887cafe5635SKent Overstreet 
1888ee811287SKent Overstreet 		trace_bcache_btree_node_split(b, btree_bset_first(n1)->keys);
1889c37511b8SKent Overstreet 
1890bc9389eeSKent Overstreet 		n2 = bch_btree_node_alloc(b->c, b->level, true);
1891cafe5635SKent Overstreet 		if (IS_ERR(n2))
1892cafe5635SKent Overstreet 			goto err_free1;
1893cafe5635SKent Overstreet 
1894d6fd3b11SKent Overstreet 		if (!b->parent) {
1895bc9389eeSKent Overstreet 			n3 = bch_btree_node_alloc(b->c, b->level + 1, true);
1896cafe5635SKent Overstreet 			if (IS_ERR(n3))
1897cafe5635SKent Overstreet 				goto err_free2;
1898cafe5635SKent Overstreet 		}
1899cafe5635SKent Overstreet 
19001b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
1901cafe5635SKent Overstreet 
1902d6fd3b11SKent Overstreet 		/*
1903d6fd3b11SKent Overstreet 		 * Has to be a linear search because we don't have an auxiliary
1904cafe5635SKent Overstreet 		 * search tree yet
1905cafe5635SKent Overstreet 		 */
1906cafe5635SKent Overstreet 
1907ee811287SKent Overstreet 		while (keys < (btree_bset_first(n1)->keys * 3) / 5)
1908ee811287SKent Overstreet 			keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1),
1909fafff81cSKent Overstreet 							keys));
1910cafe5635SKent Overstreet 
1911fafff81cSKent Overstreet 		bkey_copy_key(&n1->key,
1912ee811287SKent Overstreet 			      bset_bkey_idx(btree_bset_first(n1), keys));
1913ee811287SKent Overstreet 		keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1), keys));
1914cafe5635SKent Overstreet 
1915ee811287SKent Overstreet 		btree_bset_first(n2)->keys = btree_bset_first(n1)->keys - keys;
1916ee811287SKent Overstreet 		btree_bset_first(n1)->keys = keys;
1917cafe5635SKent Overstreet 
1918ee811287SKent Overstreet 		memcpy(btree_bset_first(n2)->start,
1919ee811287SKent Overstreet 		       bset_bkey_last(btree_bset_first(n1)),
1920ee811287SKent Overstreet 		       btree_bset_first(n2)->keys * sizeof(uint64_t));
1921cafe5635SKent Overstreet 
1922cafe5635SKent Overstreet 		bkey_copy_key(&n2->key, &b->key);
1923cafe5635SKent Overstreet 
192417e21a9fSKent Overstreet 		bch_keylist_add(&parent_keys, &n2->key);
1925b54d6934SKent Overstreet 		bch_btree_node_write(n2, &cl);
1926cafe5635SKent Overstreet 		rw_unlock(true, n2);
1927c37511b8SKent Overstreet 	} else {
1928ee811287SKent Overstreet 		trace_bcache_btree_node_compact(b, btree_bset_first(n1)->keys);
1929c37511b8SKent Overstreet 
19301b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
1931c37511b8SKent Overstreet 	}
1932cafe5635SKent Overstreet 
193317e21a9fSKent Overstreet 	bch_keylist_add(&parent_keys, &n1->key);
1934b54d6934SKent Overstreet 	bch_btree_node_write(n1, &cl);
1935cafe5635SKent Overstreet 
1936cafe5635SKent Overstreet 	if (n3) {
1937d6fd3b11SKent Overstreet 		/* Depth increases, make a new root */
1938cafe5635SKent Overstreet 		bkey_copy_key(&n3->key, &MAX_KEY);
193917e21a9fSKent Overstreet 		bch_btree_insert_keys(n3, op, &parent_keys, NULL);
1940b54d6934SKent Overstreet 		bch_btree_node_write(n3, &cl);
1941cafe5635SKent Overstreet 
1942b54d6934SKent Overstreet 		closure_sync(&cl);
1943cafe5635SKent Overstreet 		bch_btree_set_root(n3);
1944cafe5635SKent Overstreet 		rw_unlock(true, n3);
194517e21a9fSKent Overstreet 
194617e21a9fSKent Overstreet 		btree_node_free(b);
1947d6fd3b11SKent Overstreet 	} else if (!b->parent) {
1948d6fd3b11SKent Overstreet 		/* Root filled up but didn't need to be split */
1949b54d6934SKent Overstreet 		closure_sync(&cl);
1950cafe5635SKent Overstreet 		bch_btree_set_root(n1);
195117e21a9fSKent Overstreet 
195217e21a9fSKent Overstreet 		btree_node_free(b);
1953cafe5635SKent Overstreet 	} else {
195417e21a9fSKent Overstreet 		/* Split a non root node */
1955b54d6934SKent Overstreet 		closure_sync(&cl);
195617e21a9fSKent Overstreet 		make_btree_freeing_key(b, parent_keys.top);
195717e21a9fSKent Overstreet 		bch_keylist_push(&parent_keys);
195817e21a9fSKent Overstreet 
195917e21a9fSKent Overstreet 		btree_node_free(b);
196017e21a9fSKent Overstreet 
196117e21a9fSKent Overstreet 		bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
196217e21a9fSKent Overstreet 		BUG_ON(!bch_keylist_empty(&parent_keys));
1963cafe5635SKent Overstreet 	}
1964cafe5635SKent Overstreet 
1965cafe5635SKent Overstreet 	rw_unlock(true, n1);
1966cafe5635SKent Overstreet 
1967169ef1cfSKent Overstreet 	bch_time_stats_update(&b->c->btree_split_time, start_time);
1968cafe5635SKent Overstreet 
1969cafe5635SKent Overstreet 	return 0;
1970cafe5635SKent Overstreet err_free2:
19715f5837d2SKent Overstreet 	bkey_put(b->c, &n2->key);
1972e8e1d468SKent Overstreet 	btree_node_free(n2);
1973cafe5635SKent Overstreet 	rw_unlock(true, n2);
1974cafe5635SKent Overstreet err_free1:
19755f5837d2SKent Overstreet 	bkey_put(b->c, &n1->key);
1976e8e1d468SKent Overstreet 	btree_node_free(n1);
1977cafe5635SKent Overstreet 	rw_unlock(true, n1);
1978cafe5635SKent Overstreet err:
19795f5837d2SKent Overstreet 	WARN(1, "bcache: btree split failed");
19805f5837d2SKent Overstreet 
1981cafe5635SKent Overstreet 	if (n3 == ERR_PTR(-EAGAIN) ||
1982cafe5635SKent Overstreet 	    n2 == ERR_PTR(-EAGAIN) ||
1983cafe5635SKent Overstreet 	    n1 == ERR_PTR(-EAGAIN))
1984cafe5635SKent Overstreet 		return -EAGAIN;
1985cafe5635SKent Overstreet 
1986cafe5635SKent Overstreet 	return -ENOMEM;
1987cafe5635SKent Overstreet }
1988cafe5635SKent Overstreet 
198926c949f8SKent Overstreet static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
1990c18536a7SKent Overstreet 				 struct keylist *insert_keys,
19911b207d80SKent Overstreet 				 atomic_t *journal_ref,
19921b207d80SKent Overstreet 				 struct bkey *replace_key)
199326c949f8SKent Overstreet {
19941b207d80SKent Overstreet 	BUG_ON(b->level && replace_key);
19951b207d80SKent Overstreet 
199659158fdeSKent Overstreet 	if (bch_keylist_nkeys(insert_keys) > insert_u64s_remaining(b)) {
199726c949f8SKent Overstreet 		if (current->bio_list) {
199826c949f8SKent Overstreet 			op->lock = b->c->root->level + 1;
199917e21a9fSKent Overstreet 			return -EAGAIN;
200026c949f8SKent Overstreet 		} else if (op->lock <= b->c->root->level) {
200126c949f8SKent Overstreet 			op->lock = b->c->root->level + 1;
200217e21a9fSKent Overstreet 			return -EINTR;
200326c949f8SKent Overstreet 		} else {
200417e21a9fSKent Overstreet 			/* Invalidated all iterators */
20053b3e9e50SKent Overstreet 			int ret = btree_split(b, op, insert_keys, replace_key);
20063b3e9e50SKent Overstreet 
20073b3e9e50SKent Overstreet 			return bch_keylist_empty(insert_keys) ?
20083b3e9e50SKent Overstreet 				0 : ret ?: -EINTR;
200926c949f8SKent Overstreet 		}
201026c949f8SKent Overstreet 	} else {
2011ee811287SKent Overstreet 		BUG_ON(write_block(b) != btree_bset_last(b));
201226c949f8SKent Overstreet 
201317e21a9fSKent Overstreet 		if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
2014f269af5aSKent Overstreet 			if (!b->level)
2015c18536a7SKent Overstreet 				bch_btree_leaf_dirty(b, journal_ref);
2016f269af5aSKent Overstreet 			else
2017f269af5aSKent Overstreet 				bch_btree_node_write_sync(b);
201826c949f8SKent Overstreet 		}
201926c949f8SKent Overstreet 
202017e21a9fSKent Overstreet 		return 0;
202117e21a9fSKent Overstreet 	}
202226c949f8SKent Overstreet }
202326c949f8SKent Overstreet 
2024e7c590ebSKent Overstreet int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2025e7c590ebSKent Overstreet 			       struct bkey *check_key)
2026e7c590ebSKent Overstreet {
2027e7c590ebSKent Overstreet 	int ret = -EINTR;
2028e7c590ebSKent Overstreet 	uint64_t btree_ptr = b->key.ptr[0];
2029e7c590ebSKent Overstreet 	unsigned long seq = b->seq;
2030e7c590ebSKent Overstreet 	struct keylist insert;
2031e7c590ebSKent Overstreet 	bool upgrade = op->lock == -1;
2032e7c590ebSKent Overstreet 
2033e7c590ebSKent Overstreet 	bch_keylist_init(&insert);
2034e7c590ebSKent Overstreet 
2035e7c590ebSKent Overstreet 	if (upgrade) {
2036e7c590ebSKent Overstreet 		rw_unlock(false, b);
2037e7c590ebSKent Overstreet 		rw_lock(true, b, b->level);
2038e7c590ebSKent Overstreet 
2039e7c590ebSKent Overstreet 		if (b->key.ptr[0] != btree_ptr ||
2040e7c590ebSKent Overstreet 		    b->seq != seq + 1)
2041e7c590ebSKent Overstreet 			goto out;
2042e7c590ebSKent Overstreet 	}
2043e7c590ebSKent Overstreet 
2044e7c590ebSKent Overstreet 	SET_KEY_PTRS(check_key, 1);
2045e7c590ebSKent Overstreet 	get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2046e7c590ebSKent Overstreet 
2047e7c590ebSKent Overstreet 	SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2048e7c590ebSKent Overstreet 
2049e7c590ebSKent Overstreet 	bch_keylist_add(&insert, check_key);
2050e7c590ebSKent Overstreet 
20511b207d80SKent Overstreet 	ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2052e7c590ebSKent Overstreet 
2053e7c590ebSKent Overstreet 	BUG_ON(!ret && !bch_keylist_empty(&insert));
2054e7c590ebSKent Overstreet out:
2055e7c590ebSKent Overstreet 	if (upgrade)
2056e7c590ebSKent Overstreet 		downgrade_write(&b->lock);
2057e7c590ebSKent Overstreet 	return ret;
2058e7c590ebSKent Overstreet }
2059e7c590ebSKent Overstreet 
2060cc7b8819SKent Overstreet struct btree_insert_op {
2061cc7b8819SKent Overstreet 	struct btree_op	op;
2062cc7b8819SKent Overstreet 	struct keylist	*keys;
2063cc7b8819SKent Overstreet 	atomic_t	*journal_ref;
2064cc7b8819SKent Overstreet 	struct bkey	*replace_key;
2065cc7b8819SKent Overstreet };
2066cc7b8819SKent Overstreet 
206708239ca2SWei Yongjun static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2068cafe5635SKent Overstreet {
2069cc7b8819SKent Overstreet 	struct btree_insert_op *op = container_of(b_op,
2070cc7b8819SKent Overstreet 					struct btree_insert_op, op);
2071403b6cdeSKent Overstreet 
2072cc7b8819SKent Overstreet 	int ret = bch_btree_insert_node(b, &op->op, op->keys,
2073cc7b8819SKent Overstreet 					op->journal_ref, op->replace_key);
2074cc7b8819SKent Overstreet 	if (ret && !bch_keylist_empty(op->keys))
2075cc7b8819SKent Overstreet 		return ret;
2076cc7b8819SKent Overstreet 	else
2077cc7b8819SKent Overstreet 		return MAP_DONE;
2078cafe5635SKent Overstreet }
2079cafe5635SKent Overstreet 
2080cc7b8819SKent Overstreet int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2081cc7b8819SKent Overstreet 		     atomic_t *journal_ref, struct bkey *replace_key)
2082cafe5635SKent Overstreet {
2083cc7b8819SKent Overstreet 	struct btree_insert_op op;
2084cafe5635SKent Overstreet 	int ret = 0;
2085cafe5635SKent Overstreet 
2086cc7b8819SKent Overstreet 	BUG_ON(current->bio_list);
20874f3d4014SKent Overstreet 	BUG_ON(bch_keylist_empty(keys));
2088cafe5635SKent Overstreet 
2089cc7b8819SKent Overstreet 	bch_btree_op_init(&op.op, 0);
2090cc7b8819SKent Overstreet 	op.keys		= keys;
2091cc7b8819SKent Overstreet 	op.journal_ref	= journal_ref;
2092cc7b8819SKent Overstreet 	op.replace_key	= replace_key;
2093cafe5635SKent Overstreet 
2094cc7b8819SKent Overstreet 	while (!ret && !bch_keylist_empty(keys)) {
2095cc7b8819SKent Overstreet 		op.op.lock = 0;
2096cc7b8819SKent Overstreet 		ret = bch_btree_map_leaf_nodes(&op.op, c,
2097cc7b8819SKent Overstreet 					       &START_KEY(keys->keys),
2098cc7b8819SKent Overstreet 					       btree_insert_fn);
2099cc7b8819SKent Overstreet 	}
2100cc7b8819SKent Overstreet 
2101cc7b8819SKent Overstreet 	if (ret) {
2102cafe5635SKent Overstreet 		struct bkey *k;
2103cafe5635SKent Overstreet 
21041b207d80SKent Overstreet 		pr_err("error %i", ret);
2105cafe5635SKent Overstreet 
21064f3d4014SKent Overstreet 		while ((k = bch_keylist_pop(keys)))
21073a3b6a4eSKent Overstreet 			bkey_put(c, k);
2108cc7b8819SKent Overstreet 	} else if (op.op.insert_collision)
2109cc7b8819SKent Overstreet 		ret = -ESRCH;
21106054c6d4SKent Overstreet 
2111cafe5635SKent Overstreet 	return ret;
2112cafe5635SKent Overstreet }
2113cafe5635SKent Overstreet 
2114cafe5635SKent Overstreet void bch_btree_set_root(struct btree *b)
2115cafe5635SKent Overstreet {
2116cafe5635SKent Overstreet 	unsigned i;
2117e49c7c37SKent Overstreet 	struct closure cl;
2118e49c7c37SKent Overstreet 
2119e49c7c37SKent Overstreet 	closure_init_stack(&cl);
2120cafe5635SKent Overstreet 
2121c37511b8SKent Overstreet 	trace_bcache_btree_set_root(b);
2122c37511b8SKent Overstreet 
2123cafe5635SKent Overstreet 	BUG_ON(!b->written);
2124cafe5635SKent Overstreet 
2125cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++)
2126cafe5635SKent Overstreet 		BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2127cafe5635SKent Overstreet 
2128cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
2129cafe5635SKent Overstreet 	list_del_init(&b->list);
2130cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
2131cafe5635SKent Overstreet 
2132cafe5635SKent Overstreet 	b->c->root = b;
2133cafe5635SKent Overstreet 
2134e49c7c37SKent Overstreet 	bch_journal_meta(b->c, &cl);
2135e49c7c37SKent Overstreet 	closure_sync(&cl);
2136cafe5635SKent Overstreet }
2137cafe5635SKent Overstreet 
213848dad8baSKent Overstreet /* Map across nodes or keys */
213948dad8baSKent Overstreet 
214048dad8baSKent Overstreet static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
214148dad8baSKent Overstreet 				       struct bkey *from,
214248dad8baSKent Overstreet 				       btree_map_nodes_fn *fn, int flags)
214348dad8baSKent Overstreet {
214448dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
214548dad8baSKent Overstreet 
214648dad8baSKent Overstreet 	if (b->level) {
214748dad8baSKent Overstreet 		struct bkey *k;
214848dad8baSKent Overstreet 		struct btree_iter iter;
214948dad8baSKent Overstreet 
2150c052dd9aSKent Overstreet 		bch_btree_iter_init(&b->keys, &iter, from);
215148dad8baSKent Overstreet 
2152a85e968eSKent Overstreet 		while ((k = bch_btree_iter_next_filter(&iter, &b->keys,
215348dad8baSKent Overstreet 						       bch_ptr_bad))) {
215448dad8baSKent Overstreet 			ret = btree(map_nodes_recurse, k, b,
215548dad8baSKent Overstreet 				    op, from, fn, flags);
215648dad8baSKent Overstreet 			from = NULL;
215748dad8baSKent Overstreet 
215848dad8baSKent Overstreet 			if (ret != MAP_CONTINUE)
215948dad8baSKent Overstreet 				return ret;
216048dad8baSKent Overstreet 		}
216148dad8baSKent Overstreet 	}
216248dad8baSKent Overstreet 
216348dad8baSKent Overstreet 	if (!b->level || flags == MAP_ALL_NODES)
216448dad8baSKent Overstreet 		ret = fn(op, b);
216548dad8baSKent Overstreet 
216648dad8baSKent Overstreet 	return ret;
216748dad8baSKent Overstreet }
216848dad8baSKent Overstreet 
216948dad8baSKent Overstreet int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
217048dad8baSKent Overstreet 			  struct bkey *from, btree_map_nodes_fn *fn, int flags)
217148dad8baSKent Overstreet {
2172b54d6934SKent Overstreet 	return btree_root(map_nodes_recurse, c, op, from, fn, flags);
217348dad8baSKent Overstreet }
217448dad8baSKent Overstreet 
217548dad8baSKent Overstreet static int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
217648dad8baSKent Overstreet 				      struct bkey *from, btree_map_keys_fn *fn,
217748dad8baSKent Overstreet 				      int flags)
217848dad8baSKent Overstreet {
217948dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
218048dad8baSKent Overstreet 	struct bkey *k;
218148dad8baSKent Overstreet 	struct btree_iter iter;
218248dad8baSKent Overstreet 
2183c052dd9aSKent Overstreet 	bch_btree_iter_init(&b->keys, &iter, from);
218448dad8baSKent Overstreet 
2185a85e968eSKent Overstreet 	while ((k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad))) {
218648dad8baSKent Overstreet 		ret = !b->level
218748dad8baSKent Overstreet 			? fn(op, b, k)
218848dad8baSKent Overstreet 			: btree(map_keys_recurse, k, b, op, from, fn, flags);
218948dad8baSKent Overstreet 		from = NULL;
219048dad8baSKent Overstreet 
219148dad8baSKent Overstreet 		if (ret != MAP_CONTINUE)
219248dad8baSKent Overstreet 			return ret;
219348dad8baSKent Overstreet 	}
219448dad8baSKent Overstreet 
219548dad8baSKent Overstreet 	if (!b->level && (flags & MAP_END_KEY))
219648dad8baSKent Overstreet 		ret = fn(op, b, &KEY(KEY_INODE(&b->key),
219748dad8baSKent Overstreet 				     KEY_OFFSET(&b->key), 0));
219848dad8baSKent Overstreet 
219948dad8baSKent Overstreet 	return ret;
220048dad8baSKent Overstreet }
220148dad8baSKent Overstreet 
220248dad8baSKent Overstreet int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
220348dad8baSKent Overstreet 		       struct bkey *from, btree_map_keys_fn *fn, int flags)
220448dad8baSKent Overstreet {
2205b54d6934SKent Overstreet 	return btree_root(map_keys_recurse, c, op, from, fn, flags);
220648dad8baSKent Overstreet }
220748dad8baSKent Overstreet 
2208cafe5635SKent Overstreet /* Keybuf code */
2209cafe5635SKent Overstreet 
2210cafe5635SKent Overstreet static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2211cafe5635SKent Overstreet {
2212cafe5635SKent Overstreet 	/* Overlapping keys compare equal */
2213cafe5635SKent Overstreet 	if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2214cafe5635SKent Overstreet 		return -1;
2215cafe5635SKent Overstreet 	if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2216cafe5635SKent Overstreet 		return 1;
2217cafe5635SKent Overstreet 	return 0;
2218cafe5635SKent Overstreet }
2219cafe5635SKent Overstreet 
2220cafe5635SKent Overstreet static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2221cafe5635SKent Overstreet 					    struct keybuf_key *r)
2222cafe5635SKent Overstreet {
2223cafe5635SKent Overstreet 	return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2224cafe5635SKent Overstreet }
2225cafe5635SKent Overstreet 
222648dad8baSKent Overstreet struct refill {
222748dad8baSKent Overstreet 	struct btree_op	op;
222848a915a8SKent Overstreet 	unsigned	nr_found;
222948dad8baSKent Overstreet 	struct keybuf	*buf;
223048dad8baSKent Overstreet 	struct bkey	*end;
223148dad8baSKent Overstreet 	keybuf_pred_fn	*pred;
223248dad8baSKent Overstreet };
223348dad8baSKent Overstreet 
223448dad8baSKent Overstreet static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
223548dad8baSKent Overstreet 			    struct bkey *k)
2236cafe5635SKent Overstreet {
223748dad8baSKent Overstreet 	struct refill *refill = container_of(op, struct refill, op);
223848dad8baSKent Overstreet 	struct keybuf *buf = refill->buf;
223948dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
2240cafe5635SKent Overstreet 
224148dad8baSKent Overstreet 	if (bkey_cmp(k, refill->end) >= 0) {
224248dad8baSKent Overstreet 		ret = MAP_DONE;
224348dad8baSKent Overstreet 		goto out;
2244cafe5635SKent Overstreet 	}
2245cafe5635SKent Overstreet 
224648dad8baSKent Overstreet 	if (!KEY_SIZE(k)) /* end key */
224748dad8baSKent Overstreet 		goto out;
2248cafe5635SKent Overstreet 
224948dad8baSKent Overstreet 	if (refill->pred(buf, k)) {
2250cafe5635SKent Overstreet 		struct keybuf_key *w;
2251cafe5635SKent Overstreet 
2252cafe5635SKent Overstreet 		spin_lock(&buf->lock);
2253cafe5635SKent Overstreet 
2254cafe5635SKent Overstreet 		w = array_alloc(&buf->freelist);
225548dad8baSKent Overstreet 		if (!w) {
225648dad8baSKent Overstreet 			spin_unlock(&buf->lock);
225748dad8baSKent Overstreet 			return MAP_DONE;
225848dad8baSKent Overstreet 		}
2259cafe5635SKent Overstreet 
2260cafe5635SKent Overstreet 		w->private = NULL;
2261cafe5635SKent Overstreet 		bkey_copy(&w->key, k);
2262cafe5635SKent Overstreet 
2263cafe5635SKent Overstreet 		if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2264cafe5635SKent Overstreet 			array_free(&buf->freelist, w);
226548a915a8SKent Overstreet 		else
226648a915a8SKent Overstreet 			refill->nr_found++;
2267cafe5635SKent Overstreet 
226848dad8baSKent Overstreet 		if (array_freelist_empty(&buf->freelist))
226948dad8baSKent Overstreet 			ret = MAP_DONE;
227048dad8baSKent Overstreet 
2271cafe5635SKent Overstreet 		spin_unlock(&buf->lock);
2272cafe5635SKent Overstreet 	}
227348dad8baSKent Overstreet out:
227448dad8baSKent Overstreet 	buf->last_scanned = *k;
227548dad8baSKent Overstreet 	return ret;
2276cafe5635SKent Overstreet }
2277cafe5635SKent Overstreet 
2278cafe5635SKent Overstreet void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
227972c27061SKent Overstreet 		       struct bkey *end, keybuf_pred_fn *pred)
2280cafe5635SKent Overstreet {
2281cafe5635SKent Overstreet 	struct bkey start = buf->last_scanned;
228248dad8baSKent Overstreet 	struct refill refill;
2283cafe5635SKent Overstreet 
2284cafe5635SKent Overstreet 	cond_resched();
2285cafe5635SKent Overstreet 
2286b54d6934SKent Overstreet 	bch_btree_op_init(&refill.op, -1);
228748a915a8SKent Overstreet 	refill.nr_found	= 0;
228848dad8baSKent Overstreet 	refill.buf	= buf;
228948dad8baSKent Overstreet 	refill.end	= end;
229048dad8baSKent Overstreet 	refill.pred	= pred;
229148dad8baSKent Overstreet 
229248dad8baSKent Overstreet 	bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
229348dad8baSKent Overstreet 			   refill_keybuf_fn, MAP_END_KEY);
2294cafe5635SKent Overstreet 
229548a915a8SKent Overstreet 	trace_bcache_keyscan(refill.nr_found,
2296cafe5635SKent Overstreet 			     KEY_INODE(&start), KEY_OFFSET(&start),
229748a915a8SKent Overstreet 			     KEY_INODE(&buf->last_scanned),
229848a915a8SKent Overstreet 			     KEY_OFFSET(&buf->last_scanned));
2299cafe5635SKent Overstreet 
2300cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2301cafe5635SKent Overstreet 
2302cafe5635SKent Overstreet 	if (!RB_EMPTY_ROOT(&buf->keys)) {
2303cafe5635SKent Overstreet 		struct keybuf_key *w;
2304cafe5635SKent Overstreet 		w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2305cafe5635SKent Overstreet 		buf->start	= START_KEY(&w->key);
2306cafe5635SKent Overstreet 
2307cafe5635SKent Overstreet 		w = RB_LAST(&buf->keys, struct keybuf_key, node);
2308cafe5635SKent Overstreet 		buf->end	= w->key;
2309cafe5635SKent Overstreet 	} else {
2310cafe5635SKent Overstreet 		buf->start	= MAX_KEY;
2311cafe5635SKent Overstreet 		buf->end	= MAX_KEY;
2312cafe5635SKent Overstreet 	}
2313cafe5635SKent Overstreet 
2314cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2315cafe5635SKent Overstreet }
2316cafe5635SKent Overstreet 
2317cafe5635SKent Overstreet static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2318cafe5635SKent Overstreet {
2319cafe5635SKent Overstreet 	rb_erase(&w->node, &buf->keys);
2320cafe5635SKent Overstreet 	array_free(&buf->freelist, w);
2321cafe5635SKent Overstreet }
2322cafe5635SKent Overstreet 
2323cafe5635SKent Overstreet void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2324cafe5635SKent Overstreet {
2325cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2326cafe5635SKent Overstreet 	__bch_keybuf_del(buf, w);
2327cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2328cafe5635SKent Overstreet }
2329cafe5635SKent Overstreet 
2330cafe5635SKent Overstreet bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2331cafe5635SKent Overstreet 				  struct bkey *end)
2332cafe5635SKent Overstreet {
2333cafe5635SKent Overstreet 	bool ret = false;
2334cafe5635SKent Overstreet 	struct keybuf_key *p, *w, s;
2335cafe5635SKent Overstreet 	s.key = *start;
2336cafe5635SKent Overstreet 
2337cafe5635SKent Overstreet 	if (bkey_cmp(end, &buf->start) <= 0 ||
2338cafe5635SKent Overstreet 	    bkey_cmp(start, &buf->end) >= 0)
2339cafe5635SKent Overstreet 		return false;
2340cafe5635SKent Overstreet 
2341cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2342cafe5635SKent Overstreet 	w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2343cafe5635SKent Overstreet 
2344cafe5635SKent Overstreet 	while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2345cafe5635SKent Overstreet 		p = w;
2346cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2347cafe5635SKent Overstreet 
2348cafe5635SKent Overstreet 		if (p->private)
2349cafe5635SKent Overstreet 			ret = true;
2350cafe5635SKent Overstreet 		else
2351cafe5635SKent Overstreet 			__bch_keybuf_del(buf, p);
2352cafe5635SKent Overstreet 	}
2353cafe5635SKent Overstreet 
2354cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2355cafe5635SKent Overstreet 	return ret;
2356cafe5635SKent Overstreet }
2357cafe5635SKent Overstreet 
2358cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2359cafe5635SKent Overstreet {
2360cafe5635SKent Overstreet 	struct keybuf_key *w;
2361cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2362cafe5635SKent Overstreet 
2363cafe5635SKent Overstreet 	w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2364cafe5635SKent Overstreet 
2365cafe5635SKent Overstreet 	while (w && w->private)
2366cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2367cafe5635SKent Overstreet 
2368cafe5635SKent Overstreet 	if (w)
2369cafe5635SKent Overstreet 		w->private = ERR_PTR(-EINTR);
2370cafe5635SKent Overstreet 
2371cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2372cafe5635SKent Overstreet 	return w;
2373cafe5635SKent Overstreet }
2374cafe5635SKent Overstreet 
2375cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2376cafe5635SKent Overstreet 					  struct keybuf *buf,
237772c27061SKent Overstreet 					  struct bkey *end,
237872c27061SKent Overstreet 					  keybuf_pred_fn *pred)
2379cafe5635SKent Overstreet {
2380cafe5635SKent Overstreet 	struct keybuf_key *ret;
2381cafe5635SKent Overstreet 
2382cafe5635SKent Overstreet 	while (1) {
2383cafe5635SKent Overstreet 		ret = bch_keybuf_next(buf);
2384cafe5635SKent Overstreet 		if (ret)
2385cafe5635SKent Overstreet 			break;
2386cafe5635SKent Overstreet 
2387cafe5635SKent Overstreet 		if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2388cafe5635SKent Overstreet 			pr_debug("scan finished");
2389cafe5635SKent Overstreet 			break;
2390cafe5635SKent Overstreet 		}
2391cafe5635SKent Overstreet 
239272c27061SKent Overstreet 		bch_refill_keybuf(c, buf, end, pred);
2393cafe5635SKent Overstreet 	}
2394cafe5635SKent Overstreet 
2395cafe5635SKent Overstreet 	return ret;
2396cafe5635SKent Overstreet }
2397cafe5635SKent Overstreet 
239872c27061SKent Overstreet void bch_keybuf_init(struct keybuf *buf)
2399cafe5635SKent Overstreet {
2400cafe5635SKent Overstreet 	buf->last_scanned	= MAX_KEY;
2401cafe5635SKent Overstreet 	buf->keys		= RB_ROOT;
2402cafe5635SKent Overstreet 
2403cafe5635SKent Overstreet 	spin_lock_init(&buf->lock);
2404cafe5635SKent Overstreet 	array_allocator_init(&buf->freelist);
2405cafe5635SKent Overstreet }
2406cafe5635SKent Overstreet 
2407cafe5635SKent Overstreet void bch_btree_exit(void)
2408cafe5635SKent Overstreet {
2409cafe5635SKent Overstreet 	if (btree_io_wq)
2410cafe5635SKent Overstreet 		destroy_workqueue(btree_io_wq);
2411cafe5635SKent Overstreet }
2412cafe5635SKent Overstreet 
2413cafe5635SKent Overstreet int __init bch_btree_init(void)
2414cafe5635SKent Overstreet {
241572a44517SKent Overstreet 	btree_io_wq = create_singlethread_workqueue("bch_btree_io");
241672a44517SKent Overstreet 	if (!btree_io_wq)
2417cafe5635SKent Overstreet 		return -ENOMEM;
2418cafe5635SKent Overstreet 
2419cafe5635SKent Overstreet 	return 0;
2420cafe5635SKent Overstreet }
2421