xref: /linux/drivers/md/bcache/btree.c (revision a1f0358b2bf69be216cb6e4ea40fe7ae4d38b8a6)
1cafe5635SKent Overstreet /*
2cafe5635SKent Overstreet  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
3cafe5635SKent Overstreet  *
4cafe5635SKent Overstreet  * Uses a block device as cache for other block devices; optimized for SSDs.
5cafe5635SKent Overstreet  * All allocation is done in buckets, which should match the erase block size
6cafe5635SKent Overstreet  * of the device.
7cafe5635SKent Overstreet  *
8cafe5635SKent Overstreet  * Buckets containing cached data are kept on a heap sorted by priority;
9cafe5635SKent Overstreet  * bucket priority is increased on cache hit, and periodically all the buckets
10cafe5635SKent Overstreet  * on the heap have their priority scaled down. This currently is just used as
11cafe5635SKent Overstreet  * an LRU but in the future should allow for more intelligent heuristics.
12cafe5635SKent Overstreet  *
13cafe5635SKent Overstreet  * Buckets have an 8 bit counter; freeing is accomplished by incrementing the
14cafe5635SKent Overstreet  * counter. Garbage collection is used to remove stale pointers.
15cafe5635SKent Overstreet  *
16cafe5635SKent Overstreet  * Indexing is done via a btree; nodes are not necessarily fully sorted, rather
17cafe5635SKent Overstreet  * as keys are inserted we only sort the pages that have not yet been written.
18cafe5635SKent Overstreet  * When garbage collection is run, we resort the entire node.
19cafe5635SKent Overstreet  *
20cafe5635SKent Overstreet  * All configuration is done via sysfs; see Documentation/bcache.txt.
21cafe5635SKent Overstreet  */
22cafe5635SKent Overstreet 
23cafe5635SKent Overstreet #include "bcache.h"
24cafe5635SKent Overstreet #include "btree.h"
25cafe5635SKent Overstreet #include "debug.h"
26279afbadSKent Overstreet #include "writeback.h"
27cafe5635SKent Overstreet 
28cafe5635SKent Overstreet #include <linux/slab.h>
29cafe5635SKent Overstreet #include <linux/bitops.h>
3072a44517SKent Overstreet #include <linux/freezer.h>
31cafe5635SKent Overstreet #include <linux/hash.h>
3272a44517SKent Overstreet #include <linux/kthread.h>
33cd953ed0SGeert Uytterhoeven #include <linux/prefetch.h>
34cafe5635SKent Overstreet #include <linux/random.h>
35cafe5635SKent Overstreet #include <linux/rcupdate.h>
36cafe5635SKent Overstreet #include <trace/events/bcache.h>
37cafe5635SKent Overstreet 
38cafe5635SKent Overstreet /*
39cafe5635SKent Overstreet  * Todo:
40cafe5635SKent Overstreet  * register_bcache: Return errors out to userspace correctly
41cafe5635SKent Overstreet  *
42cafe5635SKent Overstreet  * Writeback: don't undirty key until after a cache flush
43cafe5635SKent Overstreet  *
44cafe5635SKent Overstreet  * Create an iterator for key pointers
45cafe5635SKent Overstreet  *
46cafe5635SKent Overstreet  * On btree write error, mark bucket such that it won't be freed from the cache
47cafe5635SKent Overstreet  *
48cafe5635SKent Overstreet  * Journalling:
49cafe5635SKent Overstreet  *   Check for bad keys in replay
50cafe5635SKent Overstreet  *   Propagate barriers
51cafe5635SKent Overstreet  *   Refcount journal entries in journal_replay
52cafe5635SKent Overstreet  *
53cafe5635SKent Overstreet  * Garbage collection:
54cafe5635SKent Overstreet  *   Finish incremental gc
55cafe5635SKent Overstreet  *   Gc should free old UUIDs, data for invalid UUIDs
56cafe5635SKent Overstreet  *
57cafe5635SKent Overstreet  * Provide a way to list backing device UUIDs we have data cached for, and
58cafe5635SKent Overstreet  * probably how long it's been since we've seen them, and a way to invalidate
59cafe5635SKent Overstreet  * dirty data for devices that will never be attached again
60cafe5635SKent Overstreet  *
61cafe5635SKent Overstreet  * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
62cafe5635SKent Overstreet  * that based on that and how much dirty data we have we can keep writeback
63cafe5635SKent Overstreet  * from being starved
64cafe5635SKent Overstreet  *
65cafe5635SKent Overstreet  * Add a tracepoint or somesuch to watch for writeback starvation
66cafe5635SKent Overstreet  *
67cafe5635SKent Overstreet  * When btree depth > 1 and splitting an interior node, we have to make sure
68cafe5635SKent Overstreet  * alloc_bucket() cannot fail. This should be true but is not completely
69cafe5635SKent Overstreet  * obvious.
70cafe5635SKent Overstreet  *
71cafe5635SKent Overstreet  * Make sure all allocations get charged to the root cgroup
72cafe5635SKent Overstreet  *
73cafe5635SKent Overstreet  * Plugging?
74cafe5635SKent Overstreet  *
75cafe5635SKent Overstreet  * If data write is less than hard sector size of ssd, round up offset in open
76cafe5635SKent Overstreet  * bucket to the next whole sector
77cafe5635SKent Overstreet  *
78cafe5635SKent Overstreet  * Also lookup by cgroup in get_open_bucket()
79cafe5635SKent Overstreet  *
80cafe5635SKent Overstreet  * Superblock needs to be fleshed out for multiple cache devices
81cafe5635SKent Overstreet  *
82cafe5635SKent Overstreet  * Add a sysfs tunable for the number of writeback IOs in flight
83cafe5635SKent Overstreet  *
84cafe5635SKent Overstreet  * Add a sysfs tunable for the number of open data buckets
85cafe5635SKent Overstreet  *
86cafe5635SKent Overstreet  * IO tracking: Can we track when one process is doing io on behalf of another?
87cafe5635SKent Overstreet  * IO tracking: Don't use just an average, weigh more recent stuff higher
88cafe5635SKent Overstreet  *
89cafe5635SKent Overstreet  * Test module load/unload
90cafe5635SKent Overstreet  */
91cafe5635SKent Overstreet 
92df8e8970SKent Overstreet enum {
93df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_INSERT,
94df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_BACK_MERGE,
95df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_OVERWROTE,
96df8e8970SKent Overstreet 	BTREE_INSERT_STATUS_FRONT_MERGE,
97df8e8970SKent Overstreet };
98df8e8970SKent Overstreet 
99cafe5635SKent Overstreet #define MAX_NEED_GC		64
100cafe5635SKent Overstreet #define MAX_SAVE_PRIO		72
101cafe5635SKent Overstreet 
102cafe5635SKent Overstreet #define PTR_DIRTY_BIT		(((uint64_t) 1 << 36))
103cafe5635SKent Overstreet 
104cafe5635SKent Overstreet #define PTR_HASH(c, k)							\
105cafe5635SKent Overstreet 	(((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
106cafe5635SKent Overstreet 
107cafe5635SKent Overstreet static struct workqueue_struct *btree_io_wq;
108cafe5635SKent Overstreet 
109df8e8970SKent Overstreet static inline bool should_split(struct btree *b)
110df8e8970SKent Overstreet {
111df8e8970SKent Overstreet 	struct bset *i = write_block(b);
112df8e8970SKent Overstreet 	return b->written >= btree_blocks(b) ||
113df8e8970SKent Overstreet 		(b->written + __set_blocks(i, i->keys + 15, b->c)
114df8e8970SKent Overstreet 		 > btree_blocks(b));
115df8e8970SKent Overstreet }
116df8e8970SKent Overstreet 
117df8e8970SKent Overstreet #define insert_lock(s, b)	((b)->level <= (s)->lock)
118df8e8970SKent Overstreet 
119df8e8970SKent Overstreet /*
120df8e8970SKent Overstreet  * These macros are for recursing down the btree - they handle the details of
121df8e8970SKent Overstreet  * locking and looking up nodes in the cache for you. They're best treated as
122df8e8970SKent Overstreet  * mere syntax when reading code that uses them.
123df8e8970SKent Overstreet  *
124df8e8970SKent Overstreet  * op->lock determines whether we take a read or a write lock at a given depth.
125df8e8970SKent Overstreet  * If you've got a read lock and find that you need a write lock (i.e. you're
126df8e8970SKent Overstreet  * going to have to split), set op->lock and return -EINTR; btree_root() will
127df8e8970SKent Overstreet  * call you again and you'll have the correct lock.
128df8e8970SKent Overstreet  */
129df8e8970SKent Overstreet 
130df8e8970SKent Overstreet /**
131df8e8970SKent Overstreet  * btree - recurse down the btree on a specified key
132df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
133df8e8970SKent Overstreet  * @key:	key to recurse on
134df8e8970SKent Overstreet  * @b:		parent btree node
135df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
136df8e8970SKent Overstreet  */
137df8e8970SKent Overstreet #define btree(fn, key, b, op, ...)					\
138df8e8970SKent Overstreet ({									\
139df8e8970SKent Overstreet 	int _r, l = (b)->level - 1;					\
140df8e8970SKent Overstreet 	bool _w = l <= (op)->lock;					\
141df8e8970SKent Overstreet 	struct btree *_child = bch_btree_node_get((b)->c, key, l, _w);	\
142df8e8970SKent Overstreet 	if (!IS_ERR(_child)) {						\
143df8e8970SKent Overstreet 		_child->parent = (b);					\
144df8e8970SKent Overstreet 		_r = bch_btree_ ## fn(_child, op, ##__VA_ARGS__);	\
145df8e8970SKent Overstreet 		rw_unlock(_w, _child);					\
146df8e8970SKent Overstreet 	} else								\
147df8e8970SKent Overstreet 		_r = PTR_ERR(_child);					\
148df8e8970SKent Overstreet 	_r;								\
149df8e8970SKent Overstreet })
150df8e8970SKent Overstreet 
151df8e8970SKent Overstreet /**
152df8e8970SKent Overstreet  * btree_root - call a function on the root of the btree
153df8e8970SKent Overstreet  * @fn:		function to call, which will be passed the child node
154df8e8970SKent Overstreet  * @c:		cache set
155df8e8970SKent Overstreet  * @op:		pointer to struct btree_op
156df8e8970SKent Overstreet  */
157df8e8970SKent Overstreet #define btree_root(fn, c, op, ...)					\
158df8e8970SKent Overstreet ({									\
159df8e8970SKent Overstreet 	int _r = -EINTR;						\
160df8e8970SKent Overstreet 	do {								\
161df8e8970SKent Overstreet 		struct btree *_b = (c)->root;				\
162df8e8970SKent Overstreet 		bool _w = insert_lock(op, _b);				\
163df8e8970SKent Overstreet 		rw_lock(_w, _b, _b->level);				\
164df8e8970SKent Overstreet 		if (_b == (c)->root &&					\
165df8e8970SKent Overstreet 		    _w == insert_lock(op, _b)) {			\
166df8e8970SKent Overstreet 			_b->parent = NULL;				\
167df8e8970SKent Overstreet 			_r = bch_btree_ ## fn(_b, op, ##__VA_ARGS__);	\
168df8e8970SKent Overstreet 		}							\
169df8e8970SKent Overstreet 		rw_unlock(_w, _b);					\
170df8e8970SKent Overstreet 		bch_cannibalize_unlock(c);				\
171df8e8970SKent Overstreet 		if (_r == -ENOSPC) {					\
172df8e8970SKent Overstreet 			wait_event((c)->try_wait,			\
173df8e8970SKent Overstreet 				   !(c)->try_harder);			\
174df8e8970SKent Overstreet 			_r = -EINTR;					\
175df8e8970SKent Overstreet 		}							\
176df8e8970SKent Overstreet 	} while (_r == -EINTR);						\
177df8e8970SKent Overstreet 									\
178df8e8970SKent Overstreet 	_r;								\
179df8e8970SKent Overstreet })
180df8e8970SKent Overstreet 
181cafe5635SKent Overstreet /* Btree key manipulation */
182cafe5635SKent Overstreet 
1833a3b6a4eSKent Overstreet void bkey_put(struct cache_set *c, struct bkey *k)
184e7c590ebSKent Overstreet {
185e7c590ebSKent Overstreet 	unsigned i;
186e7c590ebSKent Overstreet 
187e7c590ebSKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
188e7c590ebSKent Overstreet 		if (ptr_available(c, k, i))
189e7c590ebSKent Overstreet 			atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
190e7c590ebSKent Overstreet }
191e7c590ebSKent Overstreet 
192cafe5635SKent Overstreet /* Btree IO */
193cafe5635SKent Overstreet 
194cafe5635SKent Overstreet static uint64_t btree_csum_set(struct btree *b, struct bset *i)
195cafe5635SKent Overstreet {
196cafe5635SKent Overstreet 	uint64_t crc = b->key.ptr[0];
197cafe5635SKent Overstreet 	void *data = (void *) i + 8, *end = end(i);
198cafe5635SKent Overstreet 
199169ef1cfSKent Overstreet 	crc = bch_crc64_update(crc, data, end - data);
200c19ed23aSKent Overstreet 	return crc ^ 0xffffffffffffffffULL;
201cafe5635SKent Overstreet }
202cafe5635SKent Overstreet 
203f3059a54SKent Overstreet static void bch_btree_node_read_done(struct btree *b)
204cafe5635SKent Overstreet {
205cafe5635SKent Overstreet 	const char *err = "bad btree header";
20657943511SKent Overstreet 	struct bset *i = b->sets[0].data;
20757943511SKent Overstreet 	struct btree_iter *iter;
208cafe5635SKent Overstreet 
20957943511SKent Overstreet 	iter = mempool_alloc(b->c->fill_iter, GFP_NOWAIT);
21057943511SKent Overstreet 	iter->size = b->c->sb.bucket_size / b->c->sb.block_size;
211cafe5635SKent Overstreet 	iter->used = 0;
212cafe5635SKent Overstreet 
213280481d0SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
214280481d0SKent Overstreet 	iter->b = b;
215280481d0SKent Overstreet #endif
216280481d0SKent Overstreet 
21757943511SKent Overstreet 	if (!i->seq)
218cafe5635SKent Overstreet 		goto err;
219cafe5635SKent Overstreet 
220cafe5635SKent Overstreet 	for (;
221cafe5635SKent Overstreet 	     b->written < btree_blocks(b) && i->seq == b->sets[0].data->seq;
222cafe5635SKent Overstreet 	     i = write_block(b)) {
223cafe5635SKent Overstreet 		err = "unsupported bset version";
224cafe5635SKent Overstreet 		if (i->version > BCACHE_BSET_VERSION)
225cafe5635SKent Overstreet 			goto err;
226cafe5635SKent Overstreet 
227cafe5635SKent Overstreet 		err = "bad btree header";
228cafe5635SKent Overstreet 		if (b->written + set_blocks(i, b->c) > btree_blocks(b))
229cafe5635SKent Overstreet 			goto err;
230cafe5635SKent Overstreet 
231cafe5635SKent Overstreet 		err = "bad magic";
23281ab4190SKent Overstreet 		if (i->magic != bset_magic(&b->c->sb))
233cafe5635SKent Overstreet 			goto err;
234cafe5635SKent Overstreet 
235cafe5635SKent Overstreet 		err = "bad checksum";
236cafe5635SKent Overstreet 		switch (i->version) {
237cafe5635SKent Overstreet 		case 0:
238cafe5635SKent Overstreet 			if (i->csum != csum_set(i))
239cafe5635SKent Overstreet 				goto err;
240cafe5635SKent Overstreet 			break;
241cafe5635SKent Overstreet 		case BCACHE_BSET_VERSION:
242cafe5635SKent Overstreet 			if (i->csum != btree_csum_set(b, i))
243cafe5635SKent Overstreet 				goto err;
244cafe5635SKent Overstreet 			break;
245cafe5635SKent Overstreet 		}
246cafe5635SKent Overstreet 
247cafe5635SKent Overstreet 		err = "empty set";
248cafe5635SKent Overstreet 		if (i != b->sets[0].data && !i->keys)
249cafe5635SKent Overstreet 			goto err;
250cafe5635SKent Overstreet 
251cafe5635SKent Overstreet 		bch_btree_iter_push(iter, i->start, end(i));
252cafe5635SKent Overstreet 
253cafe5635SKent Overstreet 		b->written += set_blocks(i, b->c);
254cafe5635SKent Overstreet 	}
255cafe5635SKent Overstreet 
256cafe5635SKent Overstreet 	err = "corrupted btree";
257cafe5635SKent Overstreet 	for (i = write_block(b);
258cafe5635SKent Overstreet 	     index(i, b) < btree_blocks(b);
259cafe5635SKent Overstreet 	     i = ((void *) i) + block_bytes(b->c))
260cafe5635SKent Overstreet 		if (i->seq == b->sets[0].data->seq)
261cafe5635SKent Overstreet 			goto err;
262cafe5635SKent Overstreet 
263cafe5635SKent Overstreet 	bch_btree_sort_and_fix_extents(b, iter);
264cafe5635SKent Overstreet 
265cafe5635SKent Overstreet 	i = b->sets[0].data;
266cafe5635SKent Overstreet 	err = "short btree key";
267cafe5635SKent Overstreet 	if (b->sets[0].size &&
268cafe5635SKent Overstreet 	    bkey_cmp(&b->key, &b->sets[0].end) < 0)
269cafe5635SKent Overstreet 		goto err;
270cafe5635SKent Overstreet 
271cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
272cafe5635SKent Overstreet 		bch_bset_init_next(b);
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);
27807e86ccbSKent Overstreet 	bch_cache_set_error(b->c, "%s at bucket %zu, block %zu, %u keys",
279cafe5635SKent Overstreet 			    err, PTR_BUCKET_NR(b->c, &b->key, 0),
280cafe5635SKent Overstreet 			    index(i, b), i->keys);
281cafe5635SKent Overstreet 	goto out;
282cafe5635SKent Overstreet }
283cafe5635SKent Overstreet 
28457943511SKent Overstreet static void btree_node_read_endio(struct bio *bio, int error)
285cafe5635SKent Overstreet {
28657943511SKent Overstreet 	struct closure *cl = bio->bi_private;
28757943511SKent Overstreet 	closure_put(cl);
28857943511SKent Overstreet }
289cafe5635SKent Overstreet 
29057943511SKent Overstreet 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);
30157943511SKent Overstreet 	bio->bi_rw	= REQ_META|READ_SYNC;
30257943511SKent Overstreet 	bio->bi_size	= KEY_SIZE(&b->key) << 9;
30357943511SKent Overstreet 	bio->bi_end_io	= btree_node_read_endio;
30457943511SKent Overstreet 	bio->bi_private	= &cl;
30557943511SKent Overstreet 
30657943511SKent Overstreet 	bch_bio_map(bio, b->sets[0].data);
30757943511SKent Overstreet 
30857943511SKent Overstreet 	bch_submit_bbio(bio, b->c, &b->key, 0);
30957943511SKent Overstreet 	closure_sync(&cl);
31057943511SKent Overstreet 
31157943511SKent Overstreet 	if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
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 
32157943511SKent Overstreet 	spin_lock(&b->c->btree_read_time_lock);
32257943511SKent Overstreet 	bch_time_stats_update(&b->c->btree_read_time, start_time);
32357943511SKent Overstreet 	spin_unlock(&b->c->btree_read_time_lock);
32457943511SKent Overstreet 
32557943511SKent Overstreet 	return;
32657943511SKent Overstreet err:
32761cbd250SGeert Uytterhoeven 	bch_cache_set_error(b->c, "io error reading bucket %zu",
32857943511SKent Overstreet 			    PTR_BUCKET_NR(b->c, &b->key, 0));
329cafe5635SKent Overstreet }
330cafe5635SKent Overstreet 
331cafe5635SKent Overstreet static void btree_complete_write(struct btree *b, struct btree_write *w)
332cafe5635SKent Overstreet {
333cafe5635SKent Overstreet 	if (w->prio_blocked &&
334cafe5635SKent Overstreet 	    !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
335119ba0f8SKent Overstreet 		wake_up_allocators(b->c);
336cafe5635SKent Overstreet 
337cafe5635SKent Overstreet 	if (w->journal) {
338cafe5635SKent Overstreet 		atomic_dec_bug(w->journal);
339cafe5635SKent Overstreet 		__closure_wake_up(&b->c->journal.wait);
340cafe5635SKent Overstreet 	}
341cafe5635SKent Overstreet 
342cafe5635SKent Overstreet 	w->prio_blocked	= 0;
343cafe5635SKent Overstreet 	w->journal	= NULL;
344cafe5635SKent Overstreet }
345cafe5635SKent Overstreet 
34657943511SKent Overstreet static void __btree_node_write_done(struct closure *cl)
347cafe5635SKent Overstreet {
348cafe5635SKent Overstreet 	struct btree *b = container_of(cl, struct btree, io.cl);
349cafe5635SKent Overstreet 	struct btree_write *w = btree_prev_write(b);
350cafe5635SKent Overstreet 
351cafe5635SKent Overstreet 	bch_bbio_free(b->bio, b->c);
352cafe5635SKent Overstreet 	b->bio = NULL;
353cafe5635SKent Overstreet 	btree_complete_write(b, w);
354cafe5635SKent Overstreet 
355cafe5635SKent Overstreet 	if (btree_node_dirty(b))
356cafe5635SKent Overstreet 		queue_delayed_work(btree_io_wq, &b->work,
357cafe5635SKent Overstreet 				   msecs_to_jiffies(30000));
358cafe5635SKent Overstreet 
359cafe5635SKent Overstreet 	closure_return(cl);
360cafe5635SKent Overstreet }
361cafe5635SKent Overstreet 
36257943511SKent Overstreet static void btree_node_write_done(struct closure *cl)
363cafe5635SKent Overstreet {
364cafe5635SKent Overstreet 	struct btree *b = container_of(cl, struct btree, io.cl);
365cafe5635SKent Overstreet 	struct bio_vec *bv;
366cafe5635SKent Overstreet 	int n;
367cafe5635SKent Overstreet 
368cafe5635SKent Overstreet 	__bio_for_each_segment(bv, b->bio, n, 0)
369cafe5635SKent Overstreet 		__free_page(bv->bv_page);
370cafe5635SKent Overstreet 
37157943511SKent Overstreet 	__btree_node_write_done(cl);
372cafe5635SKent Overstreet }
373cafe5635SKent Overstreet 
37457943511SKent Overstreet static void btree_node_write_endio(struct bio *bio, int error)
37557943511SKent Overstreet {
37657943511SKent Overstreet 	struct closure *cl = bio->bi_private;
37757943511SKent Overstreet 	struct btree *b = container_of(cl, struct btree, io.cl);
37857943511SKent Overstreet 
37957943511SKent Overstreet 	if (error)
38057943511SKent Overstreet 		set_btree_node_io_error(b);
38157943511SKent Overstreet 
38257943511SKent Overstreet 	bch_bbio_count_io_errors(b->c, bio, error, "writing btree");
38357943511SKent Overstreet 	closure_put(cl);
38457943511SKent Overstreet }
38557943511SKent Overstreet 
38657943511SKent Overstreet static void do_btree_node_write(struct btree *b)
387cafe5635SKent Overstreet {
388cafe5635SKent Overstreet 	struct closure *cl = &b->io.cl;
389cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
390cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
391cafe5635SKent Overstreet 
392cafe5635SKent Overstreet 	i->version	= BCACHE_BSET_VERSION;
393cafe5635SKent Overstreet 	i->csum		= btree_csum_set(b, i);
394cafe5635SKent Overstreet 
39557943511SKent Overstreet 	BUG_ON(b->bio);
39657943511SKent Overstreet 	b->bio = bch_bbio_alloc(b->c);
39757943511SKent Overstreet 
39857943511SKent Overstreet 	b->bio->bi_end_io	= btree_node_write_endio;
399faadf0c9SKent Overstreet 	b->bio->bi_private	= cl;
400e49c7c37SKent Overstreet 	b->bio->bi_rw		= REQ_META|WRITE_SYNC|REQ_FUA;
401cafe5635SKent Overstreet 	b->bio->bi_size		= set_blocks(i, b->c) * block_bytes(b->c);
402169ef1cfSKent Overstreet 	bch_bio_map(b->bio, i);
403cafe5635SKent Overstreet 
404e49c7c37SKent Overstreet 	/*
405e49c7c37SKent Overstreet 	 * If we're appending to a leaf node, we don't technically need FUA -
406e49c7c37SKent Overstreet 	 * this write just needs to be persisted before the next journal write,
407e49c7c37SKent Overstreet 	 * which will be marked FLUSH|FUA.
408e49c7c37SKent Overstreet 	 *
409e49c7c37SKent Overstreet 	 * Similarly if we're writing a new btree root - the pointer is going to
410e49c7c37SKent Overstreet 	 * be in the next journal entry.
411e49c7c37SKent Overstreet 	 *
412e49c7c37SKent Overstreet 	 * But if we're writing a new btree node (that isn't a root) or
413e49c7c37SKent Overstreet 	 * appending to a non leaf btree node, we need either FUA or a flush
414e49c7c37SKent Overstreet 	 * when we write the parent with the new pointer. FUA is cheaper than a
415e49c7c37SKent Overstreet 	 * flush, and writes appending to leaf nodes aren't blocking anything so
416e49c7c37SKent Overstreet 	 * just make all btree node writes FUA to keep things sane.
417e49c7c37SKent Overstreet 	 */
418e49c7c37SKent Overstreet 
419cafe5635SKent Overstreet 	bkey_copy(&k.key, &b->key);
420cafe5635SKent Overstreet 	SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) + bset_offset(b, i));
421cafe5635SKent Overstreet 
4228e51e414SKent Overstreet 	if (!bio_alloc_pages(b->bio, GFP_NOIO)) {
423cafe5635SKent Overstreet 		int j;
424cafe5635SKent Overstreet 		struct bio_vec *bv;
425cafe5635SKent Overstreet 		void *base = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
426cafe5635SKent Overstreet 
427cafe5635SKent Overstreet 		bio_for_each_segment(bv, b->bio, j)
428cafe5635SKent Overstreet 			memcpy(page_address(bv->bv_page),
429cafe5635SKent Overstreet 			       base + j * PAGE_SIZE, PAGE_SIZE);
430cafe5635SKent Overstreet 
431cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
432cafe5635SKent Overstreet 
43357943511SKent Overstreet 		continue_at(cl, btree_node_write_done, NULL);
434cafe5635SKent Overstreet 	} else {
435cafe5635SKent Overstreet 		b->bio->bi_vcnt = 0;
436169ef1cfSKent Overstreet 		bch_bio_map(b->bio, i);
437cafe5635SKent Overstreet 
438cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
439cafe5635SKent Overstreet 
440cafe5635SKent Overstreet 		closure_sync(cl);
44157943511SKent Overstreet 		__btree_node_write_done(cl);
442cafe5635SKent Overstreet 	}
443cafe5635SKent Overstreet }
444cafe5635SKent Overstreet 
44557943511SKent Overstreet void bch_btree_node_write(struct btree *b, struct closure *parent)
446cafe5635SKent Overstreet {
447cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
448cafe5635SKent Overstreet 
449c37511b8SKent Overstreet 	trace_bcache_btree_write(b);
450c37511b8SKent Overstreet 
451cafe5635SKent Overstreet 	BUG_ON(current->bio_list);
45257943511SKent Overstreet 	BUG_ON(b->written >= btree_blocks(b));
45357943511SKent Overstreet 	BUG_ON(b->written && !i->keys);
45457943511SKent Overstreet 	BUG_ON(b->sets->data->seq != i->seq);
455280481d0SKent Overstreet 	bch_check_keys(b, "writing");
456cafe5635SKent Overstreet 
457cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
458cafe5635SKent Overstreet 
45957943511SKent Overstreet 	/* If caller isn't waiting for write, parent refcount is cache set */
46057943511SKent Overstreet 	closure_lock(&b->io, parent ?: &b->c->cl);
46157943511SKent Overstreet 
462cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty,	 &b->flags);
463cafe5635SKent Overstreet 	change_bit(BTREE_NODE_write_idx, &b->flags);
464cafe5635SKent Overstreet 
46557943511SKent Overstreet 	do_btree_node_write(b);
466cafe5635SKent Overstreet 
467cafe5635SKent Overstreet 	b->written += set_blocks(i, b->c);
468cafe5635SKent Overstreet 	atomic_long_add(set_blocks(i, b->c) * b->c->sb.block_size,
469cafe5635SKent Overstreet 			&PTR_CACHE(b->c, &b->key, 0)->btree_sectors_written);
470cafe5635SKent Overstreet 
471cafe5635SKent Overstreet 	bch_btree_sort_lazy(b);
472cafe5635SKent Overstreet 
473cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
474cafe5635SKent Overstreet 		bch_bset_init_next(b);
475cafe5635SKent Overstreet }
476cafe5635SKent Overstreet 
477f269af5aSKent Overstreet static void bch_btree_node_write_sync(struct btree *b)
478f269af5aSKent Overstreet {
479f269af5aSKent Overstreet 	struct closure cl;
480f269af5aSKent Overstreet 
481f269af5aSKent Overstreet 	closure_init_stack(&cl);
482f269af5aSKent Overstreet 	bch_btree_node_write(b, &cl);
483f269af5aSKent Overstreet 	closure_sync(&cl);
484f269af5aSKent Overstreet }
485f269af5aSKent Overstreet 
48657943511SKent Overstreet static void btree_node_write_work(struct work_struct *w)
487cafe5635SKent Overstreet {
488cafe5635SKent Overstreet 	struct btree *b = container_of(to_delayed_work(w), struct btree, work);
489cafe5635SKent Overstreet 
49057943511SKent Overstreet 	rw_lock(true, b, b->level);
491cafe5635SKent Overstreet 
492cafe5635SKent Overstreet 	if (btree_node_dirty(b))
49357943511SKent Overstreet 		bch_btree_node_write(b, NULL);
49457943511SKent Overstreet 	rw_unlock(true, b);
495cafe5635SKent Overstreet }
496cafe5635SKent Overstreet 
497c18536a7SKent Overstreet static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
498cafe5635SKent Overstreet {
499cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
500cafe5635SKent Overstreet 	struct btree_write *w = btree_current_write(b);
501cafe5635SKent Overstreet 
50257943511SKent Overstreet 	BUG_ON(!b->written);
50357943511SKent Overstreet 	BUG_ON(!i->keys);
504cafe5635SKent Overstreet 
50557943511SKent Overstreet 	if (!btree_node_dirty(b))
50657943511SKent Overstreet 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
50757943511SKent Overstreet 
508cafe5635SKent Overstreet 	set_btree_node_dirty(b);
509cafe5635SKent Overstreet 
510c18536a7SKent Overstreet 	if (journal_ref) {
511cafe5635SKent Overstreet 		if (w->journal &&
512c18536a7SKent Overstreet 		    journal_pin_cmp(b->c, w->journal, journal_ref)) {
513cafe5635SKent Overstreet 			atomic_dec_bug(w->journal);
514cafe5635SKent Overstreet 			w->journal = NULL;
515cafe5635SKent Overstreet 		}
516cafe5635SKent Overstreet 
517cafe5635SKent Overstreet 		if (!w->journal) {
518c18536a7SKent Overstreet 			w->journal = journal_ref;
519cafe5635SKent Overstreet 			atomic_inc(w->journal);
520cafe5635SKent Overstreet 		}
521cafe5635SKent Overstreet 	}
522cafe5635SKent Overstreet 
523cafe5635SKent Overstreet 	/* Force write if set is too big */
52457943511SKent Overstreet 	if (set_bytes(i) > PAGE_SIZE - 48 &&
52557943511SKent Overstreet 	    !current->bio_list)
52657943511SKent Overstreet 		bch_btree_node_write(b, NULL);
527cafe5635SKent Overstreet }
528cafe5635SKent Overstreet 
529cafe5635SKent Overstreet /*
530cafe5635SKent Overstreet  * Btree in memory cache - allocation/freeing
531cafe5635SKent Overstreet  * mca -> memory cache
532cafe5635SKent Overstreet  */
533cafe5635SKent Overstreet 
534cafe5635SKent Overstreet static void mca_reinit(struct btree *b)
535cafe5635SKent Overstreet {
536cafe5635SKent Overstreet 	unsigned i;
537cafe5635SKent Overstreet 
538cafe5635SKent Overstreet 	b->flags	= 0;
539cafe5635SKent Overstreet 	b->written	= 0;
540cafe5635SKent Overstreet 	b->nsets	= 0;
541cafe5635SKent Overstreet 
542cafe5635SKent Overstreet 	for (i = 0; i < MAX_BSETS; i++)
543cafe5635SKent Overstreet 		b->sets[i].size = 0;
544cafe5635SKent Overstreet 	/*
545cafe5635SKent Overstreet 	 * Second loop starts at 1 because b->sets[0]->data is the memory we
546cafe5635SKent Overstreet 	 * allocated
547cafe5635SKent Overstreet 	 */
548cafe5635SKent Overstreet 	for (i = 1; i < MAX_BSETS; i++)
549cafe5635SKent Overstreet 		b->sets[i].data = NULL;
550cafe5635SKent Overstreet }
551cafe5635SKent Overstreet 
552cafe5635SKent Overstreet #define mca_reserve(c)	(((c->root && c->root->level)		\
553cafe5635SKent Overstreet 			  ? c->root->level : 1) * 8 + 16)
554cafe5635SKent Overstreet #define mca_can_free(c)						\
555cafe5635SKent Overstreet 	max_t(int, 0, c->bucket_cache_used - mca_reserve(c))
556cafe5635SKent Overstreet 
557cafe5635SKent Overstreet static void mca_data_free(struct btree *b)
558cafe5635SKent Overstreet {
559cafe5635SKent Overstreet 	struct bset_tree *t = b->sets;
560cafe5635SKent Overstreet 	BUG_ON(!closure_is_unlocked(&b->io.cl));
561cafe5635SKent Overstreet 
562cafe5635SKent Overstreet 	if (bset_prev_bytes(b) < PAGE_SIZE)
563cafe5635SKent Overstreet 		kfree(t->prev);
564cafe5635SKent Overstreet 	else
565cafe5635SKent Overstreet 		free_pages((unsigned long) t->prev,
566cafe5635SKent Overstreet 			   get_order(bset_prev_bytes(b)));
567cafe5635SKent Overstreet 
568cafe5635SKent Overstreet 	if (bset_tree_bytes(b) < PAGE_SIZE)
569cafe5635SKent Overstreet 		kfree(t->tree);
570cafe5635SKent Overstreet 	else
571cafe5635SKent Overstreet 		free_pages((unsigned long) t->tree,
572cafe5635SKent Overstreet 			   get_order(bset_tree_bytes(b)));
573cafe5635SKent Overstreet 
574cafe5635SKent Overstreet 	free_pages((unsigned long) t->data, b->page_order);
575cafe5635SKent Overstreet 
576cafe5635SKent Overstreet 	t->prev = NULL;
577cafe5635SKent Overstreet 	t->tree = NULL;
578cafe5635SKent Overstreet 	t->data = NULL;
579cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freed);
580cafe5635SKent Overstreet 	b->c->bucket_cache_used--;
581cafe5635SKent Overstreet }
582cafe5635SKent Overstreet 
583cafe5635SKent Overstreet static void mca_bucket_free(struct btree *b)
584cafe5635SKent Overstreet {
585cafe5635SKent Overstreet 	BUG_ON(btree_node_dirty(b));
586cafe5635SKent Overstreet 
587cafe5635SKent Overstreet 	b->key.ptr[0] = 0;
588cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
589cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freeable);
590cafe5635SKent Overstreet }
591cafe5635SKent Overstreet 
592cafe5635SKent Overstreet static unsigned btree_order(struct bkey *k)
593cafe5635SKent Overstreet {
594cafe5635SKent Overstreet 	return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
595cafe5635SKent Overstreet }
596cafe5635SKent Overstreet 
597cafe5635SKent Overstreet static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
598cafe5635SKent Overstreet {
599cafe5635SKent Overstreet 	struct bset_tree *t = b->sets;
600cafe5635SKent Overstreet 	BUG_ON(t->data);
601cafe5635SKent Overstreet 
602cafe5635SKent Overstreet 	b->page_order = max_t(unsigned,
603cafe5635SKent Overstreet 			      ilog2(b->c->btree_pages),
604cafe5635SKent Overstreet 			      btree_order(k));
605cafe5635SKent Overstreet 
606cafe5635SKent Overstreet 	t->data = (void *) __get_free_pages(gfp, b->page_order);
607cafe5635SKent Overstreet 	if (!t->data)
608cafe5635SKent Overstreet 		goto err;
609cafe5635SKent Overstreet 
610cafe5635SKent Overstreet 	t->tree = bset_tree_bytes(b) < PAGE_SIZE
611cafe5635SKent Overstreet 		? kmalloc(bset_tree_bytes(b), gfp)
612cafe5635SKent Overstreet 		: (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
613cafe5635SKent Overstreet 	if (!t->tree)
614cafe5635SKent Overstreet 		goto err;
615cafe5635SKent Overstreet 
616cafe5635SKent Overstreet 	t->prev = bset_prev_bytes(b) < PAGE_SIZE
617cafe5635SKent Overstreet 		? kmalloc(bset_prev_bytes(b), gfp)
618cafe5635SKent Overstreet 		: (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
619cafe5635SKent Overstreet 	if (!t->prev)
620cafe5635SKent Overstreet 		goto err;
621cafe5635SKent Overstreet 
622cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache);
623cafe5635SKent Overstreet 	b->c->bucket_cache_used++;
624cafe5635SKent Overstreet 	return;
625cafe5635SKent Overstreet err:
626cafe5635SKent Overstreet 	mca_data_free(b);
627cafe5635SKent Overstreet }
628cafe5635SKent Overstreet 
629cafe5635SKent Overstreet static struct btree *mca_bucket_alloc(struct cache_set *c,
630cafe5635SKent Overstreet 				      struct bkey *k, gfp_t gfp)
631cafe5635SKent Overstreet {
632cafe5635SKent Overstreet 	struct btree *b = kzalloc(sizeof(struct btree), gfp);
633cafe5635SKent Overstreet 	if (!b)
634cafe5635SKent Overstreet 		return NULL;
635cafe5635SKent Overstreet 
636cafe5635SKent Overstreet 	init_rwsem(&b->lock);
637cafe5635SKent Overstreet 	lockdep_set_novalidate_class(&b->lock);
638cafe5635SKent Overstreet 	INIT_LIST_HEAD(&b->list);
63957943511SKent Overstreet 	INIT_DELAYED_WORK(&b->work, btree_node_write_work);
640cafe5635SKent Overstreet 	b->c = c;
641cafe5635SKent Overstreet 	closure_init_unlocked(&b->io);
642cafe5635SKent Overstreet 
643cafe5635SKent Overstreet 	mca_data_alloc(b, k, gfp);
644cafe5635SKent Overstreet 	return b;
645cafe5635SKent Overstreet }
646cafe5635SKent Overstreet 
647e8e1d468SKent Overstreet static int mca_reap(struct btree *b, unsigned min_order, bool flush)
648cafe5635SKent Overstreet {
649e8e1d468SKent Overstreet 	struct closure cl;
650e8e1d468SKent Overstreet 
651e8e1d468SKent Overstreet 	closure_init_stack(&cl);
652cafe5635SKent Overstreet 	lockdep_assert_held(&b->c->bucket_lock);
653cafe5635SKent Overstreet 
654cafe5635SKent Overstreet 	if (!down_write_trylock(&b->lock))
655cafe5635SKent Overstreet 		return -ENOMEM;
656cafe5635SKent Overstreet 
657e8e1d468SKent Overstreet 	BUG_ON(btree_node_dirty(b) && !b->sets[0].data);
658e8e1d468SKent Overstreet 
659e8e1d468SKent Overstreet 	if (b->page_order < min_order ||
660e8e1d468SKent Overstreet 	    (!flush &&
661e8e1d468SKent Overstreet 	     (btree_node_dirty(b) ||
662e8e1d468SKent Overstreet 	      atomic_read(&b->io.cl.remaining) != -1))) {
663cafe5635SKent Overstreet 		rw_unlock(true, b);
664cafe5635SKent Overstreet 		return -ENOMEM;
665cafe5635SKent Overstreet 	}
666cafe5635SKent Overstreet 
667f269af5aSKent Overstreet 	if (btree_node_dirty(b))
668f269af5aSKent Overstreet 		bch_btree_node_write_sync(b);
669cafe5635SKent Overstreet 
670e8e1d468SKent Overstreet 	/* wait for any in flight btree write */
671faadf0c9SKent Overstreet 	closure_wait_event(&b->io.wait, &cl,
672e8e1d468SKent Overstreet 			   atomic_read(&b->io.cl.remaining) == -1);
673e8e1d468SKent Overstreet 
674cafe5635SKent Overstreet 	return 0;
675cafe5635SKent Overstreet }
676cafe5635SKent Overstreet 
6777dc19d5aSDave Chinner static unsigned long bch_mca_scan(struct shrinker *shrink,
6787dc19d5aSDave Chinner 				  struct shrink_control *sc)
679cafe5635SKent Overstreet {
680cafe5635SKent Overstreet 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
681cafe5635SKent Overstreet 	struct btree *b, *t;
682cafe5635SKent Overstreet 	unsigned long i, nr = sc->nr_to_scan;
6837dc19d5aSDave Chinner 	unsigned long freed = 0;
684cafe5635SKent Overstreet 
685cafe5635SKent Overstreet 	if (c->shrinker_disabled)
6867dc19d5aSDave Chinner 		return SHRINK_STOP;
687cafe5635SKent Overstreet 
688cafe5635SKent Overstreet 	if (c->try_harder)
6897dc19d5aSDave Chinner 		return SHRINK_STOP;
690cafe5635SKent Overstreet 
691cafe5635SKent Overstreet 	/* Return -1 if we can't do anything right now */
692a698e08cSKent Overstreet 	if (sc->gfp_mask & __GFP_IO)
693cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
694cafe5635SKent Overstreet 	else if (!mutex_trylock(&c->bucket_lock))
695cafe5635SKent Overstreet 		return -1;
696cafe5635SKent Overstreet 
69736c9ea98SKent Overstreet 	/*
69836c9ea98SKent Overstreet 	 * It's _really_ critical that we don't free too many btree nodes - we
69936c9ea98SKent Overstreet 	 * have to always leave ourselves a reserve. The reserve is how we
70036c9ea98SKent Overstreet 	 * guarantee that allocating memory for a new btree node can always
70136c9ea98SKent Overstreet 	 * succeed, so that inserting keys into the btree can always succeed and
70236c9ea98SKent Overstreet 	 * IO can always make forward progress:
70336c9ea98SKent Overstreet 	 */
704cafe5635SKent Overstreet 	nr /= c->btree_pages;
705cafe5635SKent Overstreet 	nr = min_t(unsigned long, nr, mca_can_free(c));
706cafe5635SKent Overstreet 
707cafe5635SKent Overstreet 	i = 0;
708cafe5635SKent Overstreet 	list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
7097dc19d5aSDave Chinner 		if (freed >= nr)
710cafe5635SKent Overstreet 			break;
711cafe5635SKent Overstreet 
712cafe5635SKent Overstreet 		if (++i > 3 &&
713e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
714cafe5635SKent Overstreet 			mca_data_free(b);
715cafe5635SKent Overstreet 			rw_unlock(true, b);
7167dc19d5aSDave Chinner 			freed++;
717cafe5635SKent Overstreet 		}
718cafe5635SKent Overstreet 	}
719cafe5635SKent Overstreet 
720cafe5635SKent Overstreet 	/*
721cafe5635SKent Overstreet 	 * Can happen right when we first start up, before we've read in any
722cafe5635SKent Overstreet 	 * btree nodes
723cafe5635SKent Overstreet 	 */
724cafe5635SKent Overstreet 	if (list_empty(&c->btree_cache))
725cafe5635SKent Overstreet 		goto out;
726cafe5635SKent Overstreet 
7277dc19d5aSDave Chinner 	for (i = 0; (nr--) && i < c->bucket_cache_used; i++) {
728cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
729cafe5635SKent Overstreet 		list_rotate_left(&c->btree_cache);
730cafe5635SKent Overstreet 
731cafe5635SKent Overstreet 		if (!b->accessed &&
732e8e1d468SKent Overstreet 		    !mca_reap(b, 0, false)) {
733cafe5635SKent Overstreet 			mca_bucket_free(b);
734cafe5635SKent Overstreet 			mca_data_free(b);
735cafe5635SKent Overstreet 			rw_unlock(true, b);
7367dc19d5aSDave Chinner 			freed++;
737cafe5635SKent Overstreet 		} else
738cafe5635SKent Overstreet 			b->accessed = 0;
739cafe5635SKent Overstreet 	}
740cafe5635SKent Overstreet out:
741cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
7427dc19d5aSDave Chinner 	return freed;
7437dc19d5aSDave Chinner }
7447dc19d5aSDave Chinner 
7457dc19d5aSDave Chinner static unsigned long bch_mca_count(struct shrinker *shrink,
7467dc19d5aSDave Chinner 				   struct shrink_control *sc)
7477dc19d5aSDave Chinner {
7487dc19d5aSDave Chinner 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
7497dc19d5aSDave Chinner 
7507dc19d5aSDave Chinner 	if (c->shrinker_disabled)
7517dc19d5aSDave Chinner 		return 0;
7527dc19d5aSDave Chinner 
7537dc19d5aSDave Chinner 	if (c->try_harder)
7547dc19d5aSDave Chinner 		return 0;
7557dc19d5aSDave Chinner 
7567dc19d5aSDave Chinner 	return mca_can_free(c) * c->btree_pages;
757cafe5635SKent Overstreet }
758cafe5635SKent Overstreet 
759cafe5635SKent Overstreet void bch_btree_cache_free(struct cache_set *c)
760cafe5635SKent Overstreet {
761cafe5635SKent Overstreet 	struct btree *b;
762cafe5635SKent Overstreet 	struct closure cl;
763cafe5635SKent Overstreet 	closure_init_stack(&cl);
764cafe5635SKent Overstreet 
765cafe5635SKent Overstreet 	if (c->shrink.list.next)
766cafe5635SKent Overstreet 		unregister_shrinker(&c->shrink);
767cafe5635SKent Overstreet 
768cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
769cafe5635SKent Overstreet 
770cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
771cafe5635SKent Overstreet 	if (c->verify_data)
772cafe5635SKent Overstreet 		list_move(&c->verify_data->list, &c->btree_cache);
773cafe5635SKent Overstreet #endif
774cafe5635SKent Overstreet 
775cafe5635SKent Overstreet 	list_splice(&c->btree_cache_freeable,
776cafe5635SKent Overstreet 		    &c->btree_cache);
777cafe5635SKent Overstreet 
778cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache)) {
779cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
780cafe5635SKent Overstreet 
781cafe5635SKent Overstreet 		if (btree_node_dirty(b))
782cafe5635SKent Overstreet 			btree_complete_write(b, btree_current_write(b));
783cafe5635SKent Overstreet 		clear_bit(BTREE_NODE_dirty, &b->flags);
784cafe5635SKent Overstreet 
785cafe5635SKent Overstreet 		mca_data_free(b);
786cafe5635SKent Overstreet 	}
787cafe5635SKent Overstreet 
788cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache_freed)) {
789cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache_freed,
790cafe5635SKent Overstreet 				     struct btree, list);
791cafe5635SKent Overstreet 		list_del(&b->list);
792cafe5635SKent Overstreet 		cancel_delayed_work_sync(&b->work);
793cafe5635SKent Overstreet 		kfree(b);
794cafe5635SKent Overstreet 	}
795cafe5635SKent Overstreet 
796cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
797cafe5635SKent Overstreet }
798cafe5635SKent Overstreet 
799cafe5635SKent Overstreet int bch_btree_cache_alloc(struct cache_set *c)
800cafe5635SKent Overstreet {
801cafe5635SKent Overstreet 	unsigned i;
802cafe5635SKent Overstreet 
803cafe5635SKent Overstreet 	for (i = 0; i < mca_reserve(c); i++)
80472a44517SKent Overstreet 		if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
80572a44517SKent Overstreet 			return -ENOMEM;
806cafe5635SKent Overstreet 
807cafe5635SKent Overstreet 	list_splice_init(&c->btree_cache,
808cafe5635SKent Overstreet 			 &c->btree_cache_freeable);
809cafe5635SKent Overstreet 
810cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
811cafe5635SKent Overstreet 	mutex_init(&c->verify_lock);
812cafe5635SKent Overstreet 
813cafe5635SKent Overstreet 	c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
814cafe5635SKent Overstreet 
815cafe5635SKent Overstreet 	if (c->verify_data &&
816cafe5635SKent Overstreet 	    c->verify_data->sets[0].data)
817cafe5635SKent Overstreet 		list_del_init(&c->verify_data->list);
818cafe5635SKent Overstreet 	else
819cafe5635SKent Overstreet 		c->verify_data = NULL;
820cafe5635SKent Overstreet #endif
821cafe5635SKent Overstreet 
8227dc19d5aSDave Chinner 	c->shrink.count_objects = bch_mca_count;
8237dc19d5aSDave Chinner 	c->shrink.scan_objects = bch_mca_scan;
824cafe5635SKent Overstreet 	c->shrink.seeks = 4;
825cafe5635SKent Overstreet 	c->shrink.batch = c->btree_pages * 2;
826cafe5635SKent Overstreet 	register_shrinker(&c->shrink);
827cafe5635SKent Overstreet 
828cafe5635SKent Overstreet 	return 0;
829cafe5635SKent Overstreet }
830cafe5635SKent Overstreet 
831cafe5635SKent Overstreet /* Btree in memory cache - hash table */
832cafe5635SKent Overstreet 
833cafe5635SKent Overstreet static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
834cafe5635SKent Overstreet {
835cafe5635SKent Overstreet 	return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
836cafe5635SKent Overstreet }
837cafe5635SKent Overstreet 
838cafe5635SKent Overstreet static struct btree *mca_find(struct cache_set *c, struct bkey *k)
839cafe5635SKent Overstreet {
840cafe5635SKent Overstreet 	struct btree *b;
841cafe5635SKent Overstreet 
842cafe5635SKent Overstreet 	rcu_read_lock();
843cafe5635SKent Overstreet 	hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
844cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
845cafe5635SKent Overstreet 			goto out;
846cafe5635SKent Overstreet 	b = NULL;
847cafe5635SKent Overstreet out:
848cafe5635SKent Overstreet 	rcu_read_unlock();
849cafe5635SKent Overstreet 	return b;
850cafe5635SKent Overstreet }
851cafe5635SKent Overstreet 
852e8e1d468SKent Overstreet static struct btree *mca_cannibalize(struct cache_set *c, struct bkey *k)
853cafe5635SKent Overstreet {
854e8e1d468SKent Overstreet 	struct btree *b;
855cafe5635SKent Overstreet 
856c37511b8SKent Overstreet 	trace_bcache_btree_cache_cannibalize(c);
857c37511b8SKent Overstreet 
858e8e1d468SKent Overstreet 	if (!c->try_harder) {
859e8e1d468SKent Overstreet 		c->try_harder = current;
860cafe5635SKent Overstreet 		c->try_harder_start = local_clock();
861e8e1d468SKent Overstreet 	} else if (c->try_harder != current)
862e8e1d468SKent Overstreet 		return ERR_PTR(-ENOSPC);
863cafe5635SKent Overstreet 
864e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
865e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
866e8e1d468SKent Overstreet 			return b;
867cafe5635SKent Overstreet 
868e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
869e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), true))
870e8e1d468SKent Overstreet 			return b;
871e8e1d468SKent Overstreet 
872e8e1d468SKent Overstreet 	return ERR_PTR(-ENOMEM);
873cafe5635SKent Overstreet }
874cafe5635SKent Overstreet 
875cafe5635SKent Overstreet /*
876cafe5635SKent Overstreet  * We can only have one thread cannibalizing other cached btree nodes at a time,
877cafe5635SKent Overstreet  * or we'll deadlock. We use an open coded mutex to ensure that, which a
878cafe5635SKent Overstreet  * cannibalize_bucket() will take. This means every time we unlock the root of
879cafe5635SKent Overstreet  * the btree, we need to release this lock if we have it held.
880cafe5635SKent Overstreet  */
881df8e8970SKent Overstreet static void bch_cannibalize_unlock(struct cache_set *c)
882cafe5635SKent Overstreet {
883e8e1d468SKent Overstreet 	if (c->try_harder == current) {
884169ef1cfSKent Overstreet 		bch_time_stats_update(&c->try_harder_time, c->try_harder_start);
885cafe5635SKent Overstreet 		c->try_harder = NULL;
886e8e1d468SKent Overstreet 		wake_up(&c->try_wait);
887cafe5635SKent Overstreet 	}
888cafe5635SKent Overstreet }
889cafe5635SKent Overstreet 
890e8e1d468SKent Overstreet static struct btree *mca_alloc(struct cache_set *c, struct bkey *k, int level)
891cafe5635SKent Overstreet {
892cafe5635SKent Overstreet 	struct btree *b;
893cafe5635SKent Overstreet 
894e8e1d468SKent Overstreet 	BUG_ON(current->bio_list);
895e8e1d468SKent Overstreet 
896cafe5635SKent Overstreet 	lockdep_assert_held(&c->bucket_lock);
897cafe5635SKent Overstreet 
898cafe5635SKent Overstreet 	if (mca_find(c, k))
899cafe5635SKent Overstreet 		return NULL;
900cafe5635SKent Overstreet 
901cafe5635SKent Overstreet 	/* btree_free() doesn't free memory; it sticks the node on the end of
902cafe5635SKent Overstreet 	 * the list. Check if there's any freed nodes there:
903cafe5635SKent Overstreet 	 */
904cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freeable, list)
905e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
906cafe5635SKent Overstreet 			goto out;
907cafe5635SKent Overstreet 
908cafe5635SKent Overstreet 	/* We never free struct btree itself, just the memory that holds the on
909cafe5635SKent Overstreet 	 * disk node. Check the freed list before allocating a new one:
910cafe5635SKent Overstreet 	 */
911cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freed, list)
912e8e1d468SKent Overstreet 		if (!mca_reap(b, 0, false)) {
913cafe5635SKent Overstreet 			mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
914cafe5635SKent Overstreet 			if (!b->sets[0].data)
915cafe5635SKent Overstreet 				goto err;
916cafe5635SKent Overstreet 			else
917cafe5635SKent Overstreet 				goto out;
918cafe5635SKent Overstreet 		}
919cafe5635SKent Overstreet 
920cafe5635SKent Overstreet 	b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
921cafe5635SKent Overstreet 	if (!b)
922cafe5635SKent Overstreet 		goto err;
923cafe5635SKent Overstreet 
924cafe5635SKent Overstreet 	BUG_ON(!down_write_trylock(&b->lock));
925cafe5635SKent Overstreet 	if (!b->sets->data)
926cafe5635SKent Overstreet 		goto err;
927cafe5635SKent Overstreet out:
928cafe5635SKent Overstreet 	BUG_ON(!closure_is_unlocked(&b->io.cl));
929cafe5635SKent Overstreet 
930cafe5635SKent Overstreet 	bkey_copy(&b->key, k);
931cafe5635SKent Overstreet 	list_move(&b->list, &c->btree_cache);
932cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
933cafe5635SKent Overstreet 	hlist_add_head_rcu(&b->hash, mca_hash(c, k));
934cafe5635SKent Overstreet 
935cafe5635SKent Overstreet 	lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
936cafe5635SKent Overstreet 	b->level	= level;
937d6fd3b11SKent Overstreet 	b->parent	= (void *) ~0UL;
938cafe5635SKent Overstreet 
939cafe5635SKent Overstreet 	mca_reinit(b);
940cafe5635SKent Overstreet 
941cafe5635SKent Overstreet 	return b;
942cafe5635SKent Overstreet err:
943cafe5635SKent Overstreet 	if (b)
944cafe5635SKent Overstreet 		rw_unlock(true, b);
945cafe5635SKent Overstreet 
946e8e1d468SKent Overstreet 	b = mca_cannibalize(c, k);
947cafe5635SKent Overstreet 	if (!IS_ERR(b))
948cafe5635SKent Overstreet 		goto out;
949cafe5635SKent Overstreet 
950cafe5635SKent Overstreet 	return b;
951cafe5635SKent Overstreet }
952cafe5635SKent Overstreet 
953cafe5635SKent Overstreet /**
954cafe5635SKent Overstreet  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
955cafe5635SKent Overstreet  * in from disk if necessary.
956cafe5635SKent Overstreet  *
957b54d6934SKent Overstreet  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
958cafe5635SKent Overstreet  *
959cafe5635SKent Overstreet  * The btree node will have either a read or a write lock held, depending on
960cafe5635SKent Overstreet  * level and op->lock.
961cafe5635SKent Overstreet  */
962cafe5635SKent Overstreet struct btree *bch_btree_node_get(struct cache_set *c, struct bkey *k,
963e8e1d468SKent Overstreet 				 int level, bool write)
964cafe5635SKent Overstreet {
965cafe5635SKent Overstreet 	int i = 0;
966cafe5635SKent Overstreet 	struct btree *b;
967cafe5635SKent Overstreet 
968cafe5635SKent Overstreet 	BUG_ON(level < 0);
969cafe5635SKent Overstreet retry:
970cafe5635SKent Overstreet 	b = mca_find(c, k);
971cafe5635SKent Overstreet 
972cafe5635SKent Overstreet 	if (!b) {
97357943511SKent Overstreet 		if (current->bio_list)
97457943511SKent Overstreet 			return ERR_PTR(-EAGAIN);
97557943511SKent Overstreet 
976cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
977e8e1d468SKent Overstreet 		b = mca_alloc(c, k, level);
978cafe5635SKent Overstreet 		mutex_unlock(&c->bucket_lock);
979cafe5635SKent Overstreet 
980cafe5635SKent Overstreet 		if (!b)
981cafe5635SKent Overstreet 			goto retry;
982cafe5635SKent Overstreet 		if (IS_ERR(b))
983cafe5635SKent Overstreet 			return b;
984cafe5635SKent Overstreet 
98557943511SKent Overstreet 		bch_btree_node_read(b);
986cafe5635SKent Overstreet 
987cafe5635SKent Overstreet 		if (!write)
988cafe5635SKent Overstreet 			downgrade_write(&b->lock);
989cafe5635SKent Overstreet 	} else {
990cafe5635SKent Overstreet 		rw_lock(write, b, level);
991cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
992cafe5635SKent Overstreet 			rw_unlock(write, b);
993cafe5635SKent Overstreet 			goto retry;
994cafe5635SKent Overstreet 		}
995cafe5635SKent Overstreet 		BUG_ON(b->level != level);
996cafe5635SKent Overstreet 	}
997cafe5635SKent Overstreet 
998cafe5635SKent Overstreet 	b->accessed = 1;
999cafe5635SKent Overstreet 
1000cafe5635SKent Overstreet 	for (; i <= b->nsets && b->sets[i].size; i++) {
1001cafe5635SKent Overstreet 		prefetch(b->sets[i].tree);
1002cafe5635SKent Overstreet 		prefetch(b->sets[i].data);
1003cafe5635SKent Overstreet 	}
1004cafe5635SKent Overstreet 
1005cafe5635SKent Overstreet 	for (; i <= b->nsets; i++)
1006cafe5635SKent Overstreet 		prefetch(b->sets[i].data);
1007cafe5635SKent Overstreet 
100857943511SKent Overstreet 	if (btree_node_io_error(b)) {
1009cafe5635SKent Overstreet 		rw_unlock(write, b);
101057943511SKent Overstreet 		return ERR_PTR(-EIO);
101157943511SKent Overstreet 	}
101257943511SKent Overstreet 
1013cafe5635SKent Overstreet 	BUG_ON(!b->written);
1014cafe5635SKent Overstreet 
1015cafe5635SKent Overstreet 	return b;
1016cafe5635SKent Overstreet }
1017cafe5635SKent Overstreet 
1018cafe5635SKent Overstreet static void btree_node_prefetch(struct cache_set *c, struct bkey *k, int level)
1019cafe5635SKent Overstreet {
1020cafe5635SKent Overstreet 	struct btree *b;
1021cafe5635SKent Overstreet 
1022cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1023e8e1d468SKent Overstreet 	b = mca_alloc(c, k, level);
1024cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1025cafe5635SKent Overstreet 
1026cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(b)) {
102757943511SKent Overstreet 		bch_btree_node_read(b);
1028cafe5635SKent Overstreet 		rw_unlock(true, b);
1029cafe5635SKent Overstreet 	}
1030cafe5635SKent Overstreet }
1031cafe5635SKent Overstreet 
1032cafe5635SKent Overstreet /* Btree alloc */
1033cafe5635SKent Overstreet 
1034e8e1d468SKent Overstreet static void btree_node_free(struct btree *b)
1035cafe5635SKent Overstreet {
1036cafe5635SKent Overstreet 	unsigned i;
1037cafe5635SKent Overstreet 
1038c37511b8SKent Overstreet 	trace_bcache_btree_node_free(b);
1039c37511b8SKent Overstreet 
1040cafe5635SKent Overstreet 	BUG_ON(b == b->c->root);
1041cafe5635SKent Overstreet 
1042cafe5635SKent Overstreet 	if (btree_node_dirty(b))
1043cafe5635SKent Overstreet 		btree_complete_write(b, btree_current_write(b));
1044cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty, &b->flags);
1045cafe5635SKent Overstreet 
1046cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
1047cafe5635SKent Overstreet 
1048cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
1049cafe5635SKent Overstreet 
1050cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++) {
1051cafe5635SKent Overstreet 		BUG_ON(atomic_read(&PTR_BUCKET(b->c, &b->key, i)->pin));
1052cafe5635SKent Overstreet 
1053cafe5635SKent Overstreet 		bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
1054cafe5635SKent Overstreet 			    PTR_BUCKET(b->c, &b->key, i));
1055cafe5635SKent Overstreet 	}
1056cafe5635SKent Overstreet 
1057cafe5635SKent Overstreet 	bch_bucket_free(b->c, &b->key);
1058cafe5635SKent Overstreet 	mca_bucket_free(b);
1059cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
1060cafe5635SKent Overstreet }
1061cafe5635SKent Overstreet 
106235fcd848SKent Overstreet struct btree *bch_btree_node_alloc(struct cache_set *c, int level)
1063cafe5635SKent Overstreet {
1064cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
1065cafe5635SKent Overstreet 	struct btree *b = ERR_PTR(-EAGAIN);
1066cafe5635SKent Overstreet 
1067cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1068cafe5635SKent Overstreet retry:
106935fcd848SKent Overstreet 	if (__bch_bucket_alloc_set(c, WATERMARK_METADATA, &k.key, 1, true))
1070cafe5635SKent Overstreet 		goto err;
1071cafe5635SKent Overstreet 
10723a3b6a4eSKent Overstreet 	bkey_put(c, &k.key);
1073cafe5635SKent Overstreet 	SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1074cafe5635SKent Overstreet 
1075e8e1d468SKent Overstreet 	b = mca_alloc(c, &k.key, level);
1076cafe5635SKent Overstreet 	if (IS_ERR(b))
1077cafe5635SKent Overstreet 		goto err_free;
1078cafe5635SKent Overstreet 
1079cafe5635SKent Overstreet 	if (!b) {
1080b1a67b0fSKent Overstreet 		cache_bug(c,
1081b1a67b0fSKent Overstreet 			"Tried to allocate bucket that was in btree cache");
1082cafe5635SKent Overstreet 		goto retry;
1083cafe5635SKent Overstreet 	}
1084cafe5635SKent Overstreet 
1085cafe5635SKent Overstreet 	b->accessed = 1;
1086cafe5635SKent Overstreet 	bch_bset_init_next(b);
1087cafe5635SKent Overstreet 
1088cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1089c37511b8SKent Overstreet 
1090c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc(b);
1091cafe5635SKent Overstreet 	return b;
1092cafe5635SKent Overstreet err_free:
1093cafe5635SKent Overstreet 	bch_bucket_free(c, &k.key);
1094cafe5635SKent Overstreet err:
1095cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1096c37511b8SKent Overstreet 
1097c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc_fail(b);
1098cafe5635SKent Overstreet 	return b;
1099cafe5635SKent Overstreet }
1100cafe5635SKent Overstreet 
110135fcd848SKent Overstreet static struct btree *btree_node_alloc_replacement(struct btree *b)
1102cafe5635SKent Overstreet {
110335fcd848SKent Overstreet 	struct btree *n = bch_btree_node_alloc(b->c, b->level);
1104cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(n))
1105cafe5635SKent Overstreet 		bch_btree_sort_into(b, n);
1106cafe5635SKent Overstreet 
1107cafe5635SKent Overstreet 	return n;
1108cafe5635SKent Overstreet }
1109cafe5635SKent Overstreet 
11108835c123SKent Overstreet static void make_btree_freeing_key(struct btree *b, struct bkey *k)
11118835c123SKent Overstreet {
11128835c123SKent Overstreet 	unsigned i;
11138835c123SKent Overstreet 
11148835c123SKent Overstreet 	bkey_copy(k, &b->key);
11158835c123SKent Overstreet 	bkey_copy_key(k, &ZERO_KEY);
11168835c123SKent Overstreet 
11178835c123SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
11188835c123SKent Overstreet 		uint8_t g = PTR_BUCKET(b->c, k, i)->gen + 1;
11198835c123SKent Overstreet 
11208835c123SKent Overstreet 		SET_PTR_GEN(k, i, g);
11218835c123SKent Overstreet 	}
11228835c123SKent Overstreet 
11238835c123SKent Overstreet 	atomic_inc(&b->c->prio_blocked);
11248835c123SKent Overstreet }
11258835c123SKent Overstreet 
1126cafe5635SKent Overstreet /* Garbage collection */
1127cafe5635SKent Overstreet 
1128cafe5635SKent Overstreet uint8_t __bch_btree_mark_key(struct cache_set *c, int level, struct bkey *k)
1129cafe5635SKent Overstreet {
1130cafe5635SKent Overstreet 	uint8_t stale = 0;
1131cafe5635SKent Overstreet 	unsigned i;
1132cafe5635SKent Overstreet 	struct bucket *g;
1133cafe5635SKent Overstreet 
1134cafe5635SKent Overstreet 	/*
1135cafe5635SKent Overstreet 	 * ptr_invalid() can't return true for the keys that mark btree nodes as
1136cafe5635SKent Overstreet 	 * freed, but since ptr_bad() returns true we'll never actually use them
1137cafe5635SKent Overstreet 	 * for anything and thus we don't want mark their pointers here
1138cafe5635SKent Overstreet 	 */
1139cafe5635SKent Overstreet 	if (!bkey_cmp(k, &ZERO_KEY))
1140cafe5635SKent Overstreet 		return stale;
1141cafe5635SKent Overstreet 
1142cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
1143cafe5635SKent Overstreet 		if (!ptr_available(c, k, i))
1144cafe5635SKent Overstreet 			continue;
1145cafe5635SKent Overstreet 
1146cafe5635SKent Overstreet 		g = PTR_BUCKET(c, k, i);
1147cafe5635SKent Overstreet 
1148cafe5635SKent Overstreet 		if (gen_after(g->gc_gen, PTR_GEN(k, i)))
1149cafe5635SKent Overstreet 			g->gc_gen = PTR_GEN(k, i);
1150cafe5635SKent Overstreet 
1151cafe5635SKent Overstreet 		if (ptr_stale(c, k, i)) {
1152cafe5635SKent Overstreet 			stale = max(stale, ptr_stale(c, k, i));
1153cafe5635SKent Overstreet 			continue;
1154cafe5635SKent Overstreet 		}
1155cafe5635SKent Overstreet 
1156cafe5635SKent Overstreet 		cache_bug_on(GC_MARK(g) &&
1157cafe5635SKent Overstreet 			     (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1158cafe5635SKent Overstreet 			     c, "inconsistent ptrs: mark = %llu, level = %i",
1159cafe5635SKent Overstreet 			     GC_MARK(g), level);
1160cafe5635SKent Overstreet 
1161cafe5635SKent Overstreet 		if (level)
1162cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_METADATA);
1163cafe5635SKent Overstreet 		else if (KEY_DIRTY(k))
1164cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_DIRTY);
1165cafe5635SKent Overstreet 
1166cafe5635SKent Overstreet 		/* guard against overflow */
1167cafe5635SKent Overstreet 		SET_GC_SECTORS_USED(g, min_t(unsigned,
1168cafe5635SKent Overstreet 					     GC_SECTORS_USED(g) + KEY_SIZE(k),
1169cafe5635SKent Overstreet 					     (1 << 14) - 1));
1170cafe5635SKent Overstreet 
1171cafe5635SKent Overstreet 		BUG_ON(!GC_SECTORS_USED(g));
1172cafe5635SKent Overstreet 	}
1173cafe5635SKent Overstreet 
1174cafe5635SKent Overstreet 	return stale;
1175cafe5635SKent Overstreet }
1176cafe5635SKent Overstreet 
1177cafe5635SKent Overstreet #define btree_mark_key(b, k)	__bch_btree_mark_key(b->c, b->level, k)
1178cafe5635SKent Overstreet 
1179*a1f0358bSKent Overstreet static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1180cafe5635SKent Overstreet {
1181cafe5635SKent Overstreet 	uint8_t stale = 0;
1182*a1f0358bSKent Overstreet 	unsigned keys = 0, good_keys = 0;
1183cafe5635SKent Overstreet 	struct bkey *k;
1184cafe5635SKent Overstreet 	struct btree_iter iter;
1185cafe5635SKent Overstreet 	struct bset_tree *t;
1186cafe5635SKent Overstreet 
1187cafe5635SKent Overstreet 	gc->nodes++;
1188cafe5635SKent Overstreet 
1189cafe5635SKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1190cafe5635SKent Overstreet 		stale = max(stale, btree_mark_key(b, k));
1191*a1f0358bSKent Overstreet 		keys++;
1192cafe5635SKent Overstreet 
1193cafe5635SKent Overstreet 		if (bch_ptr_bad(b, k))
1194cafe5635SKent Overstreet 			continue;
1195cafe5635SKent Overstreet 
1196cafe5635SKent Overstreet 		gc->key_bytes += bkey_u64s(k);
1197cafe5635SKent Overstreet 		gc->nkeys++;
1198*a1f0358bSKent Overstreet 		good_keys++;
1199cafe5635SKent Overstreet 
1200cafe5635SKent Overstreet 		gc->data += KEY_SIZE(k);
1201cafe5635SKent Overstreet 	}
1202cafe5635SKent Overstreet 
1203cafe5635SKent Overstreet 	for (t = b->sets; t <= &b->sets[b->nsets]; t++)
1204cafe5635SKent Overstreet 		btree_bug_on(t->size &&
1205cafe5635SKent Overstreet 			     bset_written(b, t) &&
1206cafe5635SKent Overstreet 			     bkey_cmp(&b->key, &t->end) < 0,
1207cafe5635SKent Overstreet 			     b, "found short btree key in gc");
1208cafe5635SKent Overstreet 
1209*a1f0358bSKent Overstreet 	if (b->c->gc_always_rewrite)
1210*a1f0358bSKent Overstreet 		return true;
1211*a1f0358bSKent Overstreet 
1212*a1f0358bSKent Overstreet 	if (stale > 10)
1213*a1f0358bSKent Overstreet 		return true;
1214*a1f0358bSKent Overstreet 
1215*a1f0358bSKent Overstreet 	if ((keys - good_keys) * 2 > keys)
1216*a1f0358bSKent Overstreet 		return true;
1217*a1f0358bSKent Overstreet 
1218*a1f0358bSKent Overstreet 	return false;
1219cafe5635SKent Overstreet }
1220cafe5635SKent Overstreet 
1221*a1f0358bSKent Overstreet #define GC_MERGE_NODES	4U
1222cafe5635SKent Overstreet 
1223cafe5635SKent Overstreet struct gc_merge_info {
1224cafe5635SKent Overstreet 	struct btree	*b;
1225cafe5635SKent Overstreet 	unsigned	keys;
1226cafe5635SKent Overstreet };
1227cafe5635SKent Overstreet 
1228*a1f0358bSKent Overstreet static int bch_btree_insert_node(struct btree *, struct btree_op *,
1229*a1f0358bSKent Overstreet 				 struct keylist *, atomic_t *, struct bkey *);
1230*a1f0358bSKent Overstreet 
1231*a1f0358bSKent Overstreet static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
1232*a1f0358bSKent Overstreet 			     struct keylist *keylist, struct gc_stat *gc,
1233e8e1d468SKent Overstreet 			     struct gc_merge_info *r)
1234cafe5635SKent Overstreet {
1235*a1f0358bSKent Overstreet 	unsigned i, nodes = 0, keys = 0, blocks;
1236*a1f0358bSKent Overstreet 	struct btree *new_nodes[GC_MERGE_NODES];
1237b54d6934SKent Overstreet 	struct closure cl;
1238*a1f0358bSKent Overstreet 	struct bkey *k;
1239b54d6934SKent Overstreet 
1240*a1f0358bSKent Overstreet 	memset(new_nodes, 0, sizeof(new_nodes));
1241b54d6934SKent Overstreet 	closure_init_stack(&cl);
1242cafe5635SKent Overstreet 
1243*a1f0358bSKent Overstreet 	while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1244cafe5635SKent Overstreet 		keys += r[nodes++].keys;
1245cafe5635SKent Overstreet 
1246cafe5635SKent Overstreet 	blocks = btree_default_blocks(b->c) * 2 / 3;
1247cafe5635SKent Overstreet 
1248cafe5635SKent Overstreet 	if (nodes < 2 ||
1249cafe5635SKent Overstreet 	    __set_blocks(b->sets[0].data, keys, b->c) > blocks * (nodes - 1))
1250*a1f0358bSKent Overstreet 		return 0;
1251cafe5635SKent Overstreet 
1252*a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1253*a1f0358bSKent Overstreet 		new_nodes[i] = btree_node_alloc_replacement(r[i].b);
1254*a1f0358bSKent Overstreet 		if (IS_ERR_OR_NULL(new_nodes[i]))
1255*a1f0358bSKent Overstreet 			goto out_nocoalesce;
1256cafe5635SKent Overstreet 	}
1257cafe5635SKent Overstreet 
1258cafe5635SKent Overstreet 	for (i = nodes - 1; i > 0; --i) {
1259*a1f0358bSKent Overstreet 		struct bset *n1 = new_nodes[i]->sets->data;
1260*a1f0358bSKent Overstreet 		struct bset *n2 = new_nodes[i - 1]->sets->data;
1261cafe5635SKent Overstreet 		struct bkey *k, *last = NULL;
1262cafe5635SKent Overstreet 
1263cafe5635SKent Overstreet 		keys = 0;
1264cafe5635SKent Overstreet 
1265*a1f0358bSKent Overstreet 		if (i > 1) {
1266cafe5635SKent Overstreet 			for (k = n2->start;
1267cafe5635SKent Overstreet 			     k < end(n2);
1268cafe5635SKent Overstreet 			     k = bkey_next(k)) {
1269cafe5635SKent Overstreet 				if (__set_blocks(n1, n1->keys + keys +
1270cafe5635SKent Overstreet 						 bkey_u64s(k), b->c) > blocks)
1271cafe5635SKent Overstreet 					break;
1272cafe5635SKent Overstreet 
1273cafe5635SKent Overstreet 				last = k;
1274cafe5635SKent Overstreet 				keys += bkey_u64s(k);
1275cafe5635SKent Overstreet 			}
1276*a1f0358bSKent Overstreet 		} else {
1277*a1f0358bSKent Overstreet 			/*
1278*a1f0358bSKent Overstreet 			 * Last node we're not getting rid of - we're getting
1279*a1f0358bSKent Overstreet 			 * rid of the node at r[0]. Have to try and fit all of
1280*a1f0358bSKent Overstreet 			 * the remaining keys into this node; we can't ensure
1281*a1f0358bSKent Overstreet 			 * they will always fit due to rounding and variable
1282*a1f0358bSKent Overstreet 			 * length keys (shouldn't be possible in practice,
1283*a1f0358bSKent Overstreet 			 * though)
1284*a1f0358bSKent Overstreet 			 */
1285*a1f0358bSKent Overstreet 			if (__set_blocks(n1, n1->keys + n2->keys,
1286*a1f0358bSKent Overstreet 					 b->c) > btree_blocks(new_nodes[i]))
1287*a1f0358bSKent Overstreet 				goto out_nocoalesce;
1288*a1f0358bSKent Overstreet 
1289*a1f0358bSKent Overstreet 			keys = n2->keys;
1290*a1f0358bSKent Overstreet 			/* Take the key of the node we're getting rid of */
1291*a1f0358bSKent Overstreet 			last = &r->b->key;
1292*a1f0358bSKent Overstreet 		}
1293cafe5635SKent Overstreet 
1294cafe5635SKent Overstreet 		BUG_ON(__set_blocks(n1, n1->keys + keys,
1295*a1f0358bSKent Overstreet 				    b->c) > btree_blocks(new_nodes[i]));
1296cafe5635SKent Overstreet 
1297*a1f0358bSKent Overstreet 		if (last)
1298*a1f0358bSKent Overstreet 			bkey_copy_key(&new_nodes[i]->key, last);
1299cafe5635SKent Overstreet 
1300cafe5635SKent Overstreet 		memcpy(end(n1),
1301cafe5635SKent Overstreet 		       n2->start,
1302cafe5635SKent Overstreet 		       (void *) node(n2, keys) - (void *) n2->start);
1303cafe5635SKent Overstreet 
1304cafe5635SKent Overstreet 		n1->keys += keys;
1305*a1f0358bSKent Overstreet 		r[i].keys = n1->keys;
1306cafe5635SKent Overstreet 
1307cafe5635SKent Overstreet 		memmove(n2->start,
1308cafe5635SKent Overstreet 			node(n2, keys),
1309cafe5635SKent Overstreet 			(void *) end(n2) - (void *) node(n2, keys));
1310cafe5635SKent Overstreet 
1311cafe5635SKent Overstreet 		n2->keys -= keys;
1312cafe5635SKent Overstreet 
1313*a1f0358bSKent Overstreet 		if (bch_keylist_realloc(keylist,
1314*a1f0358bSKent Overstreet 					KEY_PTRS(&new_nodes[i]->key), b->c))
1315*a1f0358bSKent Overstreet 			goto out_nocoalesce;
1316*a1f0358bSKent Overstreet 
1317*a1f0358bSKent Overstreet 		bch_btree_node_write(new_nodes[i], &cl);
1318*a1f0358bSKent Overstreet 		bch_keylist_add(keylist, &new_nodes[i]->key);
1319cafe5635SKent Overstreet 	}
1320cafe5635SKent Overstreet 
1321*a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1322*a1f0358bSKent Overstreet 		if (bch_keylist_realloc(keylist, KEY_PTRS(&r[i].b->key), b->c))
1323*a1f0358bSKent Overstreet 			goto out_nocoalesce;
1324*a1f0358bSKent Overstreet 
1325*a1f0358bSKent Overstreet 		make_btree_freeing_key(r[i].b, keylist->top);
1326*a1f0358bSKent Overstreet 		bch_keylist_push(keylist);
1327*a1f0358bSKent Overstreet 	}
1328*a1f0358bSKent Overstreet 
1329*a1f0358bSKent Overstreet 	/* We emptied out this node */
1330*a1f0358bSKent Overstreet 	BUG_ON(new_nodes[0]->sets->data->keys);
1331*a1f0358bSKent Overstreet 	btree_node_free(new_nodes[0]);
1332*a1f0358bSKent Overstreet 	rw_unlock(true, new_nodes[0]);
1333*a1f0358bSKent Overstreet 
1334*a1f0358bSKent Overstreet 	closure_sync(&cl);
1335*a1f0358bSKent Overstreet 
1336*a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1337*a1f0358bSKent Overstreet 		btree_node_free(r[i].b);
1338*a1f0358bSKent Overstreet 		rw_unlock(true, r[i].b);
1339*a1f0358bSKent Overstreet 
1340*a1f0358bSKent Overstreet 		r[i].b = new_nodes[i];
1341*a1f0358bSKent Overstreet 	}
1342*a1f0358bSKent Overstreet 
1343*a1f0358bSKent Overstreet 	bch_btree_insert_node(b, op, keylist, NULL, NULL);
1344*a1f0358bSKent Overstreet 	BUG_ON(!bch_keylist_empty(keylist));
1345*a1f0358bSKent Overstreet 
1346*a1f0358bSKent Overstreet 	memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1347*a1f0358bSKent Overstreet 	r[nodes - 1].b = ERR_PTR(-EINTR);
1348cafe5635SKent Overstreet 
1349c37511b8SKent Overstreet 	trace_bcache_btree_gc_coalesce(nodes);
1350cafe5635SKent Overstreet 	gc->nodes--;
1351cafe5635SKent Overstreet 
1352*a1f0358bSKent Overstreet 	/* Invalidated our iterator */
1353*a1f0358bSKent Overstreet 	return -EINTR;
1354*a1f0358bSKent Overstreet 
1355*a1f0358bSKent Overstreet out_nocoalesce:
1356*a1f0358bSKent Overstreet 	closure_sync(&cl);
1357*a1f0358bSKent Overstreet 
1358*a1f0358bSKent Overstreet 	while ((k = bch_keylist_pop(keylist)))
1359*a1f0358bSKent Overstreet 		if (!bkey_cmp(k, &ZERO_KEY))
1360*a1f0358bSKent Overstreet 			atomic_dec(&b->c->prio_blocked);
1361*a1f0358bSKent Overstreet 
1362*a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++)
1363*a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(new_nodes[i])) {
1364*a1f0358bSKent Overstreet 			btree_node_free(new_nodes[i]);
1365*a1f0358bSKent Overstreet 			rw_unlock(true, new_nodes[i]);
1366*a1f0358bSKent Overstreet 		}
1367*a1f0358bSKent Overstreet 	return 0;
1368*a1f0358bSKent Overstreet }
1369*a1f0358bSKent Overstreet 
1370*a1f0358bSKent Overstreet static unsigned btree_gc_count_keys(struct btree *b)
1371*a1f0358bSKent Overstreet {
1372*a1f0358bSKent Overstreet 	struct bkey *k;
1373*a1f0358bSKent Overstreet 	struct btree_iter iter;
1374*a1f0358bSKent Overstreet 	unsigned ret = 0;
1375*a1f0358bSKent Overstreet 
1376*a1f0358bSKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_bad)
1377*a1f0358bSKent Overstreet 		ret += bkey_u64s(k);
1378*a1f0358bSKent Overstreet 
1379*a1f0358bSKent Overstreet 	return ret;
1380cafe5635SKent Overstreet }
1381cafe5635SKent Overstreet 
1382cafe5635SKent Overstreet static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1383cafe5635SKent Overstreet 			    struct closure *writes, struct gc_stat *gc)
1384cafe5635SKent Overstreet {
1385cafe5635SKent Overstreet 	unsigned i;
1386*a1f0358bSKent Overstreet 	int ret = 0;
1387*a1f0358bSKent Overstreet 	bool should_rewrite;
1388*a1f0358bSKent Overstreet 	struct btree *n;
1389*a1f0358bSKent Overstreet 	struct bkey *k;
1390*a1f0358bSKent Overstreet 	struct keylist keys;
1391*a1f0358bSKent Overstreet 	struct btree_iter iter;
1392cafe5635SKent Overstreet 	struct gc_merge_info r[GC_MERGE_NODES];
1393*a1f0358bSKent Overstreet 	struct gc_merge_info *last = r + GC_MERGE_NODES - 1;
1394cafe5635SKent Overstreet 
1395*a1f0358bSKent Overstreet 	bch_keylist_init(&keys);
1396*a1f0358bSKent Overstreet 	bch_btree_iter_init(b, &iter, &b->c->gc_done);
1397cafe5635SKent Overstreet 
1398*a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1399*a1f0358bSKent Overstreet 		r[i].b = ERR_PTR(-EINTR);
1400cafe5635SKent Overstreet 
1401*a1f0358bSKent Overstreet 	while (1) {
1402*a1f0358bSKent Overstreet 		k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad);
1403*a1f0358bSKent Overstreet 		if (k) {
1404*a1f0358bSKent Overstreet 			r->b = bch_btree_node_get(b->c, k, b->level - 1, true);
1405cafe5635SKent Overstreet 			if (IS_ERR(r->b)) {
1406cafe5635SKent Overstreet 				ret = PTR_ERR(r->b);
1407cafe5635SKent Overstreet 				break;
1408cafe5635SKent Overstreet 			}
1409cafe5635SKent Overstreet 
1410*a1f0358bSKent Overstreet 			r->keys = btree_gc_count_keys(r->b);
1411cafe5635SKent Overstreet 
1412*a1f0358bSKent Overstreet 			ret = btree_gc_coalesce(b, op, &keys, gc, r);
1413*a1f0358bSKent Overstreet 			if (ret)
1414cafe5635SKent Overstreet 				break;
1415cafe5635SKent Overstreet 		}
1416cafe5635SKent Overstreet 
1417*a1f0358bSKent Overstreet 		if (!last->b)
1418*a1f0358bSKent Overstreet 			break;
1419cafe5635SKent Overstreet 
1420*a1f0358bSKent Overstreet 		if (!IS_ERR(last->b)) {
1421*a1f0358bSKent Overstreet 			should_rewrite = btree_gc_mark_node(last->b, gc);
1422*a1f0358bSKent Overstreet 			if (should_rewrite) {
1423*a1f0358bSKent Overstreet 				n = btree_node_alloc_replacement(last->b);
1424cafe5635SKent Overstreet 
1425*a1f0358bSKent Overstreet 				if (!IS_ERR_OR_NULL(n)) {
1426*a1f0358bSKent Overstreet 					bch_btree_node_write_sync(n);
1427*a1f0358bSKent Overstreet 					bch_keylist_add(&keys, &n->key);
1428cafe5635SKent Overstreet 
1429*a1f0358bSKent Overstreet 					make_btree_freeing_key(last->b,
1430*a1f0358bSKent Overstreet 							       keys.top);
1431*a1f0358bSKent Overstreet 					bch_keylist_push(&keys);
1432cafe5635SKent Overstreet 
1433*a1f0358bSKent Overstreet 					btree_node_free(last->b);
1434*a1f0358bSKent Overstreet 
1435*a1f0358bSKent Overstreet 					bch_btree_insert_node(b, op, &keys,
1436*a1f0358bSKent Overstreet 							      NULL, NULL);
1437*a1f0358bSKent Overstreet 					BUG_ON(!bch_keylist_empty(&keys));
1438*a1f0358bSKent Overstreet 
1439*a1f0358bSKent Overstreet 					rw_unlock(true, last->b);
1440*a1f0358bSKent Overstreet 					last->b = n;
1441*a1f0358bSKent Overstreet 
1442*a1f0358bSKent Overstreet 					/* Invalidated our iterator */
1443*a1f0358bSKent Overstreet 					ret = -EINTR;
1444*a1f0358bSKent Overstreet 					break;
1445*a1f0358bSKent Overstreet 				}
1446*a1f0358bSKent Overstreet 			}
1447*a1f0358bSKent Overstreet 
1448*a1f0358bSKent Overstreet 			if (last->b->level) {
1449*a1f0358bSKent Overstreet 				ret = btree_gc_recurse(last->b, op, writes, gc);
1450*a1f0358bSKent Overstreet 				if (ret)
1451*a1f0358bSKent Overstreet 					break;
1452*a1f0358bSKent Overstreet 			}
1453*a1f0358bSKent Overstreet 
1454*a1f0358bSKent Overstreet 			bkey_copy_key(&b->c->gc_done, &last->b->key);
1455*a1f0358bSKent Overstreet 
1456*a1f0358bSKent Overstreet 			/*
1457*a1f0358bSKent Overstreet 			 * Must flush leaf nodes before gc ends, since replace
1458*a1f0358bSKent Overstreet 			 * operations aren't journalled
1459cafe5635SKent Overstreet 			 */
1460*a1f0358bSKent Overstreet 			if (btree_node_dirty(last->b))
1461*a1f0358bSKent Overstreet 				bch_btree_node_write(last->b, writes);
1462*a1f0358bSKent Overstreet 			rw_unlock(true, last->b);
1463*a1f0358bSKent Overstreet 		}
1464*a1f0358bSKent Overstreet 
1465*a1f0358bSKent Overstreet 		memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1466*a1f0358bSKent Overstreet 		r->b = NULL;
1467*a1f0358bSKent Overstreet 
1468cafe5635SKent Overstreet 		if (need_resched()) {
1469cafe5635SKent Overstreet 			ret = -EAGAIN;
1470cafe5635SKent Overstreet 			break;
1471cafe5635SKent Overstreet 		}
1472cafe5635SKent Overstreet 	}
1473cafe5635SKent Overstreet 
1474*a1f0358bSKent Overstreet 	for (i = 0; i < GC_MERGE_NODES; i++)
1475*a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(r[i].b)) {
1476*a1f0358bSKent Overstreet 			if (btree_node_dirty(r[i].b))
1477*a1f0358bSKent Overstreet 				bch_btree_node_write(r[i].b, writes);
1478*a1f0358bSKent Overstreet 			rw_unlock(true, r[i].b);
1479*a1f0358bSKent Overstreet 		}
1480cafe5635SKent Overstreet 
1481*a1f0358bSKent Overstreet 	bch_keylist_free(&keys);
1482cafe5635SKent Overstreet 
1483cafe5635SKent Overstreet 	return ret;
1484cafe5635SKent Overstreet }
1485cafe5635SKent Overstreet 
1486cafe5635SKent Overstreet static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1487cafe5635SKent Overstreet 			     struct closure *writes, struct gc_stat *gc)
1488cafe5635SKent Overstreet {
1489cafe5635SKent Overstreet 	struct btree *n = NULL;
1490*a1f0358bSKent Overstreet 	int ret = 0;
1491*a1f0358bSKent Overstreet 	bool should_rewrite;
1492cafe5635SKent Overstreet 
1493*a1f0358bSKent Overstreet 	should_rewrite = btree_gc_mark_node(b, gc);
1494*a1f0358bSKent Overstreet 	if (should_rewrite) {
149535fcd848SKent Overstreet 		n = btree_node_alloc_replacement(b);
1496cafe5635SKent Overstreet 
1497cafe5635SKent Overstreet 		if (!IS_ERR_OR_NULL(n)) {
1498*a1f0358bSKent Overstreet 			bch_btree_node_write_sync(n);
1499*a1f0358bSKent Overstreet 			bch_btree_set_root(n);
1500*a1f0358bSKent Overstreet 			btree_node_free(b);
1501*a1f0358bSKent Overstreet 			rw_unlock(true, n);
1502*a1f0358bSKent Overstreet 
1503*a1f0358bSKent Overstreet 			return -EINTR;
1504cafe5635SKent Overstreet 		}
1505*a1f0358bSKent Overstreet 	}
1506*a1f0358bSKent Overstreet 
1507*a1f0358bSKent Overstreet 	if (b->level) {
1508*a1f0358bSKent Overstreet 		ret = btree_gc_recurse(b, op, writes, gc);
1509*a1f0358bSKent Overstreet 		if (ret)
1510*a1f0358bSKent Overstreet 			return ret;
1511*a1f0358bSKent Overstreet 	}
1512*a1f0358bSKent Overstreet 
1513*a1f0358bSKent Overstreet 	bkey_copy_key(&b->c->gc_done, &b->key);
1514cafe5635SKent Overstreet 
1515cafe5635SKent Overstreet 	return ret;
1516cafe5635SKent Overstreet }
1517cafe5635SKent Overstreet 
1518cafe5635SKent Overstreet static void btree_gc_start(struct cache_set *c)
1519cafe5635SKent Overstreet {
1520cafe5635SKent Overstreet 	struct cache *ca;
1521cafe5635SKent Overstreet 	struct bucket *b;
1522cafe5635SKent Overstreet 	unsigned i;
1523cafe5635SKent Overstreet 
1524cafe5635SKent Overstreet 	if (!c->gc_mark_valid)
1525cafe5635SKent Overstreet 		return;
1526cafe5635SKent Overstreet 
1527cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1528cafe5635SKent Overstreet 
1529cafe5635SKent Overstreet 	c->gc_mark_valid = 0;
1530cafe5635SKent Overstreet 	c->gc_done = ZERO_KEY;
1531cafe5635SKent Overstreet 
1532cafe5635SKent Overstreet 	for_each_cache(ca, c, i)
1533cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1534cafe5635SKent Overstreet 			b->gc_gen = b->gen;
153529ebf465SKent Overstreet 			if (!atomic_read(&b->pin)) {
1536cafe5635SKent Overstreet 				SET_GC_MARK(b, GC_MARK_RECLAIMABLE);
153729ebf465SKent Overstreet 				SET_GC_SECTORS_USED(b, 0);
153829ebf465SKent Overstreet 			}
1539cafe5635SKent Overstreet 		}
1540cafe5635SKent Overstreet 
1541cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1542cafe5635SKent Overstreet }
1543cafe5635SKent Overstreet 
1544cafe5635SKent Overstreet size_t bch_btree_gc_finish(struct cache_set *c)
1545cafe5635SKent Overstreet {
1546cafe5635SKent Overstreet 	size_t available = 0;
1547cafe5635SKent Overstreet 	struct bucket *b;
1548cafe5635SKent Overstreet 	struct cache *ca;
1549cafe5635SKent Overstreet 	unsigned i;
1550cafe5635SKent Overstreet 
1551cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1552cafe5635SKent Overstreet 
1553cafe5635SKent Overstreet 	set_gc_sectors(c);
1554cafe5635SKent Overstreet 	c->gc_mark_valid = 1;
1555cafe5635SKent Overstreet 	c->need_gc	= 0;
1556cafe5635SKent Overstreet 
1557cafe5635SKent Overstreet 	if (c->root)
1558cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(&c->root->key); i++)
1559cafe5635SKent Overstreet 			SET_GC_MARK(PTR_BUCKET(c, &c->root->key, i),
1560cafe5635SKent Overstreet 				    GC_MARK_METADATA);
1561cafe5635SKent Overstreet 
1562cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1563cafe5635SKent Overstreet 		SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1564cafe5635SKent Overstreet 			    GC_MARK_METADATA);
1565cafe5635SKent Overstreet 
1566cafe5635SKent Overstreet 	for_each_cache(ca, c, i) {
1567cafe5635SKent Overstreet 		uint64_t *i;
1568cafe5635SKent Overstreet 
1569cafe5635SKent Overstreet 		ca->invalidate_needs_gc = 0;
1570cafe5635SKent Overstreet 
1571cafe5635SKent Overstreet 		for (i = ca->sb.d; i < ca->sb.d + ca->sb.keys; i++)
1572cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1573cafe5635SKent Overstreet 
1574cafe5635SKent Overstreet 		for (i = ca->prio_buckets;
1575cafe5635SKent Overstreet 		     i < ca->prio_buckets + prio_buckets(ca) * 2; i++)
1576cafe5635SKent Overstreet 			SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1577cafe5635SKent Overstreet 
1578cafe5635SKent Overstreet 		for_each_bucket(b, ca) {
1579cafe5635SKent Overstreet 			b->last_gc	= b->gc_gen;
1580cafe5635SKent Overstreet 			c->need_gc	= max(c->need_gc, bucket_gc_gen(b));
1581cafe5635SKent Overstreet 
1582cafe5635SKent Overstreet 			if (!atomic_read(&b->pin) &&
1583cafe5635SKent Overstreet 			    GC_MARK(b) == GC_MARK_RECLAIMABLE) {
1584cafe5635SKent Overstreet 				available++;
1585cafe5635SKent Overstreet 				if (!GC_SECTORS_USED(b))
1586cafe5635SKent Overstreet 					bch_bucket_add_unused(ca, b);
1587cafe5635SKent Overstreet 			}
1588cafe5635SKent Overstreet 		}
1589cafe5635SKent Overstreet 	}
1590cafe5635SKent Overstreet 
1591cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1592cafe5635SKent Overstreet 	return available;
1593cafe5635SKent Overstreet }
1594cafe5635SKent Overstreet 
159572a44517SKent Overstreet static void bch_btree_gc(struct cache_set *c)
1596cafe5635SKent Overstreet {
1597cafe5635SKent Overstreet 	int ret;
1598cafe5635SKent Overstreet 	unsigned long available;
1599cafe5635SKent Overstreet 	struct gc_stat stats;
1600cafe5635SKent Overstreet 	struct closure writes;
1601cafe5635SKent Overstreet 	struct btree_op op;
1602cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
160357943511SKent Overstreet 
1604c37511b8SKent Overstreet 	trace_bcache_gc_start(c);
1605cafe5635SKent Overstreet 
1606cafe5635SKent Overstreet 	memset(&stats, 0, sizeof(struct gc_stat));
1607cafe5635SKent Overstreet 	closure_init_stack(&writes);
1608b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1609cafe5635SKent Overstreet 
1610cafe5635SKent Overstreet 	btree_gc_start(c);
1611cafe5635SKent Overstreet 
1612*a1f0358bSKent Overstreet 	do {
1613cafe5635SKent Overstreet 		ret = btree_root(gc_root, c, &op, &writes, &stats);
1614cafe5635SKent Overstreet 		closure_sync(&writes);
1615cafe5635SKent Overstreet 
1616*a1f0358bSKent Overstreet 		if (ret && ret != -EAGAIN)
1617cafe5635SKent Overstreet 			pr_warn("gc failed!");
1618*a1f0358bSKent Overstreet 	} while (ret);
1619cafe5635SKent Overstreet 
1620cafe5635SKent Overstreet 	available = bch_btree_gc_finish(c);
162157943511SKent Overstreet 	wake_up_allocators(c);
162257943511SKent Overstreet 
1623169ef1cfSKent Overstreet 	bch_time_stats_update(&c->btree_gc_time, start_time);
1624cafe5635SKent Overstreet 
1625cafe5635SKent Overstreet 	stats.key_bytes *= sizeof(uint64_t);
1626cafe5635SKent Overstreet 	stats.data	<<= 9;
1627cafe5635SKent Overstreet 	stats.in_use	= (c->nbuckets - available) * 100 / c->nbuckets;
1628cafe5635SKent Overstreet 	memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1629cafe5635SKent Overstreet 
1630c37511b8SKent Overstreet 	trace_bcache_gc_end(c);
1631cafe5635SKent Overstreet 
163272a44517SKent Overstreet 	bch_moving_gc(c);
1633cafe5635SKent Overstreet }
1634cafe5635SKent Overstreet 
163572a44517SKent Overstreet static int bch_gc_thread(void *arg)
1636cafe5635SKent Overstreet {
163772a44517SKent Overstreet 	struct cache_set *c = arg;
1638*a1f0358bSKent Overstreet 	struct cache *ca;
1639*a1f0358bSKent Overstreet 	unsigned i;
164072a44517SKent Overstreet 
164172a44517SKent Overstreet 	while (1) {
1642*a1f0358bSKent Overstreet again:
164372a44517SKent Overstreet 		bch_btree_gc(c);
164472a44517SKent Overstreet 
164572a44517SKent Overstreet 		set_current_state(TASK_INTERRUPTIBLE);
164672a44517SKent Overstreet 		if (kthread_should_stop())
164772a44517SKent Overstreet 			break;
164872a44517SKent Overstreet 
1649*a1f0358bSKent Overstreet 		mutex_lock(&c->bucket_lock);
1650*a1f0358bSKent Overstreet 
1651*a1f0358bSKent Overstreet 		for_each_cache(ca, c, i)
1652*a1f0358bSKent Overstreet 			if (ca->invalidate_needs_gc) {
1653*a1f0358bSKent Overstreet 				mutex_unlock(&c->bucket_lock);
1654*a1f0358bSKent Overstreet 				set_current_state(TASK_RUNNING);
1655*a1f0358bSKent Overstreet 				goto again;
1656*a1f0358bSKent Overstreet 			}
1657*a1f0358bSKent Overstreet 
1658*a1f0358bSKent Overstreet 		mutex_unlock(&c->bucket_lock);
1659*a1f0358bSKent Overstreet 
166072a44517SKent Overstreet 		try_to_freeze();
166172a44517SKent Overstreet 		schedule();
166272a44517SKent Overstreet 	}
166372a44517SKent Overstreet 
166472a44517SKent Overstreet 	return 0;
166572a44517SKent Overstreet }
166672a44517SKent Overstreet 
166772a44517SKent Overstreet int bch_gc_thread_start(struct cache_set *c)
166872a44517SKent Overstreet {
166972a44517SKent Overstreet 	c->gc_thread = kthread_create(bch_gc_thread, c, "bcache_gc");
167072a44517SKent Overstreet 	if (IS_ERR(c->gc_thread))
167172a44517SKent Overstreet 		return PTR_ERR(c->gc_thread);
167272a44517SKent Overstreet 
167372a44517SKent Overstreet 	set_task_state(c->gc_thread, TASK_INTERRUPTIBLE);
167472a44517SKent Overstreet 	return 0;
1675cafe5635SKent Overstreet }
1676cafe5635SKent Overstreet 
1677cafe5635SKent Overstreet /* Initial partial gc */
1678cafe5635SKent Overstreet 
1679cafe5635SKent Overstreet static int bch_btree_check_recurse(struct btree *b, struct btree_op *op,
1680cafe5635SKent Overstreet 				   unsigned long **seen)
1681cafe5635SKent Overstreet {
1682cafe5635SKent Overstreet 	int ret;
1683cafe5635SKent Overstreet 	unsigned i;
1684cafe5635SKent Overstreet 	struct bkey *k;
1685cafe5635SKent Overstreet 	struct bucket *g;
1686cafe5635SKent Overstreet 	struct btree_iter iter;
1687cafe5635SKent Overstreet 
1688cafe5635SKent Overstreet 	for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1689cafe5635SKent Overstreet 		for (i = 0; i < KEY_PTRS(k); i++) {
1690cafe5635SKent Overstreet 			if (!ptr_available(b->c, k, i))
1691cafe5635SKent Overstreet 				continue;
1692cafe5635SKent Overstreet 
1693cafe5635SKent Overstreet 			g = PTR_BUCKET(b->c, k, i);
1694cafe5635SKent Overstreet 
1695cafe5635SKent Overstreet 			if (!__test_and_set_bit(PTR_BUCKET_NR(b->c, k, i),
1696cafe5635SKent Overstreet 						seen[PTR_DEV(k, i)]) ||
1697cafe5635SKent Overstreet 			    !ptr_stale(b->c, k, i)) {
1698cafe5635SKent Overstreet 				g->gen = PTR_GEN(k, i);
1699cafe5635SKent Overstreet 
1700cafe5635SKent Overstreet 				if (b->level)
1701cafe5635SKent Overstreet 					g->prio = BTREE_PRIO;
1702cafe5635SKent Overstreet 				else if (g->prio == BTREE_PRIO)
1703cafe5635SKent Overstreet 					g->prio = INITIAL_PRIO;
1704cafe5635SKent Overstreet 			}
1705cafe5635SKent Overstreet 		}
1706cafe5635SKent Overstreet 
1707cafe5635SKent Overstreet 		btree_mark_key(b, k);
1708cafe5635SKent Overstreet 	}
1709cafe5635SKent Overstreet 
1710cafe5635SKent Overstreet 	if (b->level) {
1711cafe5635SKent Overstreet 		k = bch_next_recurse_key(b, &ZERO_KEY);
1712cafe5635SKent Overstreet 
1713cafe5635SKent Overstreet 		while (k) {
1714cafe5635SKent Overstreet 			struct bkey *p = bch_next_recurse_key(b, k);
1715cafe5635SKent Overstreet 			if (p)
1716cafe5635SKent Overstreet 				btree_node_prefetch(b->c, p, b->level - 1);
1717cafe5635SKent Overstreet 
1718cafe5635SKent Overstreet 			ret = btree(check_recurse, k, b, op, seen);
1719cafe5635SKent Overstreet 			if (ret)
1720cafe5635SKent Overstreet 				return ret;
1721cafe5635SKent Overstreet 
1722cafe5635SKent Overstreet 			k = p;
1723cafe5635SKent Overstreet 		}
1724cafe5635SKent Overstreet 	}
1725cafe5635SKent Overstreet 
1726cafe5635SKent Overstreet 	return 0;
1727cafe5635SKent Overstreet }
1728cafe5635SKent Overstreet 
1729c18536a7SKent Overstreet int bch_btree_check(struct cache_set *c)
1730cafe5635SKent Overstreet {
1731cafe5635SKent Overstreet 	int ret = -ENOMEM;
1732cafe5635SKent Overstreet 	unsigned i;
1733cafe5635SKent Overstreet 	unsigned long *seen[MAX_CACHES_PER_SET];
1734c18536a7SKent Overstreet 	struct btree_op op;
1735cafe5635SKent Overstreet 
1736cafe5635SKent Overstreet 	memset(seen, 0, sizeof(seen));
1737b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1738cafe5635SKent Overstreet 
1739cafe5635SKent Overstreet 	for (i = 0; c->cache[i]; i++) {
1740cafe5635SKent Overstreet 		size_t n = DIV_ROUND_UP(c->cache[i]->sb.nbuckets, 8);
1741cafe5635SKent Overstreet 		seen[i] = kmalloc(n, GFP_KERNEL);
1742cafe5635SKent Overstreet 		if (!seen[i])
1743cafe5635SKent Overstreet 			goto err;
1744cafe5635SKent Overstreet 
1745cafe5635SKent Overstreet 		/* Disables the seen array until prio_read() uses it too */
1746cafe5635SKent Overstreet 		memset(seen[i], 0xFF, n);
1747cafe5635SKent Overstreet 	}
1748cafe5635SKent Overstreet 
1749c18536a7SKent Overstreet 	ret = btree_root(check_recurse, c, &op, seen);
1750cafe5635SKent Overstreet err:
1751cafe5635SKent Overstreet 	for (i = 0; i < MAX_CACHES_PER_SET; i++)
1752cafe5635SKent Overstreet 		kfree(seen[i]);
1753cafe5635SKent Overstreet 	return ret;
1754cafe5635SKent Overstreet }
1755cafe5635SKent Overstreet 
1756cafe5635SKent Overstreet /* Btree insertion */
1757cafe5635SKent Overstreet 
1758cafe5635SKent Overstreet static void shift_keys(struct btree *b, struct bkey *where, struct bkey *insert)
1759cafe5635SKent Overstreet {
1760cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
1761cafe5635SKent Overstreet 
1762cafe5635SKent Overstreet 	memmove((uint64_t *) where + bkey_u64s(insert),
1763cafe5635SKent Overstreet 		where,
1764cafe5635SKent Overstreet 		(void *) end(i) - (void *) where);
1765cafe5635SKent Overstreet 
1766cafe5635SKent Overstreet 	i->keys += bkey_u64s(insert);
1767cafe5635SKent Overstreet 	bkey_copy(where, insert);
1768cafe5635SKent Overstreet 	bch_bset_fix_lookup_table(b, where);
1769cafe5635SKent Overstreet }
1770cafe5635SKent Overstreet 
17711b207d80SKent Overstreet static bool fix_overlapping_extents(struct btree *b, struct bkey *insert,
1772cafe5635SKent Overstreet 				    struct btree_iter *iter,
17731b207d80SKent Overstreet 				    struct bkey *replace_key)
1774cafe5635SKent Overstreet {
1775279afbadSKent Overstreet 	void subtract_dirty(struct bkey *k, uint64_t offset, int sectors)
1776cafe5635SKent Overstreet 	{
1777279afbadSKent Overstreet 		if (KEY_DIRTY(k))
1778279afbadSKent Overstreet 			bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
1779279afbadSKent Overstreet 						     offset, -sectors);
1780cafe5635SKent Overstreet 	}
1781cafe5635SKent Overstreet 
1782279afbadSKent Overstreet 	uint64_t old_offset;
1783cafe5635SKent Overstreet 	unsigned old_size, sectors_found = 0;
1784cafe5635SKent Overstreet 
1785cafe5635SKent Overstreet 	while (1) {
1786cafe5635SKent Overstreet 		struct bkey *k = bch_btree_iter_next(iter);
1787cafe5635SKent Overstreet 		if (!k ||
1788cafe5635SKent Overstreet 		    bkey_cmp(&START_KEY(k), insert) >= 0)
1789cafe5635SKent Overstreet 			break;
1790cafe5635SKent Overstreet 
1791cafe5635SKent Overstreet 		if (bkey_cmp(k, &START_KEY(insert)) <= 0)
1792cafe5635SKent Overstreet 			continue;
1793cafe5635SKent Overstreet 
1794279afbadSKent Overstreet 		old_offset = KEY_START(k);
1795cafe5635SKent Overstreet 		old_size = KEY_SIZE(k);
1796cafe5635SKent Overstreet 
1797cafe5635SKent Overstreet 		/*
1798cafe5635SKent Overstreet 		 * We might overlap with 0 size extents; we can't skip these
1799cafe5635SKent Overstreet 		 * because if they're in the set we're inserting to we have to
1800cafe5635SKent Overstreet 		 * adjust them so they don't overlap with the key we're
18011b207d80SKent Overstreet 		 * inserting. But we don't want to check them for replace
1802cafe5635SKent Overstreet 		 * operations.
1803cafe5635SKent Overstreet 		 */
1804cafe5635SKent Overstreet 
18051b207d80SKent Overstreet 		if (replace_key && KEY_SIZE(k)) {
1806cafe5635SKent Overstreet 			/*
1807cafe5635SKent Overstreet 			 * k might have been split since we inserted/found the
1808cafe5635SKent Overstreet 			 * key we're replacing
1809cafe5635SKent Overstreet 			 */
1810cafe5635SKent Overstreet 			unsigned i;
1811cafe5635SKent Overstreet 			uint64_t offset = KEY_START(k) -
18121b207d80SKent Overstreet 				KEY_START(replace_key);
1813cafe5635SKent Overstreet 
1814cafe5635SKent Overstreet 			/* But it must be a subset of the replace key */
18151b207d80SKent Overstreet 			if (KEY_START(k) < KEY_START(replace_key) ||
18161b207d80SKent Overstreet 			    KEY_OFFSET(k) > KEY_OFFSET(replace_key))
1817cafe5635SKent Overstreet 				goto check_failed;
1818cafe5635SKent Overstreet 
1819cafe5635SKent Overstreet 			/* We didn't find a key that we were supposed to */
1820cafe5635SKent Overstreet 			if (KEY_START(k) > KEY_START(insert) + sectors_found)
1821cafe5635SKent Overstreet 				goto check_failed;
1822cafe5635SKent Overstreet 
18231b207d80SKent Overstreet 			if (KEY_PTRS(replace_key) != KEY_PTRS(k))
1824cafe5635SKent Overstreet 				goto check_failed;
1825cafe5635SKent Overstreet 
1826cafe5635SKent Overstreet 			/* skip past gen */
1827cafe5635SKent Overstreet 			offset <<= 8;
1828cafe5635SKent Overstreet 
18291b207d80SKent Overstreet 			BUG_ON(!KEY_PTRS(replace_key));
1830cafe5635SKent Overstreet 
18311b207d80SKent Overstreet 			for (i = 0; i < KEY_PTRS(replace_key); i++)
18321b207d80SKent Overstreet 				if (k->ptr[i] != replace_key->ptr[i] + offset)
1833cafe5635SKent Overstreet 					goto check_failed;
1834cafe5635SKent Overstreet 
1835cafe5635SKent Overstreet 			sectors_found = KEY_OFFSET(k) - KEY_START(insert);
1836cafe5635SKent Overstreet 		}
1837cafe5635SKent Overstreet 
1838cafe5635SKent Overstreet 		if (bkey_cmp(insert, k) < 0 &&
1839cafe5635SKent Overstreet 		    bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0) {
1840cafe5635SKent Overstreet 			/*
1841cafe5635SKent Overstreet 			 * We overlapped in the middle of an existing key: that
1842cafe5635SKent Overstreet 			 * means we have to split the old key. But we have to do
1843cafe5635SKent Overstreet 			 * slightly different things depending on whether the
1844cafe5635SKent Overstreet 			 * old key has been written out yet.
1845cafe5635SKent Overstreet 			 */
1846cafe5635SKent Overstreet 
1847cafe5635SKent Overstreet 			struct bkey *top;
1848cafe5635SKent Overstreet 
1849279afbadSKent Overstreet 			subtract_dirty(k, KEY_START(insert), KEY_SIZE(insert));
1850cafe5635SKent Overstreet 
1851cafe5635SKent Overstreet 			if (bkey_written(b, k)) {
1852cafe5635SKent Overstreet 				/*
1853cafe5635SKent Overstreet 				 * We insert a new key to cover the top of the
1854cafe5635SKent Overstreet 				 * old key, and the old key is modified in place
1855cafe5635SKent Overstreet 				 * to represent the bottom split.
1856cafe5635SKent Overstreet 				 *
1857cafe5635SKent Overstreet 				 * It's completely arbitrary whether the new key
1858cafe5635SKent Overstreet 				 * is the top or the bottom, but it has to match
1859cafe5635SKent Overstreet 				 * up with what btree_sort_fixup() does - it
1860cafe5635SKent Overstreet 				 * doesn't check for this kind of overlap, it
1861cafe5635SKent Overstreet 				 * depends on us inserting a new key for the top
1862cafe5635SKent Overstreet 				 * here.
1863cafe5635SKent Overstreet 				 */
1864cafe5635SKent Overstreet 				top = bch_bset_search(b, &b->sets[b->nsets],
1865cafe5635SKent Overstreet 						      insert);
1866cafe5635SKent Overstreet 				shift_keys(b, top, k);
1867cafe5635SKent Overstreet 			} else {
1868cafe5635SKent Overstreet 				BKEY_PADDED(key) temp;
1869cafe5635SKent Overstreet 				bkey_copy(&temp.key, k);
1870cafe5635SKent Overstreet 				shift_keys(b, k, &temp.key);
1871cafe5635SKent Overstreet 				top = bkey_next(k);
1872cafe5635SKent Overstreet 			}
1873cafe5635SKent Overstreet 
1874cafe5635SKent Overstreet 			bch_cut_front(insert, top);
1875cafe5635SKent Overstreet 			bch_cut_back(&START_KEY(insert), k);
1876cafe5635SKent Overstreet 			bch_bset_fix_invalidated_key(b, k);
1877cafe5635SKent Overstreet 			return false;
1878cafe5635SKent Overstreet 		}
1879cafe5635SKent Overstreet 
1880cafe5635SKent Overstreet 		if (bkey_cmp(insert, k) < 0) {
1881cafe5635SKent Overstreet 			bch_cut_front(insert, k);
1882cafe5635SKent Overstreet 		} else {
18831fa8455dSKent Overstreet 			if (bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0)
18841fa8455dSKent Overstreet 				old_offset = KEY_START(insert);
18851fa8455dSKent Overstreet 
1886cafe5635SKent Overstreet 			if (bkey_written(b, k) &&
1887cafe5635SKent Overstreet 			    bkey_cmp(&START_KEY(insert), &START_KEY(k)) <= 0) {
1888cafe5635SKent Overstreet 				/*
1889cafe5635SKent Overstreet 				 * Completely overwrote, so we don't have to
1890cafe5635SKent Overstreet 				 * invalidate the binary search tree
1891cafe5635SKent Overstreet 				 */
1892cafe5635SKent Overstreet 				bch_cut_front(k, k);
1893cafe5635SKent Overstreet 			} else {
1894cafe5635SKent Overstreet 				__bch_cut_back(&START_KEY(insert), k);
1895cafe5635SKent Overstreet 				bch_bset_fix_invalidated_key(b, k);
1896cafe5635SKent Overstreet 			}
1897cafe5635SKent Overstreet 		}
1898cafe5635SKent Overstreet 
1899279afbadSKent Overstreet 		subtract_dirty(k, old_offset, old_size - KEY_SIZE(k));
1900cafe5635SKent Overstreet 	}
1901cafe5635SKent Overstreet 
1902cafe5635SKent Overstreet check_failed:
19031b207d80SKent Overstreet 	if (replace_key) {
1904cafe5635SKent Overstreet 		if (!sectors_found) {
1905cafe5635SKent Overstreet 			return true;
1906cafe5635SKent Overstreet 		} else if (sectors_found < KEY_SIZE(insert)) {
1907cafe5635SKent Overstreet 			SET_KEY_OFFSET(insert, KEY_OFFSET(insert) -
1908cafe5635SKent Overstreet 				       (KEY_SIZE(insert) - sectors_found));
1909cafe5635SKent Overstreet 			SET_KEY_SIZE(insert, sectors_found);
1910cafe5635SKent Overstreet 		}
1911cafe5635SKent Overstreet 	}
1912cafe5635SKent Overstreet 
1913cafe5635SKent Overstreet 	return false;
1914cafe5635SKent Overstreet }
1915cafe5635SKent Overstreet 
1916cafe5635SKent Overstreet static bool btree_insert_key(struct btree *b, struct btree_op *op,
19171b207d80SKent Overstreet 			     struct bkey *k, struct bkey *replace_key)
1918cafe5635SKent Overstreet {
1919cafe5635SKent Overstreet 	struct bset *i = b->sets[b->nsets].data;
1920cafe5635SKent Overstreet 	struct bkey *m, *prev;
192185b1492eSKent Overstreet 	unsigned status = BTREE_INSERT_STATUS_INSERT;
1922cafe5635SKent Overstreet 
1923cafe5635SKent Overstreet 	BUG_ON(bkey_cmp(k, &b->key) > 0);
1924cafe5635SKent Overstreet 	BUG_ON(b->level && !KEY_PTRS(k));
1925cafe5635SKent Overstreet 	BUG_ON(!b->level && !KEY_OFFSET(k));
1926cafe5635SKent Overstreet 
1927cafe5635SKent Overstreet 	if (!b->level) {
1928cafe5635SKent Overstreet 		struct btree_iter iter;
1929cafe5635SKent Overstreet 
1930cafe5635SKent Overstreet 		/*
1931cafe5635SKent Overstreet 		 * bset_search() returns the first key that is strictly greater
1932cafe5635SKent Overstreet 		 * than the search key - but for back merging, we want to find
19330eacac22SKent Overstreet 		 * the previous key.
1934cafe5635SKent Overstreet 		 */
1935cafe5635SKent Overstreet 		prev = NULL;
19360eacac22SKent Overstreet 		m = bch_btree_iter_init(b, &iter, PRECEDING_KEY(&START_KEY(k)));
1937cafe5635SKent Overstreet 
19381b207d80SKent Overstreet 		if (fix_overlapping_extents(b, k, &iter, replace_key)) {
19391b207d80SKent Overstreet 			op->insert_collision = true;
1940cafe5635SKent Overstreet 			return false;
19411b207d80SKent Overstreet 		}
1942cafe5635SKent Overstreet 
19431fa8455dSKent Overstreet 		if (KEY_DIRTY(k))
19441fa8455dSKent Overstreet 			bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
19451fa8455dSKent Overstreet 						     KEY_START(k), KEY_SIZE(k));
19461fa8455dSKent Overstreet 
1947cafe5635SKent Overstreet 		while (m != end(i) &&
1948cafe5635SKent Overstreet 		       bkey_cmp(k, &START_KEY(m)) > 0)
1949cafe5635SKent Overstreet 			prev = m, m = bkey_next(m);
1950cafe5635SKent Overstreet 
1951cafe5635SKent Overstreet 		if (key_merging_disabled(b->c))
1952cafe5635SKent Overstreet 			goto insert;
1953cafe5635SKent Overstreet 
1954cafe5635SKent Overstreet 		/* prev is in the tree, if we merge we're done */
195585b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_BACK_MERGE;
1956cafe5635SKent Overstreet 		if (prev &&
1957cafe5635SKent Overstreet 		    bch_bkey_try_merge(b, prev, k))
1958cafe5635SKent Overstreet 			goto merged;
1959cafe5635SKent Overstreet 
196085b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_OVERWROTE;
1961cafe5635SKent Overstreet 		if (m != end(i) &&
1962cafe5635SKent Overstreet 		    KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
1963cafe5635SKent Overstreet 			goto copy;
1964cafe5635SKent Overstreet 
196585b1492eSKent Overstreet 		status = BTREE_INSERT_STATUS_FRONT_MERGE;
1966cafe5635SKent Overstreet 		if (m != end(i) &&
1967cafe5635SKent Overstreet 		    bch_bkey_try_merge(b, k, m))
1968cafe5635SKent Overstreet 			goto copy;
19691b207d80SKent Overstreet 	} else {
19701b207d80SKent Overstreet 		BUG_ON(replace_key);
1971cafe5635SKent Overstreet 		m = bch_bset_search(b, &b->sets[b->nsets], k);
19721b207d80SKent Overstreet 	}
1973cafe5635SKent Overstreet 
1974cafe5635SKent Overstreet insert:	shift_keys(b, m, k);
1975cafe5635SKent Overstreet copy:	bkey_copy(m, k);
1976cafe5635SKent Overstreet merged:
19771b207d80SKent Overstreet 	bch_check_keys(b, "%u for %s", status,
19781b207d80SKent Overstreet 		       replace_key ? "replace" : "insert");
1979cafe5635SKent Overstreet 
1980cafe5635SKent Overstreet 	if (b->level && !KEY_OFFSET(k))
198157943511SKent Overstreet 		btree_current_write(b)->prio_blocked++;
1982cafe5635SKent Overstreet 
19831b207d80SKent Overstreet 	trace_bcache_btree_insert_key(b, k, replace_key != NULL, status);
1984cafe5635SKent Overstreet 
1985cafe5635SKent Overstreet 	return true;
1986cafe5635SKent Overstreet }
1987cafe5635SKent Overstreet 
198826c949f8SKent Overstreet static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
19891b207d80SKent Overstreet 				  struct keylist *insert_keys,
19901b207d80SKent Overstreet 				  struct bkey *replace_key)
1991cafe5635SKent Overstreet {
1992cafe5635SKent Overstreet 	bool ret = false;
1993280481d0SKent Overstreet 	int oldsize = bch_count_data(b);
1994cafe5635SKent Overstreet 
199526c949f8SKent Overstreet 	while (!bch_keylist_empty(insert_keys)) {
1996403b6cdeSKent Overstreet 		struct bset *i = write_block(b);
1997c2f95ae2SKent Overstreet 		struct bkey *k = insert_keys->keys;
199826c949f8SKent Overstreet 
1999403b6cdeSKent Overstreet 		if (b->written + __set_blocks(i, i->keys + bkey_u64s(k), b->c)
2000403b6cdeSKent Overstreet 		    > btree_blocks(b))
2001403b6cdeSKent Overstreet 			break;
2002403b6cdeSKent Overstreet 
2003403b6cdeSKent Overstreet 		if (bkey_cmp(k, &b->key) <= 0) {
20043a3b6a4eSKent Overstreet 			if (!b->level)
20053a3b6a4eSKent Overstreet 				bkey_put(b->c, k);
200626c949f8SKent Overstreet 
20071b207d80SKent Overstreet 			ret |= btree_insert_key(b, op, k, replace_key);
200826c949f8SKent Overstreet 			bch_keylist_pop_front(insert_keys);
200926c949f8SKent Overstreet 		} else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
201026c949f8SKent Overstreet 			BKEY_PADDED(key) temp;
2011c2f95ae2SKent Overstreet 			bkey_copy(&temp.key, insert_keys->keys);
201226c949f8SKent Overstreet 
201326c949f8SKent Overstreet 			bch_cut_back(&b->key, &temp.key);
2014c2f95ae2SKent Overstreet 			bch_cut_front(&b->key, insert_keys->keys);
201526c949f8SKent Overstreet 
20161b207d80SKent Overstreet 			ret |= btree_insert_key(b, op, &temp.key, replace_key);
201726c949f8SKent Overstreet 			break;
201826c949f8SKent Overstreet 		} else {
201926c949f8SKent Overstreet 			break;
202026c949f8SKent Overstreet 		}
2021cafe5635SKent Overstreet 	}
2022cafe5635SKent Overstreet 
2023403b6cdeSKent Overstreet 	BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
2024403b6cdeSKent Overstreet 
2025cafe5635SKent Overstreet 	BUG_ON(bch_count_data(b) < oldsize);
2026cafe5635SKent Overstreet 	return ret;
2027cafe5635SKent Overstreet }
2028cafe5635SKent Overstreet 
202926c949f8SKent Overstreet static int btree_split(struct btree *b, struct btree_op *op,
203026c949f8SKent Overstreet 		       struct keylist *insert_keys,
20311b207d80SKent Overstreet 		       struct keylist *parent_keys,
20321b207d80SKent Overstreet 		       struct bkey *replace_key)
2033cafe5635SKent Overstreet {
2034d6fd3b11SKent Overstreet 	bool split;
2035cafe5635SKent Overstreet 	struct btree *n1, *n2 = NULL, *n3 = NULL;
2036cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
2037b54d6934SKent Overstreet 	struct closure cl;
2038b54d6934SKent Overstreet 
2039b54d6934SKent Overstreet 	closure_init_stack(&cl);
2040cafe5635SKent Overstreet 
204135fcd848SKent Overstreet 	n1 = btree_node_alloc_replacement(b);
2042cafe5635SKent Overstreet 	if (IS_ERR(n1))
2043cafe5635SKent Overstreet 		goto err;
2044cafe5635SKent Overstreet 
2045cafe5635SKent Overstreet 	split = set_blocks(n1->sets[0].data, n1->c) > (btree_blocks(b) * 4) / 5;
2046cafe5635SKent Overstreet 
2047cafe5635SKent Overstreet 	if (split) {
2048cafe5635SKent Overstreet 		unsigned keys = 0;
2049cafe5635SKent Overstreet 
2050c37511b8SKent Overstreet 		trace_bcache_btree_node_split(b, n1->sets[0].data->keys);
2051c37511b8SKent Overstreet 
205235fcd848SKent Overstreet 		n2 = bch_btree_node_alloc(b->c, b->level);
2053cafe5635SKent Overstreet 		if (IS_ERR(n2))
2054cafe5635SKent Overstreet 			goto err_free1;
2055cafe5635SKent Overstreet 
2056d6fd3b11SKent Overstreet 		if (!b->parent) {
205735fcd848SKent Overstreet 			n3 = bch_btree_node_alloc(b->c, b->level + 1);
2058cafe5635SKent Overstreet 			if (IS_ERR(n3))
2059cafe5635SKent Overstreet 				goto err_free2;
2060cafe5635SKent Overstreet 		}
2061cafe5635SKent Overstreet 
20621b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2063cafe5635SKent Overstreet 
2064d6fd3b11SKent Overstreet 		/*
2065d6fd3b11SKent Overstreet 		 * Has to be a linear search because we don't have an auxiliary
2066cafe5635SKent Overstreet 		 * search tree yet
2067cafe5635SKent Overstreet 		 */
2068cafe5635SKent Overstreet 
2069cafe5635SKent Overstreet 		while (keys < (n1->sets[0].data->keys * 3) / 5)
2070cafe5635SKent Overstreet 			keys += bkey_u64s(node(n1->sets[0].data, keys));
2071cafe5635SKent Overstreet 
2072cafe5635SKent Overstreet 		bkey_copy_key(&n1->key, node(n1->sets[0].data, keys));
2073cafe5635SKent Overstreet 		keys += bkey_u64s(node(n1->sets[0].data, keys));
2074cafe5635SKent Overstreet 
2075cafe5635SKent Overstreet 		n2->sets[0].data->keys = n1->sets[0].data->keys - keys;
2076cafe5635SKent Overstreet 		n1->sets[0].data->keys = keys;
2077cafe5635SKent Overstreet 
2078cafe5635SKent Overstreet 		memcpy(n2->sets[0].data->start,
2079cafe5635SKent Overstreet 		       end(n1->sets[0].data),
2080cafe5635SKent Overstreet 		       n2->sets[0].data->keys * sizeof(uint64_t));
2081cafe5635SKent Overstreet 
2082cafe5635SKent Overstreet 		bkey_copy_key(&n2->key, &b->key);
2083cafe5635SKent Overstreet 
208426c949f8SKent Overstreet 		bch_keylist_add(parent_keys, &n2->key);
2085b54d6934SKent Overstreet 		bch_btree_node_write(n2, &cl);
2086cafe5635SKent Overstreet 		rw_unlock(true, n2);
2087c37511b8SKent Overstreet 	} else {
2088c37511b8SKent Overstreet 		trace_bcache_btree_node_compact(b, n1->sets[0].data->keys);
2089c37511b8SKent Overstreet 
20901b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2091c37511b8SKent Overstreet 	}
2092cafe5635SKent Overstreet 
209326c949f8SKent Overstreet 	bch_keylist_add(parent_keys, &n1->key);
2094b54d6934SKent Overstreet 	bch_btree_node_write(n1, &cl);
2095cafe5635SKent Overstreet 
2096cafe5635SKent Overstreet 	if (n3) {
2097d6fd3b11SKent Overstreet 		/* Depth increases, make a new root */
2098d6fd3b11SKent Overstreet 
2099cafe5635SKent Overstreet 		bkey_copy_key(&n3->key, &MAX_KEY);
21001b207d80SKent Overstreet 		bch_btree_insert_keys(n3, op, parent_keys, NULL);
2101b54d6934SKent Overstreet 		bch_btree_node_write(n3, &cl);
2102cafe5635SKent Overstreet 
2103b54d6934SKent Overstreet 		closure_sync(&cl);
2104cafe5635SKent Overstreet 		bch_btree_set_root(n3);
2105cafe5635SKent Overstreet 		rw_unlock(true, n3);
2106d6fd3b11SKent Overstreet 	} else if (!b->parent) {
2107d6fd3b11SKent Overstreet 		/* Root filled up but didn't need to be split */
2108d6fd3b11SKent Overstreet 
2109c2f95ae2SKent Overstreet 		bch_keylist_reset(parent_keys);
2110b54d6934SKent Overstreet 		closure_sync(&cl);
2111cafe5635SKent Overstreet 		bch_btree_set_root(n1);
2112cafe5635SKent Overstreet 	} else {
2113b54d6934SKent Overstreet 		closure_sync(&cl);
21148835c123SKent Overstreet 		make_btree_freeing_key(b, parent_keys->top);
21158835c123SKent Overstreet 		bch_keylist_push(parent_keys);
2116cafe5635SKent Overstreet 	}
2117cafe5635SKent Overstreet 
2118cafe5635SKent Overstreet 	rw_unlock(true, n1);
2119e8e1d468SKent Overstreet 	btree_node_free(b);
2120cafe5635SKent Overstreet 
2121169ef1cfSKent Overstreet 	bch_time_stats_update(&b->c->btree_split_time, start_time);
2122cafe5635SKent Overstreet 
2123cafe5635SKent Overstreet 	return 0;
2124cafe5635SKent Overstreet err_free2:
2125e8e1d468SKent Overstreet 	btree_node_free(n2);
2126cafe5635SKent Overstreet 	rw_unlock(true, n2);
2127cafe5635SKent Overstreet err_free1:
2128e8e1d468SKent Overstreet 	btree_node_free(n1);
2129cafe5635SKent Overstreet 	rw_unlock(true, n1);
2130cafe5635SKent Overstreet err:
2131cafe5635SKent Overstreet 	if (n3 == ERR_PTR(-EAGAIN) ||
2132cafe5635SKent Overstreet 	    n2 == ERR_PTR(-EAGAIN) ||
2133cafe5635SKent Overstreet 	    n1 == ERR_PTR(-EAGAIN))
2134cafe5635SKent Overstreet 		return -EAGAIN;
2135cafe5635SKent Overstreet 
2136cafe5635SKent Overstreet 	pr_warn("couldn't split");
2137cafe5635SKent Overstreet 	return -ENOMEM;
2138cafe5635SKent Overstreet }
2139cafe5635SKent Overstreet 
214026c949f8SKent Overstreet static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
2141c18536a7SKent Overstreet 				 struct keylist *insert_keys,
21421b207d80SKent Overstreet 				 atomic_t *journal_ref,
21431b207d80SKent Overstreet 				 struct bkey *replace_key)
214426c949f8SKent Overstreet {
214526c949f8SKent Overstreet 	int ret = 0;
214626c949f8SKent Overstreet 	struct keylist split_keys;
214726c949f8SKent Overstreet 
214826c949f8SKent Overstreet 	bch_keylist_init(&split_keys);
214926c949f8SKent Overstreet 
215026c949f8SKent Overstreet 	do {
21511b207d80SKent Overstreet 		BUG_ON(b->level && replace_key);
21521b207d80SKent Overstreet 
215326c949f8SKent Overstreet 		if (should_split(b)) {
215426c949f8SKent Overstreet 			if (current->bio_list) {
215526c949f8SKent Overstreet 				op->lock = b->c->root->level + 1;
215626c949f8SKent Overstreet 				ret = -EAGAIN;
215726c949f8SKent Overstreet 			} else if (op->lock <= b->c->root->level) {
215826c949f8SKent Overstreet 				op->lock = b->c->root->level + 1;
215926c949f8SKent Overstreet 				ret = -EINTR;
216026c949f8SKent Overstreet 			} else {
216126c949f8SKent Overstreet 				struct btree *parent = b->parent;
216226c949f8SKent Overstreet 
216326c949f8SKent Overstreet 				ret = btree_split(b, op, insert_keys,
21641b207d80SKent Overstreet 						  &split_keys, replace_key);
216526c949f8SKent Overstreet 				insert_keys = &split_keys;
21661b207d80SKent Overstreet 				replace_key = NULL;
216726c949f8SKent Overstreet 				b = parent;
2168403b6cdeSKent Overstreet 				if (!ret)
2169403b6cdeSKent Overstreet 					ret = -EINTR;
217026c949f8SKent Overstreet 			}
217126c949f8SKent Overstreet 		} else {
217226c949f8SKent Overstreet 			BUG_ON(write_block(b) != b->sets[b->nsets].data);
217326c949f8SKent Overstreet 
21741b207d80SKent Overstreet 			if (bch_btree_insert_keys(b, op, insert_keys,
21751b207d80SKent Overstreet 						  replace_key)) {
2176f269af5aSKent Overstreet 				if (!b->level)
2177c18536a7SKent Overstreet 					bch_btree_leaf_dirty(b, journal_ref);
2178f269af5aSKent Overstreet 				else
2179f269af5aSKent Overstreet 					bch_btree_node_write_sync(b);
218026c949f8SKent Overstreet 			}
218126c949f8SKent Overstreet 		}
218226c949f8SKent Overstreet 	} while (!bch_keylist_empty(&split_keys));
218326c949f8SKent Overstreet 
218426c949f8SKent Overstreet 	return ret;
218526c949f8SKent Overstreet }
218626c949f8SKent Overstreet 
2187e7c590ebSKent Overstreet int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2188e7c590ebSKent Overstreet 			       struct bkey *check_key)
2189e7c590ebSKent Overstreet {
2190e7c590ebSKent Overstreet 	int ret = -EINTR;
2191e7c590ebSKent Overstreet 	uint64_t btree_ptr = b->key.ptr[0];
2192e7c590ebSKent Overstreet 	unsigned long seq = b->seq;
2193e7c590ebSKent Overstreet 	struct keylist insert;
2194e7c590ebSKent Overstreet 	bool upgrade = op->lock == -1;
2195e7c590ebSKent Overstreet 
2196e7c590ebSKent Overstreet 	bch_keylist_init(&insert);
2197e7c590ebSKent Overstreet 
2198e7c590ebSKent Overstreet 	if (upgrade) {
2199e7c590ebSKent Overstreet 		rw_unlock(false, b);
2200e7c590ebSKent Overstreet 		rw_lock(true, b, b->level);
2201e7c590ebSKent Overstreet 
2202e7c590ebSKent Overstreet 		if (b->key.ptr[0] != btree_ptr ||
2203e7c590ebSKent Overstreet 		    b->seq != seq + 1)
2204e7c590ebSKent Overstreet 			goto out;
2205e7c590ebSKent Overstreet 	}
2206e7c590ebSKent Overstreet 
2207e7c590ebSKent Overstreet 	SET_KEY_PTRS(check_key, 1);
2208e7c590ebSKent Overstreet 	get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2209e7c590ebSKent Overstreet 
2210e7c590ebSKent Overstreet 	SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2211e7c590ebSKent Overstreet 
2212e7c590ebSKent Overstreet 	bch_keylist_add(&insert, check_key);
2213e7c590ebSKent Overstreet 
22141b207d80SKent Overstreet 	ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2215e7c590ebSKent Overstreet 
2216e7c590ebSKent Overstreet 	BUG_ON(!ret && !bch_keylist_empty(&insert));
2217e7c590ebSKent Overstreet out:
2218e7c590ebSKent Overstreet 	if (upgrade)
2219e7c590ebSKent Overstreet 		downgrade_write(&b->lock);
2220e7c590ebSKent Overstreet 	return ret;
2221e7c590ebSKent Overstreet }
2222e7c590ebSKent Overstreet 
2223cc7b8819SKent Overstreet struct btree_insert_op {
2224cc7b8819SKent Overstreet 	struct btree_op	op;
2225cc7b8819SKent Overstreet 	struct keylist	*keys;
2226cc7b8819SKent Overstreet 	atomic_t	*journal_ref;
2227cc7b8819SKent Overstreet 	struct bkey	*replace_key;
2228cc7b8819SKent Overstreet };
2229cc7b8819SKent Overstreet 
2230cc7b8819SKent Overstreet int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2231cafe5635SKent Overstreet {
2232cc7b8819SKent Overstreet 	struct btree_insert_op *op = container_of(b_op,
2233cc7b8819SKent Overstreet 					struct btree_insert_op, op);
2234403b6cdeSKent Overstreet 
2235cc7b8819SKent Overstreet 	int ret = bch_btree_insert_node(b, &op->op, op->keys,
2236cc7b8819SKent Overstreet 					op->journal_ref, op->replace_key);
2237cc7b8819SKent Overstreet 	if (ret && !bch_keylist_empty(op->keys))
2238cc7b8819SKent Overstreet 		return ret;
2239cc7b8819SKent Overstreet 	else
2240cc7b8819SKent Overstreet 		return MAP_DONE;
2241cafe5635SKent Overstreet }
2242cafe5635SKent Overstreet 
2243cc7b8819SKent Overstreet int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2244cc7b8819SKent Overstreet 		     atomic_t *journal_ref, struct bkey *replace_key)
2245cafe5635SKent Overstreet {
2246cc7b8819SKent Overstreet 	struct btree_insert_op op;
2247cafe5635SKent Overstreet 	int ret = 0;
2248cafe5635SKent Overstreet 
2249cc7b8819SKent Overstreet 	BUG_ON(current->bio_list);
22504f3d4014SKent Overstreet 	BUG_ON(bch_keylist_empty(keys));
2251cafe5635SKent Overstreet 
2252cc7b8819SKent Overstreet 	bch_btree_op_init(&op.op, 0);
2253cc7b8819SKent Overstreet 	op.keys		= keys;
2254cc7b8819SKent Overstreet 	op.journal_ref	= journal_ref;
2255cc7b8819SKent Overstreet 	op.replace_key	= replace_key;
2256cafe5635SKent Overstreet 
2257cc7b8819SKent Overstreet 	while (!ret && !bch_keylist_empty(keys)) {
2258cc7b8819SKent Overstreet 		op.op.lock = 0;
2259cc7b8819SKent Overstreet 		ret = bch_btree_map_leaf_nodes(&op.op, c,
2260cc7b8819SKent Overstreet 					       &START_KEY(keys->keys),
2261cc7b8819SKent Overstreet 					       btree_insert_fn);
2262cc7b8819SKent Overstreet 	}
2263cc7b8819SKent Overstreet 
2264cc7b8819SKent Overstreet 	if (ret) {
2265cafe5635SKent Overstreet 		struct bkey *k;
2266cafe5635SKent Overstreet 
22671b207d80SKent Overstreet 		pr_err("error %i", ret);
2268cafe5635SKent Overstreet 
22694f3d4014SKent Overstreet 		while ((k = bch_keylist_pop(keys)))
22703a3b6a4eSKent Overstreet 			bkey_put(c, k);
2271cc7b8819SKent Overstreet 	} else if (op.op.insert_collision)
2272cc7b8819SKent Overstreet 		ret = -ESRCH;
22736054c6d4SKent Overstreet 
2274cafe5635SKent Overstreet 	return ret;
2275cafe5635SKent Overstreet }
2276cafe5635SKent Overstreet 
2277cafe5635SKent Overstreet void bch_btree_set_root(struct btree *b)
2278cafe5635SKent Overstreet {
2279cafe5635SKent Overstreet 	unsigned i;
2280e49c7c37SKent Overstreet 	struct closure cl;
2281e49c7c37SKent Overstreet 
2282e49c7c37SKent Overstreet 	closure_init_stack(&cl);
2283cafe5635SKent Overstreet 
2284c37511b8SKent Overstreet 	trace_bcache_btree_set_root(b);
2285c37511b8SKent Overstreet 
2286cafe5635SKent Overstreet 	BUG_ON(!b->written);
2287cafe5635SKent Overstreet 
2288cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++)
2289cafe5635SKent Overstreet 		BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2290cafe5635SKent Overstreet 
2291cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
2292cafe5635SKent Overstreet 	list_del_init(&b->list);
2293cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
2294cafe5635SKent Overstreet 
2295cafe5635SKent Overstreet 	b->c->root = b;
2296cafe5635SKent Overstreet 
2297e49c7c37SKent Overstreet 	bch_journal_meta(b->c, &cl);
2298e49c7c37SKent Overstreet 	closure_sync(&cl);
2299cafe5635SKent Overstreet }
2300cafe5635SKent Overstreet 
230148dad8baSKent Overstreet /* Map across nodes or keys */
230248dad8baSKent Overstreet 
230348dad8baSKent Overstreet static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
230448dad8baSKent Overstreet 				       struct bkey *from,
230548dad8baSKent Overstreet 				       btree_map_nodes_fn *fn, int flags)
230648dad8baSKent Overstreet {
230748dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
230848dad8baSKent Overstreet 
230948dad8baSKent Overstreet 	if (b->level) {
231048dad8baSKent Overstreet 		struct bkey *k;
231148dad8baSKent Overstreet 		struct btree_iter iter;
231248dad8baSKent Overstreet 
231348dad8baSKent Overstreet 		bch_btree_iter_init(b, &iter, from);
231448dad8baSKent Overstreet 
231548dad8baSKent Overstreet 		while ((k = bch_btree_iter_next_filter(&iter, b,
231648dad8baSKent Overstreet 						       bch_ptr_bad))) {
231748dad8baSKent Overstreet 			ret = btree(map_nodes_recurse, k, b,
231848dad8baSKent Overstreet 				    op, from, fn, flags);
231948dad8baSKent Overstreet 			from = NULL;
232048dad8baSKent Overstreet 
232148dad8baSKent Overstreet 			if (ret != MAP_CONTINUE)
232248dad8baSKent Overstreet 				return ret;
232348dad8baSKent Overstreet 		}
232448dad8baSKent Overstreet 	}
232548dad8baSKent Overstreet 
232648dad8baSKent Overstreet 	if (!b->level || flags == MAP_ALL_NODES)
232748dad8baSKent Overstreet 		ret = fn(op, b);
232848dad8baSKent Overstreet 
232948dad8baSKent Overstreet 	return ret;
233048dad8baSKent Overstreet }
233148dad8baSKent Overstreet 
233248dad8baSKent Overstreet int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
233348dad8baSKent Overstreet 			  struct bkey *from, btree_map_nodes_fn *fn, int flags)
233448dad8baSKent Overstreet {
2335b54d6934SKent Overstreet 	return btree_root(map_nodes_recurse, c, op, from, fn, flags);
233648dad8baSKent Overstreet }
233748dad8baSKent Overstreet 
233848dad8baSKent Overstreet static int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
233948dad8baSKent Overstreet 				      struct bkey *from, btree_map_keys_fn *fn,
234048dad8baSKent Overstreet 				      int flags)
234148dad8baSKent Overstreet {
234248dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
234348dad8baSKent Overstreet 	struct bkey *k;
234448dad8baSKent Overstreet 	struct btree_iter iter;
234548dad8baSKent Overstreet 
234648dad8baSKent Overstreet 	bch_btree_iter_init(b, &iter, from);
234748dad8baSKent Overstreet 
234848dad8baSKent Overstreet 	while ((k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad))) {
234948dad8baSKent Overstreet 		ret = !b->level
235048dad8baSKent Overstreet 			? fn(op, b, k)
235148dad8baSKent Overstreet 			: btree(map_keys_recurse, k, b, op, from, fn, flags);
235248dad8baSKent Overstreet 		from = NULL;
235348dad8baSKent Overstreet 
235448dad8baSKent Overstreet 		if (ret != MAP_CONTINUE)
235548dad8baSKent Overstreet 			return ret;
235648dad8baSKent Overstreet 	}
235748dad8baSKent Overstreet 
235848dad8baSKent Overstreet 	if (!b->level && (flags & MAP_END_KEY))
235948dad8baSKent Overstreet 		ret = fn(op, b, &KEY(KEY_INODE(&b->key),
236048dad8baSKent Overstreet 				     KEY_OFFSET(&b->key), 0));
236148dad8baSKent Overstreet 
236248dad8baSKent Overstreet 	return ret;
236348dad8baSKent Overstreet }
236448dad8baSKent Overstreet 
236548dad8baSKent Overstreet int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
236648dad8baSKent Overstreet 		       struct bkey *from, btree_map_keys_fn *fn, int flags)
236748dad8baSKent Overstreet {
2368b54d6934SKent Overstreet 	return btree_root(map_keys_recurse, c, op, from, fn, flags);
236948dad8baSKent Overstreet }
237048dad8baSKent Overstreet 
2371cafe5635SKent Overstreet /* Keybuf code */
2372cafe5635SKent Overstreet 
2373cafe5635SKent Overstreet static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2374cafe5635SKent Overstreet {
2375cafe5635SKent Overstreet 	/* Overlapping keys compare equal */
2376cafe5635SKent Overstreet 	if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2377cafe5635SKent Overstreet 		return -1;
2378cafe5635SKent Overstreet 	if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2379cafe5635SKent Overstreet 		return 1;
2380cafe5635SKent Overstreet 	return 0;
2381cafe5635SKent Overstreet }
2382cafe5635SKent Overstreet 
2383cafe5635SKent Overstreet static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2384cafe5635SKent Overstreet 					    struct keybuf_key *r)
2385cafe5635SKent Overstreet {
2386cafe5635SKent Overstreet 	return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2387cafe5635SKent Overstreet }
2388cafe5635SKent Overstreet 
238948dad8baSKent Overstreet struct refill {
239048dad8baSKent Overstreet 	struct btree_op	op;
239148dad8baSKent Overstreet 	struct keybuf	*buf;
239248dad8baSKent Overstreet 	struct bkey	*end;
239348dad8baSKent Overstreet 	keybuf_pred_fn	*pred;
239448dad8baSKent Overstreet };
239548dad8baSKent Overstreet 
239648dad8baSKent Overstreet static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
239748dad8baSKent Overstreet 			    struct bkey *k)
2398cafe5635SKent Overstreet {
239948dad8baSKent Overstreet 	struct refill *refill = container_of(op, struct refill, op);
240048dad8baSKent Overstreet 	struct keybuf *buf = refill->buf;
240148dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
2402cafe5635SKent Overstreet 
240348dad8baSKent Overstreet 	if (bkey_cmp(k, refill->end) >= 0) {
240448dad8baSKent Overstreet 		ret = MAP_DONE;
240548dad8baSKent Overstreet 		goto out;
2406cafe5635SKent Overstreet 	}
2407cafe5635SKent Overstreet 
240848dad8baSKent Overstreet 	if (!KEY_SIZE(k)) /* end key */
240948dad8baSKent Overstreet 		goto out;
2410cafe5635SKent Overstreet 
241148dad8baSKent Overstreet 	if (refill->pred(buf, k)) {
2412cafe5635SKent Overstreet 		struct keybuf_key *w;
2413cafe5635SKent Overstreet 
2414cafe5635SKent Overstreet 		spin_lock(&buf->lock);
2415cafe5635SKent Overstreet 
2416cafe5635SKent Overstreet 		w = array_alloc(&buf->freelist);
241748dad8baSKent Overstreet 		if (!w) {
241848dad8baSKent Overstreet 			spin_unlock(&buf->lock);
241948dad8baSKent Overstreet 			return MAP_DONE;
242048dad8baSKent Overstreet 		}
2421cafe5635SKent Overstreet 
2422cafe5635SKent Overstreet 		w->private = NULL;
2423cafe5635SKent Overstreet 		bkey_copy(&w->key, k);
2424cafe5635SKent Overstreet 
2425cafe5635SKent Overstreet 		if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2426cafe5635SKent Overstreet 			array_free(&buf->freelist, w);
2427cafe5635SKent Overstreet 
242848dad8baSKent Overstreet 		if (array_freelist_empty(&buf->freelist))
242948dad8baSKent Overstreet 			ret = MAP_DONE;
243048dad8baSKent Overstreet 
2431cafe5635SKent Overstreet 		spin_unlock(&buf->lock);
2432cafe5635SKent Overstreet 	}
243348dad8baSKent Overstreet out:
243448dad8baSKent Overstreet 	buf->last_scanned = *k;
243548dad8baSKent Overstreet 	return ret;
2436cafe5635SKent Overstreet }
2437cafe5635SKent Overstreet 
2438cafe5635SKent Overstreet void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
243972c27061SKent Overstreet 		       struct bkey *end, keybuf_pred_fn *pred)
2440cafe5635SKent Overstreet {
2441cafe5635SKent Overstreet 	struct bkey start = buf->last_scanned;
244248dad8baSKent Overstreet 	struct refill refill;
2443cafe5635SKent Overstreet 
2444cafe5635SKent Overstreet 	cond_resched();
2445cafe5635SKent Overstreet 
2446b54d6934SKent Overstreet 	bch_btree_op_init(&refill.op, -1);
244748dad8baSKent Overstreet 	refill.buf = buf;
244848dad8baSKent Overstreet 	refill.end = end;
244948dad8baSKent Overstreet 	refill.pred = pred;
245048dad8baSKent Overstreet 
245148dad8baSKent Overstreet 	bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
245248dad8baSKent Overstreet 			   refill_keybuf_fn, MAP_END_KEY);
2453cafe5635SKent Overstreet 
2454cafe5635SKent Overstreet 	pr_debug("found %s keys from %llu:%llu to %llu:%llu",
2455cafe5635SKent Overstreet 		 RB_EMPTY_ROOT(&buf->keys) ? "no" :
2456cafe5635SKent Overstreet 		 array_freelist_empty(&buf->freelist) ? "some" : "a few",
2457cafe5635SKent Overstreet 		 KEY_INODE(&start), KEY_OFFSET(&start),
2458cafe5635SKent Overstreet 		 KEY_INODE(&buf->last_scanned), KEY_OFFSET(&buf->last_scanned));
2459cafe5635SKent Overstreet 
2460cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2461cafe5635SKent Overstreet 
2462cafe5635SKent Overstreet 	if (!RB_EMPTY_ROOT(&buf->keys)) {
2463cafe5635SKent Overstreet 		struct keybuf_key *w;
2464cafe5635SKent Overstreet 		w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2465cafe5635SKent Overstreet 		buf->start	= START_KEY(&w->key);
2466cafe5635SKent Overstreet 
2467cafe5635SKent Overstreet 		w = RB_LAST(&buf->keys, struct keybuf_key, node);
2468cafe5635SKent Overstreet 		buf->end	= w->key;
2469cafe5635SKent Overstreet 	} else {
2470cafe5635SKent Overstreet 		buf->start	= MAX_KEY;
2471cafe5635SKent Overstreet 		buf->end	= MAX_KEY;
2472cafe5635SKent Overstreet 	}
2473cafe5635SKent Overstreet 
2474cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2475cafe5635SKent Overstreet }
2476cafe5635SKent Overstreet 
2477cafe5635SKent Overstreet static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2478cafe5635SKent Overstreet {
2479cafe5635SKent Overstreet 	rb_erase(&w->node, &buf->keys);
2480cafe5635SKent Overstreet 	array_free(&buf->freelist, w);
2481cafe5635SKent Overstreet }
2482cafe5635SKent Overstreet 
2483cafe5635SKent Overstreet void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2484cafe5635SKent Overstreet {
2485cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2486cafe5635SKent Overstreet 	__bch_keybuf_del(buf, w);
2487cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2488cafe5635SKent Overstreet }
2489cafe5635SKent Overstreet 
2490cafe5635SKent Overstreet bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2491cafe5635SKent Overstreet 				  struct bkey *end)
2492cafe5635SKent Overstreet {
2493cafe5635SKent Overstreet 	bool ret = false;
2494cafe5635SKent Overstreet 	struct keybuf_key *p, *w, s;
2495cafe5635SKent Overstreet 	s.key = *start;
2496cafe5635SKent Overstreet 
2497cafe5635SKent Overstreet 	if (bkey_cmp(end, &buf->start) <= 0 ||
2498cafe5635SKent Overstreet 	    bkey_cmp(start, &buf->end) >= 0)
2499cafe5635SKent Overstreet 		return false;
2500cafe5635SKent Overstreet 
2501cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2502cafe5635SKent Overstreet 	w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2503cafe5635SKent Overstreet 
2504cafe5635SKent Overstreet 	while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2505cafe5635SKent Overstreet 		p = w;
2506cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2507cafe5635SKent Overstreet 
2508cafe5635SKent Overstreet 		if (p->private)
2509cafe5635SKent Overstreet 			ret = true;
2510cafe5635SKent Overstreet 		else
2511cafe5635SKent Overstreet 			__bch_keybuf_del(buf, p);
2512cafe5635SKent Overstreet 	}
2513cafe5635SKent Overstreet 
2514cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2515cafe5635SKent Overstreet 	return ret;
2516cafe5635SKent Overstreet }
2517cafe5635SKent Overstreet 
2518cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2519cafe5635SKent Overstreet {
2520cafe5635SKent Overstreet 	struct keybuf_key *w;
2521cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2522cafe5635SKent Overstreet 
2523cafe5635SKent Overstreet 	w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2524cafe5635SKent Overstreet 
2525cafe5635SKent Overstreet 	while (w && w->private)
2526cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2527cafe5635SKent Overstreet 
2528cafe5635SKent Overstreet 	if (w)
2529cafe5635SKent Overstreet 		w->private = ERR_PTR(-EINTR);
2530cafe5635SKent Overstreet 
2531cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2532cafe5635SKent Overstreet 	return w;
2533cafe5635SKent Overstreet }
2534cafe5635SKent Overstreet 
2535cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2536cafe5635SKent Overstreet 					  struct keybuf *buf,
253772c27061SKent Overstreet 					  struct bkey *end,
253872c27061SKent Overstreet 					  keybuf_pred_fn *pred)
2539cafe5635SKent Overstreet {
2540cafe5635SKent Overstreet 	struct keybuf_key *ret;
2541cafe5635SKent Overstreet 
2542cafe5635SKent Overstreet 	while (1) {
2543cafe5635SKent Overstreet 		ret = bch_keybuf_next(buf);
2544cafe5635SKent Overstreet 		if (ret)
2545cafe5635SKent Overstreet 			break;
2546cafe5635SKent Overstreet 
2547cafe5635SKent Overstreet 		if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2548cafe5635SKent Overstreet 			pr_debug("scan finished");
2549cafe5635SKent Overstreet 			break;
2550cafe5635SKent Overstreet 		}
2551cafe5635SKent Overstreet 
255272c27061SKent Overstreet 		bch_refill_keybuf(c, buf, end, pred);
2553cafe5635SKent Overstreet 	}
2554cafe5635SKent Overstreet 
2555cafe5635SKent Overstreet 	return ret;
2556cafe5635SKent Overstreet }
2557cafe5635SKent Overstreet 
255872c27061SKent Overstreet void bch_keybuf_init(struct keybuf *buf)
2559cafe5635SKent Overstreet {
2560cafe5635SKent Overstreet 	buf->last_scanned	= MAX_KEY;
2561cafe5635SKent Overstreet 	buf->keys		= RB_ROOT;
2562cafe5635SKent Overstreet 
2563cafe5635SKent Overstreet 	spin_lock_init(&buf->lock);
2564cafe5635SKent Overstreet 	array_allocator_init(&buf->freelist);
2565cafe5635SKent Overstreet }
2566cafe5635SKent Overstreet 
2567cafe5635SKent Overstreet void bch_btree_exit(void)
2568cafe5635SKent Overstreet {
2569cafe5635SKent Overstreet 	if (btree_io_wq)
2570cafe5635SKent Overstreet 		destroy_workqueue(btree_io_wq);
2571cafe5635SKent Overstreet }
2572cafe5635SKent Overstreet 
2573cafe5635SKent Overstreet int __init bch_btree_init(void)
2574cafe5635SKent Overstreet {
257572a44517SKent Overstreet 	btree_io_wq = create_singlethread_workqueue("bch_btree_io");
257672a44517SKent Overstreet 	if (!btree_io_wq)
2577cafe5635SKent Overstreet 		return -ENOMEM;
2578cafe5635SKent Overstreet 
2579cafe5635SKent Overstreet 	return 0;
2580cafe5635SKent Overstreet }
2581