xref: /linux/drivers/md/bcache/btree.c (revision 2831231d4c3f999d2d062b23dfbc8b0faa4bc6e0)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2cafe5635SKent Overstreet /*
3cafe5635SKent Overstreet  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
4cafe5635SKent Overstreet  *
5cafe5635SKent Overstreet  * Uses a block device as cache for other block devices; optimized for SSDs.
6cafe5635SKent Overstreet  * All allocation is done in buckets, which should match the erase block size
7cafe5635SKent Overstreet  * of the device.
8cafe5635SKent Overstreet  *
9cafe5635SKent Overstreet  * Buckets containing cached data are kept on a heap sorted by priority;
10cafe5635SKent Overstreet  * bucket priority is increased on cache hit, and periodically all the buckets
11cafe5635SKent Overstreet  * on the heap have their priority scaled down. This currently is just used as
12cafe5635SKent Overstreet  * an LRU but in the future should allow for more intelligent heuristics.
13cafe5635SKent Overstreet  *
14cafe5635SKent Overstreet  * Buckets have an 8 bit counter; freeing is accomplished by incrementing the
15cafe5635SKent Overstreet  * counter. Garbage collection is used to remove stale pointers.
16cafe5635SKent Overstreet  *
17cafe5635SKent Overstreet  * Indexing is done via a btree; nodes are not necessarily fully sorted, rather
18cafe5635SKent Overstreet  * as keys are inserted we only sort the pages that have not yet been written.
19cafe5635SKent Overstreet  * When garbage collection is run, we resort the entire node.
20cafe5635SKent Overstreet  *
21cafe5635SKent Overstreet  * All configuration is done via sysfs; see Documentation/bcache.txt.
22cafe5635SKent Overstreet  */
23cafe5635SKent Overstreet 
24cafe5635SKent Overstreet #include "bcache.h"
25cafe5635SKent Overstreet #include "btree.h"
26cafe5635SKent Overstreet #include "debug.h"
2765d45231SKent Overstreet #include "extents.h"
28cafe5635SKent Overstreet 
29cafe5635SKent Overstreet #include <linux/slab.h>
30cafe5635SKent Overstreet #include <linux/bitops.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>
36e6017571SIngo Molnar #include <linux/sched/clock.h>
37b2d09103SIngo Molnar #include <linux/rculist.h>
38b2d09103SIngo Molnar 
39cafe5635SKent Overstreet #include <trace/events/bcache.h>
40cafe5635SKent Overstreet 
41cafe5635SKent Overstreet /*
42cafe5635SKent Overstreet  * Todo:
43cafe5635SKent Overstreet  * register_bcache: Return errors out to userspace correctly
44cafe5635SKent Overstreet  *
45cafe5635SKent Overstreet  * Writeback: don't undirty key until after a cache flush
46cafe5635SKent Overstreet  *
47cafe5635SKent Overstreet  * Create an iterator for key pointers
48cafe5635SKent Overstreet  *
49cafe5635SKent Overstreet  * On btree write error, mark bucket such that it won't be freed from the cache
50cafe5635SKent Overstreet  *
51cafe5635SKent Overstreet  * Journalling:
52cafe5635SKent Overstreet  *   Check for bad keys in replay
53cafe5635SKent Overstreet  *   Propagate barriers
54cafe5635SKent Overstreet  *   Refcount journal entries in journal_replay
55cafe5635SKent Overstreet  *
56cafe5635SKent Overstreet  * Garbage collection:
57cafe5635SKent Overstreet  *   Finish incremental gc
58cafe5635SKent Overstreet  *   Gc should free old UUIDs, data for invalid UUIDs
59cafe5635SKent Overstreet  *
60cafe5635SKent Overstreet  * Provide a way to list backing device UUIDs we have data cached for, and
61cafe5635SKent Overstreet  * probably how long it's been since we've seen them, and a way to invalidate
62cafe5635SKent Overstreet  * dirty data for devices that will never be attached again
63cafe5635SKent Overstreet  *
64cafe5635SKent Overstreet  * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
65cafe5635SKent Overstreet  * that based on that and how much dirty data we have we can keep writeback
66cafe5635SKent Overstreet  * from being starved
67cafe5635SKent Overstreet  *
68cafe5635SKent Overstreet  * Add a tracepoint or somesuch to watch for writeback starvation
69cafe5635SKent Overstreet  *
70cafe5635SKent Overstreet  * When btree depth > 1 and splitting an interior node, we have to make sure
71cafe5635SKent Overstreet  * alloc_bucket() cannot fail. This should be true but is not completely
72cafe5635SKent Overstreet  * obvious.
73cafe5635SKent Overstreet  *
74cafe5635SKent Overstreet  * Plugging?
75cafe5635SKent Overstreet  *
76cafe5635SKent Overstreet  * If data write is less than hard sector size of ssd, round up offset in open
77cafe5635SKent Overstreet  * bucket to the next whole sector
78cafe5635SKent Overstreet  *
79cafe5635SKent Overstreet  * Superblock needs to be fleshed out for multiple cache devices
80cafe5635SKent Overstreet  *
81cafe5635SKent Overstreet  * Add a sysfs tunable for the number of writeback IOs in flight
82cafe5635SKent Overstreet  *
83cafe5635SKent Overstreet  * Add a sysfs tunable for the number of open data buckets
84cafe5635SKent Overstreet  *
85cafe5635SKent Overstreet  * IO tracking: Can we track when one process is doing io on behalf of another?
86cafe5635SKent Overstreet  * IO tracking: Don't use just an average, weigh more recent stuff higher
87cafe5635SKent Overstreet  *
88cafe5635SKent Overstreet  * Test module load/unload
89cafe5635SKent Overstreet  */
90cafe5635SKent Overstreet 
91cafe5635SKent Overstreet #define MAX_NEED_GC		64
92cafe5635SKent Overstreet #define MAX_SAVE_PRIO		72
93cafe5635SKent Overstreet 
94cafe5635SKent Overstreet #define PTR_DIRTY_BIT		(((uint64_t) 1 << 36))
95cafe5635SKent Overstreet 
96cafe5635SKent Overstreet #define PTR_HASH(c, k)							\
97cafe5635SKent Overstreet 	(((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
98cafe5635SKent Overstreet 
99df8e8970SKent Overstreet #define insert_lock(s, b)	((b)->level <= (s)->lock)
100df8e8970SKent Overstreet 
101df8e8970SKent Overstreet /*
102df8e8970SKent Overstreet  * These macros are for recursing down the btree - they handle the details of
103df8e8970SKent Overstreet  * locking and looking up nodes in the cache for you. They're best treated as
104df8e8970SKent Overstreet  * mere syntax when reading code that uses them.
105df8e8970SKent Overstreet  *
106df8e8970SKent Overstreet  * op->lock determines whether we take a read or a write lock at a given depth.
107df8e8970SKent Overstreet  * If you've got a read lock and find that you need a write lock (i.e. you're
108df8e8970SKent Overstreet  * going to have to split), set op->lock and return -EINTR; btree_root() will
109df8e8970SKent Overstreet  * call you again and you'll have the correct lock.
110df8e8970SKent Overstreet  */
111df8e8970SKent Overstreet 
112df8e8970SKent Overstreet /**
113df8e8970SKent Overstreet  * btree - recurse down the btree on a specified key
114df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
115df8e8970SKent Overstreet  * @key:	key to recurse on
116df8e8970SKent Overstreet  * @b:		parent btree node
117df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
118df8e8970SKent Overstreet  */
119df8e8970SKent Overstreet #define btree(fn, key, b, op, ...)					\
120df8e8970SKent Overstreet ({									\
121df8e8970SKent Overstreet 	int _r, l = (b)->level - 1;					\
122df8e8970SKent Overstreet 	bool _w = l <= (op)->lock;					\
1232452cc89SSlava Pestov 	struct btree *_child = bch_btree_node_get((b)->c, op, key, l,	\
1242452cc89SSlava Pestov 						  _w, b);		\
125df8e8970SKent Overstreet 	if (!IS_ERR(_child)) {						\
126df8e8970SKent Overstreet 		_r = bch_btree_ ## fn(_child, op, ##__VA_ARGS__);	\
127df8e8970SKent Overstreet 		rw_unlock(_w, _child);					\
128df8e8970SKent Overstreet 	} else								\
129df8e8970SKent Overstreet 		_r = PTR_ERR(_child);					\
130df8e8970SKent Overstreet 	_r;								\
131df8e8970SKent Overstreet })
132df8e8970SKent Overstreet 
133df8e8970SKent Overstreet /**
134df8e8970SKent Overstreet  * btree_root - call a function on the root of the btree
135df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
136df8e8970SKent Overstreet  * @c:		cache set
137df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
138df8e8970SKent Overstreet  */
139df8e8970SKent Overstreet #define btree_root(fn, c, op, ...)					\
140df8e8970SKent Overstreet ({									\
141df8e8970SKent Overstreet 	int _r = -EINTR;						\
142df8e8970SKent Overstreet 	do {								\
143df8e8970SKent Overstreet 		struct btree *_b = (c)->root;				\
144df8e8970SKent Overstreet 		bool _w = insert_lock(op, _b);				\
145df8e8970SKent Overstreet 		rw_lock(_w, _b, _b->level);				\
146df8e8970SKent Overstreet 		if (_b == (c)->root &&					\
147df8e8970SKent Overstreet 		    _w == insert_lock(op, _b)) {			\
148df8e8970SKent Overstreet 			_r = bch_btree_ ## fn(_b, op, ##__VA_ARGS__);	\
149df8e8970SKent Overstreet 		}							\
150df8e8970SKent Overstreet 		rw_unlock(_w, _b);					\
1510a63b66dSKent Overstreet 		bch_cannibalize_unlock(c);				\
15278365411SKent Overstreet 		if (_r == -EINTR)					\
15378365411SKent Overstreet 			schedule();					\
154df8e8970SKent Overstreet 	} while (_r == -EINTR);						\
155df8e8970SKent Overstreet 									\
1560a63b66dSKent Overstreet 	finish_wait(&(c)->btree_cache_wait, &(op)->wait);		\
157df8e8970SKent Overstreet 	_r;								\
158df8e8970SKent Overstreet })
159df8e8970SKent Overstreet 
160a85e968eSKent Overstreet static inline struct bset *write_block(struct btree *b)
161a85e968eSKent Overstreet {
162a85e968eSKent Overstreet 	return ((void *) btree_bset_first(b)) + b->written * block_bytes(b->c);
163a85e968eSKent Overstreet }
164a85e968eSKent Overstreet 
1652a285686SKent Overstreet static void bch_btree_init_next(struct btree *b)
1662a285686SKent Overstreet {
1672a285686SKent Overstreet 	/* If not a leaf node, always sort */
1682a285686SKent Overstreet 	if (b->level && b->keys.nsets)
1692a285686SKent Overstreet 		bch_btree_sort(&b->keys, &b->c->sort);
1702a285686SKent Overstreet 	else
1712a285686SKent Overstreet 		bch_btree_sort_lazy(&b->keys, &b->c->sort);
1722a285686SKent Overstreet 
1732a285686SKent Overstreet 	if (b->written < btree_blocks(b))
1742a285686SKent Overstreet 		bch_bset_init_next(&b->keys, write_block(b),
1752a285686SKent Overstreet 				   bset_magic(&b->c->sb));
1762a285686SKent Overstreet 
1772a285686SKent Overstreet }
1782a285686SKent Overstreet 
179cafe5635SKent Overstreet /* Btree key manipulation */
180cafe5635SKent Overstreet 
1813a3b6a4eSKent Overstreet void bkey_put(struct cache_set *c, struct bkey *k)
182e7c590ebSKent Overstreet {
183e7c590ebSKent Overstreet 	unsigned i;
184e7c590ebSKent Overstreet 
185e7c590ebSKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
186e7c590ebSKent Overstreet 		if (ptr_available(c, k, i))
187e7c590ebSKent Overstreet 			atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
188e7c590ebSKent Overstreet }
189e7c590ebSKent Overstreet 
190cafe5635SKent Overstreet /* Btree IO */
191cafe5635SKent Overstreet 
192cafe5635SKent Overstreet static uint64_t btree_csum_set(struct btree *b, struct bset *i)
193cafe5635SKent Overstreet {
194cafe5635SKent Overstreet 	uint64_t crc = b->key.ptr[0];
195fafff81cSKent Overstreet 	void *data = (void *) i + 8, *end = bset_bkey_last(i);
196cafe5635SKent Overstreet 
197169ef1cfSKent Overstreet 	crc = bch_crc64_update(crc, data, end - data);
198c19ed23aSKent Overstreet 	return crc ^ 0xffffffffffffffffULL;
199cafe5635SKent Overstreet }
200cafe5635SKent Overstreet 
20178b77bf8SKent Overstreet void bch_btree_node_read_done(struct btree *b)
202cafe5635SKent Overstreet {
203cafe5635SKent Overstreet 	const char *err = "bad btree header";
204ee811287SKent Overstreet 	struct bset *i = btree_bset_first(b);
20557943511SKent Overstreet 	struct btree_iter *iter;
206cafe5635SKent Overstreet 
207bcf090e0SKent Overstreet 	iter = mempool_alloc(b->c->fill_iter, GFP_NOIO);
20857943511SKent Overstreet 	iter->size = b->c->sb.bucket_size / b->c->sb.block_size;
209cafe5635SKent Overstreet 	iter->used = 0;
210cafe5635SKent Overstreet 
211280481d0SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
212c052dd9aSKent Overstreet 	iter->b = &b->keys;
213280481d0SKent Overstreet #endif
214280481d0SKent Overstreet 
21557943511SKent Overstreet 	if (!i->seq)
216cafe5635SKent Overstreet 		goto err;
217cafe5635SKent Overstreet 
218cafe5635SKent Overstreet 	for (;
219a85e968eSKent Overstreet 	     b->written < btree_blocks(b) && i->seq == b->keys.set[0].data->seq;
220cafe5635SKent Overstreet 	     i = write_block(b)) {
221cafe5635SKent Overstreet 		err = "unsupported bset version";
222cafe5635SKent Overstreet 		if (i->version > BCACHE_BSET_VERSION)
223cafe5635SKent Overstreet 			goto err;
224cafe5635SKent Overstreet 
225cafe5635SKent Overstreet 		err = "bad btree header";
226ee811287SKent Overstreet 		if (b->written + set_blocks(i, block_bytes(b->c)) >
227ee811287SKent Overstreet 		    btree_blocks(b))
228cafe5635SKent Overstreet 			goto err;
229cafe5635SKent Overstreet 
230cafe5635SKent Overstreet 		err = "bad magic";
23181ab4190SKent Overstreet 		if (i->magic != bset_magic(&b->c->sb))
232cafe5635SKent Overstreet 			goto err;
233cafe5635SKent Overstreet 
234cafe5635SKent Overstreet 		err = "bad checksum";
235cafe5635SKent Overstreet 		switch (i->version) {
236cafe5635SKent Overstreet 		case 0:
237cafe5635SKent Overstreet 			if (i->csum != csum_set(i))
238cafe5635SKent Overstreet 				goto err;
239cafe5635SKent Overstreet 			break;
240cafe5635SKent Overstreet 		case BCACHE_BSET_VERSION:
241cafe5635SKent Overstreet 			if (i->csum != btree_csum_set(b, i))
242cafe5635SKent Overstreet 				goto err;
243cafe5635SKent Overstreet 			break;
244cafe5635SKent Overstreet 		}
245cafe5635SKent Overstreet 
246cafe5635SKent Overstreet 		err = "empty set";
247a85e968eSKent Overstreet 		if (i != b->keys.set[0].data && !i->keys)
248cafe5635SKent Overstreet 			goto err;
249cafe5635SKent Overstreet 
250fafff81cSKent Overstreet 		bch_btree_iter_push(iter, i->start, bset_bkey_last(i));
251cafe5635SKent Overstreet 
252ee811287SKent Overstreet 		b->written += set_blocks(i, block_bytes(b->c));
253cafe5635SKent Overstreet 	}
254cafe5635SKent Overstreet 
255cafe5635SKent Overstreet 	err = "corrupted btree";
256cafe5635SKent Overstreet 	for (i = write_block(b);
257a85e968eSKent Overstreet 	     bset_sector_offset(&b->keys, i) < KEY_SIZE(&b->key);
258cafe5635SKent Overstreet 	     i = ((void *) i) + block_bytes(b->c))
259a85e968eSKent Overstreet 		if (i->seq == b->keys.set[0].data->seq)
260cafe5635SKent Overstreet 			goto err;
261cafe5635SKent Overstreet 
262a85e968eSKent Overstreet 	bch_btree_sort_and_fix_extents(&b->keys, iter, &b->c->sort);
263cafe5635SKent Overstreet 
264a85e968eSKent Overstreet 	i = b->keys.set[0].data;
265cafe5635SKent Overstreet 	err = "short btree key";
266a85e968eSKent Overstreet 	if (b->keys.set[0].size &&
267a85e968eSKent Overstreet 	    bkey_cmp(&b->key, &b->keys.set[0].end) < 0)
268cafe5635SKent Overstreet 		goto err;
269cafe5635SKent Overstreet 
270cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
271a85e968eSKent Overstreet 		bch_bset_init_next(&b->keys, write_block(b),
272a85e968eSKent Overstreet 				   bset_magic(&b->c->sb));
273cafe5635SKent Overstreet out:
27457943511SKent Overstreet 	mempool_free(iter, b->c->fill_iter);
27557943511SKent Overstreet 	return;
276cafe5635SKent Overstreet err:
277cafe5635SKent Overstreet 	set_btree_node_io_error(b);
27888b9f8c4SKent Overstreet 	bch_cache_set_error(b->c, "%s at bucket %zu, block %u, %u keys",
279cafe5635SKent Overstreet 			    err, PTR_BUCKET_NR(b->c, &b->key, 0),
28088b9f8c4SKent Overstreet 			    bset_block_offset(b, i), i->keys);
281cafe5635SKent Overstreet 	goto out;
282cafe5635SKent Overstreet }
283cafe5635SKent Overstreet 
2844246a0b6SChristoph Hellwig static void btree_node_read_endio(struct bio *bio)
285cafe5635SKent Overstreet {
28657943511SKent Overstreet 	struct closure *cl = bio->bi_private;
28757943511SKent Overstreet 	closure_put(cl);
28857943511SKent Overstreet }
289cafe5635SKent Overstreet 
29078b77bf8SKent Overstreet static void bch_btree_node_read(struct btree *b)
29157943511SKent Overstreet {
29257943511SKent Overstreet 	uint64_t start_time = local_clock();
29357943511SKent Overstreet 	struct closure cl;
29457943511SKent Overstreet 	struct bio *bio;
295cafe5635SKent Overstreet 
296c37511b8SKent Overstreet 	trace_bcache_btree_read(b);
297c37511b8SKent Overstreet 
29857943511SKent Overstreet 	closure_init_stack(&cl);
299cafe5635SKent Overstreet 
30057943511SKent Overstreet 	bio = bch_bbio_alloc(b->c);
3014f024f37SKent Overstreet 	bio->bi_iter.bi_size = KEY_SIZE(&b->key) << 9;
30257943511SKent Overstreet 	bio->bi_end_io	= btree_node_read_endio;
30357943511SKent Overstreet 	bio->bi_private	= &cl;
30470fd7614SChristoph Hellwig 	bio->bi_opf = REQ_OP_READ | REQ_META;
30557943511SKent Overstreet 
306a85e968eSKent Overstreet 	bch_bio_map(bio, b->keys.set[0].data);
30757943511SKent Overstreet 
30857943511SKent Overstreet 	bch_submit_bbio(bio, b->c, &b->key, 0);
30957943511SKent Overstreet 	closure_sync(&cl);
31057943511SKent Overstreet 
3114e4cbee9SChristoph Hellwig 	if (bio->bi_status)
31257943511SKent Overstreet 		set_btree_node_io_error(b);
31357943511SKent Overstreet 
31457943511SKent Overstreet 	bch_bbio_free(bio, b->c);
31557943511SKent Overstreet 
31657943511SKent Overstreet 	if (btree_node_io_error(b))
31757943511SKent Overstreet 		goto err;
31857943511SKent Overstreet 
31957943511SKent Overstreet 	bch_btree_node_read_done(b);
32057943511SKent Overstreet 	bch_time_stats_update(&b->c->btree_read_time, start_time);
32157943511SKent Overstreet 
32257943511SKent Overstreet 	return;
32357943511SKent Overstreet err:
32461cbd250SGeert Uytterhoeven 	bch_cache_set_error(b->c, "io error reading bucket %zu",
32557943511SKent Overstreet 			    PTR_BUCKET_NR(b->c, &b->key, 0));
326cafe5635SKent Overstreet }
327cafe5635SKent Overstreet 
328cafe5635SKent Overstreet static void btree_complete_write(struct btree *b, struct btree_write *w)
329cafe5635SKent Overstreet {
330cafe5635SKent Overstreet 	if (w->prio_blocked &&
331cafe5635SKent Overstreet 	    !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
332119ba0f8SKent Overstreet 		wake_up_allocators(b->c);
333cafe5635SKent Overstreet 
334cafe5635SKent Overstreet 	if (w->journal) {
335cafe5635SKent Overstreet 		atomic_dec_bug(w->journal);
336cafe5635SKent Overstreet 		__closure_wake_up(&b->c->journal.wait);
337cafe5635SKent Overstreet 	}
338cafe5635SKent Overstreet 
339cafe5635SKent Overstreet 	w->prio_blocked	= 0;
340cafe5635SKent Overstreet 	w->journal	= NULL;
341cafe5635SKent Overstreet }
342cafe5635SKent Overstreet 
343cb7a583eSKent Overstreet static void btree_node_write_unlock(struct closure *cl)
344cb7a583eSKent Overstreet {
345cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
346cb7a583eSKent Overstreet 
347cb7a583eSKent Overstreet 	up(&b->io_mutex);
348cb7a583eSKent Overstreet }
349cb7a583eSKent Overstreet 
35057943511SKent Overstreet static void __btree_node_write_done(struct closure *cl)
351cafe5635SKent Overstreet {
352cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
353cafe5635SKent Overstreet 	struct btree_write *w = btree_prev_write(b);
354cafe5635SKent Overstreet 
355cafe5635SKent Overstreet 	bch_bbio_free(b->bio, b->c);
356cafe5635SKent Overstreet 	b->bio = NULL;
357cafe5635SKent Overstreet 	btree_complete_write(b, w);
358cafe5635SKent Overstreet 
359cafe5635SKent Overstreet 	if (btree_node_dirty(b))
36056b30770SKent Overstreet 		schedule_delayed_work(&b->work, 30 * HZ);
361cafe5635SKent Overstreet 
362cb7a583eSKent Overstreet 	closure_return_with_destructor(cl, btree_node_write_unlock);
363cafe5635SKent Overstreet }
364cafe5635SKent Overstreet 
36557943511SKent Overstreet static void btree_node_write_done(struct closure *cl)
366cafe5635SKent Overstreet {
367cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
368cafe5635SKent Overstreet 
369491221f8SGuoqing Jiang 	bio_free_pages(b->bio);
37057943511SKent Overstreet 	__btree_node_write_done(cl);
371cafe5635SKent Overstreet }
372cafe5635SKent Overstreet 
3734246a0b6SChristoph Hellwig static void btree_node_write_endio(struct bio *bio)
37457943511SKent Overstreet {
37557943511SKent Overstreet 	struct closure *cl = bio->bi_private;
376cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
37757943511SKent Overstreet 
3784e4cbee9SChristoph Hellwig 	if (bio->bi_status)
37957943511SKent Overstreet 		set_btree_node_io_error(b);
38057943511SKent Overstreet 
3814e4cbee9SChristoph Hellwig 	bch_bbio_count_io_errors(b->c, bio, bio->bi_status, "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;
399ee811287SKent Overstreet 	b->bio->bi_iter.bi_size	= roundup(set_bytes(i), block_bytes(b->c));
40070fd7614SChristoph Hellwig 	b->bio->bi_opf		= REQ_OP_WRITE | REQ_META | REQ_FUA;
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 
42225d8be77SMing Lei 	if (!bch_bio_alloc_pages(b->bio, __GFP_NOWARN|GFP_NOWAIT)) {
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 {
435c2421edfSMing Lei 		/* No problem for multipage bvec since the bio is just allocated */
436cafe5635SKent Overstreet 		b->bio->bi_vcnt = 0;
437169ef1cfSKent Overstreet 		bch_bio_map(b->bio, i);
438cafe5635SKent Overstreet 
439cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
440cafe5635SKent Overstreet 
441cafe5635SKent Overstreet 		closure_sync(cl);
442cb7a583eSKent Overstreet 		continue_at_nobarrier(cl, __btree_node_write_done, NULL);
443cafe5635SKent Overstreet 	}
444cafe5635SKent Overstreet }
445cafe5635SKent Overstreet 
4462a285686SKent Overstreet void __bch_btree_node_write(struct btree *b, struct closure *parent)
447cafe5635SKent Overstreet {
448ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
449cafe5635SKent Overstreet 
4502a285686SKent Overstreet 	lockdep_assert_held(&b->write_lock);
4512a285686SKent Overstreet 
452c37511b8SKent Overstreet 	trace_bcache_btree_write(b);
453c37511b8SKent Overstreet 
454cafe5635SKent Overstreet 	BUG_ON(current->bio_list);
45557943511SKent Overstreet 	BUG_ON(b->written >= btree_blocks(b));
45657943511SKent Overstreet 	BUG_ON(b->written && !i->keys);
457ee811287SKent Overstreet 	BUG_ON(btree_bset_first(b)->seq != i->seq);
458dc9d98d6SKent Overstreet 	bch_check_keys(&b->keys, "writing");
459cafe5635SKent Overstreet 
460cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
461cafe5635SKent Overstreet 
46257943511SKent Overstreet 	/* If caller isn't waiting for write, parent refcount is cache set */
463cb7a583eSKent Overstreet 	down(&b->io_mutex);
464cb7a583eSKent Overstreet 	closure_init(&b->io, parent ?: &b->c->cl);
46557943511SKent Overstreet 
466cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty,	 &b->flags);
467cafe5635SKent Overstreet 	change_bit(BTREE_NODE_write_idx, &b->flags);
468cafe5635SKent Overstreet 
46957943511SKent Overstreet 	do_btree_node_write(b);
470cafe5635SKent Overstreet 
471ee811287SKent Overstreet 	atomic_long_add(set_blocks(i, block_bytes(b->c)) * b->c->sb.block_size,
472cafe5635SKent Overstreet 			&PTR_CACHE(b->c, &b->key, 0)->btree_sectors_written);
473cafe5635SKent Overstreet 
474a85e968eSKent Overstreet 	b->written += set_blocks(i, block_bytes(b->c));
4752a285686SKent Overstreet }
476a85e968eSKent Overstreet 
4772a285686SKent Overstreet void bch_btree_node_write(struct btree *b, struct closure *parent)
4782a285686SKent Overstreet {
4792a285686SKent Overstreet 	unsigned nsets = b->keys.nsets;
4802a285686SKent Overstreet 
4812a285686SKent Overstreet 	lockdep_assert_held(&b->lock);
4822a285686SKent Overstreet 
4832a285686SKent Overstreet 	__bch_btree_node_write(b, parent);
484cafe5635SKent Overstreet 
48578b77bf8SKent Overstreet 	/*
48678b77bf8SKent Overstreet 	 * do verify if there was more than one set initially (i.e. we did a
48778b77bf8SKent Overstreet 	 * sort) and we sorted down to a single set:
48878b77bf8SKent Overstreet 	 */
4892a285686SKent Overstreet 	if (nsets && !b->keys.nsets)
49078b77bf8SKent Overstreet 		bch_btree_verify(b);
49178b77bf8SKent Overstreet 
4922a285686SKent Overstreet 	bch_btree_init_next(b);
493cafe5635SKent Overstreet }
494cafe5635SKent Overstreet 
495f269af5aSKent Overstreet static void bch_btree_node_write_sync(struct btree *b)
496f269af5aSKent Overstreet {
497f269af5aSKent Overstreet 	struct closure cl;
498f269af5aSKent Overstreet 
499f269af5aSKent Overstreet 	closure_init_stack(&cl);
5002a285686SKent Overstreet 
5012a285686SKent Overstreet 	mutex_lock(&b->write_lock);
502f269af5aSKent Overstreet 	bch_btree_node_write(b, &cl);
5032a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
5042a285686SKent Overstreet 
505f269af5aSKent Overstreet 	closure_sync(&cl);
506f269af5aSKent Overstreet }
507f269af5aSKent Overstreet 
50857943511SKent Overstreet static void btree_node_write_work(struct work_struct *w)
509cafe5635SKent Overstreet {
510cafe5635SKent Overstreet 	struct btree *b = container_of(to_delayed_work(w), struct btree, work);
511cafe5635SKent Overstreet 
5122a285686SKent Overstreet 	mutex_lock(&b->write_lock);
513cafe5635SKent Overstreet 	if (btree_node_dirty(b))
5142a285686SKent Overstreet 		__bch_btree_node_write(b, NULL);
5152a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
516cafe5635SKent Overstreet }
517cafe5635SKent Overstreet 
518c18536a7SKent Overstreet static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
519cafe5635SKent Overstreet {
520ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
521cafe5635SKent Overstreet 	struct btree_write *w = btree_current_write(b);
522cafe5635SKent Overstreet 
5232a285686SKent Overstreet 	lockdep_assert_held(&b->write_lock);
5242a285686SKent Overstreet 
52557943511SKent Overstreet 	BUG_ON(!b->written);
52657943511SKent Overstreet 	BUG_ON(!i->keys);
527cafe5635SKent Overstreet 
52857943511SKent Overstreet 	if (!btree_node_dirty(b))
52956b30770SKent Overstreet 		schedule_delayed_work(&b->work, 30 * HZ);
53057943511SKent Overstreet 
531cafe5635SKent Overstreet 	set_btree_node_dirty(b);
532cafe5635SKent Overstreet 
533c18536a7SKent Overstreet 	if (journal_ref) {
534cafe5635SKent Overstreet 		if (w->journal &&
535c18536a7SKent Overstreet 		    journal_pin_cmp(b->c, w->journal, journal_ref)) {
536cafe5635SKent Overstreet 			atomic_dec_bug(w->journal);
537cafe5635SKent Overstreet 			w->journal = NULL;
538cafe5635SKent Overstreet 		}
539cafe5635SKent Overstreet 
540cafe5635SKent Overstreet 		if (!w->journal) {
541c18536a7SKent Overstreet 			w->journal = journal_ref;
542cafe5635SKent Overstreet 			atomic_inc(w->journal);
543cafe5635SKent Overstreet 		}
544cafe5635SKent Overstreet 	}
545cafe5635SKent Overstreet 
546cafe5635SKent Overstreet 	/* Force write if set is too big */
54757943511SKent Overstreet 	if (set_bytes(i) > PAGE_SIZE - 48 &&
54857943511SKent Overstreet 	    !current->bio_list)
54957943511SKent Overstreet 		bch_btree_node_write(b, NULL);
550cafe5635SKent Overstreet }
551cafe5635SKent Overstreet 
552cafe5635SKent Overstreet /*
553cafe5635SKent Overstreet  * Btree in memory cache - allocation/freeing
554cafe5635SKent Overstreet  * mca -> memory cache
555cafe5635SKent Overstreet  */
556cafe5635SKent Overstreet 
557cafe5635SKent Overstreet #define mca_reserve(c)	(((c->root && c->root->level)		\
558cafe5635SKent Overstreet 			  ? c->root->level : 1) * 8 + 16)
559cafe5635SKent Overstreet #define mca_can_free(c)						\
5600a63b66dSKent Overstreet 	max_t(int, 0, c->btree_cache_used - mca_reserve(c))
561cafe5635SKent Overstreet 
562cafe5635SKent Overstreet static void mca_data_free(struct btree *b)
563cafe5635SKent Overstreet {
564cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
565cafe5635SKent Overstreet 
566a85e968eSKent Overstreet 	bch_btree_keys_free(&b->keys);
567cafe5635SKent Overstreet 
5680a63b66dSKent Overstreet 	b->c->btree_cache_used--;
569ee811287SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freed);
570cafe5635SKent Overstreet }
571cafe5635SKent Overstreet 
572cafe5635SKent Overstreet static void mca_bucket_free(struct btree *b)
573cafe5635SKent Overstreet {
574cafe5635SKent Overstreet 	BUG_ON(btree_node_dirty(b));
575cafe5635SKent Overstreet 
576cafe5635SKent Overstreet 	b->key.ptr[0] = 0;
577cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
578cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freeable);
579cafe5635SKent Overstreet }
580cafe5635SKent Overstreet 
581cafe5635SKent Overstreet static unsigned btree_order(struct bkey *k)
582cafe5635SKent Overstreet {
583cafe5635SKent Overstreet 	return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
584cafe5635SKent Overstreet }
585cafe5635SKent Overstreet 
586cafe5635SKent Overstreet static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
587cafe5635SKent Overstreet {
588a85e968eSKent Overstreet 	if (!bch_btree_keys_alloc(&b->keys,
589ee811287SKent Overstreet 				  max_t(unsigned,
590cafe5635SKent Overstreet 					ilog2(b->c->btree_pages),
591ee811287SKent Overstreet 					btree_order(k)),
592ee811287SKent Overstreet 				  gfp)) {
5930a63b66dSKent Overstreet 		b->c->btree_cache_used++;
594ee811287SKent Overstreet 		list_move(&b->list, &b->c->btree_cache);
595ee811287SKent Overstreet 	} else {
596ee811287SKent Overstreet 		list_move(&b->list, &b->c->btree_cache_freed);
597ee811287SKent Overstreet 	}
598cafe5635SKent Overstreet }
599cafe5635SKent Overstreet 
600cafe5635SKent Overstreet static struct btree *mca_bucket_alloc(struct cache_set *c,
601cafe5635SKent Overstreet 				      struct bkey *k, gfp_t gfp)
602cafe5635SKent Overstreet {
603cafe5635SKent Overstreet 	struct btree *b = kzalloc(sizeof(struct btree), gfp);
604cafe5635SKent Overstreet 	if (!b)
605cafe5635SKent Overstreet 		return NULL;
606cafe5635SKent Overstreet 
607cafe5635SKent Overstreet 	init_rwsem(&b->lock);
608cafe5635SKent Overstreet 	lockdep_set_novalidate_class(&b->lock);
6092a285686SKent Overstreet 	mutex_init(&b->write_lock);
6102a285686SKent Overstreet 	lockdep_set_novalidate_class(&b->write_lock);
611cafe5635SKent Overstreet 	INIT_LIST_HEAD(&b->list);
61257943511SKent Overstreet 	INIT_DELAYED_WORK(&b->work, btree_node_write_work);
613cafe5635SKent Overstreet 	b->c = c;
614cb7a583eSKent Overstreet 	sema_init(&b->io_mutex, 1);
615cafe5635SKent Overstreet 
616cafe5635SKent Overstreet 	mca_data_alloc(b, k, gfp);
617cafe5635SKent Overstreet 	return b;
618cafe5635SKent Overstreet }
619cafe5635SKent Overstreet 
620e8e1d468SKent Overstreet static int mca_reap(struct btree *b, unsigned min_order, bool flush)
621cafe5635SKent Overstreet {
622e8e1d468SKent Overstreet 	struct closure cl;
623e8e1d468SKent Overstreet 
624e8e1d468SKent Overstreet 	closure_init_stack(&cl);
625cafe5635SKent Overstreet 	lockdep_assert_held(&b->c->bucket_lock);
626cafe5635SKent Overstreet 
627cafe5635SKent Overstreet 	if (!down_write_trylock(&b->lock))
628cafe5635SKent Overstreet 		return -ENOMEM;
629cafe5635SKent Overstreet 
630a85e968eSKent Overstreet 	BUG_ON(btree_node_dirty(b) && !b->keys.set[0].data);
631e8e1d468SKent Overstreet 
632a85e968eSKent Overstreet 	if (b->keys.page_order < min_order)
633cb7a583eSKent Overstreet 		goto out_unlock;
634cb7a583eSKent Overstreet 
635cb7a583eSKent Overstreet 	if (!flush) {
636cb7a583eSKent Overstreet 		if (btree_node_dirty(b))
637cb7a583eSKent Overstreet 			goto out_unlock;
638cb7a583eSKent Overstreet 
639cb7a583eSKent Overstreet 		if (down_trylock(&b->io_mutex))
640cb7a583eSKent Overstreet 			goto out_unlock;
641cb7a583eSKent Overstreet 		up(&b->io_mutex);
642cafe5635SKent Overstreet 	}
643cafe5635SKent Overstreet 
6442a285686SKent Overstreet 	mutex_lock(&b->write_lock);
645f269af5aSKent Overstreet 	if (btree_node_dirty(b))
6462a285686SKent Overstreet 		__bch_btree_node_write(b, &cl);
6472a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
6482a285686SKent Overstreet 
6492a285686SKent Overstreet 	closure_sync(&cl);
650cafe5635SKent Overstreet 
651e8e1d468SKent Overstreet 	/* wait for any in flight btree write */
652cb7a583eSKent Overstreet 	down(&b->io_mutex);
653cb7a583eSKent Overstreet 	up(&b->io_mutex);
654e8e1d468SKent Overstreet 
655cafe5635SKent Overstreet 	return 0;
656cb7a583eSKent Overstreet out_unlock:
657cb7a583eSKent Overstreet 	rw_unlock(true, b);
658cb7a583eSKent Overstreet 	return -ENOMEM;
659cafe5635SKent Overstreet }
660cafe5635SKent Overstreet 
6617dc19d5aSDave Chinner static unsigned long bch_mca_scan(struct shrinker *shrink,
6627dc19d5aSDave Chinner 				  struct shrink_control *sc)
663cafe5635SKent Overstreet {
664cafe5635SKent Overstreet 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
665cafe5635SKent Overstreet 	struct btree *b, *t;
666cafe5635SKent Overstreet 	unsigned long i, nr = sc->nr_to_scan;
6677dc19d5aSDave Chinner 	unsigned long freed = 0;
668cafe5635SKent Overstreet 
669cafe5635SKent Overstreet 	if (c->shrinker_disabled)
6707dc19d5aSDave Chinner 		return SHRINK_STOP;
671cafe5635SKent Overstreet 
6720a63b66dSKent Overstreet 	if (c->btree_cache_alloc_lock)
6737dc19d5aSDave Chinner 		return SHRINK_STOP;
674cafe5635SKent Overstreet 
675cafe5635SKent Overstreet 	/* Return -1 if we can't do anything right now */
676a698e08cSKent Overstreet 	if (sc->gfp_mask & __GFP_IO)
677cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
678cafe5635SKent Overstreet 	else if (!mutex_trylock(&c->bucket_lock))
679cafe5635SKent Overstreet 		return -1;
680cafe5635SKent Overstreet 
68136c9ea98SKent Overstreet 	/*
68236c9ea98SKent Overstreet 	 * It's _really_ critical that we don't free too many btree nodes - we
68336c9ea98SKent Overstreet 	 * have to always leave ourselves a reserve. The reserve is how we
68436c9ea98SKent Overstreet 	 * guarantee that allocating memory for a new btree node can always
68536c9ea98SKent Overstreet 	 * succeed, so that inserting keys into the btree can always succeed and
68636c9ea98SKent Overstreet 	 * IO can always make forward progress:
68736c9ea98SKent Overstreet 	 */
688cafe5635SKent Overstreet 	nr /= c->btree_pages;
689cafe5635SKent Overstreet 	nr = min_t(unsigned long, nr, mca_can_free(c));
690cafe5635SKent Overstreet 
691cafe5635SKent Overstreet 	i = 0;
692cafe5635SKent Overstreet 	list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
6937dc19d5aSDave Chinner 		if (freed >= nr)
694cafe5635SKent Overstreet 			break;
695cafe5635SKent Overstreet 
696cafe5635SKent Overstreet 		if (++i > 3 &&
697e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
698cafe5635SKent Overstreet 			mca_data_free(b);
699cafe5635SKent Overstreet 			rw_unlock(true, b);
7007dc19d5aSDave Chinner 			freed++;
701cafe5635SKent Overstreet 		}
702cafe5635SKent Overstreet 	}
703cafe5635SKent Overstreet 
7040a63b66dSKent Overstreet 	for (i = 0; (nr--) && i < c->btree_cache_used; i++) {
705cafe5635SKent Overstreet 		if (list_empty(&c->btree_cache))
706cafe5635SKent Overstreet 			goto out;
707cafe5635SKent Overstreet 
708cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
709cafe5635SKent Overstreet 		list_rotate_left(&c->btree_cache);
710cafe5635SKent Overstreet 
711cafe5635SKent Overstreet 		if (!b->accessed &&
712e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
713cafe5635SKent Overstreet 			mca_bucket_free(b);
714cafe5635SKent Overstreet 			mca_data_free(b);
715cafe5635SKent Overstreet 			rw_unlock(true, b);
7167dc19d5aSDave Chinner 			freed++;
717cafe5635SKent Overstreet 		} else
718cafe5635SKent Overstreet 			b->accessed = 0;
719cafe5635SKent Overstreet 	}
720cafe5635SKent Overstreet out:
721cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
7227dc19d5aSDave Chinner 	return freed;
7237dc19d5aSDave Chinner }
7247dc19d5aSDave Chinner 
7257dc19d5aSDave Chinner static unsigned long bch_mca_count(struct shrinker *shrink,
7267dc19d5aSDave Chinner 				   struct shrink_control *sc)
7277dc19d5aSDave Chinner {
7287dc19d5aSDave Chinner 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
7297dc19d5aSDave Chinner 
7307dc19d5aSDave Chinner 	if (c->shrinker_disabled)
7317dc19d5aSDave Chinner 		return 0;
7327dc19d5aSDave Chinner 
7330a63b66dSKent Overstreet 	if (c->btree_cache_alloc_lock)
7347dc19d5aSDave Chinner 		return 0;
7357dc19d5aSDave Chinner 
7367dc19d5aSDave Chinner 	return mca_can_free(c) * c->btree_pages;
737cafe5635SKent Overstreet }
738cafe5635SKent Overstreet 
739cafe5635SKent Overstreet void bch_btree_cache_free(struct cache_set *c)
740cafe5635SKent Overstreet {
741cafe5635SKent Overstreet 	struct btree *b;
742cafe5635SKent Overstreet 	struct closure cl;
743cafe5635SKent Overstreet 	closure_init_stack(&cl);
744cafe5635SKent Overstreet 
745cafe5635SKent Overstreet 	if (c->shrink.list.next)
746cafe5635SKent Overstreet 		unregister_shrinker(&c->shrink);
747cafe5635SKent Overstreet 
748cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
749cafe5635SKent Overstreet 
750cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
751cafe5635SKent Overstreet 	if (c->verify_data)
752cafe5635SKent Overstreet 		list_move(&c->verify_data->list, &c->btree_cache);
75378b77bf8SKent Overstreet 
75478b77bf8SKent Overstreet 	free_pages((unsigned long) c->verify_ondisk, ilog2(bucket_pages(c)));
755cafe5635SKent Overstreet #endif
756cafe5635SKent Overstreet 
757cafe5635SKent Overstreet 	list_splice(&c->btree_cache_freeable,
758cafe5635SKent Overstreet 		    &c->btree_cache);
759cafe5635SKent Overstreet 
760cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache)) {
761cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
762cafe5635SKent Overstreet 
763cafe5635SKent Overstreet 		if (btree_node_dirty(b))
764cafe5635SKent Overstreet 			btree_complete_write(b, btree_current_write(b));
765cafe5635SKent Overstreet 		clear_bit(BTREE_NODE_dirty, &b->flags);
766cafe5635SKent Overstreet 
767cafe5635SKent Overstreet 		mca_data_free(b);
768cafe5635SKent Overstreet 	}
769cafe5635SKent Overstreet 
770cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache_freed)) {
771cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache_freed,
772cafe5635SKent Overstreet 				     struct btree, list);
773cafe5635SKent Overstreet 		list_del(&b->list);
774cafe5635SKent Overstreet 		cancel_delayed_work_sync(&b->work);
775cafe5635SKent Overstreet 		kfree(b);
776cafe5635SKent Overstreet 	}
777cafe5635SKent Overstreet 
778cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
779cafe5635SKent Overstreet }
780cafe5635SKent Overstreet 
781cafe5635SKent Overstreet int bch_btree_cache_alloc(struct cache_set *c)
782cafe5635SKent Overstreet {
783cafe5635SKent Overstreet 	unsigned i;
784cafe5635SKent Overstreet 
785cafe5635SKent Overstreet 	for (i = 0; i < mca_reserve(c); i++)
78672a44517SKent Overstreet 		if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
78772a44517SKent Overstreet 			return -ENOMEM;
788cafe5635SKent Overstreet 
789cafe5635SKent Overstreet 	list_splice_init(&c->btree_cache,
790cafe5635SKent Overstreet 			 &c->btree_cache_freeable);
791cafe5635SKent Overstreet 
792cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
793cafe5635SKent Overstreet 	mutex_init(&c->verify_lock);
794cafe5635SKent Overstreet 
79578b77bf8SKent Overstreet 	c->verify_ondisk = (void *)
79678b77bf8SKent Overstreet 		__get_free_pages(GFP_KERNEL, ilog2(bucket_pages(c)));
79778b77bf8SKent Overstreet 
798cafe5635SKent Overstreet 	c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
799cafe5635SKent Overstreet 
800cafe5635SKent Overstreet 	if (c->verify_data &&
801a85e968eSKent Overstreet 	    c->verify_data->keys.set->data)
802cafe5635SKent Overstreet 		list_del_init(&c->verify_data->list);
803cafe5635SKent Overstreet 	else
804cafe5635SKent Overstreet 		c->verify_data = NULL;
805cafe5635SKent Overstreet #endif
806cafe5635SKent Overstreet 
8077dc19d5aSDave Chinner 	c->shrink.count_objects = bch_mca_count;
8087dc19d5aSDave Chinner 	c->shrink.scan_objects = bch_mca_scan;
809cafe5635SKent Overstreet 	c->shrink.seeks = 4;
810cafe5635SKent Overstreet 	c->shrink.batch = c->btree_pages * 2;
8116c4ca1e3SMichael Lyle 
8126c4ca1e3SMichael Lyle 	if (register_shrinker(&c->shrink))
8136c4ca1e3SMichael Lyle 		pr_warn("bcache: %s: could not register shrinker",
8146c4ca1e3SMichael Lyle 				__func__);
815cafe5635SKent Overstreet 
816cafe5635SKent Overstreet 	return 0;
817cafe5635SKent Overstreet }
818cafe5635SKent Overstreet 
819cafe5635SKent Overstreet /* Btree in memory cache - hash table */
820cafe5635SKent Overstreet 
821cafe5635SKent Overstreet static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
822cafe5635SKent Overstreet {
823cafe5635SKent Overstreet 	return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
824cafe5635SKent Overstreet }
825cafe5635SKent Overstreet 
826cafe5635SKent Overstreet static struct btree *mca_find(struct cache_set *c, struct bkey *k)
827cafe5635SKent Overstreet {
828cafe5635SKent Overstreet 	struct btree *b;
829cafe5635SKent Overstreet 
830cafe5635SKent Overstreet 	rcu_read_lock();
831cafe5635SKent Overstreet 	hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
832cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
833cafe5635SKent Overstreet 			goto out;
834cafe5635SKent Overstreet 	b = NULL;
835cafe5635SKent Overstreet out:
836cafe5635SKent Overstreet 	rcu_read_unlock();
837cafe5635SKent Overstreet 	return b;
838cafe5635SKent Overstreet }
839cafe5635SKent Overstreet 
8400a63b66dSKent Overstreet static int mca_cannibalize_lock(struct cache_set *c, struct btree_op *op)
8410a63b66dSKent Overstreet {
8420a63b66dSKent Overstreet 	struct task_struct *old;
8430a63b66dSKent Overstreet 
8440a63b66dSKent Overstreet 	old = cmpxchg(&c->btree_cache_alloc_lock, NULL, current);
8450a63b66dSKent Overstreet 	if (old && old != current) {
8460a63b66dSKent Overstreet 		if (op)
8470a63b66dSKent Overstreet 			prepare_to_wait(&c->btree_cache_wait, &op->wait,
8480a63b66dSKent Overstreet 					TASK_UNINTERRUPTIBLE);
8490a63b66dSKent Overstreet 		return -EINTR;
8500a63b66dSKent Overstreet 	}
8510a63b66dSKent Overstreet 
8520a63b66dSKent Overstreet 	return 0;
8530a63b66dSKent Overstreet }
8540a63b66dSKent Overstreet 
8550a63b66dSKent Overstreet static struct btree *mca_cannibalize(struct cache_set *c, struct btree_op *op,
8560a63b66dSKent Overstreet 				     struct bkey *k)
857cafe5635SKent Overstreet {
858e8e1d468SKent Overstreet 	struct btree *b;
859cafe5635SKent Overstreet 
860c37511b8SKent Overstreet 	trace_bcache_btree_cache_cannibalize(c);
861c37511b8SKent Overstreet 
8620a63b66dSKent Overstreet 	if (mca_cannibalize_lock(c, op))
8630a63b66dSKent Overstreet 		return ERR_PTR(-EINTR);
864cafe5635SKent Overstreet 
865e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
866e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
867e8e1d468SKent Overstreet 			return b;
868cafe5635SKent Overstreet 
869e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
870e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), true))
871e8e1d468SKent Overstreet 			return b;
872e8e1d468SKent Overstreet 
8730a63b66dSKent Overstreet 	WARN(1, "btree cache cannibalize failed\n");
874e8e1d468SKent Overstreet 	return ERR_PTR(-ENOMEM);
875cafe5635SKent Overstreet }
876cafe5635SKent Overstreet 
877cafe5635SKent Overstreet /*
878cafe5635SKent Overstreet  * We can only have one thread cannibalizing other cached btree nodes at a time,
879cafe5635SKent Overstreet  * or we'll deadlock. We use an open coded mutex to ensure that, which a
880cafe5635SKent Overstreet  * cannibalize_bucket() will take. This means every time we unlock the root of
881cafe5635SKent Overstreet  * the btree, we need to release this lock if we have it held.
882cafe5635SKent Overstreet  */
883df8e8970SKent Overstreet static void bch_cannibalize_unlock(struct cache_set *c)
884cafe5635SKent Overstreet {
8850a63b66dSKent Overstreet 	if (c->btree_cache_alloc_lock == current) {
8860a63b66dSKent Overstreet 		c->btree_cache_alloc_lock = NULL;
8870a63b66dSKent Overstreet 		wake_up(&c->btree_cache_wait);
888cafe5635SKent Overstreet 	}
889cafe5635SKent Overstreet }
890cafe5635SKent Overstreet 
8910a63b66dSKent Overstreet static struct btree *mca_alloc(struct cache_set *c, struct btree_op *op,
8920a63b66dSKent Overstreet 			       struct bkey *k, int level)
893cafe5635SKent Overstreet {
894cafe5635SKent Overstreet 	struct btree *b;
895cafe5635SKent Overstreet 
896e8e1d468SKent Overstreet 	BUG_ON(current->bio_list);
897e8e1d468SKent Overstreet 
898cafe5635SKent Overstreet 	lockdep_assert_held(&c->bucket_lock);
899cafe5635SKent Overstreet 
900cafe5635SKent Overstreet 	if (mca_find(c, k))
901cafe5635SKent Overstreet 		return NULL;
902cafe5635SKent Overstreet 
903cafe5635SKent Overstreet 	/* btree_free() doesn't free memory; it sticks the node on the end of
904cafe5635SKent Overstreet 	 * the list. Check if there's any freed nodes there:
905cafe5635SKent Overstreet 	 */
906cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freeable, list)
907e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
908cafe5635SKent Overstreet 			goto out;
909cafe5635SKent Overstreet 
910cafe5635SKent Overstreet 	/* We never free struct btree itself, just the memory that holds the on
911cafe5635SKent Overstreet 	 * disk node. Check the freed list before allocating a new one:
912cafe5635SKent Overstreet 	 */
913cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freed, list)
914e8e1d468SKent Overstreet 		if (!mca_reap(b, 0, false)) {
915cafe5635SKent Overstreet 			mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
916a85e968eSKent Overstreet 			if (!b->keys.set[0].data)
917cafe5635SKent Overstreet 				goto err;
918cafe5635SKent Overstreet 			else
919cafe5635SKent Overstreet 				goto out;
920cafe5635SKent Overstreet 		}
921cafe5635SKent Overstreet 
922cafe5635SKent Overstreet 	b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
923cafe5635SKent Overstreet 	if (!b)
924cafe5635SKent Overstreet 		goto err;
925cafe5635SKent Overstreet 
926cafe5635SKent Overstreet 	BUG_ON(!down_write_trylock(&b->lock));
927a85e968eSKent Overstreet 	if (!b->keys.set->data)
928cafe5635SKent Overstreet 		goto err;
929cafe5635SKent Overstreet out:
930cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
931cafe5635SKent Overstreet 
932cafe5635SKent Overstreet 	bkey_copy(&b->key, k);
933cafe5635SKent Overstreet 	list_move(&b->list, &c->btree_cache);
934cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
935cafe5635SKent Overstreet 	hlist_add_head_rcu(&b->hash, mca_hash(c, k));
936cafe5635SKent Overstreet 
937cafe5635SKent Overstreet 	lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
938d6fd3b11SKent Overstreet 	b->parent	= (void *) ~0UL;
939a85e968eSKent Overstreet 	b->flags	= 0;
940a85e968eSKent Overstreet 	b->written	= 0;
941a85e968eSKent Overstreet 	b->level	= level;
942cafe5635SKent Overstreet 
94365d45231SKent Overstreet 	if (!b->level)
944a85e968eSKent Overstreet 		bch_btree_keys_init(&b->keys, &bch_extent_keys_ops,
945a85e968eSKent Overstreet 				    &b->c->expensive_debug_checks);
94665d45231SKent Overstreet 	else
947a85e968eSKent Overstreet 		bch_btree_keys_init(&b->keys, &bch_btree_keys_ops,
948a85e968eSKent Overstreet 				    &b->c->expensive_debug_checks);
949cafe5635SKent Overstreet 
950cafe5635SKent Overstreet 	return b;
951cafe5635SKent Overstreet err:
952cafe5635SKent Overstreet 	if (b)
953cafe5635SKent Overstreet 		rw_unlock(true, b);
954cafe5635SKent Overstreet 
9550a63b66dSKent Overstreet 	b = mca_cannibalize(c, op, k);
956cafe5635SKent Overstreet 	if (!IS_ERR(b))
957cafe5635SKent Overstreet 		goto out;
958cafe5635SKent Overstreet 
959cafe5635SKent Overstreet 	return b;
960cafe5635SKent Overstreet }
961cafe5635SKent Overstreet 
962cafe5635SKent Overstreet /**
963cafe5635SKent Overstreet  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
964cafe5635SKent Overstreet  * in from disk if necessary.
965cafe5635SKent Overstreet  *
966b54d6934SKent Overstreet  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
967cafe5635SKent Overstreet  *
968cafe5635SKent Overstreet  * The btree node will have either a read or a write lock held, depending on
969cafe5635SKent Overstreet  * level and op->lock.
970cafe5635SKent Overstreet  */
9710a63b66dSKent Overstreet struct btree *bch_btree_node_get(struct cache_set *c, struct btree_op *op,
9722452cc89SSlava Pestov 				 struct bkey *k, int level, bool write,
9732452cc89SSlava Pestov 				 struct btree *parent)
974cafe5635SKent Overstreet {
975cafe5635SKent Overstreet 	int i = 0;
976cafe5635SKent Overstreet 	struct btree *b;
977cafe5635SKent Overstreet 
978cafe5635SKent Overstreet 	BUG_ON(level < 0);
979cafe5635SKent Overstreet retry:
980cafe5635SKent Overstreet 	b = mca_find(c, k);
981cafe5635SKent Overstreet 
982cafe5635SKent Overstreet 	if (!b) {
98357943511SKent Overstreet 		if (current->bio_list)
98457943511SKent Overstreet 			return ERR_PTR(-EAGAIN);
98557943511SKent Overstreet 
986cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
9870a63b66dSKent Overstreet 		b = mca_alloc(c, op, k, level);
988cafe5635SKent Overstreet 		mutex_unlock(&c->bucket_lock);
989cafe5635SKent Overstreet 
990cafe5635SKent Overstreet 		if (!b)
991cafe5635SKent Overstreet 			goto retry;
992cafe5635SKent Overstreet 		if (IS_ERR(b))
993cafe5635SKent Overstreet 			return b;
994cafe5635SKent Overstreet 
99557943511SKent Overstreet 		bch_btree_node_read(b);
996cafe5635SKent Overstreet 
997cafe5635SKent Overstreet 		if (!write)
998cafe5635SKent Overstreet 			downgrade_write(&b->lock);
999cafe5635SKent Overstreet 	} else {
1000cafe5635SKent Overstreet 		rw_lock(write, b, level);
1001cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
1002cafe5635SKent Overstreet 			rw_unlock(write, b);
1003cafe5635SKent Overstreet 			goto retry;
1004cafe5635SKent Overstreet 		}
1005cafe5635SKent Overstreet 		BUG_ON(b->level != level);
1006cafe5635SKent Overstreet 	}
1007cafe5635SKent Overstreet 
10082452cc89SSlava Pestov 	b->parent = parent;
1009cafe5635SKent Overstreet 	b->accessed = 1;
1010cafe5635SKent Overstreet 
1011a85e968eSKent Overstreet 	for (; i <= b->keys.nsets && b->keys.set[i].size; i++) {
1012a85e968eSKent Overstreet 		prefetch(b->keys.set[i].tree);
1013a85e968eSKent Overstreet 		prefetch(b->keys.set[i].data);
1014cafe5635SKent Overstreet 	}
1015cafe5635SKent Overstreet 
1016a85e968eSKent Overstreet 	for (; i <= b->keys.nsets; i++)
1017a85e968eSKent Overstreet 		prefetch(b->keys.set[i].data);
1018cafe5635SKent Overstreet 
101957943511SKent Overstreet 	if (btree_node_io_error(b)) {
1020cafe5635SKent Overstreet 		rw_unlock(write, b);
102157943511SKent Overstreet 		return ERR_PTR(-EIO);
102257943511SKent Overstreet 	}
102357943511SKent Overstreet 
1024cafe5635SKent Overstreet 	BUG_ON(!b->written);
1025cafe5635SKent Overstreet 
1026cafe5635SKent Overstreet 	return b;
1027cafe5635SKent Overstreet }
1028cafe5635SKent Overstreet 
10292452cc89SSlava Pestov static void btree_node_prefetch(struct btree *parent, struct bkey *k)
1030cafe5635SKent Overstreet {
1031cafe5635SKent Overstreet 	struct btree *b;
1032cafe5635SKent Overstreet 
10332452cc89SSlava Pestov 	mutex_lock(&parent->c->bucket_lock);
10342452cc89SSlava Pestov 	b = mca_alloc(parent->c, NULL, k, parent->level - 1);
10352452cc89SSlava Pestov 	mutex_unlock(&parent->c->bucket_lock);
1036cafe5635SKent Overstreet 
1037cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(b)) {
10382452cc89SSlava Pestov 		b->parent = parent;
103957943511SKent Overstreet 		bch_btree_node_read(b);
1040cafe5635SKent Overstreet 		rw_unlock(true, b);
1041cafe5635SKent Overstreet 	}
1042cafe5635SKent Overstreet }
1043cafe5635SKent Overstreet 
1044cafe5635SKent Overstreet /* Btree alloc */
1045cafe5635SKent Overstreet 
1046e8e1d468SKent Overstreet static void btree_node_free(struct btree *b)
1047cafe5635SKent Overstreet {
1048c37511b8SKent Overstreet 	trace_bcache_btree_node_free(b);
1049c37511b8SKent Overstreet 
1050cafe5635SKent Overstreet 	BUG_ON(b == b->c->root);
1051cafe5635SKent Overstreet 
10522a285686SKent Overstreet 	mutex_lock(&b->write_lock);
10532a285686SKent Overstreet 
1054cafe5635SKent Overstreet 	if (btree_node_dirty(b))
1055cafe5635SKent Overstreet 		btree_complete_write(b, btree_current_write(b));
1056cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty, &b->flags);
1057cafe5635SKent Overstreet 
10582a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
10592a285686SKent Overstreet 
1060cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
1061cafe5635SKent Overstreet 
1062cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
1063cafe5635SKent Overstreet 	bch_bucket_free(b->c, &b->key);
1064cafe5635SKent Overstreet 	mca_bucket_free(b);
1065cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
1066cafe5635SKent Overstreet }
1067cafe5635SKent Overstreet 
1068c5aa4a31SSlava Pestov struct btree *__bch_btree_node_alloc(struct cache_set *c, struct btree_op *op,
10692452cc89SSlava Pestov 				     int level, bool wait,
10702452cc89SSlava Pestov 				     struct btree *parent)
1071cafe5635SKent Overstreet {
1072cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
1073cafe5635SKent Overstreet 	struct btree *b = ERR_PTR(-EAGAIN);
1074cafe5635SKent Overstreet 
1075cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1076cafe5635SKent Overstreet retry:
1077c5aa4a31SSlava Pestov 	if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, wait))
1078cafe5635SKent Overstreet 		goto err;
1079cafe5635SKent Overstreet 
10803a3b6a4eSKent Overstreet 	bkey_put(c, &k.key);
1081cafe5635SKent Overstreet 	SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1082cafe5635SKent Overstreet 
10830a63b66dSKent Overstreet 	b = mca_alloc(c, op, &k.key, level);
1084cafe5635SKent Overstreet 	if (IS_ERR(b))
1085cafe5635SKent Overstreet 		goto err_free;
1086cafe5635SKent Overstreet 
1087cafe5635SKent Overstreet 	if (!b) {
1088b1a67b0fSKent Overstreet 		cache_bug(c,
1089b1a67b0fSKent Overstreet 			"Tried to allocate bucket that was in btree cache");
1090cafe5635SKent Overstreet 		goto retry;
1091cafe5635SKent Overstreet 	}
1092cafe5635SKent Overstreet 
1093cafe5635SKent Overstreet 	b->accessed = 1;
10942452cc89SSlava Pestov 	b->parent = parent;
1095a85e968eSKent Overstreet 	bch_bset_init_next(&b->keys, b->keys.set->data, bset_magic(&b->c->sb));
1096cafe5635SKent Overstreet 
1097cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1098c37511b8SKent Overstreet 
1099c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc(b);
1100cafe5635SKent Overstreet 	return b;
1101cafe5635SKent Overstreet err_free:
1102cafe5635SKent Overstreet 	bch_bucket_free(c, &k.key);
1103cafe5635SKent Overstreet err:
1104cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1105c37511b8SKent Overstreet 
1106913dc33fSSlava Pestov 	trace_bcache_btree_node_alloc_fail(c);
1107cafe5635SKent Overstreet 	return b;
1108cafe5635SKent Overstreet }
1109cafe5635SKent Overstreet 
1110c5aa4a31SSlava Pestov static struct btree *bch_btree_node_alloc(struct cache_set *c,
11112452cc89SSlava Pestov 					  struct btree_op *op, int level,
11122452cc89SSlava Pestov 					  struct btree *parent)
1113c5aa4a31SSlava Pestov {
11142452cc89SSlava Pestov 	return __bch_btree_node_alloc(c, op, level, op != NULL, parent);
1115c5aa4a31SSlava Pestov }
1116c5aa4a31SSlava Pestov 
11170a63b66dSKent Overstreet static struct btree *btree_node_alloc_replacement(struct btree *b,
11180a63b66dSKent Overstreet 						  struct btree_op *op)
1119cafe5635SKent Overstreet {
11202452cc89SSlava Pestov 	struct btree *n = bch_btree_node_alloc(b->c, op, b->level, b->parent);
112167539e85SKent Overstreet 	if (!IS_ERR_OR_NULL(n)) {
11222a285686SKent Overstreet 		mutex_lock(&n->write_lock);
112389ebb4a2SKent Overstreet 		bch_btree_sort_into(&b->keys, &n->keys, &b->c->sort);
112467539e85SKent Overstreet 		bkey_copy_key(&n->key, &b->key);
11252a285686SKent Overstreet 		mutex_unlock(&n->write_lock);
112667539e85SKent Overstreet 	}
1127cafe5635SKent Overstreet 
1128cafe5635SKent Overstreet 	return n;
1129cafe5635SKent Overstreet }
1130cafe5635SKent Overstreet 
11318835c123SKent Overstreet static void make_btree_freeing_key(struct btree *b, struct bkey *k)
11328835c123SKent Overstreet {
11338835c123SKent Overstreet 	unsigned i;
11348835c123SKent Overstreet 
113505335cffSKent Overstreet 	mutex_lock(&b->c->bucket_lock);
113605335cffSKent Overstreet 
113705335cffSKent Overstreet 	atomic_inc(&b->c->prio_blocked);
113805335cffSKent Overstreet 
11398835c123SKent Overstreet 	bkey_copy(k, &b->key);
11408835c123SKent Overstreet 	bkey_copy_key(k, &ZERO_KEY);
11418835c123SKent Overstreet 
114205335cffSKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
114305335cffSKent Overstreet 		SET_PTR_GEN(k, i,
114405335cffSKent Overstreet 			    bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
114505335cffSKent Overstreet 					PTR_BUCKET(b->c, &b->key, i)));
11468835c123SKent Overstreet 
114705335cffSKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
11488835c123SKent Overstreet }
11498835c123SKent Overstreet 
115078365411SKent Overstreet static int btree_check_reserve(struct btree *b, struct btree_op *op)
115178365411SKent Overstreet {
115278365411SKent Overstreet 	struct cache_set *c = b->c;
115378365411SKent Overstreet 	struct cache *ca;
11540a63b66dSKent Overstreet 	unsigned i, reserve = (c->root->level - b->level) * 2 + 1;
115578365411SKent Overstreet 
115678365411SKent Overstreet 	mutex_lock(&c->bucket_lock);
115778365411SKent Overstreet 
115878365411SKent Overstreet 	for_each_cache(ca, c, i)
115978365411SKent Overstreet 		if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
116078365411SKent Overstreet 			if (op)
11610a63b66dSKent Overstreet 				prepare_to_wait(&c->btree_cache_wait, &op->wait,
116278365411SKent Overstreet 						TASK_UNINTERRUPTIBLE);
11630a63b66dSKent Overstreet 			mutex_unlock(&c->bucket_lock);
11640a63b66dSKent Overstreet 			return -EINTR;
116578365411SKent Overstreet 		}
116678365411SKent Overstreet 
116778365411SKent Overstreet 	mutex_unlock(&c->bucket_lock);
11680a63b66dSKent Overstreet 
11690a63b66dSKent Overstreet 	return mca_cannibalize_lock(b->c, op);
117078365411SKent Overstreet }
117178365411SKent Overstreet 
1172cafe5635SKent Overstreet /* Garbage collection */
1173cafe5635SKent Overstreet 
1174487dded8SKent Overstreet static uint8_t __bch_btree_mark_key(struct cache_set *c, int level,
1175487dded8SKent Overstreet 				    struct bkey *k)
1176cafe5635SKent Overstreet {
1177cafe5635SKent Overstreet 	uint8_t stale = 0;
1178cafe5635SKent Overstreet 	unsigned i;
1179cafe5635SKent Overstreet 	struct bucket *g;
1180cafe5635SKent Overstreet 
1181cafe5635SKent Overstreet 	/*
1182cafe5635SKent Overstreet 	 * ptr_invalid() can't return true for the keys that mark btree nodes as
1183cafe5635SKent Overstreet 	 * freed, but since ptr_bad() returns true we'll never actually use them
1184cafe5635SKent Overstreet 	 * for anything and thus we don't want mark their pointers here
1185cafe5635SKent Overstreet 	 */
1186cafe5635SKent Overstreet 	if (!bkey_cmp(k, &ZERO_KEY))
1187cafe5635SKent Overstreet 		return stale;
1188cafe5635SKent Overstreet 
1189cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
1190cafe5635SKent Overstreet 		if (!ptr_available(c, k, i))
1191cafe5635SKent Overstreet 			continue;
1192cafe5635SKent Overstreet 
1193cafe5635SKent Overstreet 		g = PTR_BUCKET(c, k, i);
1194cafe5635SKent Overstreet 
11953a2fd9d5SKent Overstreet 		if (gen_after(g->last_gc, PTR_GEN(k, i)))
11963a2fd9d5SKent Overstreet 			g->last_gc = PTR_GEN(k, i);
1197cafe5635SKent Overstreet 
1198cafe5635SKent Overstreet 		if (ptr_stale(c, k, i)) {
1199cafe5635SKent Overstreet 			stale = max(stale, ptr_stale(c, k, i));
1200cafe5635SKent Overstreet 			continue;
1201cafe5635SKent Overstreet 		}
1202cafe5635SKent Overstreet 
1203cafe5635SKent Overstreet 		cache_bug_on(GC_MARK(g) &&
1204cafe5635SKent Overstreet 			     (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1205cafe5635SKent Overstreet 			     c, "inconsistent ptrs: mark = %llu, level = %i",
1206cafe5635SKent Overstreet 			     GC_MARK(g), level);
1207cafe5635SKent Overstreet 
1208cafe5635SKent Overstreet 		if (level)
1209cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_METADATA);
1210cafe5635SKent Overstreet 		else if (KEY_DIRTY(k))
1211cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_DIRTY);
12124fe6a816SKent Overstreet 		else if (!GC_MARK(g))
12134fe6a816SKent Overstreet 			SET_GC_MARK(g, GC_MARK_RECLAIMABLE);
1214cafe5635SKent Overstreet 
1215cafe5635SKent Overstreet 		/* guard against overflow */
1216cafe5635SKent Overstreet 		SET_GC_SECTORS_USED(g, min_t(unsigned,
1217cafe5635SKent Overstreet 					     GC_SECTORS_USED(g) + KEY_SIZE(k),
121894717447SDarrick J. Wong 					     MAX_GC_SECTORS_USED));
1219cafe5635SKent Overstreet 
1220cafe5635SKent Overstreet 		BUG_ON(!GC_SECTORS_USED(g));
1221cafe5635SKent Overstreet 	}
1222cafe5635SKent Overstreet 
1223cafe5635SKent Overstreet 	return stale;
1224cafe5635SKent Overstreet }
1225cafe5635SKent Overstreet 
1226cafe5635SKent Overstreet #define btree_mark_key(b, k)	__bch_btree_mark_key(b->c, b->level, k)
1227cafe5635SKent Overstreet 
1228487dded8SKent Overstreet void bch_initial_mark_key(struct cache_set *c, int level, struct bkey *k)
1229487dded8SKent Overstreet {
1230487dded8SKent Overstreet 	unsigned i;
1231487dded8SKent Overstreet 
1232487dded8SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
1233487dded8SKent Overstreet 		if (ptr_available(c, k, i) &&
1234487dded8SKent Overstreet 		    !ptr_stale(c, k, i)) {
1235487dded8SKent Overstreet 			struct bucket *b = PTR_BUCKET(c, k, i);
1236487dded8SKent Overstreet 
1237487dded8SKent Overstreet 			b->gen = PTR_GEN(k, i);
1238487dded8SKent Overstreet 
1239487dded8SKent Overstreet 			if (level && bkey_cmp(k, &ZERO_KEY))
1240487dded8SKent Overstreet 				b->prio = BTREE_PRIO;
1241487dded8SKent Overstreet 			else if (!level && b->prio == BTREE_PRIO)
1242487dded8SKent Overstreet 				b->prio = INITIAL_PRIO;
1243487dded8SKent Overstreet 		}
1244487dded8SKent Overstreet 
1245487dded8SKent Overstreet 	__bch_btree_mark_key(c, level, k);
1246487dded8SKent Overstreet }
1247487dded8SKent Overstreet 
1248d44c2f9eSTang Junhui void bch_update_bucket_in_use(struct cache_set *c, struct gc_stat *stats)
1249d44c2f9eSTang Junhui {
1250d44c2f9eSTang Junhui 	stats->in_use = (c->nbuckets - c->avail_nbuckets) * 100 / c->nbuckets;
1251d44c2f9eSTang Junhui }
1252d44c2f9eSTang Junhui 
1253a1f0358bSKent Overstreet static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1254cafe5635SKent Overstreet {
1255cafe5635SKent Overstreet 	uint8_t stale = 0;
1256a1f0358bSKent Overstreet 	unsigned keys = 0, good_keys = 0;
1257cafe5635SKent Overstreet 	struct bkey *k;
1258cafe5635SKent Overstreet 	struct btree_iter iter;
1259cafe5635SKent Overstreet 	struct bset_tree *t;
1260cafe5635SKent Overstreet 
1261cafe5635SKent Overstreet 	gc->nodes++;
1262cafe5635SKent Overstreet 
1263c052dd9aSKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid) {
1264cafe5635SKent Overstreet 		stale = max(stale, btree_mark_key(b, k));
1265a1f0358bSKent Overstreet 		keys++;
1266cafe5635SKent Overstreet 
1267a85e968eSKent Overstreet 		if (bch_ptr_bad(&b->keys, k))
1268cafe5635SKent Overstreet 			continue;
1269cafe5635SKent Overstreet 
1270cafe5635SKent Overstreet 		gc->key_bytes += bkey_u64s(k);
1271cafe5635SKent Overstreet 		gc->nkeys++;
1272a1f0358bSKent Overstreet 		good_keys++;
1273cafe5635SKent Overstreet 
1274cafe5635SKent Overstreet 		gc->data += KEY_SIZE(k);
1275cafe5635SKent Overstreet 	}
1276cafe5635SKent Overstreet 
1277a85e968eSKent Overstreet 	for (t = b->keys.set; t <= &b->keys.set[b->keys.nsets]; t++)
1278cafe5635SKent Overstreet 		btree_bug_on(t->size &&
1279a85e968eSKent Overstreet 			     bset_written(&b->keys, t) &&
1280cafe5635SKent Overstreet 			     bkey_cmp(&b->key, &t->end) < 0,
1281cafe5635SKent Overstreet 			     b, "found short btree key in gc");
1282cafe5635SKent Overstreet 
1283a1f0358bSKent Overstreet 	if (b->c->gc_always_rewrite)
1284a1f0358bSKent Overstreet 		return true;
1285a1f0358bSKent Overstreet 
1286a1f0358bSKent Overstreet 	if (stale > 10)
1287a1f0358bSKent Overstreet 		return true;
1288a1f0358bSKent Overstreet 
1289a1f0358bSKent Overstreet 	if ((keys - good_keys) * 2 > keys)
1290a1f0358bSKent Overstreet 		return true;
1291a1f0358bSKent Overstreet 
1292a1f0358bSKent Overstreet 	return false;
1293cafe5635SKent Overstreet }
1294cafe5635SKent Overstreet 
1295a1f0358bSKent Overstreet #define GC_MERGE_NODES	4U
1296cafe5635SKent Overstreet 
1297cafe5635SKent Overstreet struct gc_merge_info {
1298cafe5635SKent Overstreet 	struct btree	*b;
1299cafe5635SKent Overstreet 	unsigned	keys;
1300cafe5635SKent Overstreet };
1301cafe5635SKent Overstreet 
1302a1f0358bSKent Overstreet static int bch_btree_insert_node(struct btree *, struct btree_op *,
1303a1f0358bSKent Overstreet 				 struct keylist *, atomic_t *, struct bkey *);
1304a1f0358bSKent Overstreet 
1305a1f0358bSKent Overstreet static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
13060a63b66dSKent Overstreet 			     struct gc_stat *gc, struct gc_merge_info *r)
1307cafe5635SKent Overstreet {
1308a1f0358bSKent Overstreet 	unsigned i, nodes = 0, keys = 0, blocks;
1309a1f0358bSKent Overstreet 	struct btree *new_nodes[GC_MERGE_NODES];
13100a63b66dSKent Overstreet 	struct keylist keylist;
1311b54d6934SKent Overstreet 	struct closure cl;
1312a1f0358bSKent Overstreet 	struct bkey *k;
1313b54d6934SKent Overstreet 
13140a63b66dSKent Overstreet 	bch_keylist_init(&keylist);
13150a63b66dSKent Overstreet 
13160a63b66dSKent Overstreet 	if (btree_check_reserve(b, NULL))
13170a63b66dSKent Overstreet 		return 0;
13180a63b66dSKent Overstreet 
1319a1f0358bSKent Overstreet 	memset(new_nodes, 0, sizeof(new_nodes));
1320b54d6934SKent Overstreet 	closure_init_stack(&cl);
1321cafe5635SKent Overstreet 
1322a1f0358bSKent Overstreet 	while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1323cafe5635SKent Overstreet 		keys += r[nodes++].keys;
1324cafe5635SKent Overstreet 
1325cafe5635SKent Overstreet 	blocks = btree_default_blocks(b->c) * 2 / 3;
1326cafe5635SKent Overstreet 
1327cafe5635SKent Overstreet 	if (nodes < 2 ||
1328a85e968eSKent Overstreet 	    __set_blocks(b->keys.set[0].data, keys,
1329ee811287SKent Overstreet 			 block_bytes(b->c)) > blocks * (nodes - 1))
1330a1f0358bSKent Overstreet 		return 0;
1331cafe5635SKent Overstreet 
1332a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
13330a63b66dSKent Overstreet 		new_nodes[i] = btree_node_alloc_replacement(r[i].b, NULL);
1334a1f0358bSKent Overstreet 		if (IS_ERR_OR_NULL(new_nodes[i]))
1335a1f0358bSKent Overstreet 			goto out_nocoalesce;
1336cafe5635SKent Overstreet 	}
1337cafe5635SKent Overstreet 
13380a63b66dSKent Overstreet 	/*
13390a63b66dSKent Overstreet 	 * We have to check the reserve here, after we've allocated our new
13400a63b66dSKent Overstreet 	 * nodes, to make sure the insert below will succeed - we also check
13410a63b66dSKent Overstreet 	 * before as an optimization to potentially avoid a bunch of expensive
13420a63b66dSKent Overstreet 	 * allocs/sorts
13430a63b66dSKent Overstreet 	 */
13440a63b66dSKent Overstreet 	if (btree_check_reserve(b, NULL))
13450a63b66dSKent Overstreet 		goto out_nocoalesce;
13460a63b66dSKent Overstreet 
13472a285686SKent Overstreet 	for (i = 0; i < nodes; i++)
13482a285686SKent Overstreet 		mutex_lock(&new_nodes[i]->write_lock);
13492a285686SKent Overstreet 
1350cafe5635SKent Overstreet 	for (i = nodes - 1; i > 0; --i) {
1351ee811287SKent Overstreet 		struct bset *n1 = btree_bset_first(new_nodes[i]);
1352ee811287SKent Overstreet 		struct bset *n2 = btree_bset_first(new_nodes[i - 1]);
1353cafe5635SKent Overstreet 		struct bkey *k, *last = NULL;
1354cafe5635SKent Overstreet 
1355cafe5635SKent Overstreet 		keys = 0;
1356cafe5635SKent Overstreet 
1357a1f0358bSKent Overstreet 		if (i > 1) {
1358cafe5635SKent Overstreet 			for (k = n2->start;
1359fafff81cSKent Overstreet 			     k < bset_bkey_last(n2);
1360cafe5635SKent Overstreet 			     k = bkey_next(k)) {
1361cafe5635SKent Overstreet 				if (__set_blocks(n1, n1->keys + keys +
1362ee811287SKent Overstreet 						 bkey_u64s(k),
1363ee811287SKent Overstreet 						 block_bytes(b->c)) > blocks)
1364cafe5635SKent Overstreet 					break;
1365cafe5635SKent Overstreet 
1366cafe5635SKent Overstreet 				last = k;
1367cafe5635SKent Overstreet 				keys += bkey_u64s(k);
1368cafe5635SKent Overstreet 			}
1369a1f0358bSKent Overstreet 		} else {
1370a1f0358bSKent Overstreet 			/*
1371a1f0358bSKent Overstreet 			 * Last node we're not getting rid of - we're getting
1372a1f0358bSKent Overstreet 			 * rid of the node at r[0]. Have to try and fit all of
1373a1f0358bSKent Overstreet 			 * the remaining keys into this node; we can't ensure
1374a1f0358bSKent Overstreet 			 * they will always fit due to rounding and variable
1375a1f0358bSKent Overstreet 			 * length keys (shouldn't be possible in practice,
1376a1f0358bSKent Overstreet 			 * though)
1377a1f0358bSKent Overstreet 			 */
1378a1f0358bSKent Overstreet 			if (__set_blocks(n1, n1->keys + n2->keys,
1379ee811287SKent Overstreet 					 block_bytes(b->c)) >
1380ee811287SKent Overstreet 			    btree_blocks(new_nodes[i]))
1381a1f0358bSKent Overstreet 				goto out_nocoalesce;
1382a1f0358bSKent Overstreet 
1383a1f0358bSKent Overstreet 			keys = n2->keys;
1384a1f0358bSKent Overstreet 			/* Take the key of the node we're getting rid of */
1385a1f0358bSKent Overstreet 			last = &r->b->key;
1386a1f0358bSKent Overstreet 		}
1387cafe5635SKent Overstreet 
1388ee811287SKent Overstreet 		BUG_ON(__set_blocks(n1, n1->keys + keys, block_bytes(b->c)) >
1389ee811287SKent Overstreet 		       btree_blocks(new_nodes[i]));
1390cafe5635SKent Overstreet 
1391a1f0358bSKent Overstreet 		if (last)
1392a1f0358bSKent Overstreet 			bkey_copy_key(&new_nodes[i]->key, last);
1393cafe5635SKent Overstreet 
1394fafff81cSKent Overstreet 		memcpy(bset_bkey_last(n1),
1395cafe5635SKent Overstreet 		       n2->start,
1396fafff81cSKent Overstreet 		       (void *) bset_bkey_idx(n2, keys) - (void *) n2->start);
1397cafe5635SKent Overstreet 
1398cafe5635SKent Overstreet 		n1->keys += keys;
1399a1f0358bSKent Overstreet 		r[i].keys = n1->keys;
1400cafe5635SKent Overstreet 
1401cafe5635SKent Overstreet 		memmove(n2->start,
1402fafff81cSKent Overstreet 			bset_bkey_idx(n2, keys),
1403fafff81cSKent Overstreet 			(void *) bset_bkey_last(n2) -
1404fafff81cSKent Overstreet 			(void *) bset_bkey_idx(n2, keys));
1405cafe5635SKent Overstreet 
1406cafe5635SKent Overstreet 		n2->keys -= keys;
1407cafe5635SKent Overstreet 
14080a63b66dSKent Overstreet 		if (__bch_keylist_realloc(&keylist,
1409085d2a3dSKent Overstreet 					  bkey_u64s(&new_nodes[i]->key)))
1410a1f0358bSKent Overstreet 			goto out_nocoalesce;
1411a1f0358bSKent Overstreet 
1412a1f0358bSKent Overstreet 		bch_btree_node_write(new_nodes[i], &cl);
14130a63b66dSKent Overstreet 		bch_keylist_add(&keylist, &new_nodes[i]->key);
1414cafe5635SKent Overstreet 	}
1415cafe5635SKent Overstreet 
14162a285686SKent Overstreet 	for (i = 0; i < nodes; i++)
14172a285686SKent Overstreet 		mutex_unlock(&new_nodes[i]->write_lock);
14182a285686SKent Overstreet 
141905335cffSKent Overstreet 	closure_sync(&cl);
142005335cffSKent Overstreet 
142105335cffSKent Overstreet 	/* We emptied out this node */
142205335cffSKent Overstreet 	BUG_ON(btree_bset_first(new_nodes[0])->keys);
142305335cffSKent Overstreet 	btree_node_free(new_nodes[0]);
142405335cffSKent Overstreet 	rw_unlock(true, new_nodes[0]);
1425400ffaa2SSlava Pestov 	new_nodes[0] = NULL;
142605335cffSKent Overstreet 
1427a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
14280a63b66dSKent Overstreet 		if (__bch_keylist_realloc(&keylist, bkey_u64s(&r[i].b->key)))
1429a1f0358bSKent Overstreet 			goto out_nocoalesce;
1430a1f0358bSKent Overstreet 
14310a63b66dSKent Overstreet 		make_btree_freeing_key(r[i].b, keylist.top);
14320a63b66dSKent Overstreet 		bch_keylist_push(&keylist);
1433a1f0358bSKent Overstreet 	}
1434a1f0358bSKent Overstreet 
14350a63b66dSKent Overstreet 	bch_btree_insert_node(b, op, &keylist, NULL, NULL);
14360a63b66dSKent Overstreet 	BUG_ON(!bch_keylist_empty(&keylist));
1437a1f0358bSKent Overstreet 
1438a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1439a1f0358bSKent Overstreet 		btree_node_free(r[i].b);
1440a1f0358bSKent Overstreet 		rw_unlock(true, r[i].b);
1441a1f0358bSKent Overstreet 
1442a1f0358bSKent Overstreet 		r[i].b = new_nodes[i];
1443a1f0358bSKent Overstreet 	}
1444a1f0358bSKent Overstreet 
1445a1f0358bSKent Overstreet 	memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1446a1f0358bSKent Overstreet 	r[nodes - 1].b = ERR_PTR(-EINTR);
1447cafe5635SKent Overstreet 
1448c37511b8SKent Overstreet 	trace_bcache_btree_gc_coalesce(nodes);
1449cafe5635SKent Overstreet 	gc->nodes--;
1450cafe5635SKent Overstreet 
14510a63b66dSKent Overstreet 	bch_keylist_free(&keylist);
14520a63b66dSKent Overstreet 
1453a1f0358bSKent Overstreet 	/* Invalidated our iterator */
1454a1f0358bSKent Overstreet 	return -EINTR;
1455a1f0358bSKent Overstreet 
1456a1f0358bSKent Overstreet out_nocoalesce:
1457a1f0358bSKent Overstreet 	closure_sync(&cl);
14580a63b66dSKent Overstreet 	bch_keylist_free(&keylist);
1459a1f0358bSKent Overstreet 
14600a63b66dSKent Overstreet 	while ((k = bch_keylist_pop(&keylist)))
1461a1f0358bSKent Overstreet 		if (!bkey_cmp(k, &ZERO_KEY))
1462a1f0358bSKent Overstreet 			atomic_dec(&b->c->prio_blocked);
1463a1f0358bSKent Overstreet 
1464a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++)
1465a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(new_nodes[i])) {
1466a1f0358bSKent Overstreet 			btree_node_free(new_nodes[i]);
1467a1f0358bSKent Overstreet 			rw_unlock(true, new_nodes[i]);
1468a1f0358bSKent Overstreet 		}
1469a1f0358bSKent Overstreet 	return 0;
1470a1f0358bSKent Overstreet }
1471a1f0358bSKent Overstreet 
14720a63b66dSKent Overstreet static int btree_gc_rewrite_node(struct btree *b, struct btree_op *op,
14730a63b66dSKent Overstreet 				 struct btree *replace)
14740a63b66dSKent Overstreet {
14750a63b66dSKent Overstreet 	struct keylist keys;
14760a63b66dSKent Overstreet 	struct btree *n;
14770a63b66dSKent Overstreet 
14780a63b66dSKent Overstreet 	if (btree_check_reserve(b, NULL))
14790a63b66dSKent Overstreet 		return 0;
14800a63b66dSKent Overstreet 
14810a63b66dSKent Overstreet 	n = btree_node_alloc_replacement(replace, NULL);
14820a63b66dSKent Overstreet 
14830a63b66dSKent Overstreet 	/* recheck reserve after allocating replacement node */
14840a63b66dSKent Overstreet 	if (btree_check_reserve(b, NULL)) {
14850a63b66dSKent Overstreet 		btree_node_free(n);
14860a63b66dSKent Overstreet 		rw_unlock(true, n);
14870a63b66dSKent Overstreet 		return 0;
14880a63b66dSKent Overstreet 	}
14890a63b66dSKent Overstreet 
14900a63b66dSKent Overstreet 	bch_btree_node_write_sync(n);
14910a63b66dSKent Overstreet 
14920a63b66dSKent Overstreet 	bch_keylist_init(&keys);
14930a63b66dSKent Overstreet 	bch_keylist_add(&keys, &n->key);
14940a63b66dSKent Overstreet 
14950a63b66dSKent Overstreet 	make_btree_freeing_key(replace, keys.top);
14960a63b66dSKent Overstreet 	bch_keylist_push(&keys);
14970a63b66dSKent Overstreet 
14980a63b66dSKent Overstreet 	bch_btree_insert_node(b, op, &keys, NULL, NULL);
14990a63b66dSKent Overstreet 	BUG_ON(!bch_keylist_empty(&keys));
15000a63b66dSKent Overstreet 
15010a63b66dSKent Overstreet 	btree_node_free(replace);
15020a63b66dSKent Overstreet 	rw_unlock(true, n);
15030a63b66dSKent Overstreet 
15040a63b66dSKent Overstreet 	/* Invalidated our iterator */
15050a63b66dSKent Overstreet 	return -EINTR;
15060a63b66dSKent Overstreet }
15070a63b66dSKent Overstreet 
1508a1f0358bSKent Overstreet static unsigned btree_gc_count_keys(struct btree *b)
1509a1f0358bSKent Overstreet {
1510a1f0358bSKent Overstreet 	struct bkey *k;
1511a1f0358bSKent Overstreet 	struct btree_iter iter;
1512a1f0358bSKent Overstreet 	unsigned ret = 0;
1513a1f0358bSKent Overstreet 
1514c052dd9aSKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_bad)
1515a1f0358bSKent Overstreet 		ret += bkey_u64s(k);
1516a1f0358bSKent Overstreet 
1517a1f0358bSKent Overstreet 	return ret;
1518cafe5635SKent Overstreet }
1519cafe5635SKent Overstreet 
1520cafe5635SKent Overstreet static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1521cafe5635SKent Overstreet 			    struct closure *writes, struct gc_stat *gc)
1522cafe5635SKent Overstreet {
1523a1f0358bSKent Overstreet 	int ret = 0;
1524a1f0358bSKent Overstreet 	bool should_rewrite;
1525a1f0358bSKent Overstreet 	struct bkey *k;
1526a1f0358bSKent Overstreet 	struct btree_iter iter;
1527cafe5635SKent Overstreet 	struct gc_merge_info r[GC_MERGE_NODES];
15282a285686SKent Overstreet 	struct gc_merge_info *i, *last = r + ARRAY_SIZE(r) - 1;
1529cafe5635SKent Overstreet 
1530c052dd9aSKent Overstreet 	bch_btree_iter_init(&b->keys, &iter, &b->c->gc_done);
1531cafe5635SKent Overstreet 
15322a285686SKent Overstreet 	for (i = r; i < r + ARRAY_SIZE(r); i++)
15332a285686SKent Overstreet 		i->b = ERR_PTR(-EINTR);
1534cafe5635SKent Overstreet 
1535a1f0358bSKent Overstreet 	while (1) {
1536a85e968eSKent Overstreet 		k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad);
1537a1f0358bSKent Overstreet 		if (k) {
15380a63b66dSKent Overstreet 			r->b = bch_btree_node_get(b->c, op, k, b->level - 1,
15392452cc89SSlava Pestov 						  true, b);
1540cafe5635SKent Overstreet 			if (IS_ERR(r->b)) {
1541cafe5635SKent Overstreet 				ret = PTR_ERR(r->b);
1542cafe5635SKent Overstreet 				break;
1543cafe5635SKent Overstreet 			}
1544cafe5635SKent Overstreet 
1545a1f0358bSKent Overstreet 			r->keys = btree_gc_count_keys(r->b);
1546cafe5635SKent Overstreet 
15470a63b66dSKent Overstreet 			ret = btree_gc_coalesce(b, op, gc, r);
1548a1f0358bSKent Overstreet 			if (ret)
1549cafe5635SKent Overstreet 				break;
1550cafe5635SKent Overstreet 		}
1551cafe5635SKent Overstreet 
1552a1f0358bSKent Overstreet 		if (!last->b)
1553a1f0358bSKent Overstreet 			break;
1554cafe5635SKent Overstreet 
1555a1f0358bSKent Overstreet 		if (!IS_ERR(last->b)) {
1556a1f0358bSKent Overstreet 			should_rewrite = btree_gc_mark_node(last->b, gc);
15570a63b66dSKent Overstreet 			if (should_rewrite) {
15580a63b66dSKent Overstreet 				ret = btree_gc_rewrite_node(b, op, last->b);
15590a63b66dSKent Overstreet 				if (ret)
1560a1f0358bSKent Overstreet 					break;
1561a1f0358bSKent Overstreet 			}
1562a1f0358bSKent Overstreet 
1563a1f0358bSKent Overstreet 			if (last->b->level) {
1564a1f0358bSKent Overstreet 				ret = btree_gc_recurse(last->b, op, writes, gc);
1565a1f0358bSKent Overstreet 				if (ret)
1566a1f0358bSKent Overstreet 					break;
1567a1f0358bSKent Overstreet 			}
1568a1f0358bSKent Overstreet 
1569a1f0358bSKent Overstreet 			bkey_copy_key(&b->c->gc_done, &last->b->key);
1570a1f0358bSKent Overstreet 
1571a1f0358bSKent Overstreet 			/*
1572a1f0358bSKent Overstreet 			 * Must flush leaf nodes before gc ends, since replace
1573a1f0358bSKent Overstreet 			 * operations aren't journalled
1574cafe5635SKent Overstreet 			 */
15752a285686SKent Overstreet 			mutex_lock(&last->b->write_lock);
1576a1f0358bSKent Overstreet 			if (btree_node_dirty(last->b))
1577a1f0358bSKent Overstreet 				bch_btree_node_write(last->b, writes);
15782a285686SKent Overstreet 			mutex_unlock(&last->b->write_lock);
1579a1f0358bSKent Overstreet 			rw_unlock(true, last->b);
1580a1f0358bSKent Overstreet 		}
1581a1f0358bSKent Overstreet 
1582a1f0358bSKent Overstreet 		memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1583a1f0358bSKent Overstreet 		r->b = NULL;
1584a1f0358bSKent Overstreet 
1585cafe5635SKent Overstreet 		if (need_resched()) {
1586cafe5635SKent Overstreet 			ret = -EAGAIN;
1587cafe5635SKent Overstreet 			break;
1588cafe5635SKent Overstreet 		}
1589cafe5635SKent Overstreet 	}
1590cafe5635SKent Overstreet 
15912a285686SKent Overstreet 	for (i = r; i < r + ARRAY_SIZE(r); i++)
15922a285686SKent Overstreet 		if (!IS_ERR_OR_NULL(i->b)) {
15932a285686SKent Overstreet 			mutex_lock(&i->b->write_lock);
15942a285686SKent Overstreet 			if (btree_node_dirty(i->b))
15952a285686SKent Overstreet 				bch_btree_node_write(i->b, writes);
15962a285686SKent Overstreet 			mutex_unlock(&i->b->write_lock);
15972a285686SKent Overstreet 			rw_unlock(true, i->b);
1598a1f0358bSKent Overstreet 		}
1599cafe5635SKent Overstreet 
1600cafe5635SKent Overstreet 	return ret;
1601cafe5635SKent Overstreet }
1602cafe5635SKent Overstreet 
1603cafe5635SKent Overstreet static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1604cafe5635SKent Overstreet 			     struct closure *writes, struct gc_stat *gc)
1605cafe5635SKent Overstreet {
1606cafe5635SKent Overstreet 	struct btree *n = NULL;
1607a1f0358bSKent Overstreet 	int ret = 0;
1608a1f0358bSKent Overstreet 	bool should_rewrite;
1609cafe5635SKent Overstreet 
1610a1f0358bSKent Overstreet 	should_rewrite = btree_gc_mark_node(b, gc);
1611a1f0358bSKent Overstreet 	if (should_rewrite) {
16120a63b66dSKent Overstreet 		n = btree_node_alloc_replacement(b, NULL);
1613cafe5635SKent Overstreet 
1614cafe5635SKent Overstreet 		if (!IS_ERR_OR_NULL(n)) {
1615a1f0358bSKent Overstreet 			bch_btree_node_write_sync(n);
16162a285686SKent Overstreet 
1617a1f0358bSKent Overstreet 			bch_btree_set_root(n);
1618a1f0358bSKent Overstreet 			btree_node_free(b);
1619a1f0358bSKent Overstreet 			rw_unlock(true, n);
1620a1f0358bSKent Overstreet 
1621a1f0358bSKent Overstreet 			return -EINTR;
1622cafe5635SKent Overstreet 		}
1623a1f0358bSKent Overstreet 	}
1624a1f0358bSKent Overstreet 
1625487dded8SKent Overstreet 	__bch_btree_mark_key(b->c, b->level + 1, &b->key);
1626487dded8SKent Overstreet 
1627a1f0358bSKent Overstreet 	if (b->level) {
1628a1f0358bSKent Overstreet 		ret = btree_gc_recurse(b, op, writes, gc);
1629a1f0358bSKent Overstreet 		if (ret)
1630a1f0358bSKent Overstreet 			return ret;
1631a1f0358bSKent Overstreet 	}
1632a1f0358bSKent Overstreet 
1633a1f0358bSKent Overstreet 	bkey_copy_key(&b->c->gc_done, &b->key);
1634cafe5635SKent Overstreet 
1635cafe5635SKent Overstreet 	return ret;
1636cafe5635SKent Overstreet }
1637cafe5635SKent Overstreet 
1638cafe5635SKent Overstreet static void btree_gc_start(struct cache_set *c)
1639cafe5635SKent Overstreet {
1640cafe5635SKent Overstreet 	struct cache *ca;
1641cafe5635SKent Overstreet 	struct bucket *b;
1642cafe5635SKent Overstreet 	unsigned i;
1643cafe5635SKent Overstreet 
1644cafe5635SKent Overstreet 	if (!c->gc_mark_valid)
1645cafe5635SKent Overstreet 		return;
1646cafe5635SKent Overstreet 
1647cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1648cafe5635SKent Overstreet 
1649cafe5635SKent Overstreet 	c->gc_mark_valid = 0;
1650cafe5635SKent Overstreet 	c->gc_done = ZERO_KEY;
1651cafe5635SKent Overstreet 
1652cafe5635SKent Overstreet 	for_each_cache(ca, c, i)
1653cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
16543a2fd9d5SKent Overstreet 			b->last_gc = b->gen;
165529ebf465SKent Overstreet 			if (!atomic_read(&b->pin)) {
16564fe6a816SKent Overstreet 				SET_GC_MARK(b, 0);
165729ebf465SKent Overstreet 				SET_GC_SECTORS_USED(b, 0);
165829ebf465SKent Overstreet 			}
1659cafe5635SKent Overstreet 		}
1660cafe5635SKent Overstreet 
1661cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1662cafe5635SKent Overstreet }
1663cafe5635SKent Overstreet 
1664d44c2f9eSTang Junhui static void bch_btree_gc_finish(struct cache_set *c)
1665cafe5635SKent Overstreet {
1666cafe5635SKent Overstreet 	struct bucket *b;
1667cafe5635SKent Overstreet 	struct cache *ca;
1668cafe5635SKent Overstreet 	unsigned i;
1669cafe5635SKent Overstreet 
1670cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1671cafe5635SKent Overstreet 
1672cafe5635SKent Overstreet 	set_gc_sectors(c);
1673cafe5635SKent Overstreet 	c->gc_mark_valid = 1;
1674cafe5635SKent Overstreet 	c->need_gc	= 0;
1675cafe5635SKent Overstreet 
1676cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1677cafe5635SKent Overstreet 		SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1678cafe5635SKent Overstreet 			    GC_MARK_METADATA);
1679cafe5635SKent Overstreet 
1680bf0a628aSNicholas Swenson 	/* don't reclaim buckets to which writeback keys point */
1681bf0a628aSNicholas Swenson 	rcu_read_lock();
1682*2831231dSColy Li 	for (i = 0; i < c->devices_max_used; i++) {
1683bf0a628aSNicholas Swenson 		struct bcache_device *d = c->devices[i];
1684bf0a628aSNicholas Swenson 		struct cached_dev *dc;
1685bf0a628aSNicholas Swenson 		struct keybuf_key *w, *n;
1686bf0a628aSNicholas Swenson 		unsigned j;
1687bf0a628aSNicholas Swenson 
1688bf0a628aSNicholas Swenson 		if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
1689bf0a628aSNicholas Swenson 			continue;
1690bf0a628aSNicholas Swenson 		dc = container_of(d, struct cached_dev, disk);
1691bf0a628aSNicholas Swenson 
1692bf0a628aSNicholas Swenson 		spin_lock(&dc->writeback_keys.lock);
1693bf0a628aSNicholas Swenson 		rbtree_postorder_for_each_entry_safe(w, n,
1694bf0a628aSNicholas Swenson 					&dc->writeback_keys.keys, node)
1695bf0a628aSNicholas Swenson 			for (j = 0; j < KEY_PTRS(&w->key); j++)
1696bf0a628aSNicholas Swenson 				SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
1697bf0a628aSNicholas Swenson 					    GC_MARK_DIRTY);
1698bf0a628aSNicholas Swenson 		spin_unlock(&dc->writeback_keys.lock);
1699bf0a628aSNicholas Swenson 	}
1700bf0a628aSNicholas Swenson 	rcu_read_unlock();
1701bf0a628aSNicholas Swenson 
1702d44c2f9eSTang Junhui 	c->avail_nbuckets = 0;
1703cafe5635SKent Overstreet 	for_each_cache(ca, c, i) {
1704cafe5635SKent Overstreet 		uint64_t *i;
1705cafe5635SKent Overstreet 
1706cafe5635SKent Overstreet 		ca->invalidate_needs_gc = 0;
1707cafe5635SKent Overstreet 
1708cafe5635SKent Overstreet 		for (i = ca->sb.d; i < ca->sb.d + ca->sb.keys; i++)
1709cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1710cafe5635SKent Overstreet 
1711cafe5635SKent Overstreet 		for (i = ca->prio_buckets;
1712cafe5635SKent Overstreet 		     i < ca->prio_buckets + prio_buckets(ca) * 2; i++)
1713cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1714cafe5635SKent Overstreet 
1715cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1716cafe5635SKent Overstreet 			c->need_gc	= max(c->need_gc, bucket_gc_gen(b));
1717cafe5635SKent Overstreet 
17184fe6a816SKent Overstreet 			if (atomic_read(&b->pin))
17194fe6a816SKent Overstreet 				continue;
17204fe6a816SKent Overstreet 
17214fe6a816SKent Overstreet 			BUG_ON(!GC_MARK(b) && GC_SECTORS_USED(b));
17224fe6a816SKent Overstreet 
17234fe6a816SKent Overstreet 			if (!GC_MARK(b) || GC_MARK(b) == GC_MARK_RECLAIMABLE)
1724d44c2f9eSTang Junhui 				c->avail_nbuckets++;
1725cafe5635SKent Overstreet 		}
1726cafe5635SKent Overstreet 	}
1727cafe5635SKent Overstreet 
1728cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1729cafe5635SKent Overstreet }
1730cafe5635SKent Overstreet 
173172a44517SKent Overstreet static void bch_btree_gc(struct cache_set *c)
1732cafe5635SKent Overstreet {
1733cafe5635SKent Overstreet 	int ret;
1734cafe5635SKent Overstreet 	struct gc_stat stats;
1735cafe5635SKent Overstreet 	struct closure writes;
1736cafe5635SKent Overstreet 	struct btree_op op;
1737cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
173857943511SKent Overstreet 
1739c37511b8SKent Overstreet 	trace_bcache_gc_start(c);
1740cafe5635SKent Overstreet 
1741cafe5635SKent Overstreet 	memset(&stats, 0, sizeof(struct gc_stat));
1742cafe5635SKent Overstreet 	closure_init_stack(&writes);
1743b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1744cafe5635SKent Overstreet 
1745cafe5635SKent Overstreet 	btree_gc_start(c);
1746cafe5635SKent Overstreet 
1747a1f0358bSKent Overstreet 	do {
1748cafe5635SKent Overstreet 		ret = btree_root(gc_root, c, &op, &writes, &stats);
1749cafe5635SKent Overstreet 		closure_sync(&writes);
1750c5f1e5adSKent Overstreet 		cond_resched();
1751cafe5635SKent Overstreet 
1752a1f0358bSKent Overstreet 		if (ret && ret != -EAGAIN)
1753cafe5635SKent Overstreet 			pr_warn("gc failed!");
1754a1f0358bSKent Overstreet 	} while (ret);
1755cafe5635SKent Overstreet 
1756d44c2f9eSTang Junhui 	bch_btree_gc_finish(c);
175757943511SKent Overstreet 	wake_up_allocators(c);
175857943511SKent Overstreet 
1759169ef1cfSKent Overstreet 	bch_time_stats_update(&c->btree_gc_time, start_time);
1760cafe5635SKent Overstreet 
1761cafe5635SKent Overstreet 	stats.key_bytes *= sizeof(uint64_t);
1762cafe5635SKent Overstreet 	stats.data	<<= 9;
1763d44c2f9eSTang Junhui 	bch_update_bucket_in_use(c, &stats);
1764cafe5635SKent Overstreet 	memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1765cafe5635SKent Overstreet 
1766c37511b8SKent Overstreet 	trace_bcache_gc_end(c);
1767cafe5635SKent Overstreet 
176872a44517SKent Overstreet 	bch_moving_gc(c);
1769cafe5635SKent Overstreet }
1770cafe5635SKent Overstreet 
1771be628be0SKent Overstreet static bool gc_should_run(struct cache_set *c)
1772cafe5635SKent Overstreet {
1773a1f0358bSKent Overstreet 	struct cache *ca;
1774a1f0358bSKent Overstreet 	unsigned i;
177572a44517SKent Overstreet 
1776be628be0SKent Overstreet 	for_each_cache(ca, c, i)
1777be628be0SKent Overstreet 		if (ca->invalidate_needs_gc)
1778be628be0SKent Overstreet 			return true;
177972a44517SKent Overstreet 
1780be628be0SKent Overstreet 	if (atomic_read(&c->sectors_to_gc) < 0)
1781be628be0SKent Overstreet 		return true;
1782be628be0SKent Overstreet 
1783be628be0SKent Overstreet 	return false;
1784be628be0SKent Overstreet }
1785be628be0SKent Overstreet 
1786be628be0SKent Overstreet static int bch_gc_thread(void *arg)
1787be628be0SKent Overstreet {
1788be628be0SKent Overstreet 	struct cache_set *c = arg;
1789be628be0SKent Overstreet 
1790be628be0SKent Overstreet 	while (1) {
1791be628be0SKent Overstreet 		wait_event_interruptible(c->gc_wait,
1792be628be0SKent Overstreet 			   kthread_should_stop() || gc_should_run(c));
1793be628be0SKent Overstreet 
179472a44517SKent Overstreet 		if (kthread_should_stop())
179572a44517SKent Overstreet 			break;
179672a44517SKent Overstreet 
1797be628be0SKent Overstreet 		set_gc_sectors(c);
1798be628be0SKent Overstreet 		bch_btree_gc(c);
179972a44517SKent Overstreet 	}
180072a44517SKent Overstreet 
180172a44517SKent Overstreet 	return 0;
180272a44517SKent Overstreet }
180372a44517SKent Overstreet 
180472a44517SKent Overstreet int bch_gc_thread_start(struct cache_set *c)
180572a44517SKent Overstreet {
1806be628be0SKent Overstreet 	c->gc_thread = kthread_run(bch_gc_thread, c, "bcache_gc");
18079d134117SVasyl Gomonovych 	return PTR_ERR_OR_ZERO(c->gc_thread);
1808cafe5635SKent Overstreet }
1809cafe5635SKent Overstreet 
1810cafe5635SKent Overstreet /* Initial partial gc */
1811cafe5635SKent Overstreet 
1812487dded8SKent Overstreet static int bch_btree_check_recurse(struct btree *b, struct btree_op *op)
1813cafe5635SKent Overstreet {
181450310164SKent Overstreet 	int ret = 0;
181550310164SKent Overstreet 	struct bkey *k, *p = NULL;
1816cafe5635SKent Overstreet 	struct btree_iter iter;
1817cafe5635SKent Overstreet 
1818487dded8SKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid)
1819487dded8SKent Overstreet 		bch_initial_mark_key(b->c, b->level, k);
1820cafe5635SKent Overstreet 
1821487dded8SKent Overstreet 	bch_initial_mark_key(b->c, b->level + 1, &b->key);
1822cafe5635SKent Overstreet 
1823cafe5635SKent Overstreet 	if (b->level) {
1824c052dd9aSKent Overstreet 		bch_btree_iter_init(&b->keys, &iter, NULL);
1825cafe5635SKent Overstreet 
182650310164SKent Overstreet 		do {
1827a85e968eSKent Overstreet 			k = bch_btree_iter_next_filter(&iter, &b->keys,
1828a85e968eSKent Overstreet 						       bch_ptr_bad);
182950310164SKent Overstreet 			if (k)
18302452cc89SSlava Pestov 				btree_node_prefetch(b, k);
183150310164SKent Overstreet 
1832cafe5635SKent Overstreet 			if (p)
1833487dded8SKent Overstreet 				ret = btree(check_recurse, p, b, op);
1834cafe5635SKent Overstreet 
183550310164SKent Overstreet 			p = k;
183650310164SKent Overstreet 		} while (p && !ret);
1837cafe5635SKent Overstreet 	}
1838cafe5635SKent Overstreet 
1839487dded8SKent Overstreet 	return ret;
1840cafe5635SKent Overstreet }
1841cafe5635SKent Overstreet 
1842c18536a7SKent Overstreet int bch_btree_check(struct cache_set *c)
1843cafe5635SKent Overstreet {
1844c18536a7SKent Overstreet 	struct btree_op op;
1845cafe5635SKent Overstreet 
1846b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1847cafe5635SKent Overstreet 
1848487dded8SKent Overstreet 	return btree_root(check_recurse, c, &op);
1849cafe5635SKent Overstreet }
1850cafe5635SKent Overstreet 
18512531d9eeSKent Overstreet void bch_initial_gc_finish(struct cache_set *c)
18522531d9eeSKent Overstreet {
18532531d9eeSKent Overstreet 	struct cache *ca;
18542531d9eeSKent Overstreet 	struct bucket *b;
18552531d9eeSKent Overstreet 	unsigned i;
18562531d9eeSKent Overstreet 
18572531d9eeSKent Overstreet 	bch_btree_gc_finish(c);
18582531d9eeSKent Overstreet 
18592531d9eeSKent Overstreet 	mutex_lock(&c->bucket_lock);
18602531d9eeSKent Overstreet 
18612531d9eeSKent Overstreet 	/*
18622531d9eeSKent Overstreet 	 * We need to put some unused buckets directly on the prio freelist in
18632531d9eeSKent Overstreet 	 * order to get the allocator thread started - it needs freed buckets in
18642531d9eeSKent Overstreet 	 * order to rewrite the prios and gens, and it needs to rewrite prios
18652531d9eeSKent Overstreet 	 * and gens in order to free buckets.
18662531d9eeSKent Overstreet 	 *
18672531d9eeSKent Overstreet 	 * This is only safe for buckets that have no live data in them, which
18682531d9eeSKent Overstreet 	 * there should always be some of.
18692531d9eeSKent Overstreet 	 */
18702531d9eeSKent Overstreet 	for_each_cache(ca, c, i) {
18712531d9eeSKent Overstreet 		for_each_bucket(b, ca) {
18722531d9eeSKent Overstreet 			if (fifo_full(&ca->free[RESERVE_PRIO]))
18732531d9eeSKent Overstreet 				break;
18742531d9eeSKent Overstreet 
18752531d9eeSKent Overstreet 			if (bch_can_invalidate_bucket(ca, b) &&
18762531d9eeSKent Overstreet 			    !GC_MARK(b)) {
18772531d9eeSKent Overstreet 				__bch_invalidate_one_bucket(ca, b);
18782531d9eeSKent Overstreet 				fifo_push(&ca->free[RESERVE_PRIO],
18792531d9eeSKent Overstreet 					  b - ca->buckets);
18802531d9eeSKent Overstreet 			}
18812531d9eeSKent Overstreet 		}
18822531d9eeSKent Overstreet 	}
18832531d9eeSKent Overstreet 
18842531d9eeSKent Overstreet 	mutex_unlock(&c->bucket_lock);
18852531d9eeSKent Overstreet }
18862531d9eeSKent Overstreet 
1887cafe5635SKent Overstreet /* Btree insertion */
1888cafe5635SKent Overstreet 
1889829a60b9SKent Overstreet static bool btree_insert_key(struct btree *b, struct bkey *k,
18901b207d80SKent Overstreet 			     struct bkey *replace_key)
1891cafe5635SKent Overstreet {
1892829a60b9SKent Overstreet 	unsigned status;
1893cafe5635SKent Overstreet 
1894cafe5635SKent Overstreet 	BUG_ON(bkey_cmp(k, &b->key) > 0);
1895cafe5635SKent Overstreet 
1896829a60b9SKent Overstreet 	status = bch_btree_insert_key(&b->keys, k, replace_key);
1897829a60b9SKent Overstreet 	if (status != BTREE_INSERT_STATUS_NO_INSERT) {
1898dc9d98d6SKent Overstreet 		bch_check_keys(&b->keys, "%u for %s", status,
18991b207d80SKent Overstreet 			       replace_key ? "replace" : "insert");
1900cafe5635SKent Overstreet 
1901829a60b9SKent Overstreet 		trace_bcache_btree_insert_key(b, k, replace_key != NULL,
1902829a60b9SKent Overstreet 					      status);
1903cafe5635SKent Overstreet 		return true;
1904829a60b9SKent Overstreet 	} else
1905829a60b9SKent Overstreet 		return false;
1906cafe5635SKent Overstreet }
1907cafe5635SKent Overstreet 
190859158fdeSKent Overstreet static size_t insert_u64s_remaining(struct btree *b)
190959158fdeSKent Overstreet {
19103572324aSKent Overstreet 	long ret = bch_btree_keys_u64s_remaining(&b->keys);
191159158fdeSKent Overstreet 
191259158fdeSKent Overstreet 	/*
191359158fdeSKent Overstreet 	 * Might land in the middle of an existing extent and have to split it
191459158fdeSKent Overstreet 	 */
191559158fdeSKent Overstreet 	if (b->keys.ops->is_extents)
191659158fdeSKent Overstreet 		ret -= KEY_MAX_U64S;
191759158fdeSKent Overstreet 
191859158fdeSKent Overstreet 	return max(ret, 0L);
191959158fdeSKent Overstreet }
192059158fdeSKent Overstreet 
192126c949f8SKent Overstreet static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
19221b207d80SKent Overstreet 				  struct keylist *insert_keys,
19231b207d80SKent Overstreet 				  struct bkey *replace_key)
1924cafe5635SKent Overstreet {
1925cafe5635SKent Overstreet 	bool ret = false;
1926dc9d98d6SKent Overstreet 	int oldsize = bch_count_data(&b->keys);
1927cafe5635SKent Overstreet 
192826c949f8SKent Overstreet 	while (!bch_keylist_empty(insert_keys)) {
1929c2f95ae2SKent Overstreet 		struct bkey *k = insert_keys->keys;
193026c949f8SKent Overstreet 
193159158fdeSKent Overstreet 		if (bkey_u64s(k) > insert_u64s_remaining(b))
1932403b6cdeSKent Overstreet 			break;
1933403b6cdeSKent Overstreet 
1934403b6cdeSKent Overstreet 		if (bkey_cmp(k, &b->key) <= 0) {
19353a3b6a4eSKent Overstreet 			if (!b->level)
19363a3b6a4eSKent Overstreet 				bkey_put(b->c, k);
193726c949f8SKent Overstreet 
1938829a60b9SKent Overstreet 			ret |= btree_insert_key(b, k, replace_key);
193926c949f8SKent Overstreet 			bch_keylist_pop_front(insert_keys);
194026c949f8SKent Overstreet 		} else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
194126c949f8SKent Overstreet 			BKEY_PADDED(key) temp;
1942c2f95ae2SKent Overstreet 			bkey_copy(&temp.key, insert_keys->keys);
194326c949f8SKent Overstreet 
194426c949f8SKent Overstreet 			bch_cut_back(&b->key, &temp.key);
1945c2f95ae2SKent Overstreet 			bch_cut_front(&b->key, insert_keys->keys);
194626c949f8SKent Overstreet 
1947829a60b9SKent Overstreet 			ret |= btree_insert_key(b, &temp.key, replace_key);
194826c949f8SKent Overstreet 			break;
194926c949f8SKent Overstreet 		} else {
195026c949f8SKent Overstreet 			break;
195126c949f8SKent Overstreet 		}
1952cafe5635SKent Overstreet 	}
1953cafe5635SKent Overstreet 
1954829a60b9SKent Overstreet 	if (!ret)
1955829a60b9SKent Overstreet 		op->insert_collision = true;
1956829a60b9SKent Overstreet 
1957403b6cdeSKent Overstreet 	BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
1958403b6cdeSKent Overstreet 
1959dc9d98d6SKent Overstreet 	BUG_ON(bch_count_data(&b->keys) < oldsize);
1960cafe5635SKent Overstreet 	return ret;
1961cafe5635SKent Overstreet }
1962cafe5635SKent Overstreet 
196326c949f8SKent Overstreet static int btree_split(struct btree *b, struct btree_op *op,
196426c949f8SKent Overstreet 		       struct keylist *insert_keys,
19651b207d80SKent Overstreet 		       struct bkey *replace_key)
1966cafe5635SKent Overstreet {
1967d6fd3b11SKent Overstreet 	bool split;
1968cafe5635SKent Overstreet 	struct btree *n1, *n2 = NULL, *n3 = NULL;
1969cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
1970b54d6934SKent Overstreet 	struct closure cl;
197117e21a9fSKent Overstreet 	struct keylist parent_keys;
1972b54d6934SKent Overstreet 
1973b54d6934SKent Overstreet 	closure_init_stack(&cl);
197417e21a9fSKent Overstreet 	bch_keylist_init(&parent_keys);
1975cafe5635SKent Overstreet 
19760a63b66dSKent Overstreet 	if (btree_check_reserve(b, op)) {
19770a63b66dSKent Overstreet 		if (!b->level)
197878365411SKent Overstreet 			return -EINTR;
19790a63b66dSKent Overstreet 		else
19800a63b66dSKent Overstreet 			WARN(1, "insufficient reserve for split\n");
19810a63b66dSKent Overstreet 	}
198278365411SKent Overstreet 
19830a63b66dSKent Overstreet 	n1 = btree_node_alloc_replacement(b, op);
1984cafe5635SKent Overstreet 	if (IS_ERR(n1))
1985cafe5635SKent Overstreet 		goto err;
1986cafe5635SKent Overstreet 
1987ee811287SKent Overstreet 	split = set_blocks(btree_bset_first(n1),
1988ee811287SKent Overstreet 			   block_bytes(n1->c)) > (btree_blocks(b) * 4) / 5;
1989cafe5635SKent Overstreet 
1990cafe5635SKent Overstreet 	if (split) {
1991cafe5635SKent Overstreet 		unsigned keys = 0;
1992cafe5635SKent Overstreet 
1993ee811287SKent Overstreet 		trace_bcache_btree_node_split(b, btree_bset_first(n1)->keys);
1994c37511b8SKent Overstreet 
19952452cc89SSlava Pestov 		n2 = bch_btree_node_alloc(b->c, op, b->level, b->parent);
1996cafe5635SKent Overstreet 		if (IS_ERR(n2))
1997cafe5635SKent Overstreet 			goto err_free1;
1998cafe5635SKent Overstreet 
1999d6fd3b11SKent Overstreet 		if (!b->parent) {
20002452cc89SSlava Pestov 			n3 = bch_btree_node_alloc(b->c, op, b->level + 1, NULL);
2001cafe5635SKent Overstreet 			if (IS_ERR(n3))
2002cafe5635SKent Overstreet 				goto err_free2;
2003cafe5635SKent Overstreet 		}
2004cafe5635SKent Overstreet 
20052a285686SKent Overstreet 		mutex_lock(&n1->write_lock);
20062a285686SKent Overstreet 		mutex_lock(&n2->write_lock);
20072a285686SKent Overstreet 
20081b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2009cafe5635SKent Overstreet 
2010d6fd3b11SKent Overstreet 		/*
2011d6fd3b11SKent Overstreet 		 * Has to be a linear search because we don't have an auxiliary
2012cafe5635SKent Overstreet 		 * search tree yet
2013cafe5635SKent Overstreet 		 */
2014cafe5635SKent Overstreet 
2015ee811287SKent Overstreet 		while (keys < (btree_bset_first(n1)->keys * 3) / 5)
2016ee811287SKent Overstreet 			keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1),
2017fafff81cSKent Overstreet 							keys));
2018cafe5635SKent Overstreet 
2019fafff81cSKent Overstreet 		bkey_copy_key(&n1->key,
2020ee811287SKent Overstreet 			      bset_bkey_idx(btree_bset_first(n1), keys));
2021ee811287SKent Overstreet 		keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1), keys));
2022cafe5635SKent Overstreet 
2023ee811287SKent Overstreet 		btree_bset_first(n2)->keys = btree_bset_first(n1)->keys - keys;
2024ee811287SKent Overstreet 		btree_bset_first(n1)->keys = keys;
2025cafe5635SKent Overstreet 
2026ee811287SKent Overstreet 		memcpy(btree_bset_first(n2)->start,
2027ee811287SKent Overstreet 		       bset_bkey_last(btree_bset_first(n1)),
2028ee811287SKent Overstreet 		       btree_bset_first(n2)->keys * sizeof(uint64_t));
2029cafe5635SKent Overstreet 
2030cafe5635SKent Overstreet 		bkey_copy_key(&n2->key, &b->key);
2031cafe5635SKent Overstreet 
203217e21a9fSKent Overstreet 		bch_keylist_add(&parent_keys, &n2->key);
2033b54d6934SKent Overstreet 		bch_btree_node_write(n2, &cl);
20342a285686SKent Overstreet 		mutex_unlock(&n2->write_lock);
2035cafe5635SKent Overstreet 		rw_unlock(true, n2);
2036c37511b8SKent Overstreet 	} else {
2037ee811287SKent Overstreet 		trace_bcache_btree_node_compact(b, btree_bset_first(n1)->keys);
2038c37511b8SKent Overstreet 
20392a285686SKent Overstreet 		mutex_lock(&n1->write_lock);
20401b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2041c37511b8SKent Overstreet 	}
2042cafe5635SKent Overstreet 
204317e21a9fSKent Overstreet 	bch_keylist_add(&parent_keys, &n1->key);
2044b54d6934SKent Overstreet 	bch_btree_node_write(n1, &cl);
20452a285686SKent Overstreet 	mutex_unlock(&n1->write_lock);
2046cafe5635SKent Overstreet 
2047cafe5635SKent Overstreet 	if (n3) {
2048d6fd3b11SKent Overstreet 		/* Depth increases, make a new root */
20492a285686SKent Overstreet 		mutex_lock(&n3->write_lock);
2050cafe5635SKent Overstreet 		bkey_copy_key(&n3->key, &MAX_KEY);
205117e21a9fSKent Overstreet 		bch_btree_insert_keys(n3, op, &parent_keys, NULL);
2052b54d6934SKent Overstreet 		bch_btree_node_write(n3, &cl);
20532a285686SKent Overstreet 		mutex_unlock(&n3->write_lock);
2054cafe5635SKent Overstreet 
2055b54d6934SKent Overstreet 		closure_sync(&cl);
2056cafe5635SKent Overstreet 		bch_btree_set_root(n3);
2057cafe5635SKent Overstreet 		rw_unlock(true, n3);
2058d6fd3b11SKent Overstreet 	} else if (!b->parent) {
2059d6fd3b11SKent Overstreet 		/* Root filled up but didn't need to be split */
2060b54d6934SKent Overstreet 		closure_sync(&cl);
2061cafe5635SKent Overstreet 		bch_btree_set_root(n1);
2062cafe5635SKent Overstreet 	} else {
206317e21a9fSKent Overstreet 		/* Split a non root node */
2064b54d6934SKent Overstreet 		closure_sync(&cl);
206517e21a9fSKent Overstreet 		make_btree_freeing_key(b, parent_keys.top);
206617e21a9fSKent Overstreet 		bch_keylist_push(&parent_keys);
206717e21a9fSKent Overstreet 
206817e21a9fSKent Overstreet 		bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
206917e21a9fSKent Overstreet 		BUG_ON(!bch_keylist_empty(&parent_keys));
2070cafe5635SKent Overstreet 	}
2071cafe5635SKent Overstreet 
207205335cffSKent Overstreet 	btree_node_free(b);
2073cafe5635SKent Overstreet 	rw_unlock(true, n1);
2074cafe5635SKent Overstreet 
2075169ef1cfSKent Overstreet 	bch_time_stats_update(&b->c->btree_split_time, start_time);
2076cafe5635SKent Overstreet 
2077cafe5635SKent Overstreet 	return 0;
2078cafe5635SKent Overstreet err_free2:
20795f5837d2SKent Overstreet 	bkey_put(b->c, &n2->key);
2080e8e1d468SKent Overstreet 	btree_node_free(n2);
2081cafe5635SKent Overstreet 	rw_unlock(true, n2);
2082cafe5635SKent Overstreet err_free1:
20835f5837d2SKent Overstreet 	bkey_put(b->c, &n1->key);
2084e8e1d468SKent Overstreet 	btree_node_free(n1);
2085cafe5635SKent Overstreet 	rw_unlock(true, n1);
2086cafe5635SKent Overstreet err:
20870a63b66dSKent Overstreet 	WARN(1, "bcache: btree split failed (level %u)", b->level);
20885f5837d2SKent Overstreet 
2089cafe5635SKent Overstreet 	if (n3 == ERR_PTR(-EAGAIN) ||
2090cafe5635SKent Overstreet 	    n2 == ERR_PTR(-EAGAIN) ||
2091cafe5635SKent Overstreet 	    n1 == ERR_PTR(-EAGAIN))
2092cafe5635SKent Overstreet 		return -EAGAIN;
2093cafe5635SKent Overstreet 
2094cafe5635SKent Overstreet 	return -ENOMEM;
2095cafe5635SKent Overstreet }
2096cafe5635SKent Overstreet 
209726c949f8SKent Overstreet static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
2098c18536a7SKent Overstreet 				 struct keylist *insert_keys,
20991b207d80SKent Overstreet 				 atomic_t *journal_ref,
21001b207d80SKent Overstreet 				 struct bkey *replace_key)
210126c949f8SKent Overstreet {
21022a285686SKent Overstreet 	struct closure cl;
21032a285686SKent Overstreet 
21041b207d80SKent Overstreet 	BUG_ON(b->level && replace_key);
21051b207d80SKent Overstreet 
21062a285686SKent Overstreet 	closure_init_stack(&cl);
21072a285686SKent Overstreet 
21082a285686SKent Overstreet 	mutex_lock(&b->write_lock);
21092a285686SKent Overstreet 
21102a285686SKent Overstreet 	if (write_block(b) != btree_bset_last(b) &&
21112a285686SKent Overstreet 	    b->keys.last_set_unwritten)
21122a285686SKent Overstreet 		bch_btree_init_next(b); /* just wrote a set */
21132a285686SKent Overstreet 
211459158fdeSKent Overstreet 	if (bch_keylist_nkeys(insert_keys) > insert_u64s_remaining(b)) {
21152a285686SKent Overstreet 		mutex_unlock(&b->write_lock);
21162a285686SKent Overstreet 		goto split;
21172a285686SKent Overstreet 	}
21182a285686SKent Overstreet 
21192a285686SKent Overstreet 	BUG_ON(write_block(b) != btree_bset_last(b));
21202a285686SKent Overstreet 
21212a285686SKent Overstreet 	if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
21222a285686SKent Overstreet 		if (!b->level)
21232a285686SKent Overstreet 			bch_btree_leaf_dirty(b, journal_ref);
21242a285686SKent Overstreet 		else
21252a285686SKent Overstreet 			bch_btree_node_write(b, &cl);
21262a285686SKent Overstreet 	}
21272a285686SKent Overstreet 
21282a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
21292a285686SKent Overstreet 
21302a285686SKent Overstreet 	/* wait for btree node write if necessary, after unlock */
21312a285686SKent Overstreet 	closure_sync(&cl);
21322a285686SKent Overstreet 
21332a285686SKent Overstreet 	return 0;
21342a285686SKent Overstreet split:
213526c949f8SKent Overstreet 	if (current->bio_list) {
213626c949f8SKent Overstreet 		op->lock = b->c->root->level + 1;
213717e21a9fSKent Overstreet 		return -EAGAIN;
213826c949f8SKent Overstreet 	} else if (op->lock <= b->c->root->level) {
213926c949f8SKent Overstreet 		op->lock = b->c->root->level + 1;
214017e21a9fSKent Overstreet 		return -EINTR;
214126c949f8SKent Overstreet 	} else {
214217e21a9fSKent Overstreet 		/* Invalidated all iterators */
21433b3e9e50SKent Overstreet 		int ret = btree_split(b, op, insert_keys, replace_key);
21443b3e9e50SKent Overstreet 
21452a285686SKent Overstreet 		if (bch_keylist_empty(insert_keys))
214617e21a9fSKent Overstreet 			return 0;
21472a285686SKent Overstreet 		else if (!ret)
21482a285686SKent Overstreet 			return -EINTR;
21492a285686SKent Overstreet 		return ret;
215017e21a9fSKent Overstreet 	}
215126c949f8SKent Overstreet }
215226c949f8SKent Overstreet 
2153e7c590ebSKent Overstreet int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2154e7c590ebSKent Overstreet 			       struct bkey *check_key)
2155e7c590ebSKent Overstreet {
2156e7c590ebSKent Overstreet 	int ret = -EINTR;
2157e7c590ebSKent Overstreet 	uint64_t btree_ptr = b->key.ptr[0];
2158e7c590ebSKent Overstreet 	unsigned long seq = b->seq;
2159e7c590ebSKent Overstreet 	struct keylist insert;
2160e7c590ebSKent Overstreet 	bool upgrade = op->lock == -1;
2161e7c590ebSKent Overstreet 
2162e7c590ebSKent Overstreet 	bch_keylist_init(&insert);
2163e7c590ebSKent Overstreet 
2164e7c590ebSKent Overstreet 	if (upgrade) {
2165e7c590ebSKent Overstreet 		rw_unlock(false, b);
2166e7c590ebSKent Overstreet 		rw_lock(true, b, b->level);
2167e7c590ebSKent Overstreet 
2168e7c590ebSKent Overstreet 		if (b->key.ptr[0] != btree_ptr ||
21692ef9ccbfSZheng Liu                    b->seq != seq + 1) {
21702ef9ccbfSZheng Liu                        op->lock = b->level;
2171e7c590ebSKent Overstreet 			goto out;
2172e7c590ebSKent Overstreet                }
21732ef9ccbfSZheng Liu 	}
2174e7c590ebSKent Overstreet 
2175e7c590ebSKent Overstreet 	SET_KEY_PTRS(check_key, 1);
2176e7c590ebSKent Overstreet 	get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2177e7c590ebSKent Overstreet 
2178e7c590ebSKent Overstreet 	SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2179e7c590ebSKent Overstreet 
2180e7c590ebSKent Overstreet 	bch_keylist_add(&insert, check_key);
2181e7c590ebSKent Overstreet 
21821b207d80SKent Overstreet 	ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2183e7c590ebSKent Overstreet 
2184e7c590ebSKent Overstreet 	BUG_ON(!ret && !bch_keylist_empty(&insert));
2185e7c590ebSKent Overstreet out:
2186e7c590ebSKent Overstreet 	if (upgrade)
2187e7c590ebSKent Overstreet 		downgrade_write(&b->lock);
2188e7c590ebSKent Overstreet 	return ret;
2189e7c590ebSKent Overstreet }
2190e7c590ebSKent Overstreet 
2191cc7b8819SKent Overstreet struct btree_insert_op {
2192cc7b8819SKent Overstreet 	struct btree_op	op;
2193cc7b8819SKent Overstreet 	struct keylist	*keys;
2194cc7b8819SKent Overstreet 	atomic_t	*journal_ref;
2195cc7b8819SKent Overstreet 	struct bkey	*replace_key;
2196cc7b8819SKent Overstreet };
2197cc7b8819SKent Overstreet 
219808239ca2SWei Yongjun static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2199cafe5635SKent Overstreet {
2200cc7b8819SKent Overstreet 	struct btree_insert_op *op = container_of(b_op,
2201cc7b8819SKent Overstreet 					struct btree_insert_op, op);
2202403b6cdeSKent Overstreet 
2203cc7b8819SKent Overstreet 	int ret = bch_btree_insert_node(b, &op->op, op->keys,
2204cc7b8819SKent Overstreet 					op->journal_ref, op->replace_key);
2205cc7b8819SKent Overstreet 	if (ret && !bch_keylist_empty(op->keys))
2206cc7b8819SKent Overstreet 		return ret;
2207cc7b8819SKent Overstreet 	else
2208cc7b8819SKent Overstreet 		return MAP_DONE;
2209cafe5635SKent Overstreet }
2210cafe5635SKent Overstreet 
2211cc7b8819SKent Overstreet int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2212cc7b8819SKent Overstreet 		     atomic_t *journal_ref, struct bkey *replace_key)
2213cafe5635SKent Overstreet {
2214cc7b8819SKent Overstreet 	struct btree_insert_op op;
2215cafe5635SKent Overstreet 	int ret = 0;
2216cafe5635SKent Overstreet 
2217cc7b8819SKent Overstreet 	BUG_ON(current->bio_list);
22184f3d4014SKent Overstreet 	BUG_ON(bch_keylist_empty(keys));
2219cafe5635SKent Overstreet 
2220cc7b8819SKent Overstreet 	bch_btree_op_init(&op.op, 0);
2221cc7b8819SKent Overstreet 	op.keys		= keys;
2222cc7b8819SKent Overstreet 	op.journal_ref	= journal_ref;
2223cc7b8819SKent Overstreet 	op.replace_key	= replace_key;
2224cafe5635SKent Overstreet 
2225cc7b8819SKent Overstreet 	while (!ret && !bch_keylist_empty(keys)) {
2226cc7b8819SKent Overstreet 		op.op.lock = 0;
2227cc7b8819SKent Overstreet 		ret = bch_btree_map_leaf_nodes(&op.op, c,
2228cc7b8819SKent Overstreet 					       &START_KEY(keys->keys),
2229cc7b8819SKent Overstreet 					       btree_insert_fn);
2230cc7b8819SKent Overstreet 	}
2231cc7b8819SKent Overstreet 
2232cc7b8819SKent Overstreet 	if (ret) {
2233cafe5635SKent Overstreet 		struct bkey *k;
2234cafe5635SKent Overstreet 
22351b207d80SKent Overstreet 		pr_err("error %i", ret);
2236cafe5635SKent Overstreet 
22374f3d4014SKent Overstreet 		while ((k = bch_keylist_pop(keys)))
22383a3b6a4eSKent Overstreet 			bkey_put(c, k);
2239cc7b8819SKent Overstreet 	} else if (op.op.insert_collision)
2240cc7b8819SKent Overstreet 		ret = -ESRCH;
22416054c6d4SKent Overstreet 
2242cafe5635SKent Overstreet 	return ret;
2243cafe5635SKent Overstreet }
2244cafe5635SKent Overstreet 
2245cafe5635SKent Overstreet void bch_btree_set_root(struct btree *b)
2246cafe5635SKent Overstreet {
2247cafe5635SKent Overstreet 	unsigned i;
2248e49c7c37SKent Overstreet 	struct closure cl;
2249e49c7c37SKent Overstreet 
2250e49c7c37SKent Overstreet 	closure_init_stack(&cl);
2251cafe5635SKent Overstreet 
2252c37511b8SKent Overstreet 	trace_bcache_btree_set_root(b);
2253c37511b8SKent Overstreet 
2254cafe5635SKent Overstreet 	BUG_ON(!b->written);
2255cafe5635SKent Overstreet 
2256cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++)
2257cafe5635SKent Overstreet 		BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2258cafe5635SKent Overstreet 
2259cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
2260cafe5635SKent Overstreet 	list_del_init(&b->list);
2261cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
2262cafe5635SKent Overstreet 
2263cafe5635SKent Overstreet 	b->c->root = b;
2264cafe5635SKent Overstreet 
2265e49c7c37SKent Overstreet 	bch_journal_meta(b->c, &cl);
2266e49c7c37SKent Overstreet 	closure_sync(&cl);
2267cafe5635SKent Overstreet }
2268cafe5635SKent Overstreet 
226948dad8baSKent Overstreet /* Map across nodes or keys */
227048dad8baSKent Overstreet 
227148dad8baSKent Overstreet static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
227248dad8baSKent Overstreet 				       struct bkey *from,
227348dad8baSKent Overstreet 				       btree_map_nodes_fn *fn, int flags)
227448dad8baSKent Overstreet {
227548dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
227648dad8baSKent Overstreet 
227748dad8baSKent Overstreet 	if (b->level) {
227848dad8baSKent Overstreet 		struct bkey *k;
227948dad8baSKent Overstreet 		struct btree_iter iter;
228048dad8baSKent Overstreet 
2281c052dd9aSKent Overstreet 		bch_btree_iter_init(&b->keys, &iter, from);
228248dad8baSKent Overstreet 
2283a85e968eSKent Overstreet 		while ((k = bch_btree_iter_next_filter(&iter, &b->keys,
228448dad8baSKent Overstreet 						       bch_ptr_bad))) {
228548dad8baSKent Overstreet 			ret = btree(map_nodes_recurse, k, b,
228648dad8baSKent Overstreet 				    op, from, fn, flags);
228748dad8baSKent Overstreet 			from = NULL;
228848dad8baSKent Overstreet 
228948dad8baSKent Overstreet 			if (ret != MAP_CONTINUE)
229048dad8baSKent Overstreet 				return ret;
229148dad8baSKent Overstreet 		}
229248dad8baSKent Overstreet 	}
229348dad8baSKent Overstreet 
229448dad8baSKent Overstreet 	if (!b->level || flags == MAP_ALL_NODES)
229548dad8baSKent Overstreet 		ret = fn(op, b);
229648dad8baSKent Overstreet 
229748dad8baSKent Overstreet 	return ret;
229848dad8baSKent Overstreet }
229948dad8baSKent Overstreet 
230048dad8baSKent Overstreet int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
230148dad8baSKent Overstreet 			  struct bkey *from, btree_map_nodes_fn *fn, int flags)
230248dad8baSKent Overstreet {
2303b54d6934SKent Overstreet 	return btree_root(map_nodes_recurse, c, op, from, fn, flags);
230448dad8baSKent Overstreet }
230548dad8baSKent Overstreet 
230648dad8baSKent Overstreet static int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
230748dad8baSKent Overstreet 				      struct bkey *from, btree_map_keys_fn *fn,
230848dad8baSKent Overstreet 				      int flags)
230948dad8baSKent Overstreet {
231048dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
231148dad8baSKent Overstreet 	struct bkey *k;
231248dad8baSKent Overstreet 	struct btree_iter iter;
231348dad8baSKent Overstreet 
2314c052dd9aSKent Overstreet 	bch_btree_iter_init(&b->keys, &iter, from);
231548dad8baSKent Overstreet 
2316a85e968eSKent Overstreet 	while ((k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad))) {
231748dad8baSKent Overstreet 		ret = !b->level
231848dad8baSKent Overstreet 			? fn(op, b, k)
231948dad8baSKent Overstreet 			: btree(map_keys_recurse, k, b, op, from, fn, flags);
232048dad8baSKent Overstreet 		from = NULL;
232148dad8baSKent Overstreet 
232248dad8baSKent Overstreet 		if (ret != MAP_CONTINUE)
232348dad8baSKent Overstreet 			return ret;
232448dad8baSKent Overstreet 	}
232548dad8baSKent Overstreet 
232648dad8baSKent Overstreet 	if (!b->level && (flags & MAP_END_KEY))
232748dad8baSKent Overstreet 		ret = fn(op, b, &KEY(KEY_INODE(&b->key),
232848dad8baSKent Overstreet 				     KEY_OFFSET(&b->key), 0));
232948dad8baSKent Overstreet 
233048dad8baSKent Overstreet 	return ret;
233148dad8baSKent Overstreet }
233248dad8baSKent Overstreet 
233348dad8baSKent Overstreet int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
233448dad8baSKent Overstreet 		       struct bkey *from, btree_map_keys_fn *fn, int flags)
233548dad8baSKent Overstreet {
2336b54d6934SKent Overstreet 	return btree_root(map_keys_recurse, c, op, from, fn, flags);
233748dad8baSKent Overstreet }
233848dad8baSKent Overstreet 
2339cafe5635SKent Overstreet /* Keybuf code */
2340cafe5635SKent Overstreet 
2341cafe5635SKent Overstreet static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2342cafe5635SKent Overstreet {
2343cafe5635SKent Overstreet 	/* Overlapping keys compare equal */
2344cafe5635SKent Overstreet 	if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2345cafe5635SKent Overstreet 		return -1;
2346cafe5635SKent Overstreet 	if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2347cafe5635SKent Overstreet 		return 1;
2348cafe5635SKent Overstreet 	return 0;
2349cafe5635SKent Overstreet }
2350cafe5635SKent Overstreet 
2351cafe5635SKent Overstreet static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2352cafe5635SKent Overstreet 					    struct keybuf_key *r)
2353cafe5635SKent Overstreet {
2354cafe5635SKent Overstreet 	return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2355cafe5635SKent Overstreet }
2356cafe5635SKent Overstreet 
235748dad8baSKent Overstreet struct refill {
235848dad8baSKent Overstreet 	struct btree_op	op;
235948a915a8SKent Overstreet 	unsigned	nr_found;
236048dad8baSKent Overstreet 	struct keybuf	*buf;
236148dad8baSKent Overstreet 	struct bkey	*end;
236248dad8baSKent Overstreet 	keybuf_pred_fn	*pred;
236348dad8baSKent Overstreet };
236448dad8baSKent Overstreet 
236548dad8baSKent Overstreet static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
236648dad8baSKent Overstreet 			    struct bkey *k)
2367cafe5635SKent Overstreet {
236848dad8baSKent Overstreet 	struct refill *refill = container_of(op, struct refill, op);
236948dad8baSKent Overstreet 	struct keybuf *buf = refill->buf;
237048dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
2371cafe5635SKent Overstreet 
237248dad8baSKent Overstreet 	if (bkey_cmp(k, refill->end) >= 0) {
237348dad8baSKent Overstreet 		ret = MAP_DONE;
237448dad8baSKent Overstreet 		goto out;
2375cafe5635SKent Overstreet 	}
2376cafe5635SKent Overstreet 
237748dad8baSKent Overstreet 	if (!KEY_SIZE(k)) /* end key */
237848dad8baSKent Overstreet 		goto out;
2379cafe5635SKent Overstreet 
238048dad8baSKent Overstreet 	if (refill->pred(buf, k)) {
2381cafe5635SKent Overstreet 		struct keybuf_key *w;
2382cafe5635SKent Overstreet 
2383cafe5635SKent Overstreet 		spin_lock(&buf->lock);
2384cafe5635SKent Overstreet 
2385cafe5635SKent Overstreet 		w = array_alloc(&buf->freelist);
238648dad8baSKent Overstreet 		if (!w) {
238748dad8baSKent Overstreet 			spin_unlock(&buf->lock);
238848dad8baSKent Overstreet 			return MAP_DONE;
238948dad8baSKent Overstreet 		}
2390cafe5635SKent Overstreet 
2391cafe5635SKent Overstreet 		w->private = NULL;
2392cafe5635SKent Overstreet 		bkey_copy(&w->key, k);
2393cafe5635SKent Overstreet 
2394cafe5635SKent Overstreet 		if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2395cafe5635SKent Overstreet 			array_free(&buf->freelist, w);
239648a915a8SKent Overstreet 		else
239748a915a8SKent Overstreet 			refill->nr_found++;
2398cafe5635SKent Overstreet 
239948dad8baSKent Overstreet 		if (array_freelist_empty(&buf->freelist))
240048dad8baSKent Overstreet 			ret = MAP_DONE;
240148dad8baSKent Overstreet 
2402cafe5635SKent Overstreet 		spin_unlock(&buf->lock);
2403cafe5635SKent Overstreet 	}
240448dad8baSKent Overstreet out:
240548dad8baSKent Overstreet 	buf->last_scanned = *k;
240648dad8baSKent Overstreet 	return ret;
2407cafe5635SKent Overstreet }
2408cafe5635SKent Overstreet 
2409cafe5635SKent Overstreet void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
241072c27061SKent Overstreet 		       struct bkey *end, keybuf_pred_fn *pred)
2411cafe5635SKent Overstreet {
2412cafe5635SKent Overstreet 	struct bkey start = buf->last_scanned;
241348dad8baSKent Overstreet 	struct refill refill;
2414cafe5635SKent Overstreet 
2415cafe5635SKent Overstreet 	cond_resched();
2416cafe5635SKent Overstreet 
2417b54d6934SKent Overstreet 	bch_btree_op_init(&refill.op, -1);
241848a915a8SKent Overstreet 	refill.nr_found	= 0;
241948dad8baSKent Overstreet 	refill.buf	= buf;
242048dad8baSKent Overstreet 	refill.end	= end;
242148dad8baSKent Overstreet 	refill.pred	= pred;
242248dad8baSKent Overstreet 
242348dad8baSKent Overstreet 	bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
242448dad8baSKent Overstreet 			   refill_keybuf_fn, MAP_END_KEY);
2425cafe5635SKent Overstreet 
242648a915a8SKent Overstreet 	trace_bcache_keyscan(refill.nr_found,
2427cafe5635SKent Overstreet 			     KEY_INODE(&start), KEY_OFFSET(&start),
242848a915a8SKent Overstreet 			     KEY_INODE(&buf->last_scanned),
242948a915a8SKent Overstreet 			     KEY_OFFSET(&buf->last_scanned));
2430cafe5635SKent Overstreet 
2431cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2432cafe5635SKent Overstreet 
2433cafe5635SKent Overstreet 	if (!RB_EMPTY_ROOT(&buf->keys)) {
2434cafe5635SKent Overstreet 		struct keybuf_key *w;
2435cafe5635SKent Overstreet 		w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2436cafe5635SKent Overstreet 		buf->start	= START_KEY(&w->key);
2437cafe5635SKent Overstreet 
2438cafe5635SKent Overstreet 		w = RB_LAST(&buf->keys, struct keybuf_key, node);
2439cafe5635SKent Overstreet 		buf->end	= w->key;
2440cafe5635SKent Overstreet 	} else {
2441cafe5635SKent Overstreet 		buf->start	= MAX_KEY;
2442cafe5635SKent Overstreet 		buf->end	= MAX_KEY;
2443cafe5635SKent Overstreet 	}
2444cafe5635SKent Overstreet 
2445cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2446cafe5635SKent Overstreet }
2447cafe5635SKent Overstreet 
2448cafe5635SKent Overstreet static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2449cafe5635SKent Overstreet {
2450cafe5635SKent Overstreet 	rb_erase(&w->node, &buf->keys);
2451cafe5635SKent Overstreet 	array_free(&buf->freelist, w);
2452cafe5635SKent Overstreet }
2453cafe5635SKent Overstreet 
2454cafe5635SKent Overstreet void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2455cafe5635SKent Overstreet {
2456cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2457cafe5635SKent Overstreet 	__bch_keybuf_del(buf, w);
2458cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2459cafe5635SKent Overstreet }
2460cafe5635SKent Overstreet 
2461cafe5635SKent Overstreet bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2462cafe5635SKent Overstreet 				  struct bkey *end)
2463cafe5635SKent Overstreet {
2464cafe5635SKent Overstreet 	bool ret = false;
2465cafe5635SKent Overstreet 	struct keybuf_key *p, *w, s;
2466cafe5635SKent Overstreet 	s.key = *start;
2467cafe5635SKent Overstreet 
2468cafe5635SKent Overstreet 	if (bkey_cmp(end, &buf->start) <= 0 ||
2469cafe5635SKent Overstreet 	    bkey_cmp(start, &buf->end) >= 0)
2470cafe5635SKent Overstreet 		return false;
2471cafe5635SKent Overstreet 
2472cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2473cafe5635SKent Overstreet 	w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2474cafe5635SKent Overstreet 
2475cafe5635SKent Overstreet 	while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2476cafe5635SKent Overstreet 		p = w;
2477cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2478cafe5635SKent Overstreet 
2479cafe5635SKent Overstreet 		if (p->private)
2480cafe5635SKent Overstreet 			ret = true;
2481cafe5635SKent Overstreet 		else
2482cafe5635SKent Overstreet 			__bch_keybuf_del(buf, p);
2483cafe5635SKent Overstreet 	}
2484cafe5635SKent Overstreet 
2485cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2486cafe5635SKent Overstreet 	return ret;
2487cafe5635SKent Overstreet }
2488cafe5635SKent Overstreet 
2489cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2490cafe5635SKent Overstreet {
2491cafe5635SKent Overstreet 	struct keybuf_key *w;
2492cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2493cafe5635SKent Overstreet 
2494cafe5635SKent Overstreet 	w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2495cafe5635SKent Overstreet 
2496cafe5635SKent Overstreet 	while (w && w->private)
2497cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2498cafe5635SKent Overstreet 
2499cafe5635SKent Overstreet 	if (w)
2500cafe5635SKent Overstreet 		w->private = ERR_PTR(-EINTR);
2501cafe5635SKent Overstreet 
2502cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2503cafe5635SKent Overstreet 	return w;
2504cafe5635SKent Overstreet }
2505cafe5635SKent Overstreet 
2506cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2507cafe5635SKent Overstreet 					  struct keybuf *buf,
250872c27061SKent Overstreet 					  struct bkey *end,
250972c27061SKent Overstreet 					  keybuf_pred_fn *pred)
2510cafe5635SKent Overstreet {
2511cafe5635SKent Overstreet 	struct keybuf_key *ret;
2512cafe5635SKent Overstreet 
2513cafe5635SKent Overstreet 	while (1) {
2514cafe5635SKent Overstreet 		ret = bch_keybuf_next(buf);
2515cafe5635SKent Overstreet 		if (ret)
2516cafe5635SKent Overstreet 			break;
2517cafe5635SKent Overstreet 
2518cafe5635SKent Overstreet 		if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2519cafe5635SKent Overstreet 			pr_debug("scan finished");
2520cafe5635SKent Overstreet 			break;
2521cafe5635SKent Overstreet 		}
2522cafe5635SKent Overstreet 
252372c27061SKent Overstreet 		bch_refill_keybuf(c, buf, end, pred);
2524cafe5635SKent Overstreet 	}
2525cafe5635SKent Overstreet 
2526cafe5635SKent Overstreet 	return ret;
2527cafe5635SKent Overstreet }
2528cafe5635SKent Overstreet 
252972c27061SKent Overstreet void bch_keybuf_init(struct keybuf *buf)
2530cafe5635SKent Overstreet {
2531cafe5635SKent Overstreet 	buf->last_scanned	= MAX_KEY;
2532cafe5635SKent Overstreet 	buf->keys		= RB_ROOT;
2533cafe5635SKent Overstreet 
2534cafe5635SKent Overstreet 	spin_lock_init(&buf->lock);
2535cafe5635SKent Overstreet 	array_allocator_init(&buf->freelist);
2536cafe5635SKent Overstreet }
2537